query
stringlengths
7
3.85k
document
stringlengths
11
430k
metadata
dict
negatives
listlengths
0
101
negative_scores
listlengths
0
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
Returns a string representation of the Tuple
func (this *Tuple) String() string { return fmt.Sprintf("%v", this.data) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t *Tuple) String() string {\n\tstart := \"(\"\n\tif t.IsPoint() {\n\t\tstart = \"p\" + start\n\t} else {\n\t\tstart = \"v\" + start\n\t}\n\treturn start + floatToString(t.x, 3) + \",\" + floatToString(t.y, 3) + \",\" + floatToString(t.z, 3) + \")\"\n}", "func (a Tuple) String() string {\n\tvar buf bytes.Buffer\n\tbuf.WriteRune('[')\n\tfor i := range a {\n\t\tbuf.WriteString(a[i].String())\n\t\tif i < len(a)-1 {\n\t\t\tbuf.WriteRune(' ')\n\t\t}\n\t}\n\tbuf.WriteRune(']')\n\treturn buf.String()\n}", "func (expr *TupleLiteralExpr) String() string {\n\tvar buf bytes.Buffer\n\n\tif len(expr.Members) != 0 {\n\t\tbuf.WriteString(\"{\")\n\t\tfor i, col := range expr.Members {\n\t\t\tif i != 0 {\n\t\t\t\tbuf.WriteString(\", \")\n\t\t\t}\n\t\t\tbuf.WriteString(col.String())\n\t\t}\n\t\tbuf.WriteString(\"}\")\n\t}\n\n\treturn buf.String()\n}", "func (s ByteMatchTuple) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s RegexMatchTuple) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s XssMatchTuple) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s SqlInjectionMatchTuple) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (p pair) string() string { // p is called the \"receiver\"\n return fmt.Sprintf(\"(%f, %f)\", p.x, p.y)\n}", "func (v *TypePair) String() string {\n\tif v == nil {\n\t\treturn \"<nil>\"\n\t}\n\n\tvar fields [2]string\n\ti := 0\n\tfields[i] = fmt.Sprintf(\"Left: %v\", v.Left)\n\ti++\n\tfields[i] = fmt.Sprintf(\"Right: %v\", v.Right)\n\ti++\n\n\treturn fmt.Sprintf(\"TypePair{%v}\", strings.Join(fields[:i], \", \"))\n}", "func (t Tuple) Pack() []byte {\n\tbuf := new(bytes.Buffer)\n\n\tfor i, e := range t {\n\t\tswitch e := e.(type) {\n\t\tcase nil:\n\t\t\tbuf.WriteByte(0x00)\n\t\tcase int64:\n\t\t\tencodeInt(buf, e)\n\t\tcase uint32:\n\t\t\tencodeInt(buf, int64(e))\n\t\tcase uint64:\n\t\t\tencodeInt(buf, int64(e))\n\t\tcase int:\n\t\t\tencodeInt(buf, int64(e))\n\t\tcase byte:\n\t\t\tencodeInt(buf, int64(e))\n\t\tcase []byte:\n\t\t\tencodeBytes(buf, 0x01, e)\n\t\tcase lex.KeyConvertible:\n\t\t\tencodeBytes(buf, 0x01, []byte(e.LexKey()))\n\t\tcase string:\n\t\t\tencodeBytes(buf, 0x02, []byte(e))\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"unencodable element at index %d (%v, type %T)\", i, t[i], t[i]))\n\t\t}\n\t}\n\n\treturn buf.Bytes()\n}", "func (self *T) String() string {\n\treturn fmt.Sprintf(\"%f %f %f %f\", self[0], self[1], self[2], self[3])\n}", "func (td TupleDesc) Format(tup Tuple) string {\n\tif tup == nil || tup.Count() == 0 {\n\t\treturn \"( )\"\n\t}\n\n\tvar sb strings.Builder\n\tsb.WriteString(\"( \")\n\n\tseenOne := false\n\tfor i := range td.Types {\n\t\tif seenOne {\n\t\t\tsb.WriteString(\", \")\n\t\t}\n\t\tseenOne = true\n\t\tsb.WriteString(td.FormatValue(i, tup.GetField(i)))\n\t}\n\tsb.WriteString(\" )\")\n\treturn sb.String()\n}", "func encodeTuple(t *tree.DTuple, appendTo []byte, colID uint32, scratch []byte) ([]byte, error) {\n\tappendTo = encoding.EncodeValueTag(appendTo, colID, encoding.Tuple)\n\tappendTo = encoding.EncodeNonsortingUvarint(appendTo, uint64(len(t.D)))\n\n\tvar err error\n\tfor _, dd := range t.D {\n\t\tappendTo, err = EncodeTableValue(appendTo, descpb.ColumnID(encoding.NoColumnID), dd, scratch)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn appendTo, nil\n}", "func (v Vertex) String() string {\n\treturn \"Vertex: \" + strconv.Itoa(v.X) + \",\" + strconv.Itoa(v.Y)\n}", "func (t *SPOTuple) Serialize() []byte {\n\n\tout, err := proto.Marshal(t)\n\tif err != nil {\n\t\tlog.Println(\"tuple-serialize: protobuf encoding error: \", err)\n\t}\n\treturn out\n\n}", "func (p PairType) String() string {\n\tvar first = fmt.Sprintf(\"%v\", p.first)\n\tvar second = fmt.Sprintf(\"%v\", p.second)\n\n\tif p.first == nil {\n\t\tfirst = \"pair\"\n\t}\n\tif p.second == nil {\n\t\tsecond = \"pair\"\n\t}\n\treturn fmt.Sprintf(\"pair(%v, %v)\", first, second)\n}", "func (kv *KeyValue) String() string {\n\treturn fmt.Sprintf(\"%+v\", kv.pairs)\n}", "func (t Tile) String() string {\n\treturn fmt.Sprintf(\"Tile(%d, %d, %d)\", t.X, t.Y, t.Z)\n}", "func (self *T) String() string {\n\treturn fmt.Sprintf(\"%f %f\", self[0], self[1])\n}", "func (list *ArrayList[T]) String() string {\n\treturn fmt.Sprint(list.elems)\n}", "func (pt Coord) String() string {\n\treturn fmt.Sprintf(\"{%v,%v}\", pt.x, pt.y)\n}", "func (self *T) String() string {\n\treturn fmt.Sprintf(\"%s %s\", self[0].String(), self[1].String())\n}", "func (s Permutation) String() string {\n\tres := make([]string, 2)\n\tres[0] = \"Uuid: \" + reform.Inspect(s.Uuid, true)\n\tres[1] = \"Data: \" + reform.Inspect(s.Data, true)\n\treturn strings.Join(res, \", \")\n}", "func (v *Vector3) ToString() string {\n\treturn \"(\" + strconv.FormatFloat(v.X, 'f', -1, 64) + \", \" + strconv.FormatFloat(v.Y, 'f', -1, 64) + \", \" + strconv.FormatFloat(v.Z, 'f', -1, 64) + \")\"\n}", "func (p *Point) ToString() string {\n\tx := strconv.FormatFloat(float64(p.X), 'f', 4, 32)\n\ty := strconv.FormatFloat(float64(p.Y), 'f', 4, 32)\n\n\treturn fmt.Sprintf(\"(%s, %s)\", x, y)\n}", "func (n *TreeNode) ToString() string {\n\tif n == nil {\n\t\treturn \"nil\"\n\t}\n\tif n.Left == nil && n.Right == nil {\n\t\treturn strconv.Itoa(n.Data)\n\t}\n\treturn fmt.Sprintf(\"%d => (%s, %s)\", n.Data, n.Left.ToString(), n.Right.ToString())\n}", "func (p *Pair) String() string {\n\treturn fmt.Sprintf(\"%s: %s\", p.Key, p.Value)\n}", "func (node ValTuple) Format(buf *TrackedBuffer) {\n\tbuf.astPrintf(node, \"(%v)\", Exprs(node))\n}", "func (b Block) ToString() string {\n\treturn fmt.Sprintf(\"Index: %d, TimeStamp: %s, BPM: %d, Hash: %x, PrevHash: %x\", b.Index, b.Timestamp, b.BPM, b.hash, b.prevHash)\n}", "func (o Orbit) String() string {\n\ta, e, i, Ω, ω, ν, λ, _, u := o.Elements()\n\treturn fmt.Sprintf(\"r=%.1f a=%.3f e=%.6f i=%.4f Ω=%.4f ω=%.4f ν=%.4f λ=%.4f u=%.4f\", Norm(o.rVec), a, e, Rad2deg(i), Rad2deg(Ω), Rad2deg(ω), Rad2deg(ν), Rad2deg(λ), Rad2deg(u))\n}", "func (b *BitSet) String() string {\n\tm := b.Members()\n\ts := make([]byte, 0, 4*len(m))\n\ts = append(s, '{')\n\tfor _, i := range m {\n\t\ts = append(s, fmt.Sprintf(\" %d\", i)...)\n\t}\n\treturn string(append(s, \" }\"...))\n}", "func (tid TransactionID) String() string {\n\treturn fmt.Sprintf(\"%x\", tid[:])\n}", "func (pt outPoint) String() string {\n\treturn pt.txHash.String() + \":\" + strconv.Itoa(int(pt.vout))\n}", "func (m *Hashmap) ToString() string {\n\ts := \"{\"\n\tkvps := make(chan keyValPair)\n\tgo m.iterate(kvps)\n\tfirst := true\n\tfor kvp := range kvps {\n\t\tentry := \"\"\n\t\tkey := kvp.key\n\t\tval := kvp.val\n\t\tif first {\n\t\t\tentry = fmt.Sprintf(\"%d: \\\"%s\\\"\", key, val)\n\t\t\tfirst = false\n\t\t} else {\n\t\t\tentry = fmt.Sprintf(\", %d: \\\"%s\\\"\", key, val)\n\t\t}\n\t\ts += entry\n\t\tfirst = false\n\t}\n\ts += \"}\"\n\treturn s\n}", "func (pt *outPoint) String() string {\n\treturn pt.txHash.String() + \":\" + strconv.Itoa(int(pt.vout))\n}", "func (tx Transaction) String() string {\n\tvar lines []string\n\n\tlines = append(lines, fmt.Sprintf(\"--- Transaction %x: \", tx.ID))\n\tfor i, input := range tx.Inputs {\n\t\tlines = append(lines, fmt.Sprintf(\" Input %d: \", i))\n\t\tlines = append(lines, fmt.Sprintf(\" TxID: %x\", input.ID))\n\t\tlines = append(lines, fmt.Sprintf(\" Out : %d\", input.Out))\n\t\tlines = append(lines, fmt.Sprintf(\" Signature: %x\", input.Signature))\n\t\tlines = append(lines, fmt.Sprintf(\" PubKey: %x\", input.PubKey))\n\t}\n\n\tfor i, output := range tx.Outputs {\n\t\tlines = append(lines, fmt.Sprintf(\" Output %d:\", i))\n\t\tlines = append(lines, fmt.Sprintf(\" Value: %d\", output.Value))\n\t\tlines = append(lines, fmt.Sprintf(\" PubKeyHash: %x\", output.PubKeyHash))\n\t}\n\n\treturn strings.Join(lines, \"\\n\")\n}", "func (p Pair) String() string {\n\treturn p.GetSharedCode(\"_\", false)\n}", "func (me TcoordinatesType) String() string { return xsdt.String(me).String() }", "func (m *TEQInstr) String() string {\n\treturn fmt.Sprintf(\"\\tTEQ%v %v, %s\", m.cond, m.lhs, m.rhs)\n}", "func (tx Transaction) String() string {\n\tvar lines []string\n\n\tlines = append(lines, fmt.Sprintf(\"--- Transaction %x:\", tx.ID))\n\n\tfor i, input := range tx.Vin {\n\n\t\tlines = append(lines, fmt.Sprintf(\" Input %d:\", i))\n\t\tlines = append(lines, fmt.Sprintf(\" TXID: %x\", input.Txid))\n\t\tlines = append(lines, fmt.Sprintf(\" Out: %d\", input.Vout))\n\t\tlines = append(lines, fmt.Sprintf(\" Signature: %x\", input.Signature))\n\t\tlines = append(lines, fmt.Sprintf(\" PubKey: %x\", input.PubKey))\n\t}\n\n\tfor i, output := range tx.Vout {\n\t\tlines = append(lines, fmt.Sprintf(\" Output %d:\", i))\n\t\tlines = append(lines, fmt.Sprintf(\" Value: %d\", output.Value))\n\t\tlines = append(lines, fmt.Sprintf(\" Script: %x\", output.PubKeyHash))\n\t}\n\n\treturn strings.Join(lines, \"\\n\")\n}", "func (v Vector2D) ToString() string {\n\treturn \"(\" + strconv.FormatFloat(v.X, 'f', 2, 64) + \", \" + strconv.FormatFloat(v.Y, 'f', 2, 64) + \")\"\n}", "func (self Block) ToString() string {\n\treturn fmt.Sprintf(\"%x %s %s\", self.PrevHash, self.Name, self.Nonce)\n}", "func (e *Expr) String() string {\n\tif e == nil {\n\t\treturn \"<nil>\"\n\t}\n\tb := new(bytes.Buffer)\n\tif e.Type != nil {\n\t\tb.WriteString(\"<\" + e.Type.String() + \">\")\n\t}\n\tswitch e.Kind {\n\tdefault:\n\t\tpanic(\"unknown expression type \" + fmt.Sprint(e.Kind))\n\tcase ExprError:\n\t\tb.WriteString(\"error\")\n\tcase ExprIdent:\n\t\tfmt.Fprintf(b, \"ident(%q)\", e.Ident)\n\tcase ExprBinop:\n\t\tfmt.Fprintf(b, \"binop(%v, %q, %v)\", e.Left, e.Op, e.Right)\n\tcase ExprUnop:\n\t\tfmt.Fprintf(b, \"unop(%q, %v\", e.Op, e.Left)\n\tcase ExprApply:\n\t\tfields := make([]string, len(e.Fields))\n\t\tfor i, f := range e.Fields {\n\t\t\tfields[i] = f.Expr.String()\n\t\t}\n\t\tfmt.Fprintf(b, \"apply(%v(%v))\", e.Left, strings.Join(fields, \", \"))\n\tcase ExprLit:\n\t\tfmt.Fprintf(b, \"const(%v)\", values.Sprint(e.Val, e.Type))\n\tcase ExprAscribe:\n\t\tfmt.Fprintf(b, \"ascribe(%v)\", e.Left)\n\tcase ExprBlock:\n\t\tdecls := make([]string, len(e.Decls))\n\t\tfor i := range e.Decls {\n\t\t\tdecls[i] = e.Decls[i].String()\n\t\t}\n\t\tfmt.Fprintf(b, \"block(%v in %v)\", strings.Join(decls, \", \"), e.Left)\n\tcase ExprFunc:\n\t\tfmt.Fprintf(b, \"func((%v) => %v)\", types.FieldsString(e.Args), e.Left)\n\tcase ExprTuple:\n\t\tfields := make([]string, len(e.Fields))\n\t\tfor i, f := range e.Fields {\n\t\t\tfields[i] = f.Expr.String()\n\t\t}\n\t\tfmt.Fprintf(b, \"tuple(%v)\", strings.Join(fields, \", \"))\n\tcase ExprStruct:\n\t\tlist := make([]string, len(e.Fields))\n\t\tfor i, f := range e.Fields {\n\t\t\tlist[i] = f.Name + \":\" + f.Expr.String()\n\t\t}\n\t\tfmt.Fprintf(b, \"struct(%v)\", strings.Join(list, \", \"))\n\tcase ExprList:\n\t\tlist := make([]string, len(e.List))\n\t\tfor i, ee := range e.List {\n\t\t\tlist[i] = ee.String()\n\t\t}\n\t\tfmt.Fprintf(b, \"list(%v)\", strings.Join(list, \", \"))\n\tcase ExprMap:\n\t\tvar (\n\t\t\tm = map[string]string{}\n\t\t\tkeys []string\n\t\t)\n\t\tfor ke, ve := range e.Map {\n\t\t\tkey := ke.String()\n\t\t\tm[key] = ve.String()\n\t\t\tkeys = append(keys, key)\n\t\t}\n\t\tsort.Strings(keys)\n\t\tlist := make([]string, len(keys))\n\t\tfor i, key := range keys {\n\t\t\tlist[i] = key + \":\" + m[key]\n\t\t}\n\t\tfmt.Fprintf(b, \"map(%v)\", strings.Join(list, \", \"))\n\tcase ExprVariant:\n\t\tif e.Left == nil {\n\t\t\tfmt.Fprintf(b, \"variant(#%s)\", e.Ident)\n\t\t\tbreak\n\t\t}\n\t\tfmt.Fprintf(b, \"variant(#%s, %v)\", e.Ident, e.Left)\n\tcase ExprExec:\n\t\tdecls := make([]string, len(e.Decls))\n\t\tfor i := range e.Decls {\n\t\t\tdecls[i] = e.Decls[i].String()\n\t\t}\n\t\tfmt.Fprintf(b, \"exec(decls(%v), %v, %q)\",\n\t\t\tstrings.Join(decls, \", \"), e.Type, e.Template)\n\tcase ExprCond:\n\t\tfmt.Fprintf(b, \"cond(%v, %v, %v)\", e.Cond, e.Left, e.Right)\n\tcase ExprSwitch:\n\t\tclauses := make([]string, len(e.CaseClauses))\n\t\tfor i := range e.CaseClauses {\n\t\t\tclauses[i] = e.CaseClauses[i].String()\n\t\t}\n\t\tfmt.Fprintf(b, \"switch(%v, cases(%v))\", e.Left,\n\t\t\tstrings.Join(clauses, \", \"))\n\tcase ExprDeref:\n\t\tfmt.Fprintf(b, \"deref(%v, %v)\", e.Left, e.Ident)\n\tcase ExprCompr:\n\t\tclauses := make([]string, len(e.ComprClauses))\n\t\tfor i, clause := range e.ComprClauses {\n\t\t\tswitch clause.Kind {\n\t\t\tcase ComprEnum:\n\t\t\t\tclauses[i] = fmt.Sprintf(\"enum(%v, %v)\", clause.Expr, clause.Pat)\n\t\t\tcase ComprFilter:\n\t\t\t\tclauses[i] = fmt.Sprintf(\"filter(%v)\", clause.Expr)\n\t\t\t}\n\t\t}\n\t\tfmt.Fprintf(b, \"compr(%v, %s)\", e.ComprExpr, strings.Join(clauses, \", \"))\n\tcase ExprThunk:\n\t\tfmt.Fprintf(b, \"thunk(%v, %v)\", e.Left, e.Env)\n\tcase ExprBuiltin:\n\t\tvar args string\n\t\tfor _, field := range e.Fields {\n\t\t\targs += fmt.Sprintf(\"%v, \", field.Expr)\n\t\t}\n\t\targs = strings.TrimRight(args, \" ,\")\n\t\tfmt.Fprintf(b, \"builtin(%v, %v)\", e.Op, args)\n\tcase ExprRequires:\n\t\tdecls := make([]string, len(e.Decls))\n\t\tfor i := range e.Decls {\n\t\t\tdecls[i] = e.Decls[i].String()\n\t\t}\n\t\tfmt.Fprintf(b, \"resources(%s, %s)\",\n\t\t\te.Left, strings.Join(decls, \", \"))\n\tcase ExprMake:\n\t\tdecls := make([]string, len(e.Decls))\n\t\tfor i := range e.Decls {\n\t\t\tdecls[i] = e.Decls[i].String()\n\t\t}\n\t\tfmt.Fprintf(b, \"make(%s, %v)\", e.Left, strings.Join(decls, \", \"))\n\tcase ExprIndex:\n\t\tfmt.Fprintf(b, \"index(%s, %s)\", e.Left, e.Right)\n\t}\n\treturn b.String()\n}", "func (me TCoordinatesType) String() string { return xsdt.String(me).String() }", "func toString(v value) string {\n\tvar b bytes.Buffer\n\twriteValue(&b, v)\n\treturn b.String()\n}", "func (pt *Point) String() string {\n\treturn fmt.Sprintf(\"{%d,%d}\", pt.x, pt.y)\n}", "func (v *Vector) String() string {\n\treturn fmt.Sprintf(\"[%f %f %f]\", v.X, v.Y, v.Z)\n}", "func (p packPlan) String() string {\n\tvar b byte\n\tvar err error\n\tvar s string\n\ts = \"\\n\"\n\n\tfor row := 0; row < palletWidth; row++ {\n\t\tfor col := 0; col < palletLength; col++ {\n\n\t\t\tif b, err = p.cell(uint8(col), uint8(row)); err != nil {\n\t\t\t\ts += fmt.Sprintf(\"%v, \\n\", err)\n\t\t\t\treturn s\n\t\t\t}\n\n\t\t\tif b == emptyCell {\n\t\t\t\ts += \"_\"\n\t\t\t} else {\n\t\t\t\ts += string(b)\n\t\t\t}\n\t\t}\n\t\ts += \"\\n\"\n\t}\n\treturn s\n}", "func (vertex Vertex) String() string {\n\ts := \"[\"\n\tfor i, move := range vertex.Moves {\n\t\ts = s + string(move)\n\t\tif i != len(vertex.Moves)-1 {\n\t\t\ts = s + \", \"\n\t\t}\n\t}\n\ts = s + \"]\"\n\treturn s\n}", "func (op *output) String() string {\n\treturn fmt.Sprintf(\"%s:%v\", op.txHash, op.vout)\n}", "func (v T) String() string {\n\treturn fmt.Sprint(uint32(v))\n}", "func (me TCoordinateType) String() string { return xsdt.String(me).String() }", "func (p point) String() string {\n\treturn fmt.Sprintf(\"point %d, %d\", p.x, p.y)\n}", "func (a *Vector3) String() string {\n\tif a == nil {\n\t\treturn \"\"\n\t}\n\tx := strconv.FormatFloat(a.X, 'f', -1, 64)\n\ty := strconv.FormatFloat(a.Y, 'f', -1, 64)\n\tz := strconv.FormatFloat(a.Z, 'f', -1, 64)\n\treturn strings.Join([]string{x, y, z}, \",\")\n}", "func (tx Transaction) String() string {\n\tvar lines []string\n\n\tlines = append(lines, fmt.Sprintf(\"--- Transaction %x:\", tx.ID))\n\tfor i, input := range tx.Inputs {\n\t\tlines = append(lines, fmt.Sprintf(\" Input %d:\", i))\n\t\tlines = append(lines, fmt.Sprintf(\" TXID: %x\", input.ID))\n\t\tlines = append(lines, fmt.Sprintf(\" Out: %d\", input.Out))\n\t\tlines = append(lines, fmt.Sprintf(\" Signature: %x\", input.Signature))\n\t\tlines = append(lines, fmt.Sprintf(\" PubKey: %x\", input.PubKey))\n\t}\n\n\tfor i, output := range tx.Outputs {\n\t\tlines = append(lines, fmt.Sprintf(\" Output %d:\", i))\n\t\tlines = append(lines, fmt.Sprintf(\" Value: %d\", output.Value))\n\t\tlines = append(lines, fmt.Sprintf(\" Script: %x\", output.PubKeyHash))\n\t}\n\n\treturn strings.Join(lines, \"\\n\")\n}", "func (v GeodeticPoint) String() string {\n\treturn fmt.Sprintf(\"%f,%f\", v.Longitude, v.Latitude)\n}", "func (node *HashPair) String() string {\n\treturn node.Key + \"=\" + node.Val.String()\n}", "func (its *OperationID) ToString() string {\n\tif its == nil {\n\t\treturn \"\"\n\t}\n\tvar b strings.Builder\n\t_, _ = fmt.Fprintf(&b, \"[%d:%d:%s:%d]\",\n\t\tits.Era, its.Lamport, its.CUID, its.Seq)\n\treturn b.String()\n}", "func (b *BooleanObject) ToString() string {\n\treturn fmt.Sprintf(\"%t\", b.value)\n}", "func (s Phases) ToString() string {\n\treturn fmt.Sprintf(\"%d%d%d%d%d max thruster signal: %d\", s.a, s.b, s.c, s.d, s.e, s.thrusterValue)\n}", "func (n NodesID) String() string {\n\treturn fmt.Sprintf(\"%x\", n[:])\n}", "func (e *Entry) String() string {\n\treturn fmt.Sprintf(\"%v(%v)\", e.Vector, e.Value)\n}", "func (p Pair) String() string {\n\treturn p.Base.String() + p.Delimiter + p.Quote.String()\n}", "func (p Pair) String() string {\n\treturn p.Base.String() + p.Delimiter + p.Quote.String()\n}", "func (t *TopicType) String() string {\n\treturn common.ToHex(t[:])\n}", "func (s pgStatDatabase) String() string {\n\tres := make([]string, 2)\n\tres[0] = \"DatID: \" + reform.Inspect(s.DatID, true)\n\tres[1] = \"DatName: \" + reform.Inspect(s.DatName, true)\n\treturn strings.Join(res, \", \")\n}", "func (m *MutipleValues) String() string {\n\tif m == nil {\n\t\treturn \"\"\n\t}\n\treturn strings.Join([]string(*m), \";\")\n}", "func (m *TSTInstr) String() string {\n\treturn fmt.Sprintf(\"\\tTST%v %v, %s\", m.cond, m.lhs, m.rhs)\n}", "func (me TxsdFeCompositeTypeOperator) String() string { return xsdt.String(me).String() }", "func (m Cuepoint) String() string {\n\treturn fmt.Sprintf(\"%T: %#v\", m, m.Text())\n}", "func (n NodeID) String() string {\n\treturn fmt.Sprintf(\"%x\", n[:])\n}", "func (selectedAltitude SelectedAltitude) ToString() string {\n\n\tif selectedAltitude == 0 {\n\t\treturn \"0 - no data or invalid\"\n\t}\n\n\treturn fmt.Sprintf(\"%v feet\", selectedAltitude.GetSelectedAltitude())\n\n}", "func (p *Point) String() string {\n\treturn fmt.Sprintf(\"(%d, %d)\", p.X, p.Y)\n}", "func (p Point) String() string {\n\treturn fmt.Sprintf(\"%d, %d\", p.X, p.Y)\n}", "func (u Vec) String() string {\n\treturn fmt.Sprintf(\"Vec(%v, %v)\", u.X, u.Y)\n}", "func (kvp *KVPairs) String() string {\n\tvar b strings.Builder\n\n\tb.WriteRune('{')\n\tfor i, p := range kvp.Pairs {\n\t\tif i > 0 {\n\t\t\tb.WriteString(\", \")\n\t\t}\n\t\tb.WriteString(stringutil.Sprintf(\"%s\", p))\n\t}\n\tb.WriteRune('}')\n\n\treturn b.String()\n}", "func (v *Type) String() string {\n\tif v == nil {\n\t\treturn \"<nil>\"\n\t}\n\n\tvar fields [6]string\n\ti := 0\n\tif v.SimpleType != nil {\n\t\tfields[i] = fmt.Sprintf(\"SimpleType: %v\", *(v.SimpleType))\n\t\ti++\n\t}\n\tif v.SliceType != nil {\n\t\tfields[i] = fmt.Sprintf(\"SliceType: %v\", v.SliceType)\n\t\ti++\n\t}\n\tif v.KeyValueSliceType != nil {\n\t\tfields[i] = fmt.Sprintf(\"KeyValueSliceType: %v\", v.KeyValueSliceType)\n\t\ti++\n\t}\n\tif v.MapType != nil {\n\t\tfields[i] = fmt.Sprintf(\"MapType: %v\", v.MapType)\n\t\ti++\n\t}\n\tif v.ReferenceType != nil {\n\t\tfields[i] = fmt.Sprintf(\"ReferenceType: %v\", v.ReferenceType)\n\t\ti++\n\t}\n\tif v.PointerType != nil {\n\t\tfields[i] = fmt.Sprintf(\"PointerType: %v\", v.PointerType)\n\t\ti++\n\t}\n\n\treturn fmt.Sprintf(\"Type{%v}\", strings.Join(fields[:i], \", \"))\n}", "func (a Vector) String() string {\n\ts := make([]string, len(a))\n\tfor k := range a {\n\t\ts[k] = fmt.Sprintf(\"%g\", a[k])\n\t}\n\treturn fmt.Sprintf(\"[%s]\", strings.Join(s, \", \"))\n}", "func (e *BinExpr) String() string {\n\treturn fmt.Sprintf(e.format, e.a, e.b)\n}", "func (self Hash) ToString() string {\n\treturn fmt.Sprintf(\"%x\", self)\n}", "func (p Point) String() string {\n\treturn fmt.Sprintf(\"(%d,%d)\", p.X, p.Y)\n}", "func (t *Tile) String() string {\n\treturn fmt.Sprintf(\"Tile(ID=%v)\", t.ID)\n}", "func (p polynomial) String() (str string) {\n\tfor _, m := range p.monomials {\n\t\tstr = str + \" \" + m.String() + \" +\"\n\t}\n\tstr = strings.TrimRight(str, \"+\")\n\treturn \"f(x) = \" + strings.TrimSpace(str)\n}", "func (me TPointsType) String() string { return xsdt.String(me).String() }", "func (r *AggloResult) String() string {\n\tstrs := make([]string, len(r.perm))\n\tfor i := range strs {\n\t\tif r.dict == nil {\n\t\t\tstrs[i] = fmt.Sprint(i)\n\t\t} else {\n\t\t\tstrs[i] = r.dict[i]\n\t\t}\n\t}\n\tfor _, i := range r.perm {\n\t\tj := r.pi[i]\n\t\tif i == j { // Reached the end.\n\t\t\treturn strs[i]\n\t\t}\n\t\tstrs[j] = fmt.Sprintf(\"[%s, %s, %.1f]\", strs[i], strs[j], r.lambda[i])\n\t}\n\n\t// TODO(amit): Panic if reached here.\n\treturn \"\"\n}", "func (bits Bits) String() string", "func (s SlotId) String() string {\n\treturn fmt.Sprintf(\"%s (%x)\", s.Name, s.Key)\n}", "func (w *Writer) WriteTuple(tuple ...interface{}) {\n\tsetWriterRef(w, nil, nil)\n\tcount := len(tuple)\n\tif count == 0 {\n\t\twriteEmptyList(w)\n\t\treturn\n\t}\n\twriteListHeader(w, count)\n\tfor _, v := range tuple {\n\t\tw.Serialize(v)\n\t}\n\twriteListFooter(w)\n}", "func (T transaction) String() string {\n\treturn fmt.Sprintf(\"{\\n\\t\\t\\tsender:%v,\\n\\t\\t\\treceiver:%v,\\n\\t\\t\\tamount:%v\\n\\t\\t}\", T.sender, T.receiver, T.amount)\n}", "func (v *CallValue) String() string { return strconv.FormatUint(uint64(v.progID), 10) }", "func (e *ExprXor) String() string {\n\treturn fmt.Sprintf(\"%v %v\", e.Type(), e.Ident())\n}", "func (l *GeopointLiteral) String() string {\n\treturn fmt.Sprintf(\"point(%f, %f)\", l.Val[0], l.Val[1])\n}", "func (dtk *DcmTagKey) ToString() string {\n\tvar result string\n\tif dtk.group == 0xFFFF && dtk.element == 0xFFFF {\n\t\tresult = \"(????,????)\"\n\t} else {\n\t\tresult = fmt.Sprintf(\"(%04x,%04x)\", dtk.group, dtk.element)\n\t}\n\treturn result\n}", "func (n *node) String() string {\n\treturn \"<\" + n.view.String() + \"-\\n\" + n.children[0].String() + \", \\n\" + n.children[1].String() + \", \\n\" + n.children[2].String() + \", \\n\" + n.children[3].String() + \">\"\n}", "func ToString(mp map[string]any) string {\n\tif mp == nil {\n\t\treturn \"\"\n\t}\n\tif len(mp) == 0 {\n\t\treturn \"{}\"\n\t}\n\n\tbuf := make([]byte, 0, len(mp)*16)\n\tbuf = append(buf, '{')\n\n\tfor k, val := range mp {\n\t\tbuf = append(buf, k...)\n\t\tbuf = append(buf, ':')\n\n\t\tstr := strutil.QuietString(val)\n\t\tbuf = append(buf, str...)\n\t\tbuf = append(buf, ',', ' ')\n\t}\n\n\t// remove last ', '\n\tbuf = append(buf[:len(buf)-2], '}')\n\treturn strutil.Byte2str(buf)\n}", "func (k *CallKey) String() string { return strconv.FormatUint(uint64(k.index), 10) }", "func (t *Token) ToString() string {\r\n\tvar strVal string\r\n\r\n\tswitch t.Type {\r\n\tcase scalar:\r\n\t\tstrVal = fmt.Sprint(t.ScalarValue)\r\n\tcase variable:\r\n\t\tstrVal = fmt.Sprintf(\"x%d\", t.VariableValue)\r\n\tcase plus:\r\n\t\tstrVal = \"+\"\r\n\tcase minus:\r\n\t\tstrVal = \"-\"\r\n\tcase times:\r\n\t\tstrVal = \"*\"\r\n\tcase divide:\r\n\t\tstrVal = \"/\"\r\n\tcase power:\r\n\t\tstrVal = \"^\"\r\n\tcase squareRoot:\r\n\t\tstrVal = \"square-root\"\r\n\tcase cubeRoot:\r\n\t\tstrVal = \"cube-root\"\r\n\t}\r\n\treturn strVal\r\n}", "func (p point) String() string {\n\treturn fmt.Sprintf(\"x=%d, y=%d\", p.x, p.y)\n}", "func (r Row) ToString(ft []*types.FieldType) string {\n\tvar buf []byte\n\tfor colIdx := 0; colIdx < r.Chunk().NumCols(); colIdx++ {\n\t\tif r.IsNull(colIdx) {\n\t\t\tbuf = append(buf, \"NULL\"...)\n\t\t} else {\n\t\t\tswitch ft[colIdx].EvalType() {\n\t\t\tcase types.ETInt:\n\t\t\t\tbuf = strconv.AppendInt(buf, r.GetInt64(colIdx), 10)\n\t\t\tcase types.ETString:\n\t\t\t\tswitch ft[colIdx].GetType() {\n\t\t\t\tcase mysql.TypeEnum:\n\t\t\t\t\tbuf = append(buf, r.GetEnum(colIdx).String()...)\n\t\t\t\tcase mysql.TypeSet:\n\t\t\t\t\tbuf = append(buf, r.GetSet(colIdx).String()...)\n\t\t\t\tdefault:\n\t\t\t\t\tbuf = append(buf, r.GetString(colIdx)...)\n\t\t\t\t}\n\t\t\tcase types.ETDatetime, types.ETTimestamp:\n\t\t\t\tbuf = append(buf, r.GetTime(colIdx).String()...)\n\t\t\tcase types.ETDecimal:\n\t\t\t\tbuf = append(buf, r.GetMyDecimal(colIdx).ToString()...)\n\t\t\tcase types.ETDuration:\n\t\t\t\tbuf = append(buf, r.GetDuration(colIdx, ft[colIdx].GetDecimal()).String()...)\n\t\t\tcase types.ETJson:\n\t\t\t\tbuf = append(buf, r.GetJSON(colIdx).String()...)\n\t\t\tcase types.ETReal:\n\t\t\t\tswitch ft[colIdx].GetType() {\n\t\t\t\tcase mysql.TypeFloat:\n\t\t\t\t\tbuf = strconv.AppendFloat(buf, float64(r.GetFloat32(colIdx)), 'f', -1, 32)\n\t\t\t\tcase mysql.TypeDouble:\n\t\t\t\t\tbuf = strconv.AppendFloat(buf, r.GetFloat64(colIdx), 'f', -1, 64)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif colIdx != r.Chunk().NumCols()-1 {\n\t\t\tbuf = append(buf, \", \"...)\n\t\t}\n\t}\n\treturn string(buf)\n}", "func (e entry) String() string {\n\treturn fmt.Sprintf(`\nid %v\nday %v\nreceived %v\ndispatched %v\narrived %v\ncleared %v\ncall_type %v\ngrid_location %v\nas_observed %v\naddress %v\nclearance_code %v\nresp_officer %v\nunits %v\ndescription %v\ncall_comments %v\n`,\n\t\te.id, e.day, e.received, e.dispatched, e.arrived, e.cleared, e.call_type, e.grid_location, e.as_observed, e.address,\n\t\te.clearance_code, e.resp_officer, e.units, e.description, e.call_comments)\n\n}" ]
[ "0.79209447", "0.77979815", "0.73687667", "0.7235998", "0.697652", "0.69273907", "0.6819455", "0.67232805", "0.6324634", "0.6154409", "0.61384434", "0.61242175", "0.61046237", "0.60856646", "0.60820186", "0.6044038", "0.6011396", "0.5978302", "0.5946973", "0.59240377", "0.5913056", "0.59062254", "0.58676815", "0.5843266", "0.5809294", "0.579778", "0.5797124", "0.5790227", "0.5773348", "0.575485", "0.57349557", "0.57324725", "0.57228893", "0.572242", "0.57182264", "0.57011664", "0.5689015", "0.56888855", "0.566105", "0.5658601", "0.56424725", "0.5624631", "0.56209964", "0.56126255", "0.5605995", "0.5600957", "0.56008273", "0.5598753", "0.55926543", "0.55884176", "0.55767524", "0.55696756", "0.55683684", "0.5554703", "0.554788", "0.5543307", "0.55415875", "0.55343664", "0.5532814", "0.5531326", "0.553011", "0.55156827", "0.551406", "0.551406", "0.55133307", "0.5511883", "0.5506629", "0.5506343", "0.5505986", "0.54942024", "0.5491602", "0.54797363", "0.5477108", "0.5474022", "0.54663646", "0.5463159", "0.5463034", "0.54616433", "0.54590166", "0.5457638", "0.5456817", "0.54542816", "0.5438802", "0.54289454", "0.5417505", "0.5412657", "0.541151", "0.54085225", "0.5407941", "0.5407882", "0.5399359", "0.5394518", "0.53924274", "0.53921765", "0.53919655", "0.5391687", "0.5388489", "0.5383837", "0.5382496", "0.53821117" ]
0.7824448
1
Pops the leftmost item from the Tuple and returns it
func (this *Tuple) PopLeft() interface{} { if this.Len() < 1 { return nil } ret := this.data[0] this.data = this.data[1:] return ret }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *Tuple) PopRight() interface{} {\n\tif this.Len() < 1 {\n\t\treturn nil\n\t}\n\tidx := this.Offset(-1)\n\tret := this.data[idx]\n\tthis.data = this.data[:idx]\n\treturn ret\n}", "func (this *Tuple) Left(n int) *Tuple {\n\treturn this.Slice(0, n)\n}", "func pop(headP *Node) (*Node, *Node){\n // sanity checks\n if headP == nil {\n return nil, nil\n }\n\n // 1 node.\n if (*headP).p == nil {\n return headP, nil\n }\n\n // general case..\n newHeadP := (*headP).p\n poppedP := headP\n (*poppedP).p = nil \n \n return poppedP, newHeadP\n}", "func (s *orderedItems) Pop() interface{} {\n\told := *s\n\tn := len(old)\n\tx := old[n-1]\n\t*s = old[0 : n-1]\n\treturn x\n}", "func (o *openList) Pop() interface{} {\n\topn := *o\n\tit := opn[len(opn)-1]\n\tit.pqindex = -1\n\t*o = opn[:len(opn)-1]\n\treturn it\n}", "func (s *Slot) pop() Item {\n\titem := s.item\n\ts.item = Empty\n\treturn item\n}", "func (q *queryPQ) Pop() any {\n\titem := (*q)[len(*q)-1]\n\t*q = (*q)[:len(*q)-1]\n\treturn item\n}", "func (l *TwoList) PopFront() *Element {\n\treturn l.seekFront(true)\n}", "func (l *AttributeList) Pop() (*string, *string) {\n\tif l.Len() == 0 {\n\t\treturn nil, nil\n\t}\n\tkey, val := l.first.Key, l.first.Value\n\tif l.first == l.last {\n\t\tl.last = nil\n\t}\n\tl.first = l.first.Next\n\tl.length--\n\treturn &key, &val\n}", "func (s *items) pop() (out Item) {\n\tindex := len(*s) - 1\n\tout = (*s)[index]\n\t(*s)[index] = nil\n\t*s = (*s)[:index]\n\treturn\n}", "func (this *Stack) Pop() (string, time.Time) {\n\tif this.length == 0 {\n\t\tvar t time.Time\n\t\treturn \"\", t\n\t}\n\n\tn := this.top\n\tthis.top = n.prev\n\tthis.length--\n\treturn n.value, n.time_stamp\n}", "func (pq *MinPQ) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (pe PathExpression) popOneLastLeg() (PathExpression, pathLeg) {\n\tlastLegIdx := len(pe.legs) - 1\n\tlastLeg := pe.legs[lastLegIdx]\n\t// It is used only in modification, it has been checked that there is no asterisks.\n\treturn PathExpression{legs: pe.legs[:lastLegIdx]}, lastLeg\n}", "func (p Pool) Pop() interface{} {\n\tel := p[p.Len()-1]\n\tp = p[:p.Len()-2]\n\treturn el\n}", "func pop(slice []string) (string, []string) {\n\telement := slice[0]\n\tslice = slice[1:]\n\treturn element, slice\n}", "func (pq *PriorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (list *List) Pop(idx ...int) (interface{}, error) {\n\tindex := list.getLastIndex()\n\tll := len(idx)\n\n\tif ll > 1 {\n\t\treturn nil, fmt.Errorf(\"only 1 or 0 arguments are allowed\")\n\t}\n\n\t// in case of `list.Pop()`\n\telement := list.getByIndex(index)\n\tif ll == 0 {\n\t\treturn element, list.removeByIndex(index)\n\t}\n\n\tif idx[0] > index {\n\t\treturn nil, fmt.Errorf(\"index out of range\")\n\t}\n\n\tindex = idx[0]\n\treturn element, list.removeByIndex(index)\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (arr *ArrayList) Pop() ItemType {\n if arr.length > 0 {\n // shrink by half if only a third is used - dampening resize operations\n if arr.length < arr.capacity / 3 {\n arr.resize(arr.capacity / 2)\n }\n arr.length--\n return arr.data[arr.length]\n }\n panic(\"out of bounds\")\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (s *Steps) Pop() (Step, Path) {\n\treturn s.step, s.parent\n}", "func (h *minPath) Pop() interface{} {\n\told := *h\n\tn := len(old)\n\tx := old[n-1]\n\t*h = old[0 : n-1]\n\treturn x\n}", "func (pq *MinPQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (t *topK) Pop() interface{} {\n\tn := len(t.values)\n\tx := t.values[n-1]\n\tt.values = t.values[:n-1]\n\treturn x\n}", "func (vector *Vector) PopFront() {\n\tvar element interface{}\n\telement, *vector = (*vector)[0], (*vector)[1:]\n\t// Note: dropping element here.\n\t_ = element\n}", "func (a Slice[T]) Pop() (Slice[T], T) {\n\treturn a[:len(a)-1], a[len(a)-1]\n}", "func (que *Queue) Pop() string {\n\tnode := que.values[0]\n\tque.values = que.values[1:]\n\treturn node\n}", "func (pq *MaxPQ) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (nl *nodeList) pop() *Node {\n\tsize := len(nl.elements)\n\tif size == 0 {\n\t\treturn nil\n\t}\n\n\t// This method of deletion is used instead of calling nl.Delete(), because it's faster.\n\tend := size - 1\n\tn := nl.elements[end]\n\tnl.elements[end] = nil\n\tnl.elements = nl.elements[0:end]\n\n\treturn n\n}", "func (pq *PriorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\tvar item *Item\n\tif len(old) == 0 {\n\t\treturn nil\n\t}\n\titem = old[n-1]\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\n\treturn item\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil // avoid memory leak\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil // avoid memory leak\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (pq *PriorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (l *pqList) Pop() interface{} {\n\treturn l.Remove(len(l.Slice) - 1)\n}", "func (s *SliceOfUint) Pop() uint {\n\tpoppedItem := s.items[len(s.items)-1]\n\ts.items = s.items[:len(s.items)-1]\n\treturn poppedItem\n}", "func (sll *SingleLinkedList) Pop(index int) interface{} {\n\t// Panic if index is smaller 0\n\tif index < 0 {\n\t\tpanic(\"index < 0\")\n\t}\n\n\t// Pop first element\n\tif index == 0 {\n\t\t// Result\n\t\tv := sll.first.value\n\t\t// Remove first element\n\t\tsll.first = sll.first.next\n\t\t// Decrease length\n\t\tsll.length--\n\t\treturn v\n\t}\n\n\t// Get node before the one to pop\n\tn := sll.getNode(index - 1)\n\t// Result\n\tv := n.next.value\n\t// Remove reference to remove element\n\tn.next = n.next.next\n\t// Decrease length\n\tsll.length--\n\treturn v\n}", "func (pq *PriorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\tnode := old[n-1]\n\told[n-1] = nil // avoid memory leak\n\tnode.Index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn node\n}", "func (vector *Vector) Pop() {\n\tvar element interface{}\n\telement, *vector = (*vector)[len(*vector)-1], (*vector)[:len(*vector)-1]\n\t// Note: dropping element here.\n\t_ = element\n}", "func (p *path) Pop() interface{} {\n\told := *p\n\tn := len(old)\n\tx := old[n-1]\n\t*p = old[0 : n-1]\n\treturn x\n}", "func (this *MyQueue) Pop() int {\n x := this.q[0]\n this.q = this.q[1:]\n return x\n}", "func (t *Tower) pop() (result int) {\n\tresult = (*t)[len(*t)-1]\n\t*t = (*t)[:len(*t)-1]\n\treturn result\n}", "func (this *MyStack) Pop() int {\n\ttemp := this.val[0]\n\tthis.val = this.val[1:]\n\treturn temp\n}", "func (q *Queue) Pop() Any {\n\tif q.count == 0 {\n\t\treturn nil\n\t}\n\titem := q.nodes[q.head]\n\tq.head = (q.head + 1) % len(q.nodes)\n\tq.count--\n\treturn item\n}", "func (this *Tuple) Right(n int) *Tuple {\n\tlength := this.Len()\n\tn = max(0, length-n)\n\treturn this.Slice(n, length)\n}", "func pop(in []string) (item string, out []string, ok bool) {\n\tif ok = len(in) != 0; !ok {\n\t\treturn\n\t}\n\n\titem, out = in[0], in[1:]\n\treturn\n}", "func (s *SliceOfUint64) Pop() uint64 {\n\tpoppedItem := s.items[len(s.items)-1]\n\ts.items = s.items[:len(s.items)-1]\n\treturn poppedItem\n}", "func pop(s stack, top int) (*element, int, error) {\n\tif top == -1 {\n\t\treturn nil, -1, fmt.Errorf(\"underflow\")\n\t}\n\tpoppedElement := s[top]\n\ttop--\n\treturn &poppedElement, top, nil\n}", "func (s *StackTemplate) Pop() *interface{} {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\tif last := len(*s) - 1; last < 0 {\n\t\treturn nil\n\t} else {\n\t\titem := (*s)[len(*s)-1]\n\t\treduced := (*s)[:last]\n\t\t*s = reduced\n\t\treturn &item\n\t}\n}", "func (pe PathExpression) popOneLeg() (pathLeg, PathExpression) {\n\tnewPe := PathExpression{\n\t\tlegs: pe.legs[1:],\n\t\tflags: 0,\n\t}\n\tfor _, leg := range newPe.legs {\n\t\tif leg.typ == pathLegIndex && leg.arrayIndex == -1 {\n\t\t\tnewPe.flags |= pathExpressionContainsAsterisk\n\t\t} else if leg.typ == pathLegKey && leg.dotKey == \"*\" {\n\t\t\tnewPe.flags |= pathExpressionContainsAsterisk\n\t\t} else if leg.typ == pathLegDoubleAsterisk {\n\t\t\tnewPe.flags |= pathExpressionContainsDoubleAsterisk\n\t\t}\n\t}\n\treturn pe.legs[0], newPe\n}", "func (l *List) PopFront() *Process {\n\tp := (*l)[0]\n\t*l = (*l)[1:]\n\treturn p\n}", "func lvalPop(v *LVal, i int) *LVal {\n\tx := v.Cell[i]\n\n\tv.Cell = append(v.Cell[:i], v.Cell[i+1:]...)\n\treturn x\n}", "func (h *tsHeap) Pop() interface{} {\n\tit := (*h)[len(*h)-1]\n\t// Poison the removed element, for safety.\n\tit.index = -1\n\t*h = (*h)[0 : len(*h)-1]\n\treturn it\n}", "func (h *MinKeyHeap) Pop() interface{} {\n\told := *h\n\tn := len(old)\n\tx := old[n-1]\n\t*h = old[0 : n-1]\n\treturn x\n}", "func Pop(h *PriorityQueue) *Item {\n\tn := h.Len() - 1\n\th.Swap(0, n)\n\tdown(h, 0, n)\n\treturn h.Pop()\n}", "func (q *Stack) Pop() interface{} {\n\treturn q.Items.Pop().Value\n}", "func (nl *nodeList) shift() *Node {\n\tif len(nl.elements) == 0 {\n\t\treturn nil\n\t}\n\n\t// This method of deletion is used instead of calling nl.Delete(), because it's faster.\n\tn := nl.elements[0]\n\tnl.elements[0] = nil\n\tnl.elements = nl.elements[1:]\n\treturn n\n}", "func (h *itemHeap) Pop() interface{} {\n\tl := len(*h)\n\ti := (*h)[l-1]\n\t*h = (*h)[:l-1]\n\treturn i\n}", "func (ss SliceType) Pop() (SliceType, ElementType) {\n\tif len(ss) == 0 {\n\t\treturn nil, ElementZeroValue\n\t}\n\tpopValue := ss[len(ss)-1]\n\tss = ss[:len(ss)-1]\n\treturn ss, popValue\n}", "func (s *Storage) RPop() *list.Element {\r\n\tele := s.Back()\r\n\tif ele != nil {\r\n\t\ts.Remove(ele)\r\n\t}\r\n\treturn ele\r\n}", "func (pq *PrioQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\tx := old[n-1]\n\t*pq = old[0 : n-1]\n\treturn x\n}", "func (h *PerformanceHeap) Pop() interface{} {\n\told := h.items\n\tn := len(old)\n\tx := old[n-1]\n\th.items = old[0 : n-1]\n\treturn x\n}", "func (s *SliceOfUint32) Pop() uint32 {\n\tpoppedItem := s.items[len(s.items)-1]\n\ts.items = s.items[:len(s.items)-1]\n\treturn poppedItem\n}", "func (hp *theHeap) Pop() interface{} {\n\tn := len(*hp)\n\told := *hp\n\titem := old[n-1]\n\t*hp = old[0 : n-1]\n\treturn item\n}", "func (h *Heap) Pop() interface{} {\n\told := h.slice\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil // avoid memory leak\n\titem.index = -1 // for safety\n\th.slice = old[0 : n-1]\n\treturn item\n}", "func (s *SliceOfFloat32) Pop() float32 {\n\tpoppedItem := s.items[len(s.items)-1]\n\ts.items = s.items[:len(s.items)-1]\n\treturn poppedItem\n}", "func (s *Stack) Pop() int {\n\tl := len(s-item) - 1\n\ttoRemove := s.items[l]\n\ts.items = s.items[:l]\n\treturn toRemove\n}", "func (a *ArrayObject) pop() Object {\n\tif len(a.Elements) < 1 {\n\t\treturn NULL\n\t}\n\n\tvalue := a.Elements[len(a.Elements)-1]\n\ta.Elements = a.Elements[:len(a.Elements)-1]\n\treturn value\n}", "func (this *LinkedList) Pop() interface{} {\n\tif this.head == nil {\n\t\treturn nil\n\t}\n\treturn this.RemoveAt(0)\n}", "func (t *queueStorage) Pop() interface{} {\n\tn := len(*t)\n\tres := (*t)[n-1]\n\t*t = (*t)[:n-1]\n\treturn res\n}", "func (w *walk) pop() {\n\tif len(*w) > 0 {\n\t\t*w = (*w)[:len(*w)-1]\n\t}\n}", "func (ll *LinkedList) PopLeft() (int, bool) {\n\tif ll.IsEmpty() {\n\t\treturn -1, false\n\t}\n\n\telement := ll.start.value\n\n\t// single element\n\tif ll.start == ll.end {\n\t\tll.Clear()\n\t} else {\n\t\tll.start = ll.start.next\n\t\tll.start.previous = nil\n\t\tll.length--\n\t}\n\n\treturn element, true\n}", "func (s *Stack) Pop() string {\n\tindex := len(*s) - 1\n\telement := (*s)[index]\n\t*s = (*s)[:index]\n\n\treturn element\n}", "func (h *Strings) Pop() string {\n\tif h.less == nil {\n\t\tPopToLastF(len(h.list), h.list.Less, h.list.Swap)\n\t} else {\n\t\tPopToLastF(len(h.list), h.less, h.list.Swap)\n\t}\n\n\tres := h.list[len(h.list)-1]\n\th.list[len(h.list)-1] = \"\" // remove the reference in h.list\n\th.list = h.list[:len(h.list)-1]\n\n\treturn res\n}", "func lvalTake(v *LVal, i int) *LVal {\n\tx := lvalPop(v, i)\n\treturn x\n}", "func (s *RRset) Pop() RR {\n\tif len(*s) == 0 {\n\t\treturn nil\n\t}\n\t// Pop and remove the entry\n\tr := (*s)[len(*s)-1]\n\t*s = (*s)[:len(*s)-1]\n\treturn r\n}", "func (heap *maxheap) Pop() interface{} {\n\told := *heap\n\tn := len(old)\n\n\titem := old[n-1]\n\told[n-1] = nil\n\titem.index = -1\n\n\t*heap = old[0 : n-1]\n\n\treturn item\n}", "func (s *children) pop() (out *node) {\n\tindex := len(*s) - 1\n\tout = (*s)[index]\n\t(*s)[index] = nil\n\t*s = (*s)[:index]\n\treturn\n}", "func (s *SliceOfInt64) Pop() int64 {\n\tpoppedItem := s.items[len(s.items)-1]\n\ts.items = s.items[:len(s.items)-1]\n\treturn poppedItem\n}", "func (shelf *Shelf) Pop() interface{} {\n\tx := shelf.queue[shelf.Len()-1]\n\tshelf.queue = shelf.queue[:shelf.Len()-1]\n\treturn x\n}", "func (s *MyStack) Pop() int {\n\titem := s.queue[0]\n\ts.queue = s.queue[1:]\n\treturn item\n}", "func (t *Tree) peek() item {\n\tif t.peekCount > 0 {\n\t\treturn t.token[t.peekCount-1]\n\t}\n\tt.peekCount = 1\n\tt.token[0] = t.lex.nextItem()\n\treturn t.token[0]\n}", "func (h *MaxKeyHeap) Pop() interface{} {\n\told := *h\n\tn := len(old)\n\tx := old[n-1]\n\t*h = old[0 : n-1]\n\treturn x\n}", "func Pop(tx *bolt.Tx, name []byte, position *Position) []byte {\n\tbucket := tx.Bucket(name)\n\tif bucket == nil {\n\t\treturn nil\n\t}\n\n\tcursor := bucket.Cursor()\n\t_, value := position.fn(cursor)\n\t_ = cursor.Delete()\n\treturn value\n}", "func (stepList *StepList) Pop() steps.Step {\n\tif stepList.IsEmpty() {\n\t\treturn nil\n\t}\n\tresult := stepList.List[0]\n\tstepList.List = stepList.List[1:]\n\treturn result\n}", "func (h *Queue) Pop() interface{} {\n\told := h.slice\n\tn := len(old)\n\titem := old[n-1]\n\th.slice = old[0 : n-1]\n\treturn item\n}", "func (h *Heap) Pop() interface{} {\n\tif h.size == 0 {\n\t\treturn nil\n\t}\n\tres := h.values[1]\n\th.values[1] = h.values[h.size]\n\th.values = h.values[:h.size]\n\th.size--\n\n\th.bubbleDown()\n\n\treturn res\n}", "func (stack *Stack) Pop() (stuff interface{}, err error) {\n\ttheStack := *stack\n\n\tif len(theStack) == 0 {\n\t\treturn nil, errors.New(\"Tried to pop an empty stack.\")\n\t}\n\n\t//get last element\n\tlast := theStack[len(theStack)-1]\n\t//reduce stack by 1\n\t*stack = theStack[:len(theStack)-1]\n\n\treturn last, nil\n}", "func (s *SliceOfString) Pop() string {\n\tpoppedItem := s.items[len(s.items)-1]\n\ts.items = s.items[:len(s.items)-1]\n\treturn poppedItem\n}", "func (l *SliceList[T]) PopFront() (v T, ok bool) {\n\tif len(*l) > 0 {\n\t\tv, *l = (*l)[0], (*l)[1:]\n\t\treturn\n\t}\n\n\treturn\n}", "func (l *list) pop() *listNode {\n\tif l.first == nil {\n\t\treturn nil\n\t}\n\n\tl.len--\n\tif l.first == l.tail {\n\t\taux := l.first\n\t\tl.first = nil\n\t\tl.tail = nil\n\t\treturn aux\n\t}\n\taux := l.first\n\tl.first = aux.next\n\treturn aux\n}", "func (cq *cQT) PopFront() (el T, ok bool) {\n\tvar zero T\n\tif cq.s == cq.e {\n\t\treturn zero, false\n\t}\n\tel = cq.b[cq.s&cq.m]\n\tcq.b[cq.s&cq.m] = zero\n\tcq.s++\n\treturn el, true\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.last == nil {\n\t\treturn nil, ErrEmptyList\n\t}\n\tn := l.last\n\tif l.first == n {\n\t\tl.first = nil\n\t}\n\tl.last = n.prev\n\tif l.last != nil {\n\t\tl.last.next = nil\n\t}\n\treturn n.Val, nil\n}", "func (cq *cQT) PopBack() (el T, ok bool) {\n\tvar zero T\n\tif cq.s == cq.e {\n\t\treturn zero, false\n\t}\n\tcq.e--\n\tel = cq.b[cq.e&cq.m]\n\tcq.b[cq.e&cq.m] = zero\n\treturn el, true\n}", "func (ll *LinkedList) PopFront() T {\n\tif ll.head == nil {\n\t\treturn nil\n\t}\n\n\tval := ll.head.val\n\tif ll.head == ll.tail {\n\t\tll.head = nil\n\t\tll.tail = nil\n\t} else {\n\t\thead := ll.head.next\n\t\thead.prev = nil\n\t\tll.head.next = nil\n\t\tll.head = head\n\t}\n\n\tll.size--\n\treturn val\n}", "func (ll *LinkedList) PopBack() T {\n\tif ll.tail == nil {\n\t\treturn nil\n\t}\n\n\tval := ll.tail.val\n\tif ll.head == ll.tail {\n\t\tll.head = nil\n\t\tll.tail = nil\n\t} else {\n\t\ttail := ll.tail.prev\n\t\ttail.next = nil\n\t\tll.tail.prev = nil\n\t\tll.tail = tail\n\t}\n\n\tll.size--\n\treturn val\n}", "func (s *stack) pop() int {\n\tl := len(s.items)\n\tremovedItem := s.items[l-1]\n\ts.items = s.items[:l-1]\n\treturn removedItem\n}", "func (s *Stack) Pop() (item float64) {\n\ts.Length--\n\titem = s.Items[s.Length]\n\ts.Items = s.Items[:s.Length]\n\treturn\n}", "func (md *MinQueue) Pop() interface{} {\n\told := *md\n\tn := len(old)\n\titem := old[n-1]\n\t*md = old[:n-1]\n\titem.index = n\n\treturn item\n}", "func pop(s []string) string {\n\tpop := s[0]\n\ts = remove(s, pop)\n\treturn pop\n}", "func (s *MyStack) Pop() int {\n v := s.queue1[0]\n s.queue1 = s.queue1[1:]\n return v\n}" ]
[ "0.7001776", "0.6395089", "0.6281589", "0.6274747", "0.6267232", "0.62015057", "0.6201386", "0.6188319", "0.61784905", "0.6177955", "0.61499226", "0.6148321", "0.6137886", "0.6126758", "0.61212844", "0.60814977", "0.60791075", "0.6074746", "0.60689086", "0.6036339", "0.6035134", "0.6028861", "0.6028189", "0.6027978", "0.6016628", "0.6001875", "0.5999233", "0.5991486", "0.59883434", "0.59847283", "0.5980618", "0.5980618", "0.597857", "0.5964981", "0.5958648", "0.59441495", "0.5941222", "0.59186757", "0.5916899", "0.5906855", "0.5904384", "0.5881171", "0.588098", "0.58675295", "0.5863702", "0.58616805", "0.5860036", "0.5856477", "0.583271", "0.58308417", "0.58271444", "0.5826465", "0.5820488", "0.58201575", "0.58179545", "0.581663", "0.58143413", "0.58114904", "0.5805244", "0.5796197", "0.5794532", "0.579067", "0.5764116", "0.5759319", "0.57570076", "0.57453436", "0.57364243", "0.57345176", "0.57342124", "0.5731335", "0.5718029", "0.57167095", "0.57128435", "0.5704486", "0.5703811", "0.56971", "0.5694922", "0.5691169", "0.56906515", "0.56901294", "0.56866354", "0.5686538", "0.5680672", "0.56792474", "0.5678137", "0.56778955", "0.5676717", "0.5676154", "0.5674301", "0.5670554", "0.5665916", "0.5665539", "0.56645846", "0.5663255", "0.5662633", "0.5661261", "0.5656203", "0.56552404", "0.565502", "0.5654059" ]
0.7820287
0
Pops the rightmost item from the Tuple and returns it
func (this *Tuple) PopRight() interface{} { if this.Len() < 1 { return nil } idx := this.Offset(-1) ret := this.data[idx] this.data = this.data[:idx] return ret }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *Tuple) PopLeft() interface{} {\n\tif this.Len() < 1 {\n\t\treturn nil\n\t}\n\tret := this.data[0]\n\tthis.data = this.data[1:]\n\treturn ret\n}", "func (this *Tuple) Right(n int) *Tuple {\n\tlength := this.Len()\n\tn = max(0, length-n)\n\treturn this.Slice(n, length)\n}", "func (pe PathExpression) popOneLastLeg() (PathExpression, pathLeg) {\n\tlastLegIdx := len(pe.legs) - 1\n\tlastLeg := pe.legs[lastLegIdx]\n\t// It is used only in modification, it has been checked that there is no asterisks.\n\treturn PathExpression{legs: pe.legs[:lastLegIdx]}, lastLeg\n}", "func (s *Slot) pop() Item {\n\titem := s.item\n\ts.item = Empty\n\treturn item\n}", "func (s *items) pop() (out Item) {\n\tindex := len(*s) - 1\n\tout = (*s)[index]\n\t(*s)[index] = nil\n\t*s = (*s)[:index]\n\treturn\n}", "func (o *openList) Pop() interface{} {\n\topn := *o\n\tit := opn[len(opn)-1]\n\tit.pqindex = -1\n\t*o = opn[:len(opn)-1]\n\treturn it\n}", "func (p Pool) Pop() interface{} {\n\tel := p[p.Len()-1]\n\tp = p[:p.Len()-2]\n\treturn el\n}", "func (s *Storage) RPop() *list.Element {\r\n\tele := s.Back()\r\n\tif ele != nil {\r\n\t\ts.Remove(ele)\r\n\t}\r\n\treturn ele\r\n}", "func (q *queryPQ) Pop() any {\n\titem := (*q)[len(*q)-1]\n\t*q = (*q)[:len(*q)-1]\n\treturn item\n}", "func (arr *ArrayList) Pop() ItemType {\n if arr.length > 0 {\n // shrink by half if only a third is used - dampening resize operations\n if arr.length < arr.capacity / 3 {\n arr.resize(arr.capacity / 2)\n }\n arr.length--\n return arr.data[arr.length]\n }\n panic(\"out of bounds\")\n}", "func (s *orderedItems) Pop() interface{} {\n\told := *s\n\tn := len(old)\n\tx := old[n-1]\n\t*s = old[0 : n-1]\n\treturn x\n}", "func (l *AttributeList) Pop() (*string, *string) {\n\tif l.Len() == 0 {\n\t\treturn nil, nil\n\t}\n\tkey, val := l.first.Key, l.first.Value\n\tif l.first == l.last {\n\t\tl.last = nil\n\t}\n\tl.first = l.first.Next\n\tl.length--\n\treturn &key, &val\n}", "func pop(headP *Node) (*Node, *Node){\n // sanity checks\n if headP == nil {\n return nil, nil\n }\n\n // 1 node.\n if (*headP).p == nil {\n return headP, nil\n }\n\n // general case..\n newHeadP := (*headP).p\n poppedP := headP\n (*poppedP).p = nil \n \n return poppedP, newHeadP\n}", "func pop(slice []string) (string, []string) {\n\telement := slice[0]\n\tslice = slice[1:]\n\treturn element, slice\n}", "func (this *Stack) Pop() (string, time.Time) {\n\tif this.length == 0 {\n\t\tvar t time.Time\n\t\treturn \"\", t\n\t}\n\n\tn := this.top\n\tthis.top = n.prev\n\tthis.length--\n\treturn n.value, n.time_stamp\n}", "func (t *topK) Pop() interface{} {\n\tn := len(t.values)\n\tx := t.values[n-1]\n\tt.values = t.values[:n-1]\n\treturn x\n}", "func (list *List) Pop(idx ...int) (interface{}, error) {\n\tindex := list.getLastIndex()\n\tll := len(idx)\n\n\tif ll > 1 {\n\t\treturn nil, fmt.Errorf(\"only 1 or 0 arguments are allowed\")\n\t}\n\n\t// in case of `list.Pop()`\n\telement := list.getByIndex(index)\n\tif ll == 0 {\n\t\treturn element, list.removeByIndex(index)\n\t}\n\n\tif idx[0] > index {\n\t\treturn nil, fmt.Errorf(\"index out of range\")\n\t}\n\n\tindex = idx[0]\n\treturn element, list.removeByIndex(index)\n}", "func (pq *PriorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (s *SliceOfUint) Pop() uint {\n\tpoppedItem := s.items[len(s.items)-1]\n\ts.items = s.items[:len(s.items)-1]\n\treturn poppedItem\n}", "func (s *SliceOfUint64) Pop() uint64 {\n\tpoppedItem := s.items[len(s.items)-1]\n\ts.items = s.items[:len(s.items)-1]\n\treturn poppedItem\n}", "func (d *Deque) PopRight() (res interface{}) {\n\td.rightOff--\n\tif d.rightOff < 0 {\n\t\td.rightOff = blockSize - 1\n\t\td.rightIdx = (d.rightIdx - 1 + len(d.blocks)) % len(d.blocks)\n\t\td.right = d.blocks[d.rightIdx]\n\t}\n\tres, d.right[d.rightOff] = d.right[d.rightOff], nil\n\treturn\n}", "func (pq *MaxPQ) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func pop(s stack, top int) (*element, int, error) {\n\tif top == -1 {\n\t\treturn nil, -1, fmt.Errorf(\"underflow\")\n\t}\n\tpoppedElement := s[top]\n\ttop--\n\treturn &poppedElement, top, nil\n}", "func (s *StackTemplate) Pop() *interface{} {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\tif last := len(*s) - 1; last < 0 {\n\t\treturn nil\n\t} else {\n\t\titem := (*s)[len(*s)-1]\n\t\treduced := (*s)[:last]\n\t\t*s = reduced\n\t\treturn &item\n\t}\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (tp *Tiles) TakeLast() *TilePlacement {\n\tlength := len(*tp)\n\tif length == 0 {\n\t\treturn nil\n\t}\n\n\tp := &(*tp)[length-1]\n\t*tp = (*tp)[:length-1]\n\treturn p\n}", "func (t *Tower) pop() (result int) {\n\tresult = (*t)[len(*t)-1]\n\t*t = (*t)[:len(*t)-1]\n\treturn result\n}", "func (q *Stack) Pop() interface{} {\n\treturn q.Items.Pop().Value\n}", "func (que *Queue) Pop() string {\n\tnode := que.values[0]\n\tque.values = que.values[1:]\n\treturn node\n}", "func (pq *MinPQ) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (a Slice[T]) Pop() (Slice[T], T) {\n\treturn a[:len(a)-1], a[len(a)-1]\n}", "func (pq *PriorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (nl *nodeList) pop() *Node {\n\tsize := len(nl.elements)\n\tif size == 0 {\n\t\treturn nil\n\t}\n\n\t// This method of deletion is used instead of calling nl.Delete(), because it's faster.\n\tend := size - 1\n\tn := nl.elements[end]\n\tnl.elements[end] = nil\n\tnl.elements = nl.elements[0:end]\n\n\treturn n\n}", "func (l *pqList) Pop() interface{} {\n\treturn l.Remove(len(l.Slice) - 1)\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil // avoid memory leak\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil // avoid memory leak\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (pq *PriorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\tvar item *Item\n\tif len(old) == 0 {\n\t\treturn nil\n\t}\n\titem = old[n-1]\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\n\treturn item\n}", "func (q *Queue) Pop() Any {\n\tif q.count == 0 {\n\t\treturn nil\n\t}\n\titem := q.nodes[q.head]\n\tq.head = (q.head + 1) % len(q.nodes)\n\tq.count--\n\treturn item\n}", "func (pe PathExpression) popOneLeg() (pathLeg, PathExpression) {\n\tnewPe := PathExpression{\n\t\tlegs: pe.legs[1:],\n\t\tflags: 0,\n\t}\n\tfor _, leg := range newPe.legs {\n\t\tif leg.typ == pathLegIndex && leg.arrayIndex == -1 {\n\t\t\tnewPe.flags |= pathExpressionContainsAsterisk\n\t\t} else if leg.typ == pathLegKey && leg.dotKey == \"*\" {\n\t\t\tnewPe.flags |= pathExpressionContainsAsterisk\n\t\t} else if leg.typ == pathLegDoubleAsterisk {\n\t\t\tnewPe.flags |= pathExpressionContainsDoubleAsterisk\n\t\t}\n\t}\n\treturn pe.legs[0], newPe\n}", "func (s *Steps) Pop() (Step, Path) {\n\treturn s.step, s.parent\n}", "func (vector *Vector) Pop() {\n\tvar element interface{}\n\telement, *vector = (*vector)[len(*vector)-1], (*vector)[:len(*vector)-1]\n\t// Note: dropping element here.\n\t_ = element\n}", "func Pop(h *PriorityQueue) *Item {\n\tn := h.Len() - 1\n\th.Swap(0, n)\n\tdown(h, 0, n)\n\treturn h.Pop()\n}", "func (s *Stack) Pop() (value interface{}) {\n\n if s.size > 0 {\n\n value, s.top = s.top.value, s.top.next\n\n s.size--\n\n return\n\n }\n\n return nil\n\n}", "func (s *Stack) Pop() interface{} {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tvar n *stackItem\n\tif s.top != nil {\n\t\tn = s.top\n\t\ts.top = n.next\n\t\ts.count--\n\t}\n\n\tif n == nil {\n\t\treturn nil\n\t}\n\n\treturn n.data\n\n}", "func pop(in []string) (item string, out []string, ok bool) {\n\tif ok = len(in) != 0; !ok {\n\t\treturn\n\t}\n\n\titem, out = in[0], in[1:]\n\treturn\n}", "func (s *Stack) PopSecond() DrawPather {\n\tif s.Len() < 2 {\n\t\treturn nil\n\t}\n\n\ttmp := (*s)[s.Len()-2]\n\t(*s)[s.Len()-2] = (*s)[s.Len()-1]\n\t*s = (*s)[:s.Len()-1]\n\treturn tmp\n}", "func Pop[T any](h Interface[T]) T {\n\tn := h.Len() - 1\n\th.Swap(0, n)\n\tdown(h, 0, n)\n\treturn h.Pop()\n}", "func (stack *Stack) Pop() (stuff interface{}, err error) {\n\ttheStack := *stack\n\n\tif len(theStack) == 0 {\n\t\treturn nil, errors.New(\"Tried to pop an empty stack.\")\n\t}\n\n\t//get last element\n\tlast := theStack[len(theStack)-1]\n\t//reduce stack by 1\n\t*stack = theStack[:len(theStack)-1]\n\n\treturn last, nil\n}", "func (this *MyQueue) Pop() int {\n x := this.q[0]\n this.q = this.q[1:]\n return x\n}", "func (p *path) Pop() interface{} {\n\told := *p\n\tn := len(old)\n\tx := old[n-1]\n\t*p = old[0 : n-1]\n\treturn x\n}", "func (this *MyStack) Pop() int {\n\ttemp := this.val[0]\n\tthis.val = this.val[1:]\n\treturn temp\n}", "func (s *RRset) Pop() RR {\n\tif len(*s) == 0 {\n\t\treturn nil\n\t}\n\t// Pop and remove the entry\n\tr := (*s)[len(*s)-1]\n\t*s = (*s)[:len(*s)-1]\n\treturn r\n}", "func (self *OperandStack) PopSlot() Slot {\n\tself.top--\n\tvalue := self.slots[self.top]\n\tself.slots[self.top].Num = 0\n\tself.slots[self.top].Ref = nil\n\treturn value\n}", "func (s *openCellStack) pop() (openCell, error) {\n\tif len(*s) == 0 {\n\t\treturn openCell{palletLength, palletWidth}, errStackEmpty\n\t}\n\tc := (*s)[len(*s)-1]\n\t(*s) = (*s)[:len(*s)-1]\n\treturn c, nil\n}", "func (pq *MinPQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (a *ArrayObject) pop() Object {\n\tif len(a.Elements) < 1 {\n\t\treturn NULL\n\t}\n\n\tvalue := a.Elements[len(a.Elements)-1]\n\ta.Elements = a.Elements[:len(a.Elements)-1]\n\treturn value\n}", "func (t *Map) Pop() interface{} {\n\tif t.NotEmpty() {\n\t\tkey := t.keys.Remove(t.keys.Back())\n\t\tval, ok := t.entries[key]\n\t\tdelete(t.entries, key)\n\t\tif ok {\n\t\t\treturn val.val\n\t\t}\n\t}\n\treturn nil\n}", "func (l *TwoList) PopFront() *Element {\n\treturn l.seekFront(true)\n}", "func (es *eeStack) pop() (v interface{}, t eeType) {\r\n\tt = es.popType()\r\n\tv = t.pop(es)\r\n\treturn\r\n}", "func (ll *LinkedList) PopBack() T {\n\tif ll.tail == nil {\n\t\treturn nil\n\t}\n\n\tval := ll.tail.val\n\tif ll.head == ll.tail {\n\t\tll.head = nil\n\t\tll.tail = nil\n\t} else {\n\t\ttail := ll.tail.prev\n\t\ttail.next = nil\n\t\tll.tail.prev = nil\n\t\tll.tail = tail\n\t}\n\n\tll.size--\n\treturn val\n}", "func (this *Stack) Pop() interface{} {\n\tif this.length == 0 {\n\t\treturn nil\n\t}\n\n\tn := this.top\n\tthis.top = n.prev\n\tthis.length--\n\treturn n.value\n}", "func (t *queueStorage) Pop() interface{} {\n\tn := len(*t)\n\tres := (*t)[n-1]\n\t*t = (*t)[:n-1]\n\treturn res\n}", "func (pq *PriorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\tnode := old[n-1]\n\told[n-1] = nil // avoid memory leak\n\tnode.Index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn node\n}", "func (s *children) pop() (out *node) {\n\tindex := len(*s) - 1\n\tout = (*s)[index]\n\t(*s)[index] = nil\n\t*s = (*s)[:index]\n\treturn\n}", "func (h *itemHeap) Pop() interface{} {\n\tl := len(*h)\n\ti := (*h)[l-1]\n\t*h = (*h)[:l-1]\n\treturn i\n}", "func (d *Deque) Right() interface{} {\n\tif d.rightOff > 0 {\n\t\treturn d.right[d.rightOff-1]\n\t} else {\n\t\treturn d.blocks[(d.rightIdx-1+len(d.blocks))%len(d.blocks)][blockSize-1]\n\t}\n}", "func (s *Stack) Pop() interface{} {\r\n\tn := len(s.stk)\r\n\tvalue := s.stk[n-1]\r\n\ts.stk = s.stk[:n-1]\r\n\treturn value\r\n}", "func (t Tuple2[A, B]) Unpack() (A, B) {\n\treturn t.A, t.B\n}", "func (h *minPath) Pop() interface{} {\n\told := *h\n\tn := len(old)\n\tx := old[n-1]\n\t*h = old[0 : n-1]\n\treturn x\n}", "func (s *Stack) Pop() interface{} {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\tif s.length == 0 {\n\t\treturn nil\n\t}\n\tn := s.top\n\ts.top = n.prev\n\ts.length--\n\treturn n.value\n}", "func (shelf *Shelf) Pop() interface{} {\n\tx := shelf.queue[shelf.Len()-1]\n\tshelf.queue = shelf.queue[:shelf.Len()-1]\n\treturn x\n}", "func (ss SliceType) Pop() (SliceType, ElementType) {\n\tif len(ss) == 0 {\n\t\treturn nil, ElementZeroValue\n\t}\n\tpopValue := ss[len(ss)-1]\n\tss = ss[:len(ss)-1]\n\treturn ss, popValue\n}", "func (cs *copyStack) pop() *Type {\n\tn := len(*cs)\n\tif n == 0 {\n\t\treturn nil\n\t}\n\n\tt := (*cs)[n-1]\n\t*cs = (*cs)[:n-1]\n\treturn t\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.last == nil {\n\t\treturn nil, ErrEmptyList\n\t}\n\tn := l.last\n\tif l.first == n {\n\t\tl.first = nil\n\t}\n\tl.last = n.prev\n\tif l.last != nil {\n\t\tl.last.next = nil\n\t}\n\treturn n.Val, nil\n}", "func (h *Heap) Pop() interface{} {\n\tif h.size == 0 {\n\t\treturn nil\n\t}\n\tres := h.values[1]\n\th.values[1] = h.values[h.size]\n\th.values = h.values[:h.size]\n\th.size--\n\n\th.bubbleDown()\n\n\treturn res\n}", "func (s *Stack) Pop() int {\n\tl := len(s-item) - 1\n\ttoRemove := s.items[l]\n\ts.items = s.items[:l]\n\treturn toRemove\n}", "func (s *Stack) Pop() (*Item, error) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\t// Check if stack is closed.\n\tif !s.isOpen {\n\t\treturn nil, ErrDBClosed\n\t}\n\n\t// Try to get the next item in the stack.\n\titem, err := s.getItemByID(s.head)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Remove this item from the stack.\n\tif err := s.db.Update(func(txn *badger.Txn) error {\n\t\treturn txn.Delete(item.Key)\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Decrement head position.\n\ts.head--\n\n\treturn item, nil\n}", "func (s *Stack[T]) Pop() T {\n\tv := s.array[len(s.array)-1]\n\ts.array = s.array[:len(s.array)-1]\n\treturn v\n}", "func (s *Stack) Pop() interface{} {\n\tif s.IsEmpty() {\n\t\treturn nil\n\t}\n\telement := (*s)[len(*s)-1]\n\t*s = (*s)[:len(*s)-1]\n\treturn element\n}", "func (h *Queue) Pop() interface{} {\n\told := h.slice\n\tn := len(old)\n\titem := old[n-1]\n\th.slice = old[0 : n-1]\n\treturn item\n}", "func (s *Stack) Pop() interface{} {\n\tv := s.v[len(s.v)]\n\ts.v = s.v[:len(s.v)-1]\n\treturn v\n}", "func (sll *SingleLinkedList) Pop(index int) interface{} {\n\t// Panic if index is smaller 0\n\tif index < 0 {\n\t\tpanic(\"index < 0\")\n\t}\n\n\t// Pop first element\n\tif index == 0 {\n\t\t// Result\n\t\tv := sll.first.value\n\t\t// Remove first element\n\t\tsll.first = sll.first.next\n\t\t// Decrease length\n\t\tsll.length--\n\t\treturn v\n\t}\n\n\t// Get node before the one to pop\n\tn := sll.getNode(index - 1)\n\t// Result\n\tv := n.next.value\n\t// Remove reference to remove element\n\tn.next = n.next.next\n\t// Decrease length\n\tsll.length--\n\treturn v\n}", "func (s *SliceOfString) Pop() string {\n\tpoppedItem := s.items[len(s.items)-1]\n\ts.items = s.items[:len(s.items)-1]\n\treturn poppedItem\n}", "func (s *exprStack) pop() Expression {\n\ttrace_util_0.Count(_util_00000, 163)\n\tif s.len() == 0 {\n\t\ttrace_util_0.Count(_util_00000, 165)\n\t\treturn nil\n\t}\n\ttrace_util_0.Count(_util_00000, 164)\n\tlastIdx := s.len() - 1\n\texpr := s.stack[lastIdx]\n\ts.stack = s.stack[:lastIdx]\n\treturn expr\n}", "func (h *tsHeap) Pop() interface{} {\n\tit := (*h)[len(*h)-1]\n\t// Poison the removed element, for safety.\n\tit.index = -1\n\t*h = (*h)[0 : len(*h)-1]\n\treturn it\n}", "func (hp *theHeap) Pop() interface{} {\n\tn := len(*hp)\n\told := *hp\n\titem := old[n-1]\n\t*hp = old[0 : n-1]\n\treturn item\n}", "func (w *walk) pop() {\n\tif len(*w) > 0 {\n\t\t*w = (*w)[:len(*w)-1]\n\t}\n}", "func (list *TList) TPop() string {\n\tlist.mux.Lock()\n\n\tif list.Tail() == nil {\n\t\tlist.mux.Unlock()\n\t\treturn \"\"\n\t}\n\n\tstr := util.ToString(list.list.Remove(list.Tail()))\n\tlist.mux.Unlock()\n\treturn str\n}", "func (s *SliceOfInt64) Pop() int64 {\n\tpoppedItem := s.items[len(s.items)-1]\n\ts.items = s.items[:len(s.items)-1]\n\treturn poppedItem\n}", "func (s *stack) pop() int {\n\tl := len(s.items)\n\tremovedItem := s.items[l-1]\n\ts.items = s.items[:l-1]\n\treturn removedItem\n}", "func (s *Stack) Pop() (value interface{}) {\r\n\tif s.size > 0 {\r\n\t\tvalue, s.top = s.top.value, s.top.next\r\n\t\ts.size--\r\n\t\treturn value\r\n\t}\r\n\treturn nil\r\n}", "func (s *Stack) Pop() string {\n\tindex := len(*s) - 1\n\telement := (*s)[index]\n\t*s = (*s)[:index]\n\n\treturn element\n}", "func (h *Heap) Pop() interface{} {\n\told := h.slice\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil // avoid memory leak\n\titem.index = -1 // for safety\n\th.slice = old[0 : n-1]\n\treturn item\n}", "func (s *MyStack) Pop() int {\n\titem := s.queue[0]\n\ts.queue = s.queue[1:]\n\treturn item\n}", "func rightMost(node *Node) *Node {\n\tif node == nil {\n\t\treturn nil\n\t}\n\n\tcurrent := node\n\n\tfor {\n\t\tif current.right == nil {\n\t\t\treturn current\n\t\t}\n\t\tcurrent = current.right\n\t}\n}", "func (s *Uint64) Pop() uint64 {\n\tfor val := range s.m {\n\t\tdelete(s.m, val)\n\t\treturn val\n\t}\n\treturn 0\n}", "func (cq *cQT) PopBack() (el T, ok bool) {\n\tvar zero T\n\tif cq.s == cq.e {\n\t\treturn zero, false\n\t}\n\tcq.e--\n\tel = cq.b[cq.e&cq.m]\n\tcq.b[cq.e&cq.m] = zero\n\treturn el, true\n}", "func (s *Stack) Pop() (item float64) {\n\ts.Length--\n\titem = s.Items[s.Length]\n\ts.Items = s.Items[:s.Length]\n\treturn\n}", "func (ll *LinkedList) PopRight() (int, bool) {\n\tif ll.IsEmpty() {\n\t\treturn -1, false\n\t}\n\n\telement := ll.end.value\n\n\t// single element\n\tif ll.start == ll.end {\n\t\tll.Clear()\n\t} else {\n\t\tll.end = ll.end.previous\n\t\tll.end.next = nil\n\t\tll.length--\n\t}\n\n\treturn element, true\n}" ]
[ "0.71033895", "0.6737673", "0.6415144", "0.63615215", "0.6302642", "0.6233184", "0.6197565", "0.6194584", "0.61938787", "0.6181438", "0.6158734", "0.61554414", "0.614082", "0.6131531", "0.61124057", "0.6086503", "0.6063265", "0.60419124", "0.60412616", "0.6026922", "0.6026662", "0.6024832", "0.60139734", "0.59965056", "0.5993688", "0.5975395", "0.5974389", "0.5973365", "0.59675527", "0.5965306", "0.59629095", "0.5959594", "0.5935882", "0.5934007", "0.59323186", "0.5924869", "0.5924869", "0.5914721", "0.590764", "0.59042716", "0.5901523", "0.58978313", "0.5885107", "0.5885084", "0.58816576", "0.58739465", "0.58726513", "0.58604074", "0.5848057", "0.5846142", "0.5845701", "0.5845605", "0.5843098", "0.58411324", "0.5837398", "0.5833139", "0.58234745", "0.58233815", "0.58188987", "0.5808701", "0.5807475", "0.5804176", "0.58014274", "0.57977945", "0.5797111", "0.5780946", "0.57800573", "0.57799786", "0.57666826", "0.5765737", "0.5764539", "0.5760711", "0.57557976", "0.5752539", "0.5750081", "0.5745629", "0.5742768", "0.57427394", "0.57414687", "0.57392013", "0.5730162", "0.5728014", "0.5727657", "0.57271767", "0.57263386", "0.5726328", "0.5726319", "0.5726093", "0.57251453", "0.5724782", "0.5717585", "0.5715816", "0.57155144", "0.57111216", "0.570841", "0.5702636", "0.570201", "0.5694289", "0.56941056", "0.5688342" ]
0.7744744
0
Reverses the Tuple in place
func (this *Tuple) Reverse() { for i, j := 0, this.Len()-1; i < j; i, j = i+1, j-1 { this.data[i], this.data[j] = this.data[j], this.data[i] } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (v Data) Reverse() {\n\tfor i, j := 0, len(v)-1; i < j; i, j = i+1, j-1 {\n\t\tv.Swap(i, j)\n\t}\n}", "func (elem *Items) Reverse() {\n\teLen := len(*elem)\n\tvar target int\n\tfor i := eLen/2 - 1; i >= 0; i-- {\n\t\ttarget = eLen - 1 - i\n\t\t(*elem)[i], (*elem)[target] = (*elem)[target], (*elem)[i]\n\t}\n}", "func Reverse(slice []interface{}) {\n\tfor i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {\n\t\tslice[i], slice[j] = slice[j], slice[i]\n\t}\n}", "func reverse(rs []*histRecord) {\n\tfor i := 0; i < len(rs)/2; i++ {\n\t\trs[i], rs[len(rs)-i-1] = rs[len(rs)-i-1], rs[i]\n\t}\n}", "func (t *T) Reverse() *T { return &T{lhs: t.rhs, rhs: t.lhs} }", "func reverse(args []interface{}) []interface{} {\n\treversed := make([]interface{}, len(args))\n\n\tj := 0\n\tfor i := len(args) - 1; i >= 0; i-- {\n\t\treversed[j] = args[i]\n\t\tj++\n\t}\n\n\treturn reversed\n}", "func Reverse(slice interface{}) {\n\tv := reflect.ValueOf(slice)\n\tl := v.Len()\n\tfor i := 0; i < l/2; i++ {\n\t\ta, b := v.Index(i), v.Index(l-1-i)\n\t\tt := a.Interface()\n\t\ta.Set(b)\n\t\tb.Set(reflect.ValueOf(t))\n\t}\n}", "func Reverse(nodes []graph.Node) {\n\tfor i, j := 0, len(nodes)-1; i < j; i, j = i+1, j-1 {\n\t\tnodes[i], nodes[j] = nodes[j], nodes[i]\n\t}\n}", "func (ll *Doubly[T]) Reverse() {\n\tvar Prev, Next *Node[T]\n\tcur := ll.Head\n\n\tfor cur != nil {\n\t\tNext = cur.Next\n\t\tcur.Next = Prev\n\t\tcur.Prev = Next\n\t\tPrev = cur\n\t\tcur = Next\n\t}\n\n\tll.Head = Prev\n}", "func Reverse[T any](slice []T) {\n\tfor i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {\n\t\tslice[i], slice[j] = slice[j], slice[i]\n\t}\n}", "func (h *Hash) Reverse() Hash {\n\tfor i, b := range h[:HashSize/2] {\n\t\th[i], h[HashSize-1-i] = h[HashSize-1-i], b\n\t}\n\treturn *h\n}", "func Reverse[T any](collection []T) []T {\n\tlength := len(collection)\n\thalf := length / 2\n\n\tfor i := 0; i < half; i = i + 1 {\n\t\tj := length - 1 - i\n\t\tcollection[i], collection[j] = collection[j], collection[i]\n\t}\n\n\treturn collection\n}", "func Reverse(slice interface{}) {\n\tvalue := reflect.ValueOf(slice)\n\tif value.Kind() == reflect.Ptr {\n\t\tvalue = value.Elem()\n\t}\n\tif value.Kind() != reflect.Slice {\n\t\treturn\n\t}\n\n\ttemp := reflect.New(value.Index(0).Type()).Elem()\n\tfor i, j := 0, value.Len()-1; i < j; i, j = i+1, j-1 {\n\t\ttemp.Set(value.Index(i))\n\t\tvalue.Index(i).Set(value.Index(j))\n\t\tvalue.Index(j).Set(temp)\n\t}\n}", "func reverse(commits []*vcsinfo.LongCommit) {\n\ttotal := len(commits)\n\tfor i := 0; i < total/2; i++ {\n\t\tcommits[i], commits[total-i-1] = commits[total-i-1], commits[i]\n\t}\n}", "func (h Hash32) Reversed() (res Hash32) {\n\tfor i := range h {\n\t\tres[31-i] = h[i]\n\t}\n\treturn\n}", "func Reverse(seq Sequence) Sequence {\n\tvar ff FeatureSlice\n\tfor _, f := range seq.Features() {\n\t\tff = ff.Insert(Feature{f.Key, f.Loc.Reverse(Len(seq)), f.Props.Clone()})\n\t}\n\tseq = WithFeatures(seq, ff)\n\n\tp := make([]byte, Len(seq))\n\tcopy(p, seq.Bytes())\n\tflip.Bytes(p)\n\tseq = WithBytes(seq, p)\n\n\treturn seq\n}", "func (a Slice[T]) Reverse() Slice[T] {\n\tfor i := len(a)/2 - 1; i >= 0; i-- {\n\t\topp := len(a) - 1 - i\n\t\ta[i], a[opp] = a[opp], a[i]\n\t}\n\treturn a\n}", "func reverse(s *[6]int) {\n\tfor i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n\t\ts[i], s[j] = s[j], s[i]\n\t}\n}", "func ExampleReverse() {\n\tsli := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\n\tfor i := 0; i < len(sli)/2; i++ {\n\t\tsli[i], sli[len(sli)-i-1] = sli[len(sli)-i-1], sli[i]\n\t}\n\tfmt.Println(sli)\n\n\t// Output:\n\t// [10 9 8 7 6 5 4 3 2 1]\n}", "func Inverse(arg interface{}) Value {\n\treturn Reverse(arg)\n}", "func Reverse(m Mapping) Mapping {\n\tsrc, dst := m.Mapping()\n\treturn Map(dst, src)\n}", "func (t Tuple2[A, B]) Unpack() (A, B) {\n\treturn t.A, t.B\n}", "func Reverse(ss []string) {\n\tln := len(ss)\n\n\tfor i := 0; i < ln/2; i++ {\n\t\tli := ln - i - 1\n\t\t// fmt.Println(i, \"<=>\", li)\n\t\tss[i], ss[li] = ss[li], ss[i]\n\t}\n}", "func Reverse(ss []string) {\n\tln := len(ss)\n\n\tfor i := 0; i < ln/2; i++ {\n\t\tli := ln - i - 1\n\t\t// fmt.Println(i, \"<=>\", li)\n\t\tss[i], ss[li] = ss[li], ss[i]\n\t}\n}", "func ReverseInPlace(arr []int) []int {\n\tfor i, j := 0, len(arr)-1; i < j; i, j = i+1, j-1 {\n\t\tarr[i], arr[j] = arr[j], arr[i]\n\t}\n\treturn arr\n}", "func reverse(dst, src []byte) []byte {\n\tl := len(dst)\n\tfor i, j := 0, l-1; i < (l+1)/2; {\n\t\tdst[i], dst[j] = src[j], src[i]\n\t\ti++\n\t\tj--\n\t}\n\treturn dst\n}", "func reverse(a *[arraySize]int) {\n\tfor i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {\n\t\ta[i], a[j] = a[j], a[i]\n\t}\n}", "func rev(in []byte) {\n\ts := len(in)\n\tfor i := 0; i < len(in)/2; i++ {\n\t\tin[i], in[s-1-i] = in[s-1-i], in[i]\n\t}\n}", "func (p PagesGroup) Reverse() PagesGroup {\n\tfor i, j := 0, len(p)-1; i < j; i, j = i+1, j-1 {\n\t\tp[i], p[j] = p[j], p[i]\n\t}\n\n\treturn p\n}", "func Reverse(arg interface{}) Value {\n\tif val, ok := arg.(Value); ok {\n\t\treturn val.Reverse()\n\t}\n\treturn value{value: arg, color: ReverseFm}\n}", "func reverse(s *[5]int) {\n\tfor i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n\t\ts[i], s[j] = s[j], s[i]\n\t}\n}", "func (v IntVec) Reverse() {\n\tfor i, j := 0, len(v)-1; i < j; i, j = i+1, j-1 {\n\t\tv.Swap(i, j)\n\t}\n}", "func Reverse[T any](ss []T) []T {\n\t// Avoid the allocation. If there is one element or less it is already\n\t// reversed.\n\tif len(ss) < 2 {\n\t\treturn ss\n\t}\n\n\tsorted := make([]T, len(ss))\n\tfor i := 0; i < len(ss); i++ {\n\t\tsorted[i] = ss[len(ss)-i-1]\n\t}\n\n\treturn sorted\n}", "func rev2(a *[5]int) {\n\tfor i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {\n\t\ta[i], a[j] = a[j], a[i]\n\t}\n}", "func BitReverse(a []fr.Element) {\n\tn := uint64(len(a))\n\tnn := uint64(64 - bits.TrailingZeros64(n))\n\n\tfor i := uint64(0); i < n; i++ {\n\t\tirev := bits.Reverse64(i) >> nn\n\t\tif irev > i {\n\t\t\ta[i], a[irev] = a[irev], a[i]\n\t\t}\n\t}\n}", "func reverse(input []int, left, right int) {\n\ttmp := 0\n\tfor left < right {\n\t\ttmp = input[left]\n\t\tinput[left], input[right] = input[right], tmp\n\t\tleft++\n\t\tright--\n\t}\n}", "func Reverse(seq Seq) Seq {\n\treturn RevAppend(seq, nil)\n}", "func reverse(curve *privCurve) {\n\tm := len(curve.segm)\n\tfor i, j := 0, m-1; i < j; i, j = i+1, j-1 {\n\t\tcurve.segm[i].vertex, curve.segm[j].vertex = curve.segm[j].vertex, curve.segm[i].vertex\n\t}\n}", "func reverse(s []int) {\n\tfor i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n\t\ts[i], s[j] = s[j], s[i]\n\t} \n}", "func reverse(bytes []byte) []byte {\n for i := 0; i < len(bytes)/2; i++ {\n j := len(bytes) - i - 1\n bytes[i], bytes[j] = bytes[j], bytes[i]\n }\n return bytes\n}", "func reverse(bytes []byte) []byte {\n for i := 0; i < len(bytes)/2; i++ {\n j := len(bytes) - i - 1\n bytes[i], bytes[j] = bytes[j], bytes[i]\n }\n return bytes\n}", "func (v Int32Vec) Reverse() {\n\tfor i, j := 0, len(v)-1; i < j; i, j = i+1, j-1 {\n\t\tv.Swap(i, j)\n\t}\n}", "func UnpackTuple(args Tuple, kwargs StringDict, name string, min int, max int, results ...*Object) error {\n\tif len(kwargs) != 0 {\n\t\treturn ExceptionNewf(TypeError, \"%s() does not take keyword arguments\", name)\n\t}\n\n\t// Check number of arguments\n\terr := checkNumberOfArgs(name, len(args), len(results), min, max)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Copy the results in\n\tfor i := range args {\n\t\t*results[i] = args[i]\n\t}\n\treturn nil\n}", "func reverse(s []int){\n\tfor i,j := 0,len(s)-1;i < j;i,j = i + 1,j-1{\n\t\ts[i],s[j] = s[j],s[i]\n\t}\n}", "func reverse(s []int) {\n\tfor i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n\t\ts[i], s[j] = s[j], s[i]\n\t}\n}", "func reverse(s []int) {\n\tfor i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n\t\ts[i], s[j] = s[j], s[i]\n\t}\n}", "func Reverse(slice AnySlice) {\n\tmustBeSlice(slice)\n\tcount := reflect.ValueOf(slice).Len()\n\tswapper := reflect.Swapper(slice)\n\ti := 0\n\tj := count - 1\n\tfor i < j {\n\t\tswapper(i, j)\n\t\ti++\n\t\tj--\n\t}\n}", "func rev(s []int) {\n\tfor i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n\t\ts[i], s[j] = s[j], s[i]\n\t}\n}", "func (*Functions) Reverse(in interface{}) interface{} {\n\tv := reflect.ValueOf(in)\n\tc := v.Len()\n\tout := reflect.MakeSlice(v.Type(), c, c)\n\tfor i := 0; i < c; i++ {\n\t\tout.Index(i).Set(v.Index(c - i - 1))\n\t}\n\treturn out.Interface()\n}", "func Reverse(s []int) {\n\tfor i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n\t\ts[i], s[j] = s[j], s[i]\n\n\t}\n}", "func reverse(dst []string) []string {\n\tlength := len(dst)\n\tfor i := 0; i < length/2; i++ {\n\t\tdst[i], dst[length-i-1] = dst[length-i-1], dst[i]\n\t}\n\treturn dst\n}", "func reverse(s []int) { // we expect a slice , hence arrays will not work\n\tfor i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n\t\t(s)[i], (s)[j] = (s)[j], (s)[i]\n\t}\n}", "func reverse(s []int) {\r\n\tfor i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\r\n\t\ts[i], s[j] = s[j], s[i]\r\n\t}\r\n}", "func reverse(s []int) {\n\tfor i, j := 0, len(s) - 1; i < j; i, j = i + 1, j - 1 {\n\t\ts[i], s[j] = s[j], s[i]\n\t}\n}", "func (t *Tuple) Negate() *Tuple {\n\treturn &Tuple{-t.x, -t.y, -t.z, -t.w}\n}", "func Brrev(op Op) Op", "func (p Pair) Swap() Pair {\n\tp.Base, p.Quote = p.Quote, p.Base\n\treturn p\n}", "func (t Tuple9[A, B, C, D, E, F, G, H, I]) Unpack() (A, B, C, D, E, F, G, H, I) {\n\treturn t.A, t.B, t.C, t.D, t.E, t.F, t.G, t.H, t.I\n}", "func rev(toReverse uint8) uint8 {\n\t// 76543210\n\ttoReverse = (toReverse >> 4) | (toReverse << 4) // Swap in groups of 4\n\t// 32107654\n\ttoReverse = ((toReverse & 0xcc) >> 2) | ((toReverse & 0x33) << 2) // Swap in groups of 2\n\t// 10325476\n\ttoReverse = ((toReverse & 0xaa) >> 1) | ((toReverse & 0x55) << 1) // Swap bit pairs\n\t// 01234567\n\treturn toReverse\n}", "func (s *Streams) Unreverse() {\n\ts.reverse = false\n}", "func BSWAPL(r operand.Op) { ctx.BSWAPL(r) }", "func reverse(s []int) {\n\t// start: 5 4 3 2 1 0\n\t// step: i=0, j=5\n\t// \t\t 0 4 3 2 1 5\n\t// step: i=1, j=4\n\t// \t\t 0 1 3 2 4 5\n\t// step: i=2, j=3\n\t// end: 0 1 2 3 4 5\n\tfor i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n\t\ts[i], s[j] = s[j], s[i]\n\t}\n}", "func reverse(s []int64) {\n\tfor i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n\t\ts[i], s[j] = s[j], s[i]\n\t}\n}", "func ReverseComplement(dst, src []byte) []byte {\n\tfor i := len(src) - 1; i >= 0; i-- {\n\t\tb := src[i]\n\t\tswitch b {\n\t\tcase 'a':\n\t\t\tdst = append(dst, 't')\n\t\tcase 'c':\n\t\t\tdst = append(dst, 'g')\n\t\tcase 'g':\n\t\t\tdst = append(dst, 'c')\n\t\tcase 't':\n\t\t\tdst = append(dst, 'a')\n\t\tcase 'A':\n\t\t\tdst = append(dst, 'T')\n\t\tcase 'C':\n\t\t\tdst = append(dst, 'G')\n\t\tcase 'G':\n\t\t\tdst = append(dst, 'C')\n\t\tcase 'T':\n\t\t\tdst = append(dst, 'A')\n\t\tcase 'N':\n\t\t\tdst = append(dst, 'N')\n\t\tcase 'n':\n\t\t\tdst = append(dst, 'n')\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"Unexpected base value: %q, want aAcCgGtTnN\", b))\n\t\t}\n\t}\n\treturn dst\n}", "func Reverse(operand []string) []string {\n\treversed := make([]string, len(operand))\n\tfor i := range operand {\n\t\treversed[len(operand)-i-1] = operand[i]\n\t}\n\treturn reversed\n}", "func (t Tuple8[A, B, C, D, E, F, G, H]) Unpack() (A, B, C, D, E, F, G, H) {\n\treturn t.A, t.B, t.C, t.D, t.E, t.F, t.G, t.H\n}", "func Reverse(ctx *sapphire.CommandContext) {\n\n\tvar chars []string = strings.Split(ctx.JoinedArgs(), \"\")\n\n\tfor i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {\n\t\tchars[i], chars[j] = chars[j], chars[i]\n\t}\n\n\tctx.Reply(sapphire.Escape(strings.Join(chars, \"\")))\n}", "func (c *StoreCandidates) Reverse() *StoreCandidates {\n\tfor i := len(c.Stores)/2 - 1; i >= 0; i-- {\n\t\topp := len(c.Stores) - 1 - i\n\t\tc.Stores[i], c.Stores[opp] = c.Stores[opp], c.Stores[i]\n\t}\n\treturn c\n}", "func (t Tuple3[A, B, C]) Unpack() (A, B, C) {\n\treturn t.A, t.B, t.C\n}", "func (mdl *Model) Reverse() {\n\treturn\n}", "func Negate(t Tuplelike) Tuplelike {\n\tresult := []float64{}\n\n\tfor _, value := range t.Values() {\n\t\tresult = append(result, -value)\n\t}\n\n\treturn Tuple(result)\n}", "func reverseComplement(in *bytes.Buffer) []byte {\n\tvar result []byte = make([]byte, in.Len(), in.Len())\n\tfor pos := in.Len() - 1; pos >= 0; pos-- {\n\t\tcurrent, ok := in.ReadByte()\n\t\tcheckResult(ok)\n\t\tresult[pos] = reverse(current)\n\t}\n\treturn result\n}", "func (p Pair) Swap() Pair {\n\treturn Pair{Base: p.Quote, Quote: p.Base}\n}", "func reverse3(s [3]int) {\r\n\tfor i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\r\n\t\ts[i], s[j] = s[j], s[i]\r\n\t}\r\n}", "func reverse(s []string) []string {\n\tfor head, tail := 0, len(s)-1; head < tail; head, tail = head+1, tail-1 {\n\t\ts[head], s[tail] = s[tail], s[head]\n\t}\n\treturn s\n}", "func reverse(x uint32) uint32 {\n\tx = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1))\n\tx = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2))\n\tx = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4))\n\tx = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8))\n\treturn ((x >> 16) | (x << 16))\n}", "func Reverse(sort []string) {\n\tns := len(sort) - 1\n\tfor i := 0; i < (ns+1)/2; i++ {\n\t\tsort[i], sort[ns-i] = sort[ns-i], sort[i]\n\t}\n}", "func getReverseRoute(route []Hop) []Hop {\n\treverse := make([]Hop, len(route))\n\tfor i, j := 0, len(route)-1; j >= 0; i, j = i+1, j-1 {\n\t\treverse[i].DeviceID, reverse[i].Ingress, reverse[i].Egress = route[j].DeviceID, route[j].Egress, route[j].Ingress\n\t}\n\treturn reverse\n}", "func reverse(s []int) []int {\n\tfor i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n\t\ts[i], s[j] = s[j], s[i]\n\t}\n\treturn s\n}", "func (t *Tuple) Sub(o *Tuple) *Tuple {\n\treturn &Tuple{\n\t\tt.x - o.x,\n\t\tt.y - o.y,\n\t\tt.z - o.z,\n\t\tt.w - o.w,\n\t}\n\n}", "func Reverse(src []byte) []byte {\n\tdst := make([]byte, len(src))\n\tfor i := len(src); i > 0; i-- {\n\t\tdst[len(src)-i] = src[i-1]\n\t}\n\treturn dst\n}", "func Reverse(src []byte) []byte {\n\tdst := make([]byte, len(src))\n\tfor i := len(src); i > 0; i-- {\n\t\tdst[len(src)-i] = src[i-1]\n\t}\n\treturn dst\n}", "func reversePath(path []string) []string {\n\tfor i, j := 0, len(path)-1; i < j; i, j = i+1, j-1 {\n\t\tpath[i], path[j] = path[j], path[i]\n\t}\n\treturn path\n}", "func reverseList(scores [][]string) [][]string {\n\tfor i,j := 0, len(scores)-1; i < j; i,j = i+1, j-1 {\n\t\tscores[i], scores[j] = scores[j], scores[i]\n\t} \n\treturn scores\n}", "func reverse(items []string) []string {\n\tl := len(items)\n\tvar reversed = make([]string, l)\n\tfor i, v := range items {\n\t\treversed[l-i-1] = v\n\t}\n\treturn reversed\n}", "func (l *List) Reverse() {\n\tnode := l.head\n\tnewHead, newLast := l.last, l.head\n\n\tfor node != nil {\n\t\tnode.previous, node.next = node.Next(), node.Prev()\n\t\tnode = node.Prev()\n\t}\n\n\tl.head, l.last = newHead, newLast\n}", "func (s Runes) Reverse() Runes {\n\tsz := len(s)\n\trs := make(Runes, sz)\n\tif sz > 0 {\n\t\tfor n := 0; n <= sz/2; n++ {\n\t\t\trs[n], rs[sz-n-1] = s[sz-n-1], s[n]\n\t\t}\n\t}\n\treturn rs\n}", "func (t Tuple4[A, B, C, D]) Unpack() (A, B, C, D) {\n\treturn t.A, t.B, t.C, t.D\n}", "func (p *Particle) Reverse() {\n\tp.ReverseX()\n\tp.ReverseY()\n}", "func (s *SinglyLinkedList) Reverse() {\n\tcurr := s.Head\n\tvar prev, next *Node\n\tfor curr != nil {\n\t\tnext = curr.Next\n\t\tcurr.Next = prev\n\t\tprev = curr\n\t\tcurr = next\n\t}\n\ts.Head = prev\n}", "func (l List) Reverse() List {\n\ts := make(List, len(l))\n\tfor i, j := 0, len(l)-1; i < j; i, j = i+1, j-1 {\n\t\ts[i], s[j] = l[j], l[i]\n\t}\n\treturn s\n}", "func (t Tuple7[A, B, C, D, E, F, G]) Unpack() (A, B, C, D, E, F, G) {\n\treturn t.A, t.B, t.C, t.D, t.E, t.F, t.G\n}", "func (a *ArrayObject) reverse() *ArrayObject {\n\tarrLen := len(a.Elements)\n\treversedArrElems := make([]Object, arrLen)\n\n\tfor i, element := range a.Elements {\n\t\treversedArrElems[arrLen-i-1] = element\n\t}\n\n\tnewArr := &ArrayObject{\n\t\tbaseObj: &baseObj{class: a.class},\n\t\tElements: reversedArrElems,\n\t}\n\n\treturn newArr\n}", "func reverse(numbers []int) []int {\n\tfor i, j := 0, len(numbers)-1; i < j; i, j = i+1, j-1 {\n\t\tnumbers[i], numbers[j] = numbers[j], numbers[i]\n\t}\n\n\treturn numbers\n}", "func reverse(start, end int, arr []int) {\n\tfor start < end {\n\n\t\t// swapping both indexes\n\t\t// using left and right pointers\n\t\tarr[start], arr[end] = arr[end], arr[start]\n\n\t\t// moving forward\n\t\tstart++\n\t\t// moving backwards\n\t\tend--\n\t}\n}", "func ReverseBytes(data []byte) {\n\tfor i, j := 0, len(data)-1; i < j; i, j = i+1, j-1 {\n\t\tdata[i], data[j] = data[j], data[i]\n\t}\n}", "func ReverseBytes(data []byte) {\n\tfor i, j := 0, len(data)-1; i < j; i, j = i+1, j-1 {\n\t\tdata[i], data[j] = data[j], data[i]\n\t}\n}", "func ReverseBytes(data []byte) {\n\tfor i, j := 0, len(data)-1; i < j; i, j = i+1, j-1 {\n\t\tdata[i], data[j] = data[j], data[i]\n\t}\n}", "func ReverseBytes(data []byte) {\n\tfor i, j := 0, len(data)-1; i < j; i, j = i+1, j-1 {\n\t\tdata[i], data[j] = data[j], data[i]\n\t}\n}", "func (l *List) Reverse() *List {\n\tr := List{}\n\tfor data, err := l.PopBack(); err == nil; data, err = l.PopBack() {\n\t\tr.PushBack(data)\n\t}\n\tl.first, l.last = r.first, r.last\n\treturn l\n}" ]
[ "0.6308729", "0.62434167", "0.61875665", "0.6180136", "0.61434245", "0.6137719", "0.61085224", "0.6101406", "0.60955846", "0.6085571", "0.5981546", "0.5979525", "0.5948887", "0.5882405", "0.5828438", "0.5797321", "0.5781275", "0.57673466", "0.57639754", "0.57613766", "0.5743407", "0.57316446", "0.5722914", "0.5722914", "0.5721933", "0.5720719", "0.5708893", "0.57083976", "0.5708113", "0.5699452", "0.56861234", "0.56667274", "0.56634295", "0.56516224", "0.56484365", "0.5640666", "0.563606", "0.5618818", "0.56167346", "0.560751", "0.560751", "0.5603059", "0.556733", "0.55663025", "0.5565456", "0.5565456", "0.55564505", "0.5551735", "0.5549478", "0.5544364", "0.55404335", "0.5531209", "0.5526051", "0.55231", "0.5509733", "0.5499317", "0.54864305", "0.54831207", "0.5480616", "0.5470653", "0.5466178", "0.5445345", "0.543362", "0.54314035", "0.5409682", "0.5390299", "0.53897065", "0.53677136", "0.5339954", "0.5338389", "0.53361523", "0.5334769", "0.5330533", "0.53178954", "0.5314793", "0.5309894", "0.52948105", "0.52908343", "0.5258619", "0.5257474", "0.52546287", "0.52546287", "0.5254109", "0.52492464", "0.52397984", "0.5239588", "0.5227787", "0.52198744", "0.5218745", "0.5217785", "0.5201884", "0.5197332", "0.519624", "0.5178733", "0.5176944", "0.5166673", "0.5166673", "0.5166673", "0.5166673", "0.51661026" ]
0.7713171
0
Returns true if the two items are logically "equal"
func TupleElemEq(lhsi interface{}, rhsi interface{}) bool { lhsv, rhsv := reflect.ValueOf(lhsi), reflect.ValueOf(rhsi) // IsNil panics if type is not interface-y, so use IsValid instead if lhsv.IsValid() != rhsv.IsValid() { return false } // TODO: this currently blows up if lhs can't be converted to same // type as rhs (e.g. int vs. string) switch lhsi.(type) { case nil: if rhsv.IsValid() { return false } case string: if lhsi.(string) != rhsi.(string) { return false } case int, int8, int16, int32, int64: if lhsv.Int() != rhsv.Int() { return false } case uint, uintptr, uint8, uint16, uint32, uint64: if lhsv.Uint() != rhsv.Uint() { return false } case float32, float64: if lhsv.Float() != rhsv.Float() { return false } case *Tuple: if lhsi.(*Tuple).Ne(rhsi.(*Tuple)) { return false } default: //if !lhsv.IsValid() && !rhsv.IsValid() { //return false //} // TODO: allow user-defined callback for unsupported types panic(fmt.Sprintf("unsupported type %#v for Eq in Tuple", lhsi)) } return true }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CheckEqual(src, trg *Item) bool {\n\ttype obj struct {\n\t\tsrc Attribute\n\t\ttrg Attribute\n\t}\n\tfor _, v := range []obj{\n\t\t{src.part, trg.part},\n\t\t{src.vendor, trg.vendor},\n\t\t{src.product, trg.product},\n\t\t{src.version, trg.version},\n\t\t{src.update, trg.update},\n\t\t{src.edition, trg.edition},\n\t\t{src.language, trg.language},\n\t\t{src.sw_edition, trg.sw_edition},\n\t\t{src.target_sw, trg.target_sw},\n\t\t{src.target_hw, trg.target_hw},\n\t\t{src.other, trg.other},\n\t} {\n\t\tswitch v.src.Comparison(v.trg) {\n\t\tcase Equal:\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (p Pair) Equal(cPair Pair) bool {\n\treturn p.Base.Item == cPair.Base.Item && p.Quote.Item == cPair.Quote.Item\n}", "func (i *Item) Equal(item *Item) bool {\n\tif i == nil && item == nil {\n\t\treturn true\n\t}\n\tif item == nil || i == nil {\n\t\treturn false\n\t}\n\tif i.currency == item.currency &&\n\t\ti.asset == item.asset &&\n\t\ti.exchange == item.exchange {\n\t\tif i.pairedWith == nil && item.pairedWith == nil {\n\t\t\treturn true\n\t\t}\n\t\tif i.pairedWith == nil || item.pairedWith == nil {\n\t\t\treturn false\n\t\t}\n\t\tif i.pairedWith.currency == item.pairedWith.currency &&\n\t\t\ti.pairedWith.asset == item.pairedWith.asset &&\n\t\t\ti.pairedWith.exchange == item.pairedWith.exchange {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func equal(a, b float64) bool {\n\treturn math.Abs(a-b) <= equalityThreshold\n}", "func (b *BooleanObject) equal(e *BooleanObject) bool {\n\treturn b.value == e.value\n}", "func equalish(a, b, tolerance float64) bool {\n\tif a == b {\n\t\treturn true\n\t}\n\n\tdiff := math.Abs(a - b)\n\n\tif diff <= tolerance {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (c *Comparison) IsSame() bool {\n\treturn c.First.Start.Equal(c.Second.Start) && c.First.End.Equal(c.Second.End)\n}", "func equal(x, y []int) bool {\n\tif len(x) != len(y) {\n\t\treturn false // if the length is not the same we can stop right there\n\t}\n\t// for i := range x {\n\t// \tif x[i] != y[i] {\n\t// \t\treturn false\n\t// \t}\n\t// }\n\tfor i, v := range x {\n\t\tif v != y[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (mm MoneyMarket) Equal(mmCompareTo MoneyMarket) bool {\n\tif mm.Denom != mmCompareTo.Denom {\n\t\treturn false\n\t}\n\tif !mm.BorrowLimit.Equal(mmCompareTo.BorrowLimit) {\n\t\treturn false\n\t}\n\tif mm.SpotMarketID != mmCompareTo.SpotMarketID {\n\t\treturn false\n\t}\n\tif !mm.ConversionFactor.Equal(mmCompareTo.ConversionFactor) {\n\t\treturn false\n\t}\n\tif !mm.InterestRateModel.Equal(mmCompareTo.InterestRateModel) {\n\t\treturn false\n\t}\n\tif !mm.ReserveFactor.Equal(mmCompareTo.ReserveFactor) {\n\t\treturn false\n\t}\n\tif !mm.AuctionSize.Equal(mmCompareTo.AuctionSize) {\n\t\treturn false\n\t}\n\tif !mm.KeeperRewardPercentage.Equal(mmCompareTo.KeeperRewardPercentage) {\n\t\treturn false\n\t}\n\treturn true\n}", "func (b Balance) Equal(b2 Balance) bool {\n\treturn b.Int != nil && b2.Int != nil && b.Int.Cmp(b2.Int) == 0\n}", "func (q Quantity) Equal(v Quantity) bool {\n\treturn q.Cmp(v) == 0\n}", "func isSameAndInUse(i *item, other *item) bool {\n\treturn inUse(i) &&\n\t\t(i.hash == other.hash) &&\n\n\t\t// this line consumes 50% of the CPU time\n\t\t// for tables smaller than a memory page\n\t\t// when comparing short strings\n\t\t// for long keys the line will dominate CPU\n\t\t// consumption. TODO Check RelyOnHash?\n\t\t(i.key == other.key)\n}", "func eq(o1, o2 interface{}) bool {\n\n\tf1, ok1 := ToFloat(o1)\n\tf2, ok2 := ToFloat(o2)\n\tif ok1 && ok2 {\n\t\treturn f1 == f2\n\t}\n\n\tb1, ok1 := ToBool(o1)\n\tb2, ok1 := ToBool(o2)\n\tif ok1 && ok2 {\n\t\treturn b1 == b2\n\t}\n\n\treturn o1 == o2\n}", "func isEqual(a interface{}, b interface{}) bool {\n\treturn a == b\n}", "func isEq(f Array, s Array) bool {\n\tif len(f) != len(s) {\n\t\treturn false\n\t}\n\n\tfor idx, item := range f {\n\t\tif item != s[idx] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (q Query) SequenceEqual(ctx Context, q2 Query) (bool, error) {\n\tnext1 := q.Iterate()\n\tnext2 := q2.Iterate()\n\n\tfor {\n\t\titem1, e := next1(ctx)\n\t\tif e != nil {\n\t\t\tif IsNoRows(e) {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treturn false, e\n\t\t}\n\n\t\titem2, e := next2(ctx)\n\t\tif e != nil {\n\t\t\tif IsNoRows(e) {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treturn false, e\n\t\t}\n\n\t\tok3, err := item1.EqualTo(item2, vm.EmptyCompareOption())\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif !ok3 {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\t_, err := next2(ctx)\n\tif err == nil {\n\t\treturn false, nil\n\t}\n\tif IsNoRows(err) {\n\t\treturn true, nil\n\t}\n\treturn false, err\n}", "func Equal(t, other Tuplelike) bool {\n\tfor idx, value := range t.Values() {\n\t\tif !inEpsilon(value, other.At(idx)) {\n\t\t\treturn false\n\t\t}\n\n\t}\n\treturn true\n}", "func isEqual(x, y []int) bool {\n\tif len(x) != len(y) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(x); i++ {\n\t\tif x[i] != y[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func equals(a []int, b []int) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i, n := range a {\n\t\tif n != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func same(x int, y int) bool {\n\treturn find(x) == find(y)\n}", "func equ(a *GLSQObj, b *GLSQObj) bool {\n\tif a == b {\n\t\t// If they point to the same location they obviously are equal.\n\t\treturn true\n\t}\n\n\tif a.GlsqType != b.GlsqType {\n\t\treturn false // can't be equal if types are not the same\n\t}\n\n\tswitch a.GlsqType {\n\tcase GLSQ_TYPE_INT:\n\t\treturn a.GlsqInt == b.GlsqInt\n\n\tcase GLSQ_TYPE_FLOAT:\n\t\treturn a.GlsqFloat == b.GlsqFloat\n\n\tcase GLSQ_TYPE_BOOL:\n\t\treturn a.GlsqBool == b.GlsqBool\n\t}\n\n\treturn false\n}", "func (oc *ObjectComprehension) Equal(other Value) bool {\n\treturn Compare(oc, other) == 0\n}", "func equal(a []int, b []int) bool {\n\tvar length int\n\n\tif len(a) < len(b) {\n\t\tlength = len(a)\n\t} else {\n\t\tlength = len(b)\n\t}\n\n\tfor i := 0; i < length; i++ {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func equals(p1, p2 *node) bool {\n\treturn p1.x == p2.x && p1.y == p2.y\n}", "func (seq SeqEq[S, T]) Equal(a, b S) bool {\n\tseqA := a\n\tseqB := b\n\tfor !seq.Seq.IsVoid(seqA) && !seq.Seq.IsVoid(seqB) {\n\t\theadA := seq.Seq.Head(seqA)\n\t\theadB := seq.Seq.Head(seqB)\n\t\tif headA == nil || headB == nil || !seq.Eq.Equal(*headA, *headB) {\n\t\t\treturn false\n\t\t}\n\n\t\tseqA = seq.Seq.Tail(seqA)\n\t\tseqB = seq.Seq.Tail(seqB)\n\t}\n\n\treturn seq.Seq.IsVoid(seqA) && seq.Seq.IsVoid(seqB)\n}", "func equal(a, b []byte) bool {\n if len(a) != len(b) {\n return false\n }\n for i :=0 ; i < len(a) ; i++ {\n if a[i] != b[i] {\n return false\n }\n }\n return true\n}", "func (g *Graph) Equal(g2 *Graph, debug bool) bool {\n\n\t// Check the vertices\n\tkeys1 := g.listOfKeys()\n\tkeys2 := g2.listOfKeys()\n\n\tif !SlicesHaveSameElements(&keys1, &keys2) {\n\t\tif debug {\n\t\t\tlog.Println(\"Lists of keys are different\")\n\t\t\tlog.Printf(\"Keys1: %v\\n\", keys1)\n\t\t\tlog.Printf(\"Keys2: %v\\n\", keys2)\n\t\t}\n\t\treturn false\n\t}\n\n\t// Walk through each vertex and check its connections\n\tfor _, vertex := range keys1 {\n\t\tconns1 := g.Nodes[vertex]\n\t\tconns2 := g2.Nodes[vertex]\n\n\t\tif !SetsEqual(conns1, conns2) {\n\t\t\tif debug {\n\t\t\t\tlog.Printf(\"Connections different for vertex %v\", vertex)\n\t\t\t\tlog.Printf(\"Connections 1: %v\\n\", conns1)\n\t\t\t\tlog.Printf(\"Connections 2: %v\\n\", conns2)\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func Equal(vx, vy interface{}) bool {\n\tif reflect.TypeOf(vx) != reflect.TypeOf(vy) {\n\t\treturn false\n\t}\n\n\tswitch x := vx.(type) {\n\tcase map[string]interface{}:\n\t\ty := vy.(map[string]interface{})\n\n\t\tif len(x) != len(y) {\n\t\t\treturn false\n\t\t}\n\n\t\tfor k, v := range x {\n\t\t\tval2 := y[k]\n\n\t\t\tif (v == nil) != (val2 == nil) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tif !Equal(v, val2) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\n\t\treturn true\n\tcase []interface{}:\n\t\ty := vy.([]interface{})\n\n\t\tif len(x) != len(y) {\n\t\t\treturn false\n\t\t}\n\n\t\tvar matches int\n\t\tflagged := make([]bool, len(y))\n\t\tfor _, v := range x {\n\t\t\tfor i, v2 := range y {\n\t\t\t\tif Equal(v, v2) && !flagged[i] {\n\t\t\t\t\tmatches++\n\t\t\t\t\tflagged[i] = true\n\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn matches == len(x)\n\tdefault:\n\t\treturn vx == vy\n\t}\n}", "func (e IfChange) Equal(e2 IfChange) bool {\n\treturn e.Added == e2.Added &&\n\t\te.Deleted == e2.Deleted &&\n\t\te.Attrs.Equal(e2.Attrs)\n}", "func equal(left, right []string) bool {\n\tif len(left) != len(right) {\n\t\treturn false\n\t}\n\tfor i, value := range left {\n\t\tif value != right[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func equal(slice1, slice2 Coef) bool {\n\tfor index := range slice1 {\n\t\tif math.Abs(slice1[index]-slice2[index]) > epsilon {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (s *State) IsEqual(new *State) bool {\n return s.Fid() == new.Fid()\n}", "func (bs BitStream) IsEqual(other BitStream) bool {\n\tif len(bs.bits) != len(other.bits) {\n\t\treturn false\n\t}\n\n\tfor i, b := range bs.bits {\n\t\tif b != other.bits[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func Same(t1, t2 *tree.Tree) bool {\n\tch1, ch2 := Walker(t1), Walker(t2)\n\n\tfor {\n\n\t\tv1, ok1 := <-ch1\n\t\tv2, ok2 := <-ch2\n\n\t\tif !ok1 || !ok2 {\n\t\t\treturn ok1 == ok2\n\t\t}\n\t\tif v1 != v2 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn false\n}", "func (a Vector) Equal(b []float64) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tfor k := range a {\n\t\tif !Equal(a[k], b[k]) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (v Value) Equal(w Value) bool {\n\treturn v.v == w.v\n}", "func equal(x, y []string) bool {\n if len(x) != len(y) {\n return false\n }\n for i := range x {\n if x[i] != y[i] {\n return false\n }\n }\n return true\n}", "func (sc *SetComprehension) Equal(other Value) bool {\n\treturn Compare(sc, other) == 0\n}", "func (v Vector) Equal(o Vector) bool {\n\tvDefs := v.definables()\n\toDefs := o.definables()\n\n\tfor _, metric := range order {\n\t\ta := equivalent(metric, vDefs[metric].String())\n\t\tb := equivalent(metric, oDefs[metric].String())\n\n\t\tif a != b {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func eq(args ...interface{}) bool {\n\tif len(args) == 0 {\n\t\treturn false\n\t}\n\tx := args[0]\n\tswitch x := x.(type) {\n\tcase int:\n\t\tfor _, y := range args[1:] {\n\t\t\tswitch y := y.(type) {\n\t\t\tcase int:\n\t\t\t\tif int64(x) == int64(y) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\tcase int64:\n\t\t\t\tif int64(x) == int64(y) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false\n\n\tcase int64:\n\t\tfor _, y := range args[1:] {\n\t\t\tswitch y := y.(type) {\n\t\t\tcase int:\n\t\t\t\tif int64(x) == int64(y) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\tcase int64:\n\t\t\t\tif int64(x) == int64(y) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false\n\n\tcase float32:\n\t\tfor _, y := range args[1:] {\n\t\t\tswitch y := y.(type) {\n\t\t\tcase float32:\n\t\t\t\tif float64(x) == float64(y) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\tcase float64:\n\t\t\t\tif float64(x) == float64(y) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false\n\n\tcase float64:\n\t\tfor _, y := range args[1:] {\n\t\t\tswitch y := y.(type) {\n\t\t\tcase float32:\n\t\t\t\tif float64(x) == float64(y) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\tcase float64:\n\t\t\t\tif float64(x) == float64(y) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false\n\n\tcase string, byte:\n\t\tfor _, y := range args[1:] {\n\t\t\tif x == y {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\tfor _, y := range args[1:] {\n\t\tif reflect.DeepEqual(x, y) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func eq(args ...interface{}) bool {\n\tif len(args) == 0 {\n\t\treturn false\n\t}\n\tx := args[0]\n\tswitch x := x.(type) {\n\tcase string, int, int64, byte, float32, float64:\n\t\tfor _, y := range args[1:] {\n\t\t\tif x == y {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\tfor _, y := range args[1:] {\n\t\tif reflect.DeepEqual(x, y) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func eq(args ...interface{}) bool {\n\tif len(args) == 0 {\n\t\treturn false\n\t}\n\tx := args[0]\n\tswitch x := x.(type) {\n\tcase string, int, int64, byte, float32, float64:\n\t\tfor _, y := range args[1:] {\n\t\t\tif x == y {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\tfor _, y := range args[1:] {\n\t\tif reflect.DeepEqual(x, y) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func Equal(a, b uint64) bool {\n\treturn a == b\n}", "func equal(lhs, rhs semantic.Expression) semantic.Expression {\n\treturn &semantic.BinaryOp{Type: semantic.BoolType, LHS: lhs, Operator: ast.OpEQ, RHS: rhs}\n}", "func equalPairSlice(a, b []Pair) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func Equal(left, right *big.Int) bool { return left.Cmp(right) == 0 }", "func IsEqual(a, b float64) bool {\n\treturn math.Abs(a-b) < EPSILON\n}", "func (p Pair) Equal(cPair Pair) bool {\n\treturn p.Base.Equal(cPair.Base) && p.Quote.Equal(cPair.Quote)\n}", "func AreTheSame(a []int, b []int) bool {\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func equal(z1, z2 *big.Int) bool {\n\treturn z1.Cmp(z2) == 0\n}", "func Equal(left Value, right Value) bool {\n\t// TODO: Stop-gap for now, this will need to be much more sophisticated.\n\treturn CoerceString(left) == CoerceString(right)\n}", "func isEqual(g1 types.GeometryValue, g2 types.GeometryValue) bool {\n\treturn isWithin(g1, g2) && isWithin(g2, g1)\n}", "func (n *node) equal(other *node) bool {\n\treturn n.value == other.value && n.childrenEqual(other)\n}", "func equals(A, B []int) bool {\n\tif len(A) != len(B) {\n\t\treturn false\n\t}\n\n\tfor i := range A {\n\t\tif B[i] != A[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\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 areEqual(a, b []uint64) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i, v := range a {\n\t\tif v != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (p Pair) EqualIncludeReciprocal(cPair Pair) bool {\n\tif p.Base.Item == cPair.Base.Item &&\n\t\tp.Quote.Item == cPair.Quote.Item ||\n\t\tp.Base.Item == cPair.Quote.Item &&\n\t\t\tp.Quote.Item == cPair.Base.Item {\n\t\treturn true\n\t}\n\treturn false\n}", "func (v Vector) Equals(other Vector) bool {\n\tv = v.reduce()\n\tother = other.reduce()\n\tif len(v.data) == len(other.data) {\n\t\tfor n, d1 := range v.data {\n\t\t\tif d2, ok := other.data[n]; !ok || d1 != d2 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (ac *ArrayComprehension) Equal(other Value) bool {\n\treturn Compare(ac, other) == 0\n}", "func (n *Node) isEqualTo(other *Node) bool {\n\treturn n.val.IsEqualTo(other.val)\n}", "func (b Bytes64) Equal(o Bytes64) bool { return bytes.Equal(b.Bytes(), o.Bytes()) }", "func (v Vec3i) IsEqual(other Vec3i) bool {\n\treturn (other.X == v.X) && (other.Y == v.Y) && (other.Z == v.Z)\n}", "func MovesEqual(a, b []Move) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor _, am := range a {\n\t\tequals := 0\n\t\tfor _, bm := range b {\n\t\t\tif am.Equal(bm) {\n\t\t\t\tequals++\n\t\t\t}\n\t\t}\n\t\tif equals != 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func Same(t1, t2 *tree.Tree) bool {\n\n\t// We make two channels to walk trees\n\tch1 := make(chan int)\n\tch2 := make(chan int)\n\n\t// We send both trees to walk\n\tgo Walk(t1, ch1)\n\tgo Walk(t2, ch2)\n\n\tfirstCompare, secondCompare := WalkedTreeToArray(ch1), WalkedTreeToArray(ch2)\n\n\t// Can't do this with a single loop because items can be in different orders,\n\tfor _, value := range firstCompare {\n\t\tfor i := range secondCompare {\n\t\t\tif secondCompare[i] == value {\n\t\t\t\t// We \"Delete\" this value since it has matched once\n\t\t\t\tsecondCompare = append(secondCompare[:i], secondCompare[i+1:]...)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// This helps me visualize it and I could've removed it afterwards,\n\t// But I like how it looks\n\tfmt.Println(firstCompare, secondCompare)\n\n\t// If we have 0 elements left they are the same\n\treturn len(secondCompare) == 0\n}", "func Same(expected, actual interface{}) Truth {\n\tmustBeCleanStart()\n\treturn Truth{\n\t\tValue: nice(expected) == nice(actual) && reflect.DeepEqual(actual, expected),\n\t\tDump:fmt.Sprintf(\"%#v\", actual),\n\t}\n}", "func (d Decimal) Equal(d2 Decimal) bool {\n\treturn d.Cmp(d2) == 0\n}", "func (d Decimal) Equal(d2 Decimal) bool {\n\treturn d.Cmp(d2) == 0\n}", "func (item *VersionHistoryItem) Equals(input *VersionHistoryItem) bool {\n\treturn item.Version == input.Version && item.EventID == input.EventID\n}", "func bagEq(b, c Bag) bool {\n\tif len(b) != len(c) {\n\t\treturn false\n\t}\n\tfor k, v := range b {\n\t\tif v != c[k] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (list List) Equal(other List) bool {\n\tif other.Length() != list.Length() {\n\t\treturn false\n\t}\n\tfor idx, val := range list {\n\t\tif other[idx] != val {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func IsEqual(t1, t2 TileID) bool {\n\treturn int(t1.X) == int(t2.X) && int(t1.Y) == int(t2.Y) && int(t1.Z) == int(t2.Z)\n}", "func (me TComparator) IsEqualTo() bool { return me.String() == \"EqualTo\" }", "func TestEquals(t *testing.T) {\n\tt.Parallel()\n\tfor ti, tt := range []struct {\n\t\tm1, m2 MatrixExp\n\t\teq bool\n\t}{\n\t\t{\n\t\t\tm1: GeneralZeros(1, 1),\n\t\t\tm2: GeneralZeros(1, 1),\n\t\t\teq: true,\n\t\t},\n\t\t{\n\t\t\tm1: GeneralZeros(1, 1),\n\t\t\tm2: GeneralZeros(1, 10),\n\t\t\teq: false,\n\t\t},\n\t\t{\n\t\t\tm1: GeneralZeros(10, 1),\n\t\t\tm2: GeneralZeros(1, 1),\n\t\t\teq: false,\n\t\t},\n\t\t{\n\t\t\tm1: GeneralZeros(1, 1),\n\t\t\tm2: GeneralOnes(1, 1),\n\t\t\teq: false,\n\t\t},\n\t} {\n\t\tif v := Equals(tt.m1, tt.m2); v != tt.eq {\n\t\t\tt.Errorf(\"%d: Equals(%v,%v) equals %v, want %v\", ti, tt.m1, tt.m2, v, tt.eq)\n\t\t}\n\t}\n}", "func isEqual(cnpj []uint) bool {\n\tfor i := 1; i < len(cnpj); i++ {\n\t\tif cnpj[0] != cnpj[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (a seriesIDs) equals(other seriesIDs) bool {\n\tif len(a) != len(other) {\n\t\treturn false\n\t}\n\tfor i, s := range other {\n\t\tif a[i] != s {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func equal(x, y float32, tol float64) bool {\n\tavg := (math.Abs(float64(x+y)) / 2.0)\n\tsErr := math.Abs(float64(x-y)) / (avg + 1)\n\tif sErr > tol {\n\t\treturn false\n\t}\n\treturn true\n}", "func (eps Accuracy) Equal(a, b float64) bool {\n\treturn math.Abs(a-b) < eps()\n}", "func IsEqual(eq string) bool {\n var equalsIndex int = strings.Index(eq, \"=\")\n var lhs string = eq[0:equalsIndex]\n var rhs string = eq[equalsIndex + 1:]\n var side1 float64 = NotateToDouble(Pemdas(lhs))\n var side2 float64 = NotateToDouble(Pemdas(rhs))\n\n return side1 == side2\n}", "func (bal Balance) Equals(other Balance) bool {\r\n\treturn bal.Coins == other.Coins && bal.Hours == other.Hours\r\n}", "func (v *Values) Equal(other *Values) bool {\n\tv.lock.RLock()\n\tdefer v.lock.RUnlock()\n\tother.lock.RLock()\n\tdefer other.lock.RUnlock()\n\n\treturn v.root.equal(other.root)\n}", "func (x *Money) Equal(y *Money) bool {\n\tif x.Currency != y.Currency {\n\t\treturn false\n\t}\n\treturn x.Amount.Equal(y.Amount)\n}", "func (gvk GVK) IsEqualTo(other GVK) bool {\n\treturn gvk.Group == other.Group &&\n\t\tgvk.Domain == other.Domain &&\n\t\tgvk.Version == other.Version &&\n\t\tgvk.Kind == other.Kind\n}", "func (set *lalrSet) equals(other *lalrSet) bool {\n\tif set == other {\n\t\treturn true\n\t}\n\n\tif set.size() != other.size() {\n\t\treturn false\n\t}\n\n\tfor _, list := range(set.items) {\n\t\tfor _, item := range(list) {\n\t\t\tif !other.contains(item) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func isExactEquivalent(l language.Language) bool {\n\tfor _, o := range notEquivalent {\n\t\tif o == l {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (i Int) Equal(i2 Int) bool {\n\treturn equal(i.i, i2.i)\n}", "func (p Pair) Equal(v Pair) bool {\n\treturn bytes.Equal(p.Key, v.Key) && bytes.Equal(p.Value, v.Value)\n}", "func (side *Side) IsSame(sideInQuestion *Side) bool {\n\tif string(*side) == \"SELL\" && string(*sideInQuestion) == \"SELL\" {\n\t\treturn true\n\t}\n\tif string(*side) == \"BUY\" && string(*sideInQuestion) == \"BUY\" {\n\t\treturn true\n\t}\n\tif string(*side) == \"ZERO\" && string(*sideInQuestion) == \"ZERO\" {\n\t\treturn true\n\t}\n\treturn false\n}", "func IsRoughlyEqual(a, b float32, epsilon float32) bool {\n\tif a == b {\n\t\t// Shortcut, handles infinities\n\t\treturn true\n\t} else {\n\t\t// Use absolute error\n\t\treturn Abs(a-b) < epsilon\n\t}\n}", "func (n Number) Equal(n1 Number) bool {\n\tif len(n) != len(n1) {\n\t\treturn false\n\t}\n\tfor i, x := range n {\n\t\tif n1[i] != x {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (vp *baseVectorParty) equals(other common.VectorParty, leftVP common.ListVectorParty) bool {\n\tif !other.IsList() {\n\t\treturn false\n\t}\n\n\tif vp.GetDataType() != other.GetDataType() {\n\t\treturn false\n\t}\n\n\tif vp.GetLength() != other.GetLength() {\n\t\treturn false\n\t}\n\n\trightVP := other.AsList()\n\tfor i := 0; i < other.GetLength(); i++ {\n\t\tleftValue, leftValid := leftVP.GetListValue(i)\n\t\trightValue, rightValid := rightVP.GetListValue(i)\n\t\tif !leftValid && !rightValid {\n\t\t\tcontinue\n\t\t}\n\t\tif leftValid != rightValid || !arrayValueCompare(vp.GetDataType(), leftValue, rightValue) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (p intSlice) Equal(q permutation.Sequence) bool { return reflect.DeepEqual(p, q) }", "func (av *Attributes) IsEqualTo(dest *Attributes) bool {\n\taLen := len(av.attributes)\n\tif aLen != len(dest.attributes) {\n\t\treturn false\n\t}\n\n\tvisited := make([]bool, aLen)\n\tfor i := 0; i < aLen; i++ {\n\t\ta := &av.attributes[i]\n\t\tfound := false\n\t\tfor j := 0; j < aLen; j++ {\n\t\t\tif visited[j] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif reflect.DeepEqual(*a, dest.attributes[j]) {\n\t\t\t\tvisited[j] = true\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\n\treturn true\n}", "func EqualKeys(a, b VectorClock) bool {\n if len(a.Vector) != len(b.Vector) {\n return false\n }\n for k, _:= range a.Vector{\n _, exists := b.Vector[k]\n if exists == false{\n return false\n }\n }\n return true\n}", "func equal(a, b float64) bool {\n\tif math.IsNaN(a) && math.IsNaN(b) {\n\t\treturn true\n\t}\n\tif !math.IsNaN(a) && !math.IsNaN(b) {\n\t\treturn math.Abs(a-b) < eps\n\t}\n\treturn false\n}", "func Equals(a, b interface{}) bool {\n\treturn neogointernal.Opcode2(\"EQUAL\", a, b).(bool)\n}", "func CheckEquivalent(t1, t2 *tree.Tree) bool {\n\tc1 := make(chan int)\n\tc2:= make(chan int)\n\tgo Walk(t1, c1)\n\tgo Walk(t2, c2)\n\n\tx1, x2, ok1, ok2 := 0, 0, true, true\n\n\tfor ok1 && ok2 {\n\t\tx1, ok1 = <- c1\n\t\tx2, ok2 = <- c2\n\n\t\tif ok1 != ok2 || x1 != x2 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (p pair) Equal(e Equaler) bool {\n\treturn p == e.(pair)\n}", "func (o *Echo) IsEqual(other *Echo) bool {\n\treturn o.GetID() == other.GetID()\n}", "func (a Bits) Equal(b Bits) bool {\n\tif a.Num != b.Num {\n\t\tpanic(\"receiver and argument have different number of bits\")\n\t}\n\tif a.Num == 0 {\n\t\treturn true\n\t}\n\tlast := len(a.Bits) - 1\n\tfor i, w := range a.Bits[:last] {\n\t\tif w != b.Bits[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn (a.Bits[last]^b.Bits[last])<<uint(len(a.Bits)*64-a.Num) == 0\n}", "func dishEqual(a, b *Dish, includingPrice bool) bool {\n\tres := a.Type == b.Type && a.Description == b.Description && a.Kcal == b.Kcal && a.rowID == b.rowID && a.colID == b.colID\n\tres = res && a.Date.Year() == b.Date.Year() && a.Date.Month() == b.Date.Month() && a.Date.Day() == b.Date.Day()\n\treturn res && (!includingPrice || (a.Price == b.Price))\n\n}", "func (a *Mtx) Equals(b *Mtx) bool {\n\tfor i := 0; i < 4; i++ {\n\t\tfor j := 0; j < 4; j++ {\n\t\t\tif a.el[i][j] != b.el[i][j] {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}" ]
[ "0.6836704", "0.66877675", "0.66601247", "0.6523435", "0.64968175", "0.6491126", "0.6442374", "0.635766", "0.63138324", "0.62434494", "0.62421304", "0.623856", "0.62277097", "0.622744", "0.62098587", "0.62054527", "0.61846155", "0.6177692", "0.6167293", "0.6158573", "0.61543155", "0.61517024", "0.6149697", "0.614063", "0.6136766", "0.6133424", "0.6132328", "0.6123034", "0.6104118", "0.6101941", "0.60912997", "0.609109", "0.60886806", "0.6087673", "0.60865885", "0.6083232", "0.6075923", "0.6073783", "0.6061161", "0.6054022", "0.6049145", "0.6049145", "0.6042298", "0.60327697", "0.6032147", "0.6010369", "0.6006069", "0.60002583", "0.5999798", "0.5998751", "0.5996265", "0.598271", "0.5980352", "0.5977264", "0.5977137", "0.59757125", "0.5975226", "0.5974338", "0.59705913", "0.59686935", "0.59662044", "0.595922", "0.59542096", "0.5953893", "0.5950354", "0.5946046", "0.5946046", "0.5940454", "0.59311545", "0.59251606", "0.59164923", "0.5903133", "0.58991635", "0.589802", "0.5897013", "0.58969074", "0.5891358", "0.5871353", "0.5862037", "0.5861869", "0.5859206", "0.5853889", "0.58527917", "0.58508986", "0.5840671", "0.58399713", "0.5837023", "0.5834284", "0.58336884", "0.5830928", "0.582722", "0.5826661", "0.58233607", "0.5822973", "0.5817249", "0.58139414", "0.5813852", "0.5810706", "0.5809475", "0.58006287", "0.5799758" ]
0.0
-1
Returns True if this Tuple is elementwise equal to other
func (this *Tuple) Eq(other *Tuple) bool { if this.Len() != other.Len() { return false } //return reflect.DeepEqual(this.data, other.data) for i := 0; i < this.Len(); i++ { lhsi, rhsi := this.Get(i), other.Get(i) if !TupleElemEq(lhsi, rhsi) { return false } } return true }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Equal(t, other Tuplelike) bool {\n\tfor idx, value := range t.Values() {\n\t\tif !inEpsilon(value, other.At(idx)) {\n\t\t\treturn false\n\t\t}\n\n\t}\n\treturn true\n}", "func (pair *eachPair) Equals(el interface {}) (bool) { \n other, ok := el.(*eachPair) \n if !ok { return false; }\n return pair == other\n}", "func EqualsValTuple(a, b ValTuple) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(a); i++ {\n\t\tif !EqualsExpr(a[i], b[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (td TupleDesc) Equals(other TupleDesc) bool {\n\tif len(td.Types) != len(other.Types) {\n\t\treturn false\n\t}\n\tfor i, typ := range td.Types {\n\t\tif typ != other.Types[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func TupleElemEq(lhsi interface{}, rhsi interface{}) bool {\n\tlhsv, rhsv := reflect.ValueOf(lhsi), reflect.ValueOf(rhsi)\n\t// IsNil panics if type is not interface-y, so use IsValid instead\n\tif lhsv.IsValid() != rhsv.IsValid() {\n\t\treturn false\n\t}\n\t// TODO: this currently blows up if lhs can't be converted to same\n\t// type as rhs (e.g. int vs. string)\n\tswitch lhsi.(type) {\n\tcase nil:\n\t\tif rhsv.IsValid() {\n\t\t\treturn false\n\t\t}\n\tcase string:\n\t\tif lhsi.(string) != rhsi.(string) {\n\t\t\treturn false\n\t\t}\n\tcase int, int8, int16, int32, int64:\n\t\tif lhsv.Int() != rhsv.Int() {\n\t\t\treturn false\n\t\t}\n\tcase uint, uintptr, uint8, uint16, uint32, uint64:\n\t\tif lhsv.Uint() != rhsv.Uint() {\n\t\t\treturn false\n\t\t}\n\tcase float32, float64:\n\t\tif lhsv.Float() != rhsv.Float() {\n\t\t\treturn false\n\t\t}\n\tcase *Tuple:\n\t\tif lhsi.(*Tuple).Ne(rhsi.(*Tuple)) {\n\t\t\treturn false\n\t\t}\n\tdefault:\n\t\t//if !lhsv.IsValid() && !rhsv.IsValid() {\n\t\t//return false\n\t\t//}\n\t\t// TODO: allow user-defined callback for unsupported types\n\t\tpanic(fmt.Sprintf(\"unsupported type %#v for Eq in Tuple\", lhsi))\n\t}\n\treturn true\n}", "func (t Tuple1) Equal(o Tuple) bool {\n\toT, ok := o.(Tuple1)\n\treturn t == o ||\n\t\t(ok &&\n\t\t\t(t.E1 != nil && t.E1.Equal(oT.E1)))\n}", "func (t *Tuple) Equals(o *Tuple) bool {\n\n\treturn floatEqual(t.x, o.x) && floatEqual(t.y, o.y) && floatEqual(t.z, o.z) && floatEqual(t.w, o.w)\n}", "func (t Table) Equals(other core.DxfElement) bool {\n\tif otherTable, ok := other.(Table); ok {\n\t\tif len(t) != len(otherTable) {\n\t\t\treturn false\n\t\t}\n\n\t\tfor key, element := range t {\n\t\t\tif otherElement, ok := otherTable[key]; ok {\n\t\t\t\tif !element.Equals(otherElement) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t}\n\t\treturn true\n\t}\n\n\treturn false\n}", "func equalPairSlice(a, b []Pair) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (p pair) Equal(e Equaler) bool {\n\treturn p == e.(pair)\n}", "func (p *Pair) Equals(pa Pair) bool {\n\tif p[0] == pa[0] && p[1] == pa[1] {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (sc *SetComprehension) Equal(other Value) bool {\n\treturn Compare(sc, other) == 0\n}", "func (vp *baseVectorParty) equals(other common.VectorParty, leftVP common.ListVectorParty) bool {\n\tif !other.IsList() {\n\t\treturn false\n\t}\n\n\tif vp.GetDataType() != other.GetDataType() {\n\t\treturn false\n\t}\n\n\tif vp.GetLength() != other.GetLength() {\n\t\treturn false\n\t}\n\n\trightVP := other.AsList()\n\tfor i := 0; i < other.GetLength(); i++ {\n\t\tleftValue, leftValid := leftVP.GetListValue(i)\n\t\trightValue, rightValid := rightVP.GetListValue(i)\n\t\tif !leftValid && !rightValid {\n\t\t\tcontinue\n\t\t}\n\t\tif leftValid != rightValid || !arrayValueCompare(vp.GetDataType(), leftValue, rightValue) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (a seriesIDs) equals(other seriesIDs) bool {\n\tif len(a) != len(other) {\n\t\treturn false\n\t}\n\tfor i, s := range other {\n\t\tif a[i] != s {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (this *Tuple) Ne(other *Tuple) bool {\n\treturn !this.Eq(other)\n}", "func (kvp *KVPairs) IsEqual(other Expr) bool {\n\to, ok := other.(*KVPairs)\n\tif !ok {\n\t\treturn false\n\t}\n\tif kvp.SelfReferenced != o.SelfReferenced {\n\t\treturn false\n\t}\n\n\tif len(kvp.Pairs) != len(o.Pairs) {\n\t\treturn false\n\t}\n\n\tfor i := range kvp.Pairs {\n\t\tif kvp.Pairs[i].K != o.Pairs[i].K {\n\t\t\treturn false\n\t\t}\n\t\tif !Equal(kvp.Pairs[i].V, o.Pairs[i].V) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (a *Activation) Equal(other *Activation) bool {\n\treturn a.actptr == other.actptr\n}", "func EqualsColTuple(inA, inB ColTuple) bool {\n\tif inA == nil && inB == nil {\n\t\treturn true\n\t}\n\tif inA == nil || inB == nil {\n\t\treturn false\n\t}\n\tswitch a := inA.(type) {\n\tcase ListArg:\n\t\tb, ok := inB.(ListArg)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\treturn EqualsListArg(a, b)\n\tcase *Subquery:\n\t\tb, ok := inB.(*Subquery)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\treturn EqualsRefOfSubquery(a, b)\n\tcase ValTuple:\n\t\tb, ok := inB.(ValTuple)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\treturn EqualsValTuple(a, b)\n\tdefault:\n\t\t// this should never happen\n\t\treturn false\n\t}\n}", "func (ac *ArrayComprehension) Equal(other Value) bool {\n\treturn Compare(ac, other) == 0\n}", "func (v *Values) Equal(other *Values) bool {\n\tv.lock.RLock()\n\tdefer v.lock.RUnlock()\n\tother.lock.RLock()\n\tdefer other.lock.RUnlock()\n\n\treturn v.root.equal(other.root)\n}", "func (bA *CompactBitArray) Equal(other *CompactBitArray) bool {\n\tif bA == other {\n\t\treturn true\n\t}\n\tif bA == nil || other == nil {\n\t\treturn false\n\t}\n\treturn bA.ExtraBitsStored == other.ExtraBitsStored &&\n\t\tbytes.Equal(bA.Elems, other.Elems)\n}", "func networkTupleEquals(net1 networkTuple, net2 networkTuple) bool {\n\tif net1.ip == net2.ip && net1.netMask == net2.netMask {\n\t\treturn true\n\t}\n\treturn false\n}", "func (z *Element22) Equal(x *Element22) bool {\n\treturn (z[21] == x[21]) && (z[20] == x[20]) && (z[19] == x[19]) && (z[18] == x[18]) && (z[17] == x[17]) && (z[16] == x[16]) && (z[15] == x[15]) && (z[14] == x[14]) && (z[13] == x[13]) && (z[12] == x[12]) && (z[11] == x[11]) && (z[10] == x[10]) && (z[9] == x[9]) && (z[8] == x[8]) && (z[7] == x[7]) && (z[6] == x[6]) && (z[5] == x[5]) && (z[4] == x[4]) && (z[3] == x[3]) && (z[2] == x[2]) && (z[1] == x[1]) && (z[0] == x[0])\n}", "func equal(x, y []int) bool {\n\tif len(x) != len(y) {\n\t\treturn false // if the length is not the same we can stop right there\n\t}\n\t// for i := range x {\n\t// \tif x[i] != y[i] {\n\t// \t\treturn false\n\t// \t}\n\t// }\n\tfor i, v := range x {\n\t\tif v != y[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func equals(p1, p2 *node) bool {\n\treturn p1.x == p2.x && p1.y == p2.y\n}", "func (bs BitStream) IsEqual(other BitStream) bool {\n\tif len(bs.bits) != len(other.bits) {\n\t\treturn false\n\t}\n\n\tfor i, b := range bs.bits {\n\t\tif b != other.bits[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (a Vector) Equal(b []float64) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tfor k := range a {\n\t\tif !Equal(a[k], b[k]) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (c Cell) Equal(other Elem) bool {\n\tif o, ok := other.(Cell); ok {\n\t\tif c == Nil || o == Nil {\n\t\t\treturn c == o\n\t\t}\n\n\t\tif !c.car.Equal(o.car) {\n\t\t\treturn false\n\t\t}\n\n\t\t// If this cell is equal, then continue to compare cdrs\n\t\treturn c.cdr.Equal(o.cdr)\n\t}\n\treturn false\n}", "func (a Points) Equal(b Points) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func equals(a []int, b []int) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i, n := range a {\n\t\tif n != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (a *Mtx) Equals(b *Mtx) bool {\n\tfor i := 0; i < 4; i++ {\n\t\tfor j := 0; j < 4; j++ {\n\t\t\tif a.el[i][j] != b.el[i][j] {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}", "func (p Pair) Equal(v Pair) bool {\n\treturn bytes.Equal(p.Key, v.Key) && bytes.Equal(p.Value, v.Value)\n}", "func (s Sequence) equal(other Node) bool {\n\to, ok := other.(Sequence)\n\tif !ok || len(s.elements) != len(o.elements) || s.path != o.path {\n\t\treturn false\n\t}\n\tif s.elements == nil || o.elements == nil {\n\t\treturn s.elements == nil && o.elements == nil\n\t}\n\tfor i, v := range o.elements {\n\t\tif !equal(s.elements[i], v) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (t Tuple) EqualApprox(o Tuple) bool {\n\treturn floats.EqualApprox(t.X, o.X, floats.Epsilon) &&\n\t\tfloats.EqualApprox(t.Y, o.Y, floats.Epsilon) &&\n\t\tfloats.EqualApprox(t.Z, o.Z, floats.Epsilon) &&\n\t\tfloats.EqualApprox(t.W, o.W, floats.Epsilon)\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 (a Slice[T]) IsEq(other Slice[T]) bool {\n\t// check length\n\tif len(a) != len(other) {\n\t\treturn false\n\t}\n\n\t// check values\n\tfor i, o := range a {\n\t\tif o != other[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (v Vector) Equals(other Vector) bool {\n\tv = v.reduce()\n\tother = other.reduce()\n\tif len(v.data) == len(other.data) {\n\t\tfor n, d1 := range v.data {\n\t\t\tif d2, ok := other.data[n]; !ok || d1 != d2 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (seq SeqEq[S, T]) Equal(a, b S) bool {\n\tseqA := a\n\tseqB := b\n\tfor !seq.Seq.IsVoid(seqA) && !seq.Seq.IsVoid(seqB) {\n\t\theadA := seq.Seq.Head(seqA)\n\t\theadB := seq.Seq.Head(seqB)\n\t\tif headA == nil || headB == nil || !seq.Eq.Equal(*headA, *headB) {\n\t\t\treturn false\n\t\t}\n\n\t\tseqA = seq.Seq.Tail(seqA)\n\t\tseqB = seq.Seq.Tail(seqB)\n\t}\n\n\treturn seq.Seq.IsVoid(seqA) && seq.Seq.IsVoid(seqB)\n}", "func Same[E any](x, y []E) bool {\n\treturn len(x) > 0 && len(y) > 0 && len(x) == len(y) && &x[0] == &y[0]\n}", "func (t Token) Equal(t2 Token) bool {\n\tif t.TokenType == t2.TokenType && bytes.Equal(t.Data, t2.Data) && len(t.Args) == len(t2.Args) {\n\t\tfor i := 0; i < len(t.Args); i++ {\n\t\t\tif t.Args[i].TokenType != t2.Args[i].TokenType || !bytes.Equal(t.Args[i].Data, t2.Args[i].Data) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}", "func EqualsValues(a, b Values) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(a); i++ {\n\t\tif !EqualsValTuple(a[i], b[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (oc *ObjectComprehension) Equal(other Value) bool {\n\treturn Compare(oc, other) == 0\n}", "func (p Pair) Equal(cPair Pair) bool {\n\treturn p.Base.Equal(cPair.Base) && p.Quote.Equal(cPair.Quote)\n}", "func (a Bits) Equal(b Bits) bool {\n\tif a.Num != b.Num {\n\t\tpanic(\"receiver and argument have different number of bits\")\n\t}\n\tif a.Num == 0 {\n\t\treturn true\n\t}\n\tlast := len(a.Bits) - 1\n\tfor i, w := range a.Bits[:last] {\n\t\tif w != b.Bits[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn (a.Bits[last]^b.Bits[last])<<uint(len(a.Bits)*64-a.Num) == 0\n}", "func (recv *ValueArray) Equals(other *ValueArray) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func Equal(t1, t2 Token) bool {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tif t1 == nil && t2 == nil {\n\t\treturn true\n\t}\n\n\t// we already checked for t1 == t2 == nil, so safe to do this\n\tif t1 == nil || t2 == nil {\n\t\treturn false\n\t}\n\n\tm1, err := t1.AsMap(ctx)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tfor iter := t2.Iterate(ctx); iter.Next(ctx); {\n\t\tpair := iter.Pair()\n\n\t\tv1 := m1[pair.Key.(string)]\n\t\tv2 := pair.Value\n\t\tswitch tmp := v1.(type) {\n\t\tcase time.Time:\n\t\t\ttmp2, ok := v2.(time.Time)\n\t\t\tif !ok {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\ttmp = tmp.Round(0).Truncate(time.Second)\n\t\t\ttmp2 = tmp2.Round(0).Truncate(time.Second)\n\t\t\tif !tmp.Equal(tmp2) {\n\t\t\t\treturn false\n\t\t\t}\n\t\tdefault:\n\t\t\tif v1 != v2 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tdelete(m1, pair.Key.(string))\n\t}\n\n\treturn len(m1) == 0\n}", "func (p *EdwardsPoint) Equal(other *EdwardsPoint) int {\n\t// We would like to check that the point (X/Z, Y/Z) is equal to\n\t// the point (X'/Z', Y'/Z') without converting into affine\n\t// coordinates (x, y) and (x', y'), which requires two inversions.\n\t// We have that X = xZ and X' = x'Z'. Thus, x = x' is equivalent to\n\t// (xZ)Z' = (x'Z')Z, and similarly for the y-coordinate.\n\tvar sXoZ, oXsZ, sYoZ, oYsZ field.FieldElement\n\tsXoZ.Mul(&p.inner.X, &other.inner.Z)\n\toXsZ.Mul(&other.inner.X, &p.inner.Z)\n\tsYoZ.Mul(&p.inner.Y, &other.inner.Z)\n\toYsZ.Mul(&other.inner.Y, &p.inner.Z)\n\n\treturn sXoZ.Equal(&oXsZ) & sYoZ.Equal(&oYsZ)\n}", "func (s SetValue) Equal(o attr.Value) bool {\n\tother, ok := o.(SetValue)\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\tif !s.elementType.Equal(other.elementType) {\n\t\treturn false\n\t}\n\n\tif s.state != other.state {\n\t\treturn false\n\t}\n\n\tif s.state != attr.ValueStateKnown {\n\t\treturn true\n\t}\n\n\tif len(s.elements) != len(other.elements) {\n\t\treturn false\n\t}\n\n\tfor _, elem := range s.elements {\n\t\tif !other.contains(elem) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (c *Comparison) IsSame() bool {\n\treturn c.First.Start.Equal(c.Second.Start) && c.First.End.Equal(c.Second.End)\n}", "func (t Tags) Equal(other Tags) bool {\n\tif len(t.Values()) != len(other.Values()) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(t.Values()); i++ {\n\t\tequal := t.values[i].Name.Equal(other.values[i].Name) &&\n\t\t\tt.values[i].Value.Equal(other.values[i].Value)\n\t\tif !equal {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (p Pair) Equal(cPair Pair) bool {\n\treturn p.Base.Item == cPair.Base.Item && p.Quote.Item == cPair.Quote.Item\n}", "func equals(A, B []int) bool {\n\tif len(A) != len(B) {\n\t\treturn false\n\t}\n\n\tfor i := range A {\n\t\tif B[i] != A[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func equal(left, right []string) bool {\n\tif len(left) != len(right) {\n\t\treturn false\n\t}\n\tfor i, value := range left {\n\t\tif value != right[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (p Pair) Equal(pair Pair) bool {\n\treturn p.String() == pair.String()\n}", "func (p *G2Affine) Equal(a *G2Affine) bool {\n\treturn p.X.Equal(&a.X) && p.Y.Equal(&a.Y)\n}", "func TestEquals(t *testing.T) {\n\tt.Parallel()\n\tfor ti, tt := range []struct {\n\t\tm1, m2 MatrixExp\n\t\teq bool\n\t}{\n\t\t{\n\t\t\tm1: GeneralZeros(1, 1),\n\t\t\tm2: GeneralZeros(1, 1),\n\t\t\teq: true,\n\t\t},\n\t\t{\n\t\t\tm1: GeneralZeros(1, 1),\n\t\t\tm2: GeneralZeros(1, 10),\n\t\t\teq: false,\n\t\t},\n\t\t{\n\t\t\tm1: GeneralZeros(10, 1),\n\t\t\tm2: GeneralZeros(1, 1),\n\t\t\teq: false,\n\t\t},\n\t\t{\n\t\t\tm1: GeneralZeros(1, 1),\n\t\t\tm2: GeneralOnes(1, 1),\n\t\t\teq: false,\n\t\t},\n\t} {\n\t\tif v := Equals(tt.m1, tt.m2); v != tt.eq {\n\t\t\tt.Errorf(\"%d: Equals(%v,%v) equals %v, want %v\", ti, tt.m1, tt.m2, v, tt.eq)\n\t\t}\n\t}\n}", "func (l *LabelPair) Equal(o *LabelPair) bool {\n\tswitch {\n\tcase l.Name != o.Name:\n\t\treturn false\n\tcase l.Value != o.Value:\n\t\treturn false\n\tdefault:\n\t\treturn true\n\t}\n}", "func (s ExpressionStepElementKeyIntExact) Equal(o ExpressionStep) bool {\n\tother, ok := o.(ExpressionStepElementKeyIntExact)\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\treturn int64(s) == int64(other)\n}", "func (m Membership) Equals(other Membership) bool {\n\treturn m.Owner == other.Owner &&\n\t\tm.TspAddress == other.TspAddress &&\n\t\tm.ExpiryAt.Equal(*other.ExpiryAt) &&\n\t\tm.MembershipType == other.MembershipType\n}", "func (v Set) Equal(other Set) bool {\n\tsort.Sort(other)\n\n\tfor i := 0; i < len(v); i++ {\n\t\tif v[i].Cmp(other[i]) != 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (arr *Array) Equal(other Value) bool {\n\treturn Compare(arr, other) == 0\n}", "func (g *Graph) Equal(g2 *Graph, debug bool) bool {\n\n\t// Check the vertices\n\tkeys1 := g.listOfKeys()\n\tkeys2 := g2.listOfKeys()\n\n\tif !SlicesHaveSameElements(&keys1, &keys2) {\n\t\tif debug {\n\t\t\tlog.Println(\"Lists of keys are different\")\n\t\t\tlog.Printf(\"Keys1: %v\\n\", keys1)\n\t\t\tlog.Printf(\"Keys2: %v\\n\", keys2)\n\t\t}\n\t\treturn false\n\t}\n\n\t// Walk through each vertex and check its connections\n\tfor _, vertex := range keys1 {\n\t\tconns1 := g.Nodes[vertex]\n\t\tconns2 := g2.Nodes[vertex]\n\n\t\tif !SetsEqual(conns1, conns2) {\n\t\t\tif debug {\n\t\t\t\tlog.Printf(\"Connections different for vertex %v\", vertex)\n\t\t\t\tlog.Printf(\"Connections 1: %v\\n\", conns1)\n\t\t\t\tlog.Printf(\"Connections 2: %v\\n\", conns2)\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (array Array) Equal(other Array) bool {\n\tif len(array) != len(other) {\n\t\treturn false\n\t}\n\tfor i, v := range array {\n\t\tif other[i] != v {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (ja *Array) Equals(other *Array) bool {\n\tif ja.Values == nil || other.Values == nil || len(ja.Values) != len(other.Values) {\n\t\treturn false\n\t}\n\n\tfor _, lv := range ja.Values {\n\t\tvar ok bool\n\t\tfor _, rv := range other.Values {\n\t\t\tok = compareValues(lv, rv)\n\t\t\tif ok {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (b Bytes) Equal(o Bytes) bool { return bytes.Equal(b.Bytes(), o.Bytes()) }", "func (r Representative) Equal(a, b uint64) bool {\n\tif r == nil {\n\t\treturn Equal(a, b)\n\t}\n\treturn r(a) == r(b)\n}", "func (id ArrayNodeID) Equals(other NodeID) bool {\n\tif id.Base() != other.Base() || id.Length() != other.Length() {\n\t\treturn false\n\t}\n\tswitch otherId := other.(type) {\n\tcase ArrayNodeID:\n\t\treturn bytes.Equal(id.id, otherId.id)\n\tdefault:\n\t\tfor i := 0; i < id.Length(); i++ {\n\t\t\tif id.GetDigit(i) != other.GetDigit(i) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n}", "func (k *Key) Equal(other *Key) bool {\n\treturn k.IncompleteEqual(other) && (k.LastTok() == other.LastTok())\n}", "func (v TimestampValue) Equal(other ValueNode) bool {\n\totherV, ok := other.(TimestampValue)\n\treturn ok && otherV == v\n}", "func (this *Tuple) Ge(other *Tuple) bool {\n\treturn !this.Lt(other)\n}", "func equal(x, y []string) bool {\n if len(x) != len(y) {\n return false\n }\n for i := range x {\n if x[i] != y[i] {\n return false\n }\n }\n return true\n}", "func (q Quat) Equals(other Quat) bool {\n\treturn q.EqualsEps(other, Epsilon)\n}", "func (utxo ExtBtcCompatUTXO) Equal(other Value) bool {\n\totherUTXO, ok := other.(ExtBtcCompatUTXO)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn utxo.TxHash.Equal(otherUTXO.TxHash) &&\n\t\tutxo.VOut.Equal(otherUTXO.VOut) &&\n\t\tutxo.ScriptPubKey.Equal(otherUTXO.ScriptPubKey) &&\n\t\tutxo.Amount.Equal(otherUTXO.Amount) &&\n\t\tutxo.GHash.Equal(otherUTXO.GHash)\n}", "func (iter *RbTreeIterator) Equal(other iterator.ConstIterator) bool {\n\totherIter, ok := other.(*RbTreeIterator)\n\tif !ok {\n\t\treturn false\n\t}\n\tif otherIter.node == iter.node {\n\t\treturn true\n\t}\n\treturn false\n}", "func (addr *wtIn6Addr) equal(other *wtIn6Addr) bool {\n\n\tif addr == nil || other == nil {\n\t\treturn false\n\t}\n\n\tfor i := 0; i < 16; i++ {\n\t\tif addr.Byte[i] != other.Byte[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func same(x int, y int) bool {\n\treturn find(x) == find(y)\n}", "func (this *Base) equals(other Piece) bool {\n\tif this.getName() != other.getName() {\n\t\treturn false\n\t}\n\n\tif this.getKanji() != other.getKanji() {\n\t\treturn false\n\t}\n\n\tif this.getColor() != other.getColor() {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func eq(x, y []string) bool {\n\t// NOTE: set equal\n\treturn sset.Equal(x, y)\n}", "func (n *node) equal(other *node) bool {\n\treturn n.value == other.value && n.childrenEqual(other)\n}", "func (ft *FieldType) Equal(other *FieldType) bool {\n\t// We do not need to compare whole `ft.flag == other.flag` when wrapping cast upon an Expression.\n\t// but need compare unsigned_flag of ft.flag.\n\t// When tp is float or double with decimal unspecified, do not check whether flen is equal,\n\t// because flen for them is useless.\n\t// The decimal field can be ignored if the type is int or string.\n\ttpEqual := (ft.GetType() == other.GetType()) || (ft.GetType() == mysql.TypeVarchar && other.GetType() == mysql.TypeVarString) || (ft.GetType() == mysql.TypeVarString && other.GetType() == mysql.TypeVarchar)\n\tflenEqual := ft.flen == other.flen || (ft.EvalType() == ETReal && ft.decimal == UnspecifiedLength)\n\tignoreDecimal := ft.EvalType() == ETInt || ft.EvalType() == ETString\n\tpartialEqual := tpEqual &&\n\t\t(ignoreDecimal || ft.decimal == other.decimal) &&\n\t\tft.charset == other.charset &&\n\t\tft.collate == other.collate &&\n\t\tflenEqual &&\n\t\tmysql.HasUnsignedFlag(ft.flag) == mysql.HasUnsignedFlag(other.flag)\n\tif !partialEqual || len(ft.elems) != len(other.elems) {\n\t\treturn false\n\t}\n\tfor i := range ft.elems {\n\t\tif ft.elems[i] != other.elems[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func equal(a []int, b []int) bool {\n\tvar length int\n\n\tif len(a) < len(b) {\n\t\tlength = len(a)\n\t} else {\n\t\tlength = len(b)\n\t}\n\n\tfor i := 0; i < length; i++ {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func Equal(a, b []interface{}) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i, v := range a {\n\t\tif v != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (set *lalrSet) equals(other *lalrSet) bool {\n\tif set == other {\n\t\treturn true\n\t}\n\n\tif set.size() != other.size() {\n\t\treturn false\n\t}\n\n\tfor _, list := range(set.items) {\n\t\tfor _, item := range(list) {\n\t\t\tif !other.contains(item) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func (t *TransactionPayload) Equal(other *TransactionPayload) bool {\n\treturn bytes.Equal(t.Data, other.Data)\n}", "func (a joinedTable) equal(b joinedTable) bool {\n\treturn a.secondaryTable == b.secondaryTable && a.primaryColumn == b.primaryColumn && a.secondaryColumn == b.secondaryColumn\n}", "func (list List) Equal(other List) bool {\n\tif other.Length() != list.Length() {\n\t\treturn false\n\t}\n\tfor idx, val := range list {\n\t\tif other[idx] != val {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (v *TypePair) Equals(rhs *TypePair) bool {\n\tif v == nil {\n\t\treturn rhs == nil\n\t} else if rhs == nil {\n\t\treturn false\n\t}\n\tif !v.Left.Equals(rhs.Left) {\n\t\treturn false\n\t}\n\tif !v.Right.Equals(rhs.Right) {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (c *cell) equivalent(other *cell) bool {\n\treturn c.path == other.path &&\n\t\tc.subdom == other.subdom &&\n\t\tc.proto == other.proto\n}", "func (lv *ListValue) Equal(other ValueNode) bool {\n\totherLv, ok := other.(*ListValue)\n\tif !ok || len(lv.Entries) != len(otherLv.Entries) {\n\t\treturn false\n\t}\n\tfor i, entry := range lv.Entries {\n\t\totherEntry := otherLv.Entries[i]\n\t\tif !entry.Value.Equal(otherEntry.Value) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (p intSlice) Equal(q permutation.Sequence) bool { return reflect.DeepEqual(p, q) }", "func (s *VectorClock) Equals(otherClock VectorClock) bool {\n\tpanic(\"todo\")\n}", "func (p PlayerIndex) Equivalent(other PlayerIndex) bool {\n\n\t//Sanity check obviously-illegal values\n\tif p < AdminPlayerIndex || other < AdminPlayerIndex {\n\t\treturn false\n\t}\n\n\tif p == ObserverPlayerIndex || other == ObserverPlayerIndex {\n\t\treturn false\n\t}\n\tif p == AdminPlayerIndex || other == AdminPlayerIndex {\n\t\treturn true\n\t}\n\treturn p == other\n}", "func (in Inputs) Equals(other Inputs) bool {\n\t// Sort both sets incase they are out of order\n\tsort.Sort(in)\n\tsort.Sort(other)\n\n\tif len(in) != len(other) {\n\t\treturn false\n\t}\n\n\tfor i := range in {\n\t\tfirstInput := in[i]\n\t\tsecondInput := other[i]\n\t\tif !firstInput.Equals(secondInput) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (recv *ParamSpecValueArray) Equals(other *ParamSpecValueArray) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func (c clock) equals(other clock) bool {\n\treturn reflect.DeepEqual(c, other)\n}", "func (sig InsecureSignature) Equal(other InsecureSignature) bool {\n\treturn bool(C.CInsecureSignatureIsEqual(sig.sig, other.sig))\n}", "func (ba *BitArray) Equals(barr *BitArray) bool {\n\tif len(ba.buf) != len(barr.buf) {\n\t\treturn false\n\t}\n\tfor i, b := range ba.buf {\n\t\tif barr.buf[i] != b {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (r RawRecord) Equals(other RawRecord) bool {\n\treturn reflect.ValueOf(r).Pointer() == reflect.ValueOf(other).Pointer()\n}", "func (bits *BitArray) Eq(obits *BitArray) bool {\n\tif bits.length != obits.length {\n\t\treturn false\n\t}\n\n\tfor i := 0; i < bits.lenpad; i += _BytesPW {\n\t\twself := bytes2word(bits.bytes[i : i+_BytesPW])\n\t\twother := bytes2word(obits.bytes[i : i+_BytesPW])\n\t\tif wself != wother {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func Eql(v1, v2 Vect) bool { return v1.X == v2.X && v1.Y == v2.Y }" ]
[ "0.71708703", "0.66241527", "0.66111946", "0.6581941", "0.64175856", "0.6380936", "0.6297961", "0.61168104", "0.6090455", "0.60117775", "0.5978922", "0.5931099", "0.59009355", "0.5894657", "0.588204", "0.5870349", "0.5866866", "0.5862125", "0.5848202", "0.57785845", "0.5777972", "0.5768946", "0.57419205", "0.57392097", "0.57230574", "0.572297", "0.57202196", "0.57128745", "0.57086813", "0.5688745", "0.5673345", "0.5671624", "0.56625164", "0.5655837", "0.56554204", "0.56460446", "0.56413627", "0.56162065", "0.5608756", "0.5599666", "0.559595", "0.5591681", "0.5590403", "0.55883163", "0.55730146", "0.5569022", "0.5558868", "0.5555084", "0.55475986", "0.5540286", "0.55387557", "0.55362743", "0.5534773", "0.5526625", "0.5523633", "0.5519201", "0.55177695", "0.551344", "0.5512887", "0.5507195", "0.5502817", "0.5501507", "0.55005497", "0.54734045", "0.5471581", "0.5464831", "0.5439621", "0.5439438", "0.5435526", "0.5434537", "0.5431078", "0.542865", "0.54266715", "0.5420968", "0.54200387", "0.5418845", "0.5416425", "0.54144406", "0.54144317", "0.5413597", "0.5406738", "0.540034", "0.5391417", "0.53908634", "0.53795093", "0.53779674", "0.53741163", "0.53701264", "0.5369508", "0.53671527", "0.5365819", "0.5357436", "0.53570527", "0.53570455", "0.53532636", "0.5350433", "0.5343962", "0.5339731", "0.53392816", "0.5335711" ]
0.7626882
0
Returns True if this Tuple is not elementwise equal to other
func (this *Tuple) Ne(other *Tuple) bool { return !this.Eq(other) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Equal(t, other Tuplelike) bool {\n\tfor idx, value := range t.Values() {\n\t\tif !inEpsilon(value, other.At(idx)) {\n\t\t\treturn false\n\t\t}\n\n\t}\n\treturn true\n}", "func (this *Tuple) Eq(other *Tuple) bool {\n\tif this.Len() != other.Len() {\n\t\treturn false\n\t}\n\t//return reflect.DeepEqual(this.data, other.data)\n\tfor i := 0; i < this.Len(); i++ {\n\t\tlhsi, rhsi := this.Get(i), other.Get(i)\n\t\tif !TupleElemEq(lhsi, rhsi) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (td TupleDesc) Equals(other TupleDesc) bool {\n\tif len(td.Types) != len(other.Types) {\n\t\treturn false\n\t}\n\tfor i, typ := range td.Types {\n\t\tif typ != other.Types[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualsValTuple(a, b ValTuple) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(a); i++ {\n\t\tif !EqualsExpr(a[i], b[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func notEqual(a []int, b []int) bool {\n\tif len(a) != len(b) {\n\t\treturn true\n\t}\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (this *Tuple) Ge(other *Tuple) bool {\n\treturn !this.Lt(other)\n}", "func (a *Assertions) NotEqual(expected, actual interface{}, msgAndArgs ...interface{}) bool {\n\treturn NotEqual(a.t, expected, actual, msgAndArgs...)\n}", "func NotEqual[T any](t testing.TB, expected, actual T, msgAndArgs ...interface{}) {\n\tif !objectsAreEqual(expected, actual) {\n\t\treturn\n\t}\n\tt.Helper()\n\tmsg := formatMsgAndArgs(\"Expected values to not be equal but both were:\", msgAndArgs...)\n\tt.Fatalf(\"%s\\n%s\", msg, repr.String(expected, repr.Indent(\" \")))\n}", "func NotEqual(values ...interface{}) (failureMessage string) {\n\tif values[0] == values[1] {\n\t\tfailureMessage = fmt.Sprintf(\"Expected `%v` to not equal `%v`\", values[0], values[1])\n\t}\n\treturn\n}", "func NotEqual(t TestingT, expected, actual interface{}, extras ...interface{}) bool {\n\tif DeepEqual(expected, actual) {\n\t\texps, acts := toString(expected, actual)\n\n\t\treturn Errorf(t, \"Expect to be NOT equal\", []labeledOutput{\n\t\t\t{\n\t\t\t\tlabel: labelMessages,\n\t\t\t\tcontent: formatExtras(extras...),\n\t\t\t},\n\t\t\t{\n\t\t\t\tlabel: \"-expected\",\n\t\t\t\tcontent: exps,\n\t\t\t},\n\t\t\t{\n\t\t\t\tlabel: \"+received\",\n\t\t\t\tcontent: acts,\n\t\t\t},\n\t\t})\n\t}\n\n\treturn true\n}", "func NotEqual(u1, u2 Unit) bool {\n\treturn !Equal(u1, u2)\n}", "func notequal(lhs, rhs semantic.Expression) semantic.Expression {\n\treturn &semantic.BinaryOp{Type: semantic.BoolType, LHS: lhs, Operator: ast.OpNE, RHS: rhs}\n}", "func (t Tuple1) Equal(o Tuple) bool {\n\toT, ok := o.(Tuple1)\n\treturn t == o ||\n\t\t(ok &&\n\t\t\t(t.E1 != nil && t.E1.Equal(oT.E1)))\n}", "func NotEqual(t Testing, expected, actual interface{}, formatAndArgs ...interface{}) bool {\n\tif AreEqualObjects(expected, actual) {\n\t\texpected, actual = prettifyValues(expected, actual)\n\n\t\treturn Fail(t, fmt.Sprintf(\n\t\t\t\"Expected values are NOT equal in value.%s\",\n\t\t\tdiffValues(expected, actual),\n\t\t), formatAndArgs...)\n\t}\n\n\treturn true\n}", "func (eps Accuracy) NotEqual(a, b float64) bool {\n\treturn math.Abs(a-b) >= eps()\n}", "func isExactEquivalent(l language.Language) bool {\n\tfor _, o := range notEquivalent {\n\t\tif o == l {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func NotEqual[T comparable](val, want T, a ...any) {\n\tif want == val {\n\t\tdefMsg := fmt.Sprintf(assertionMsg+\": got '%v' want (!= '%v')\", val, want)\n\t\tDefault().reportAssertionFault(defMsg, a...)\n\t}\n}", "func (this *Tuple) Gt(other *Tuple) bool {\n\treturn !this.Le(other)\n}", "func (t *T) NotEqual(got, notWant interface{}) bool {\n\tt.Helper()\n\tnotEqual := !cmp.Equal(got, notWant)\n\tif notEqual {\n\t\tt.Logf(\"%s: got %+v, not %+v\", caller(), got, notWant)\n\t} else {\n\t\tt.Errorf(\"%s: got %+v, want not %+v\", caller(), got, notWant)\n\t}\n\treturn notEqual\n}", "func NotEqual(expected, actual interface{}) bool {\n\tif err := validateEqualArgs(expected, actual); err != nil {\n\t\treturn false\n\t}\n\n\tif ObjectsAreEqual(expected, actual) {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (a *Assertions) NotEqual(expected interface{}, actual interface{}, userMessageComponents ...interface{}) bool {\n\ta.assertion()\n\tif didFail, message := shouldNotBeEqual(expected, actual); didFail {\n\t\treturn a.fail(message, userMessageComponents...)\n\t}\n\treturn true\n}", "func TupleElemEq(lhsi interface{}, rhsi interface{}) bool {\n\tlhsv, rhsv := reflect.ValueOf(lhsi), reflect.ValueOf(rhsi)\n\t// IsNil panics if type is not interface-y, so use IsValid instead\n\tif lhsv.IsValid() != rhsv.IsValid() {\n\t\treturn false\n\t}\n\t// TODO: this currently blows up if lhs can't be converted to same\n\t// type as rhs (e.g. int vs. string)\n\tswitch lhsi.(type) {\n\tcase nil:\n\t\tif rhsv.IsValid() {\n\t\t\treturn false\n\t\t}\n\tcase string:\n\t\tif lhsi.(string) != rhsi.(string) {\n\t\t\treturn false\n\t\t}\n\tcase int, int8, int16, int32, int64:\n\t\tif lhsv.Int() != rhsv.Int() {\n\t\t\treturn false\n\t\t}\n\tcase uint, uintptr, uint8, uint16, uint32, uint64:\n\t\tif lhsv.Uint() != rhsv.Uint() {\n\t\t\treturn false\n\t\t}\n\tcase float32, float64:\n\t\tif lhsv.Float() != rhsv.Float() {\n\t\t\treturn false\n\t\t}\n\tcase *Tuple:\n\t\tif lhsi.(*Tuple).Ne(rhsi.(*Tuple)) {\n\t\t\treturn false\n\t\t}\n\tdefault:\n\t\t//if !lhsv.IsValid() && !rhsv.IsValid() {\n\t\t//return false\n\t\t//}\n\t\t// TODO: allow user-defined callback for unsupported types\n\t\tpanic(fmt.Sprintf(\"unsupported type %#v for Eq in Tuple\", lhsi))\n\t}\n\treturn true\n}", "func NotEqual(t *testing.T, expected, actual interface{}, message ...string) {\n\tif compareEquality(expected, actual) {\n\t\tt.Errorf(\"%v\\nExpected \\n\\t[%#v]\\n NOT to be\\n\\t[%#v]\\n%v \", message, actual, expected, callerInfo(2 +callStackAdjust))\n\t}\n}", "func NotEqual(a, b float64) bool {\n\treturn !IsEqual(a, b)\n}", "func equalPairSlice(a, b []Pair) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (s *Suite) NotEqual(exp, act interface{}, message ...string) bool {\n\ts.setup()\n\tif exp == act {\n\t\tif len(message) > 0 {\n\t\t\treturn s.Status.failWithCustomMsg(message[0], s.callerInfo)\n\t\t}\n\t\treturn s.Status.failWithCustomMsg(fmt.Sprintf(\"Expected %v to be not equal to %v\", exp, act), s.callerInfo)\n\t}\n\treturn s.Status.pass()\n}", "func (pair *eachPair) Equals(el interface {}) (bool) { \n other, ok := el.(*eachPair) \n if !ok { return false; }\n return pair == other\n}", "func (t *Tuple) Equals(o *Tuple) bool {\n\n\treturn floatEqual(t.x, o.x) && floatEqual(t.y, o.y) && floatEqual(t.z, o.z) && floatEqual(t.w, o.w)\n}", "func NotEqual(t *testing.T, a, b interface{}) {\n\tif a == b || reflect.DeepEqual(a, b) {\n\t\tt.Errorf(\"%v Equal: %v != %v\", line(), a, b)\n\t}\n}", "func NotEqual(t testing.TB, expected, actual interface{}, msgAndArgs ...interface{}) bool {\n\tif err := validateEqualArgs(expected, actual); err != nil {\n\t\treturn failTest(t, 1, fmt.Sprintf(\"NotEqual: invalid operation `%#v` != `%#v` (%v)\", expected, actual, err), msgAndArgs...)\n\t}\n\n\tif IsObjectEqual(expected, actual) {\n\t\treturn failTest(t, 1, fmt.Sprintf(\"NotEqual: expected not to be `%#v`\", actual), msgAndArgs...)\n\t}\n\n\treturn true\n}", "func (t TimeValue) IsNotSameAs(expected interface{}) bool {\n\treturn t.value != expected\n}", "func networkTupleEquals(net1 networkTuple, net2 networkTuple) bool {\n\tif net1.ip == net2.ip && net1.netMask == net2.netMask {\n\t\treturn true\n\t}\n\treturn false\n}", "func DeepEqualUnsorted(p1, p2 interface{}, equal func(i1, i2 int) bool) bool {\n\tv1 := reflect.ValueOf(p1)\n\tv2 := reflect.ValueOf(p2)\n\tif v1.Len() != v2.Len() {\n\t\treturn false\n\t}\n\tfor i1 := 0; i1 < v1.Len(); i1++ {\n\t\tfound := false\n\t\tfor i2 := 0; i2 < v2.Len(); i2++ {\n\t\t\tif equal(i1, i2) {\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 NotSamePointer(t testing.TB, expected, actual interface{}, msgAndArgs ...interface{}) bool {\n\tif IsPointerSame(expected, actual) {\n\t\treturn failTest(t, 1, fmt.Sprintf(\"SamePointer: expected not be `%#v` (%p)\", actual, actual), msgAndArgs...)\n\t}\n\n\treturn true\n}", "func NotEqual(object interface{}, values ...interface{}) error {\n\tfor _, value := range values {\n\t\t// shortcuts\n\t\tif value == nil && object == nil {\n\t\t\treturn xerrors.New(stringJoin(\"\\n\", fmt.Sprintf(\"should not be %s\", PrintValue(object))))\n\t\t}\n\n\t\tif (value == nil && object != nil) || (value != nil && object == nil) {\n\t\t\treturn nil\n\t\t}\n\t\t// we might be able to convert this\n\t\tcompareData := misc.MakeTypeCopy(value)\n\t\tif err := converter.Convert(object, &compareData); err == nil {\n\t\t\tobject = compareData\n\t\t}\n\t\tif cmp.Equal(value, object) {\n\t\t\treturn xerrors.New(stringJoin(\"\\n\", fmt.Sprintf(\"should not be %s\", PrintValue(object))))\n\t\t}\n\t}\n\n\treturn nil\n}", "func (me TComparator) IsNotEqualTo() bool { return me.String() == \"NotEqualTo\" }", "func (t Table) Equals(other core.DxfElement) bool {\n\tif otherTable, ok := other.(Table); ok {\n\t\tif len(t) != len(otherTable) {\n\t\t\treturn false\n\t\t}\n\n\t\tfor key, element := range t {\n\t\t\tif otherElement, ok := otherTable[key]; ok {\n\t\t\t\tif !element.Equals(otherElement) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t}\n\t\treturn true\n\t}\n\n\treturn false\n}", "func NeFn(a interface{}, b interface{}) bool {\n\treturn a != b\n}", "func EqualsColTuple(inA, inB ColTuple) bool {\n\tif inA == nil && inB == nil {\n\t\treturn true\n\t}\n\tif inA == nil || inB == nil {\n\t\treturn false\n\t}\n\tswitch a := inA.(type) {\n\tcase ListArg:\n\t\tb, ok := inB.(ListArg)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\treturn EqualsListArg(a, b)\n\tcase *Subquery:\n\t\tb, ok := inB.(*Subquery)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\treturn EqualsRefOfSubquery(a, b)\n\tcase ValTuple:\n\t\tb, ok := inB.(ValTuple)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\treturn EqualsValTuple(a, b)\n\tdefault:\n\t\t// this should never happen\n\t\treturn false\n\t}\n}", "func (dt *DateTime) NotEqual(value time.Time) *DateTime {\n\topChain := dt.chain.enter(\"NotEqual()\")\n\tdefer opChain.leave()\n\n\tif opChain.failed() {\n\t\treturn dt\n\t}\n\n\tif dt.value.Equal(value) {\n\t\topChain.fail(AssertionFailure{\n\t\t\tType: AssertNotEqual,\n\t\t\tActual: &AssertionValue{dt.value},\n\t\t\tExpected: &AssertionValue{value},\n\t\t\tErrors: []error{\n\t\t\t\terrors.New(\"expected: time points are non-equal\"),\n\t\t\t},\n\t\t})\n\t}\n\n\treturn dt\n}", "func (a Bits) Equal(b Bits) bool {\n\tif a.Num != b.Num {\n\t\tpanic(\"receiver and argument have different number of bits\")\n\t}\n\tif a.Num == 0 {\n\t\treturn true\n\t}\n\tlast := len(a.Bits) - 1\n\tfor i, w := range a.Bits[:last] {\n\t\tif w != b.Bits[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn (a.Bits[last]^b.Bits[last])<<uint(len(a.Bits)*64-a.Num) == 0\n}", "func NotEqual(lhs, rhs Expression) Expression {\n\treturn NewCall(\"not_equal\", []Expression{lhs, rhs}, nil)\n}", "func (a Points) Equal(b Points) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (a *Mtx) Equals(b *Mtx) bool {\n\tfor i := 0; i < 4; i++ {\n\t\tfor j := 0; j < 4; j++ {\n\t\t\tif a.el[i][j] != b.el[i][j] {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}", "func (a seriesIDs) equals(other seriesIDs) bool {\n\tif len(a) != len(other) {\n\t\treturn false\n\t}\n\tfor i, s := range other {\n\t\tif a[i] != s {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualsValues(a, b Values) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(a); i++ {\n\t\tif !EqualsValTuple(a[i], b[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (this *Tuple) Lt(other *Tuple) bool {\n\ttlen, olen := this.Len(), other.Len()\n\tvar n int\n\tif tlen < olen {\n\t\tn = tlen\n\t} else {\n\t\tn = olen\n\t}\n\tfor i := 0; i < n; i++ {\n\t\tlhsi, rhsi := this.Get(i), other.Get(i)\n\t\tif TupleElemLt(lhsi, rhsi) {\n\t\t\treturn true\n\t\t} else if !TupleElemEq(lhsi, rhsi) {\n\t\t\treturn false\n\t\t}\n\t}\n\t// if we get here then they matched up to n\n\tif tlen < olen {\n\t\treturn true\n\t}\n\treturn false\n}", "func (b ValExprBuilder) NotInTuple(tuple Tuple) BoolExprBuilder {\n\tif valTuple, ok := tuple.(ValTuple); ok {\n\t\tif len(valTuple.Exprs) == 0 {\n\t\t\treturn b.makeComparisonExpr(astNotIn, makeErrVal(\"empty list\"))\n\t\t}\n\t}\n\treturn b.makeComparisonExpr(astNotIn, tuple)\n}", "func (v Vector) Equals(other Vector) bool {\n\tv = v.reduce()\n\tother = other.reduce()\n\tif len(v.data) == len(other.data) {\n\t\tfor n, d1 := range v.data {\n\t\t\tif d2, ok := other.data[n]; !ok || d1 != d2 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (t *T) NotEqual(have, unwanted interface{}, desc ...string) {\n\tprefix := \"\"\n\tif len(desc) > 0 {\n\t\tprefix = strings.Join(desc, \" \") + \": \"\n\t}\n\tt.notEqualPrefix_(have, unwanted, prefix)\n}", "func EqualKeys(a, b VectorClock) bool {\n if len(a.Vector) != len(b.Vector) {\n return false\n }\n for k, _:= range a.Vector{\n _, exists := b.Vector[k]\n if exists == false{\n return false\n }\n }\n return true\n}", "func Equal(t1, t2 Token) bool {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tif t1 == nil && t2 == nil {\n\t\treturn true\n\t}\n\n\t// we already checked for t1 == t2 == nil, so safe to do this\n\tif t1 == nil || t2 == nil {\n\t\treturn false\n\t}\n\n\tm1, err := t1.AsMap(ctx)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tfor iter := t2.Iterate(ctx); iter.Next(ctx); {\n\t\tpair := iter.Pair()\n\n\t\tv1 := m1[pair.Key.(string)]\n\t\tv2 := pair.Value\n\t\tswitch tmp := v1.(type) {\n\t\tcase time.Time:\n\t\t\ttmp2, ok := v2.(time.Time)\n\t\t\tif !ok {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\ttmp = tmp.Round(0).Truncate(time.Second)\n\t\t\ttmp2 = tmp2.Round(0).Truncate(time.Second)\n\t\t\tif !tmp.Equal(tmp2) {\n\t\t\t\treturn false\n\t\t\t}\n\t\tdefault:\n\t\t\tif v1 != v2 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tdelete(m1, pair.Key.(string))\n\t}\n\n\treturn len(m1) == 0\n}", "func unequal(t *testing.T, expected, actual interface{}) {\n\tif reflect.DeepEqual(expected, actual) {\n\t\tt.Errorf(\"Did not expect %v (type %v) - Got %v (type %v)\", expected, reflect.TypeOf(expected), actual, reflect.TypeOf(actual))\n\t}\n}", "func Neq(x, y reflect.Value) reflect.Value {\n\tmustSameType(x, y)\n\tz := reflect.New(reflect.TypeOf(false)).Elem()\n\tswitch x.Type().Kind() {\n\tcase reflect.Int:\n\t\txx := int(x.Int())\n\t\tyy := int(y.Int())\n\t\tzz := xx != yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Int8:\n\t\txx := int8(x.Int())\n\t\tyy := int8(y.Int())\n\t\tzz := xx != yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Int16:\n\t\txx := int16(x.Int())\n\t\tyy := int16(y.Int())\n\t\tzz := xx != yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Int32:\n\t\txx := int32(x.Int())\n\t\tyy := int32(y.Int())\n\t\tzz := xx != yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Int64:\n\t\txx := int64(x.Int())\n\t\tyy := int64(y.Int())\n\t\tzz := xx != yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Uint:\n\t\txx := uint(x.Uint())\n\t\tyy := uint(y.Uint())\n\t\tzz := xx != yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Uint8:\n\t\txx := uint8(x.Uint())\n\t\tyy := uint8(y.Uint())\n\t\tzz := xx != yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Uint16:\n\t\txx := uint16(x.Uint())\n\t\tyy := uint16(y.Uint())\n\t\tzz := xx != yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Uint32:\n\t\txx := uint32(x.Uint())\n\t\tyy := uint32(y.Uint())\n\t\tzz := xx != yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Uint64:\n\t\txx := uint64(x.Uint())\n\t\tyy := uint64(y.Uint())\n\t\tzz := xx != yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Uintptr:\n\t\txx := uintptr(x.Uint())\n\t\tyy := uintptr(y.Uint())\n\t\tzz := xx != yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Float32:\n\t\txx := float32(x.Float())\n\t\tyy := float32(y.Float())\n\t\tzz := xx != yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Float64:\n\t\txx := float64(x.Float())\n\t\tyy := float64(y.Float())\n\t\tzz := xx != yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Complex64:\n\t\txx := complex64(x.Complex())\n\t\tyy := complex64(y.Complex())\n\t\tzz := xx != yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Complex128:\n\t\txx := complex128(x.Complex())\n\t\tyy := complex128(y.Complex())\n\t\tzz := xx != yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.String:\n\t\txx := string(x.String())\n\t\tyy := string(y.String())\n\t\tzz := xx != yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Bool:\n\t\txx := bool(x.Bool())\n\t\tyy := bool(y.Bool())\n\t\tzz := xx != yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\t}\n\tpanic(fmt.Sprintf(\"operator != not defined on %v\", x.Type()))\n}", "func (this *Tuple) Le(other *Tuple) bool {\n\treturn this.Lt(other) || this.Eq(other)\n}", "func (t *Table) Same(t2 *Table) bool {\n\treturn false\n}", "func equal(x, y []string) bool {\n if len(x) != len(y) {\n return false\n }\n for i := range x {\n if x[i] != y[i] {\n return false\n }\n }\n return true\n}", "func (kvp *KVPairs) IsEqual(other Expr) bool {\n\to, ok := other.(*KVPairs)\n\tif !ok {\n\t\treturn false\n\t}\n\tif kvp.SelfReferenced != o.SelfReferenced {\n\t\treturn false\n\t}\n\n\tif len(kvp.Pairs) != len(o.Pairs) {\n\t\treturn false\n\t}\n\n\tfor i := range kvp.Pairs {\n\t\tif kvp.Pairs[i].K != o.Pairs[i].K {\n\t\t\treturn false\n\t\t}\n\t\tif !Equal(kvp.Pairs[i].V, o.Pairs[i].V) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (a Vector) Equal(b []float64) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tfor k := range a {\n\t\tif !Equal(a[k], b[k]) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (t Tuple) EqualApprox(o Tuple) bool {\n\treturn floats.EqualApprox(t.X, o.X, floats.Epsilon) &&\n\t\tfloats.EqualApprox(t.Y, o.Y, floats.Epsilon) &&\n\t\tfloats.EqualApprox(t.Z, o.Z, floats.Epsilon) &&\n\t\tfloats.EqualApprox(t.W, o.W, floats.Epsilon)\n}", "func ErrIfMismatchedColumnsInTuple(t1, t2 sql.Type) error {\n\tv2, ok2 := t2.(TupleType)\n\tif !ok2 {\n\t\treturn sql.ErrInvalidOperandColumns.New(NumColumns(t1), NumColumns(t2))\n\t}\n\tfor _, v := range v2 {\n\t\tif err := ErrIfMismatchedColumns(t1, v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (bs BitStream) IsEqual(other BitStream) bool {\n\tif len(bs.bits) != len(other.bits) {\n\t\treturn false\n\t}\n\n\tfor i, b := range bs.bits {\n\t\tif b != other.bits[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func equal(x, y []int) bool {\n\tif len(x) != len(y) {\n\t\treturn false // if the length is not the same we can stop right there\n\t}\n\t// for i := range x {\n\t// \tif x[i] != y[i] {\n\t// \t\treturn false\n\t// \t}\n\t// }\n\tfor i, v := range x {\n\t\tif v != y[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func Equals(oneSet, otherSet Set) bool {\n\n\tif len(oneSet.mem) != len(otherSet.mem) {\n\t\treturn false\n\t}\n\t/* Obviously, if the sets have different numbers of elements, they are not\n\tequal. */\n\n\tfor k := range oneSet.mem {\n\t\tif otherSet.mem[k] == false {\n\t\t\treturn false\n\t\t}\n\t}\n\t/* If the sets have an equal number of elements and an element in one of the\n\tsets is not in the other set, they are not equal. */\n\n\treturn true\n}", "func Equal(a, b Vector) bool {\n\tpanicLength(a, b)\n\tfor i := 0; i < a.Len(); i++ {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (v Set) Equal(other Set) bool {\n\tsort.Sort(other)\n\n\tfor i := 0; i < len(v); i++ {\n\t\tif v[i].Cmp(other[i]) != 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (uid MyULID) Equal(other MyULID) bool {\n\tif len(uid) < 16 && len(other) < 16 {\n\t\treturn true\n\t}\n\tif len(uid) < 16 || len(other) < 16 {\n\t\treturn false\n\t}\n\treturn uid[:16] == other[:16]\n}", "func (d dag) equalNodes(that dag) bool {\n\tif len(d) != len(that) {\n\t\treturn false\n\t}\n\tfor id := range d {\n\t\tif _, ok := that[id]; !ok {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (k *Key) IncompleteEqual(other *Key) (ret bool) {\n\tret = (k.kc.Matches(other.kc) &&\n\t\tlen(k.toks) == len(other.toks))\n\tif ret {\n\t\tfor i, t := range k.toks {\n\t\t\tif i == len(k.toks)-1 {\n\t\t\t\t// Last token: check only Kind.\n\t\t\t\tif ret = (t.Kind == other.toks[i].Kind); !ret {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif ret = t == other.toks[i]; !ret {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (o Orbit) StrictlyEquals(o1 Orbit) (bool, error) {\n\t// Only check for non circular orbits\n\t_, e, _, _, _, ν, _, _, _ := o.Elements()\n\t_, _, _, _, _, ν1, _, _, _ := o1.Elements()\n\tif floats.EqualWithinAbs(e, 0, 2*eccentricityε) {\n\t\tif floats.EqualApprox(o.rVec, o1.rVec, 1) && floats.EqualApprox(o.vVec, o1.vVec, velocityε) {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, errors.New(\"vectors not equal\")\n\t} else if e > eccentricityε && !floats.EqualWithinAbs(ν, ν1, angleε) {\n\t\treturn false, errors.New(\"true anomaly invalid\")\n\t}\n\treturn o.Equals(o1)\n}", "func Same[E any](x, y []E) bool {\n\treturn len(x) > 0 && len(y) > 0 && len(x) == len(y) && &x[0] == &y[0]\n}", "func (l *LabelPair) Equal(o *LabelPair) bool {\n\tswitch {\n\tcase l.Name != o.Name:\n\t\treturn false\n\tcase l.Value != o.Value:\n\t\treturn false\n\tdefault:\n\t\treturn true\n\t}\n}", "func (c *CustomFuncs) HasNoDirectTupleReferences(\n\tprojections memo.ProjectionsExpr, tupleCol opt.ColumnID,\n) bool {\n\tvar check func(expr opt.Expr) bool\n\tcheck = func(expr opt.Expr) bool {\n\t\tswitch t := expr.(type) {\n\t\tcase *memo.ColumnAccessExpr:\n\t\t\tswitch t.Input.(type) {\n\t\t\tcase *memo.VariableExpr:\n\t\t\t\treturn true\n\t\t\t}\n\n\t\tcase *memo.VariableExpr:\n\t\t\treturn t.Col != tupleCol\n\t\t}\n\t\tfor i, n := 0, expr.ChildCount(); i < n; i++ {\n\t\t\tif !check(expr.Child(i)) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\n\tfor i := range projections {\n\t\tif !check(projections[i].Element) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (p PlayerIndex) Equivalent(other PlayerIndex) bool {\n\n\t//Sanity check obviously-illegal values\n\tif p < AdminPlayerIndex || other < AdminPlayerIndex {\n\t\treturn false\n\t}\n\n\tif p == ObserverPlayerIndex || other == ObserverPlayerIndex {\n\t\treturn false\n\t}\n\tif p == AdminPlayerIndex || other == AdminPlayerIndex {\n\t\treturn true\n\t}\n\treturn p == other\n}", "func setsAreDisjoint(its *assert.Assertions, itemSets ...[]string) {\n\tfor thisSetIndex, thisSet := range itemSets {\n\t\tfor _, thisItem := range thisSet {\n\t\t\tfor otherSetIndex, otherSet := range itemSets {\n\t\t\t\tif thisSetIndex != otherSetIndex {\n\t\t\t\t\tfor _, otherItem := range otherSet {\n\t\t\t\t\t\tits.NotEqual(thisItem, otherItem)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func Xor(a, b bool) bool {\n\tif a == b {\n\t\treturn false\n\t}\n\treturn true\n}", "func (s *VectorClock) Equals(otherClock VectorClock) bool {\n\tpanic(\"todo\")\n}", "func Xor(a, b bool) bool {\n\n\tif a==b {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (vp *baseVectorParty) equals(other common.VectorParty, leftVP common.ListVectorParty) bool {\n\tif !other.IsList() {\n\t\treturn false\n\t}\n\n\tif vp.GetDataType() != other.GetDataType() {\n\t\treturn false\n\t}\n\n\tif vp.GetLength() != other.GetLength() {\n\t\treturn false\n\t}\n\n\trightVP := other.AsList()\n\tfor i := 0; i < other.GetLength(); i++ {\n\t\tleftValue, leftValid := leftVP.GetListValue(i)\n\t\trightValue, rightValid := rightVP.GetListValue(i)\n\t\tif !leftValid && !rightValid {\n\t\t\tcontinue\n\t\t}\n\t\tif leftValid != rightValid || !arrayValueCompare(vp.GetDataType(), leftValue, rightValue) {\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 (i *ArrayIterator) Equals(Object) bool {\n\treturn false\n}", "func testEqualitySlicesOfPlayer(a, b []Player) bool {\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (q Quat) Equals(other Quat) bool {\n\treturn q.EqualsEps(other, Epsilon)\n}", "func (t Tags) Equal(other Tags) bool {\n\tif len(t.Values()) != len(other.Values()) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(t.Values()); i++ {\n\t\tequal := t.values[i].Name.Equal(other.values[i].Name) &&\n\t\t\tt.values[i].Value.Equal(other.values[i].Value)\n\t\tif !equal {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func extensionIDEqual(a, b []int) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (t *TT) NoEq(a, b interface{}) {\n\tif reflect.DeepEqual(a, b) {\n\t\tt.error(fmt.Sprintf(\"noeq: %d %d\", a, b))\n\t}\n}", "func (sc *SetComprehension) Equal(other Value) bool {\n\treturn Compare(sc, other) == 0\n}", "func NotEqual(scope *Scope, x tf.Output, y tf.Output, optional ...NotEqualAttr) (z tf.Output) {\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: \"NotEqual\",\n\t\tInput: []tf.Input{\n\t\t\tx, y,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func (n *Uint256) Not() *Uint256 {\n\tn.n[0] = ^n.n[0]\n\tn.n[1] = ^n.n[1]\n\tn.n[2] = ^n.n[2]\n\tn.n[3] = ^n.n[3]\n\treturn n\n}", "func isOnlySecretValueDiff(a, b Component) bool {\n\tsecValsEqual := reflect.DeepEqual(a.SecretValues, b.SecretValues)\n\ta.SecretValues = SecretValues{}\n\tb.SecretValues = SecretValues{}\n\treturn !secValsEqual && reflect.DeepEqual(a, b)\n}", "func Same(t1, t2 *tree.Tree) bool {\n\tch1 := make(chan int)\n\tch2 := make(chan int)\n\tgo Walk(t1, ch1)\n\tgo Walk(t2, ch2)\n\tvar values []int\n\tfor v1 := range ch1 {\n\t\tvalues = append(values, v1)\n\t}\n\tfor v2 := range ch2 {\n\t\tvar found bool\n\t\tvalues, found = Remove(values, v2)\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\tif len(values) != 0 {\n\t\treturn false\n\t}\n\treturn true\n}", "func Complement[T comparable](a, b []T) (aOnly, bOnly []T) {\n\tfor _, i := range a {\n\t\tif !Contains(b, i) {\n\t\t\taOnly = append(aOnly, i)\n\t\t}\n\t}\n\n\tfor _, i := range b {\n\t\tif !Contains(a, i) {\n\t\t\tbOnly = append(bOnly, i)\n\t\t}\n\t}\n\n\treturn aOnly, bOnly\n}", "func (a Slice[T]) IsEq(other Slice[T]) bool {\n\t// check length\n\tif len(a) != len(other) {\n\t\treturn false\n\t}\n\n\t// check values\n\tfor i, o := range a {\n\t\tif o != other[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (s Set) Equal(s2 Set) bool {\n\tif len(s) != len(s2) {\n\t\treturn false\n\t}\n\tfor k := range s {\n\t\tif _, ok := s2[k]; !ok {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func equal(left, right []string) bool {\n\tif len(left) != len(right) {\n\t\treturn false\n\t}\n\tfor i, value := range left {\n\t\tif value != right[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func memequal(x, y unsafe.Pointer, n uintptr) bool {\n\tfor i := uintptr(0); i < n; i++ {\n\t\tcx := *(*uint8)(unsafe.Add(x, i))\n\t\tcy := *(*uint8)(unsafe.Add(y, i))\n\t\tif cx != cy {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (utxo ExtBtcCompatUTXO) Equal(other Value) bool {\n\totherUTXO, ok := other.(ExtBtcCompatUTXO)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn utxo.TxHash.Equal(otherUTXO.TxHash) &&\n\t\tutxo.VOut.Equal(otherUTXO.VOut) &&\n\t\tutxo.ScriptPubKey.Equal(otherUTXO.ScriptPubKey) &&\n\t\tutxo.Amount.Equal(otherUTXO.Amount) &&\n\t\tutxo.GHash.Equal(otherUTXO.GHash)\n}", "func XNor(a, b Dense) Dense {\n\tshort, long := a, b\n\tif b.len < a.len {\n\t\tshort, long = b, a\n\t}\n\tr := Dense{\n\t\tbits: make([]byte, 0, BytesFor(long.len)),\n\t\tlen: long.len,\n\t\tnegated: a.negated == b.negated,\n\t}\n\tfor i := range short.bits {\n\t\tr.bits = append(r.bits, ^(a.bits[i] ^ b.bits[i]))\n\t}\n\tvar trail byte\n\tif a.negated {\n\t\ttrail = 0xFF\n\t}\n\tfor i := len(short.bits); i < len(long.bits); i++ {\n\t\tr.bits = append(r.bits, ^(trail ^ long.bits[i]))\n\t}\n\treturn r\n}", "func (htuple HTuple) Is(other IHType) bool {\n\toTpl, ok := other.(*HTuple)\n\tif !ok {\n\t\tif len(htuple.types) == 1 {\n\t\t\treturn (*htuple.types[0]).Is(other)\n\t\t}\n\t\treturn false\n\t}\n\tif len(htuple.types) != len(oTpl.types) {\n\t\treturn false\n\t}\n\tfor i, htype := range htuple.types {\n\t\tif !(*htype).Is(*oTpl.types[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func hasEqualAdjacent(g *Game, x, y int) bool {\n\n\tv := g.Board[x][y]\n\n\tif x == 0 {\n\t\tif y == 0 {\n\t\t\treturn v == g.Board[x][y+1] || v == g.Board[x+1][y]\n\t\t} else if y == g.Size-1 {\n\t\t\treturn v == g.Board[x-1][y] || v == g.Board[x][y+1]\n\t\t} else {\n\t\t\treturn v == g.Board[x][y+1] || v == g.Board[x][y-1] || v == g.Board[x+1][y]\n\t\t}\n\t} else if x == g.Size-1 {\n\t\tif y == 0 {\n\t\t\treturn v == g.Board[x][y+1] || v == g.Board[x-1][y]\n\t\t} else if y == g.Size-1 {\n\t\t\treturn v == g.Board[x-1][y] || v == g.Board[x][y-1]\n\t\t} else {\n\t\t\treturn v == g.Board[x][y+1] || v == g.Board[x][y-1] || v == g.Board[x-1][y]\n\t\t}\n\t} else {\n\n\t\tif y == 0 {\n\t\t\treturn v == g.Board[x][y+1] || v == g.Board[x-1][y] || v == g.Board[x+1][y]\n\t\t} else if y == g.Size-1 {\n\t\t\treturn v == g.Board[x-1][y] || v == g.Board[x][y-1] || v == g.Board[x+1][y]\n\t\t} else {\n\t\t\treturn v == g.Board[x][y+1] || v == g.Board[x][y-1] || v == g.Board[x-1][y] || v == g.Board[x+1][y]\n\t\t}\n\t}\n}" ]
[ "0.6762844", "0.6520316", "0.61363983", "0.6020699", "0.59709007", "0.58789635", "0.5829467", "0.5783524", "0.5724496", "0.57088166", "0.56926435", "0.56523687", "0.5629067", "0.562703", "0.56179756", "0.5610695", "0.55907154", "0.5554059", "0.55388844", "0.5535817", "0.5534358", "0.55248755", "0.5506598", "0.54875994", "0.54479134", "0.5424021", "0.54164493", "0.5403803", "0.5373942", "0.53722984", "0.5363667", "0.5346912", "0.53434026", "0.5334121", "0.53154767", "0.5251563", "0.5239194", "0.52390105", "0.52249986", "0.5213502", "0.51743764", "0.51712483", "0.51535493", "0.51230663", "0.51214266", "0.51020706", "0.5098408", "0.50955", "0.5094896", "0.50871855", "0.50627023", "0.50459576", "0.50400174", "0.50382674", "0.50118405", "0.50036085", "0.50020504", "0.4994583", "0.49914333", "0.49517113", "0.49490267", "0.4948436", "0.49457806", "0.49357808", "0.49190298", "0.49137554", "0.49012676", "0.48975813", "0.4897579", "0.48871848", "0.48690975", "0.48658597", "0.48633236", "0.48606148", "0.48571545", "0.48526967", "0.48510268", "0.48489022", "0.4847581", "0.4847343", "0.4845178", "0.484337", "0.48405343", "0.4835202", "0.4832376", "0.48319924", "0.48269492", "0.48218408", "0.481315", "0.4799695", "0.4798107", "0.47953674", "0.4786054", "0.47810194", "0.477911", "0.4777516", "0.47761503", "0.47696537", "0.4768397", "0.47649047" ]
0.7201221
0
Returns true if the item lhsi is logically less than rhsi
func TupleElemLt(lhsi interface{}, rhsi interface{}) bool { lhsv, rhsv := reflect.ValueOf(lhsi), reflect.ValueOf(rhsi) if lhsv.IsValid() && !rhsv.IsValid() { // zero value is considered least return false } switch lhsi.(type) { case nil: if rhsv.IsValid() { return true } case string: if lhsi.(string) < rhsi.(string) { return true } case int, int8, int16, int32, int64: if lhsv.Int() < rhsv.Int() { return true } case uint, uintptr, uint8, uint16, uint32, uint64: if lhsv.Uint() < rhsv.Uint() { return true } case float32, float64: if lhsv.Float() < rhsv.Float() { return true } case *Tuple: if lhsi.(*Tuple).Lt(rhsi.(*Tuple)) { return true } default: // TODO: allow user-defined callback for unsupported types panic(fmt.Sprintf("unsupported type %#v for Lt in Tuple", lhsi)) } return false }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (z *Int) Slt(x *Int) bool {\n\n\tzSign := z.Sign()\n\txSign := x.Sign()\n\n\tswitch {\n\tcase zSign >= 0 && xSign < 0:\n\t\treturn false\n\tcase zSign < 0 && xSign >= 0:\n\t\treturn true\n\tdefault:\n\t\treturn z.Lt(x)\n\t}\n}", "func IsLowS(k *ecdsa.PublicKey, s *big.Int) (bool, error) {\n\thalfOrder, ok := curveHalfOrders[k.Curve]\n\tif !ok {\n\t\treturn false, fmt.Errorf(\"curve not recognized [%s]\", k.Curve)\n\t}\n\n\treturn s.Cmp(halfOrder) != 1, nil\n\n}", "func IsLowS(k *ecdsa.PublicKey, s *big.Int) (bool, error) {\n\thalfOrder, ok := curveHalfOrders[k.Curve]\n\tif !ok {\n\t\treturn false, fmt.Errorf(\"curve not recognized [%s]\", k.Curve)\n\t}\n\n\treturn s.Cmp(halfOrder) != 1, nil\n\n}", "func (me TxsdConfidenceRating) IsLow() bool { return me.String() == \"low\" }", "func lessThanHalf(x, y Duration) bool {\n\treturn uint64(x)+uint64(x) < uint64(y)\n}", "func (hrsKey *HRSKey) Less(other HRSKey) bool {\n\tif hrsKey.Height < other.Height {\n\t\treturn true\n\t}\n\n\tif hrsKey.Height > other.Height {\n\t\treturn false\n\t}\n\n\t// height is equal, check round\n\n\tif hrsKey.Round < other.Round {\n\t\treturn true\n\t}\n\n\tif hrsKey.Round > other.Round {\n\t\treturn false\n\t}\n\n\t// round is equal, check step\n\n\tif hrsKey.Step < other.Step {\n\t\treturn true\n\t}\n\n\t// everything is equal\n\treturn false\n}", "func LT(x float64, y float64) bool {\n\treturn (x < y-e)\n}", "func Command_Lt(script *rex.Script, params []*rex.Value) {\n\tif len(params) != 2 {\n\t\trex.ErrorParamCount(\"float:lt\", \"2\")\n\t}\n\n\tresult := params[0].Float64() < params[1].Float64()\n\tif result {\n\t\tscript.RetVal = rex.NewValueBool(true)\n\t\treturn\n\t}\n\tscript.RetVal = rex.NewValueBool(false)\n}", "func (me TisoLanguageCodes) IsLt() bool { return me.String() == \"LT\" }", "func (c UintCompare) IsLess(lhs, rhs uint) bool { return c(lhs, rhs) }", "func (c Int32Compare) IsLess(lhs, rhs int32) bool { return c(lhs, rhs) }", "func (i Int) LT(i2 Int) bool {\n\treturn lt(i.i, i2.i)\n}", "func (o *FloatObject) Lt(r Object) (bool) {\n return o.Value < r.AsFloat()\n}", "func opUI64Lt(prgrm *CXProgram) {\n\texpr := prgrm.GetExpr()\n\tfp := prgrm.GetFramePointer()\n\n\toutV0 := ReadUI64(fp, expr.Inputs[0]) < ReadUI64(fp, expr.Inputs[1])\n\tWriteBool(GetFinalOffset(fp, expr.Outputs[0]), outV0)\n}", "func (items BidItems) Less(i, j int) bool {\n\treturn items[i].Price > items[j].Price\n}", "func (z *Int) Lt(x *Int) bool {\n\tif z[3] < x[3] {\n\t\treturn true\n\t}\n\tif z[3] > x[3] {\n\t\treturn false\n\t}\n\tif z[2] < x[2] {\n\t\treturn true\n\t}\n\tif z[2] > x[2] {\n\t\treturn false\n\t}\n\tif z[1] < x[1] {\n\t\treturn true\n\t}\n\tif z[1] > x[1] {\n\t\treturn false\n\t}\n\treturn z[0] < x[0]\n}", "func (x uints) Less(i, j int) bool { return x[i] < x[j] }", "func (x uints) Less(i, j int) bool { return x[i] < x[j] }", "func (x uints) Less(i, j int) bool { return x[i] < x[j] }", "func (me TgridOriginEnumType) IsLowerLeft() bool { return me == \"lowerLeft\" }", "func (i *Item) Less(o *Item) bool {\n\treturn i.GetKey() < o.GetKey()\n}", "func (h minPath) Less(i, j int) bool {\n\treturn h[i].value < h[j].value\n}", "func (i *info) less(b *info) bool {\n\tswitch t := i.Val.(type) {\n\tcase int64:\n\t\treturn t < b.Val.(int64)\n\tcase float64:\n\t\treturn t < b.Val.(float64)\n\tcase string:\n\t\treturn t < b.Val.(string)\n\tdefault:\n\t\tif ord, ok := i.Val.(util.Ordered); ok {\n\t\t\treturn ord.Less(b.Val.(util.Ordered))\n\t\t}\n\t\tlog.Fatalf(\"unhandled info value type: %s\", t)\n\t}\n\treturn false\n}", "func (items AskItems) Less(i, j int) bool {\n\treturn items[i].Price < items[j].Price\n}", "func (a Int) Less(b Item) bool {\n return a < b.(Int)\n}", "func opI16Lt(expr *CXExpression, fp int) {\n\tvar outB0 bool = (ReadI16(fp, expr.Inputs[0]) < ReadI16(fp, expr.Inputs[1]))\n\tWriteBool(GetOffset_bool(fp, expr.Outputs[0]), outB0)\n}", "func (me TseverityType) IsLow() bool { return me.String() == \"low\" }", "func (r lineRanges) Less(i, j int) bool {\n\treturn r[i].targetHeight > r[j].targetHeight\n}", "func (i *IPItemFix) Less(then btree.Item) bool {\n\tswitch ip := then.(type) {\n\tcase *IPItemFix:\n\t\treturn i.StartIP.Compare(&ip.StartIP) < 0\n\tcase *ipFix:\n\t\treturn i.EndIP.Compare(ip) < 0\n\t}\n\treturn false\n}", "func (src Version) IsLessThan(des Version) bool {\n\treturn src.compareWith(des) == Less\n}", "func less(c1, c2 cost) bool {\n\tswitch {\n\tcase c1.opCode != c2.opCode:\n\t\treturn c1.opCode < c2.opCode\n\tcase c1.isUnique == c2.isUnique:\n\t\treturn c1.vindexCost <= c2.vindexCost\n\tdefault:\n\t\treturn c1.isUnique\n\t}\n}", "func (id Identifier) IsLess(b Identifier) bool {\n\treturn bytes.Compare(id, b) == -1\n}", "func IsLess(fl validator.FieldLevel) bool {\n\n\tvalue := fl.Field().Int()\n\tparam:= fl.Param()\n\treturn value < cast.ToInt64(param)\n}", "func (h nodeList) Less(i, j int) bool {\n\treturn h[i].hash < h[j].hash\n}", "func (ei *ByIntervalTicks) Less(i, j int) bool {\n\tcursor_i := i * ei.recordLength\n\tcursor_j := j * ei.recordLength\n\n\tintervalTicks_i := io.ToUInt32(ei.buffer[cursor_i+ei.recordLength-4 : cursor_i+ei.recordLength])\n\tintervalTicks_j := io.ToUInt32(ei.buffer[cursor_j+ei.recordLength-4 : cursor_j+ei.recordLength])\n\n\treturn intervalTicks_i < intervalTicks_j\n}", "func (ei *ByIntervalTicks) Less(i, j int) bool {\n\tcursorI := i * ei.recordLength\n\tcursorJ := j * ei.recordLength\n\n\tintervalTicksI := io.ToUInt32(ei.buffer[cursorI+ei.recordLength-4 : cursorI+ei.recordLength])\n\tintervalTicksJ := io.ToUInt32(ei.buffer[cursorJ+ei.recordLength-4 : cursorJ+ei.recordLength])\n\n\treturn intervalTicksI < intervalTicksJ\n}", "func (z *Int) Sgt(x *Int) bool {\n\tzSign := z.Sign()\n\txSign := x.Sign()\n\n\tswitch {\n\tcase zSign >= 0 && xSign < 0:\n\t\treturn true\n\tcase zSign < 0 && xSign >= 0:\n\t\treturn false\n\tdefault:\n\t\treturn z.Gt(x)\n\t}\n}", "func (b *Bucket) less(r *Bucket) bool {\n\tif b.First || r.First {\n\t\treturn b.First\n\t}\n\treturn b.Signature.less(&r.Signature)\n}", "func (a *_Atom) isNH2orOHorSH() bool {\n\tif a.hCount == 0 || a.unsaturation != cmn.UnsaturationNone {\n\t\treturn false\n\t}\n\n\tswitch a.atNum {\n\tcase 7:\n\t\treturn a.hCount == 2\n\tcase 8, 16:\n\t\treturn a.hCount == 1\n\t}\n\n\treturn false\n}", "func (sv *sorterValues) RowLess(ri, rj sqlbase.EncDatumRow) bool {\n\tcmp, err := ri.Compare(&sv.alloc, sv.ordering, rj)\n\tif err != nil {\n\t\tsv.err = err\n\t\treturn false\n\t}\n\n\treturn cmp < 0\n}", "func (r *PartitionItem) Less(other btree.Item) bool {\n\tleft := r.partition.StartSlot\n\tright := other.(*PartitionItem).partition.StartSlot\n\t//return bytes.Compare(left, right) > 0\n\treturn left > right\n}", "func isHSL(fl FieldLevel) bool {\n\treturn hslRegex.MatchString(fl.Field().String())\n}", "func opI64Lt(expr *CXExpression, fp int) {\n\tvar outB0 bool = (ReadI64(fp, expr.Inputs[0]) < ReadI64(fp, expr.Inputs[1]))\n\tWriteBool(GetOffset_bool(fp, expr.Outputs[0]), outB0)\n}", "func Min(val, min any) bool { return valueCompare(val, min, \">=\") }", "func (e *ConstantExpr) Slt(other *ConstantExpr) *ConstantExpr {\n\tswitch e.Width {\n\tcase Width8:\n\t\treturn NewBoolConstantExpr(int8(e.Value) < int8(other.Value))\n\tcase Width16:\n\t\treturn NewBoolConstantExpr(int16(e.Value) < int16(other.Value))\n\tcase Width32:\n\t\treturn NewBoolConstantExpr(int32(e.Value) < int32(other.Value))\n\tcase Width64:\n\t\treturn NewBoolConstantExpr(int64(e.Value) < int64(other.Value))\n\tdefault:\n\t\tpanic(\"slt: non-standard width\")\n\t}\n}", "func (h *Halo) MinR() float64 { return 0.0001 * h.Rs }", "func (f Fixed) LessThan(f0 Fixed) bool {\n\treturn f.Cmp(f0) == -1\n}", "func (f Fixed) LessThan(f0 Fixed) bool {\n\treturn f.Cmp(f0) == -1\n}", "func (items Float64Slice) Less(i, j int) bool { return items[i] <= items[j] }", "func (s SortByFloat64) Less(i, j int) bool {\n\treturn s.Elements[i].GetFloat64(s.key) < s.Elements[j].GetFloat64(s.key)\n}", "func (h *PCPHistogram) Low() int64 { return h.h.HighestTrackableValue() }", "func checkHammer(data [][]interface{}, i int) bool {\n\td := convertOHLC(data[i])\n\t// fmt.Printf(\"Open: %v \", convertOHLC(data)[\"open\"])\n\t// fmt.Printf(\"High: %v \", convertOHLC(data)[\"high\"])\n\t// fmt.Printf(\"Low: %v \", convertOHLC(data)[\"low\"])\n\t// fmt.Printf(\"Close: %v \\n\", convertOHLC(data)[\"close\"])\n\n\tsec, dec := math.Modf(d[\"time\"])\n\tt := time.Unix(int64(sec), int64(dec*(1e9)))\n\tif d[\"close\"] > d[\"open\"] && d[\"low\"] < d[\"close\"]-5 {\n\t\tclose := d[\"close\"]\n\t\tbuyprice := d[\"open\"]\n\t\tif i-1 < 0 {\n\t\t\treturn false\n\t\t\tfmt.Print(\"\\n\")\n\t\t}\n\t\td = convertOHLC(data[i-1])\n\t\tif d[\"close\"] < d[\"open\"] && close < d[\"high\"]+10 {\n\t\t\tclose = d[\"close\"]\n\t\t\tif i+1 > len(data) {\n\t\t\t\treturn false\n\t\t\t\tfmt.Print(\"\\n\")\n\t\t\t}\n\t\t\td = convertOHLC(data[i+1])\n\t\t\tdiff := d[\"close\"] - buyprice\n\n\t\t\tsec, dec := math.Modf(d[\"time\"])\n\t\t\tt = time.Unix(int64(sec), int64(dec*(1e9)))\n\t\t\tfmt.Printf(\"Bought at: %v \", t)\n\t\t\tfmt.Printf(\"for: %v \", buyprice)\n\t\t\tfmt.Printf(\"Sold at: %v, for: %v \", t, d[\"close\"])\n\t\t\tfmt.Printf(\"Profit: %v \\n\", diff)\n\t\t\ttotalProfit = totalProfit + diff\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (bi Int) LessThan(o Int) bool {\n\treturn Cmp(bi, o) < 0\n}", "func (i identity) hgtValid() bool {\n\tif len(i.HGT) < 3 {\n\t\treturn false\n\t}\n\tswitch i.HGT[len(i.HGT)-2:] {\n\tcase \"cm\":\n\t\tn, err := strconv.Atoi(i.HGT[:len(i.HGT)-2])\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\treturn 150 <= n && n <= 193\n\tcase \"in\":\n\t\tn, err := strconv.Atoi(i.HGT[:len(i.HGT)-2])\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\treturn 59 <= n && n <= 76\n\t}\n\treturn false\n}", "func Gt(val, min any) bool { return valueCompare(val, min, \">\") }", "func (b *byWidth) Less(i, j int) bool {\n\treturn b.Values[i].Width < b.Values[j].Width\n}", "func (t ByAnnualizedLossExpectancy) Less(i, j int) bool {\n\treturn t.Threats[i].AnnualizedLossExpectancy() > t.Threats[j].AnnualizedLossExpectancy()\n}", "func (h Header) Rsv3() bool { return h.Rsv&bit7 != 0 }", "func (eps Accuracy) Less(a, b float64) bool {\n\treturn math.Max(a, b) == b && math.Abs(a-b) > eps()\n}", "func (b *byHeight) Less(i, j int) bool {\n\treturn b.Values[i].Height < b.Values[j].Height\n}", "func rising(arr []float64, len int) bool {\n\n\t// Add deffajult value as 3\n\tflag := false\n\tcurrVal := arr[0]\n\n\tfor _, val := range arr[1:] {\n\t\tlen--\n\t\tif len != 0 {\n\t\t\tif currVal > val {\n\t\t\t\tflag = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t\tbreak\n\t}\n\treturn flag\n\n}", "func (t SignedTRCs) Less(i, j int) bool {\n\tisdA, isdB := t[i].TRC.ID.ISD, t[j].TRC.ID.ISD\n\tbaseA, baseB := t[i].TRC.ID.Base, t[j].TRC.ID.Base\n\tserialA, serialB := t[i].TRC.ID.Serial, t[j].TRC.ID.Serial\n\tswitch {\n\tcase isdA != isdB:\n\t\treturn isdA < isdB\n\tcase baseA != baseB:\n\t\treturn baseA < baseB\n\tcase serialA != serialB:\n\t\treturn serialA < serialB\n\tdefault:\n\t\treturn bytes.Compare(t[i].TRC.Raw, t[j].TRC.Raw) == -1\n\t}\n}", "func (shelf *Shelf) Less(i, j int) bool {\n\treturn shelf.queue[i].Deadline(shelf.decayModifier).Before(shelf.queue[j].Deadline(shelf.decayModifier))\n}", "func Lt(val, max any) bool { return valueCompare(val, max, \"<\") }", "func (sv *sorterValues) Less(i, j int) bool {\n\tri := sv.rows[i]\n\trj := sv.rows[j]\n\n\treturn sv.invertSorting != sv.RowLess(ri, rj)\n}", "func (a Uint64) Less(b btree.Item) bool {\n\treturn a < b.(Uint64)\n}", "func (s orderedItems) Less(i, j int) bool {\n\treturn s[i].Compare(s[j]) > 0\n}", "func (h PatchPriority) Less(i, j int) bool { return h[i].priority > h[j].priority }", "func (es Envelopes) Less(i, j int) bool {\n\treturn (es[i].w < es[j].w) || (es[i].w == es[j].w && es[i].h >= es[j].h)\n}", "func Lss(x, y reflect.Value) reflect.Value {\n\tmustSameType(x, y)\n\tz := reflect.New(reflect.TypeOf(false)).Elem()\n\tswitch x.Type().Kind() {\n\tcase reflect.Int:\n\t\txx := int(x.Int())\n\t\tyy := int(y.Int())\n\t\tzz := xx < yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Int8:\n\t\txx := int8(x.Int())\n\t\tyy := int8(y.Int())\n\t\tzz := xx < yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Int16:\n\t\txx := int16(x.Int())\n\t\tyy := int16(y.Int())\n\t\tzz := xx < yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Int32:\n\t\txx := int32(x.Int())\n\t\tyy := int32(y.Int())\n\t\tzz := xx < yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Int64:\n\t\txx := int64(x.Int())\n\t\tyy := int64(y.Int())\n\t\tzz := xx < yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Uint:\n\t\txx := uint(x.Uint())\n\t\tyy := uint(y.Uint())\n\t\tzz := xx < yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Uint8:\n\t\txx := uint8(x.Uint())\n\t\tyy := uint8(y.Uint())\n\t\tzz := xx < yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Uint16:\n\t\txx := uint16(x.Uint())\n\t\tyy := uint16(y.Uint())\n\t\tzz := xx < yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Uint32:\n\t\txx := uint32(x.Uint())\n\t\tyy := uint32(y.Uint())\n\t\tzz := xx < yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Uint64:\n\t\txx := uint64(x.Uint())\n\t\tyy := uint64(y.Uint())\n\t\tzz := xx < yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Uintptr:\n\t\txx := uintptr(x.Uint())\n\t\tyy := uintptr(y.Uint())\n\t\tzz := xx < yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Float32:\n\t\txx := float32(x.Float())\n\t\tyy := float32(y.Float())\n\t\tzz := xx < yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Float64:\n\t\txx := float64(x.Float())\n\t\tyy := float64(y.Float())\n\t\tzz := xx < yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.String:\n\t\txx := string(x.String())\n\t\tyy := string(y.String())\n\t\tzz := xx < yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\t}\n\tpanic(fmt.Sprintf(\"operator < not defined on %v\", x.Type()))\n}", "func (me TComparator) IsLessThan() bool { return me.String() == \"LessThan\" }", "func (lis Config) Less(i, j int) bool {\n\treturn lis[i].Space < lis[j].Space\n}", "func (c UintEnumCompare) IsLess(nLHS int, lhs uint, nRHS int, rhs uint) bool {\n\treturn c(nLHS, lhs, nRHS, rhs)\n}", "func lt128(a0, a1, b0, b1 uint64) bool {\n\treturn (a0 < b0) || ((a0 == b0) && (a1 < b1))\n}", "func (c card) less(d card) bool {\n\tif c.number != d.number {\n\t\treturn c.number < d.number\n\t} else {\n\t\treturn c.suit < d.suit\n\t}\n}", "func (a Value) Less(b Value) bool {\n\treturn a.Compare(b) < 0\n}", "func (z ByRR) Less(i, j int) bool {\n\treturn z.Compare(i, j) < 0\n}", "func (h Header) Rsv1() bool { return h.Rsv&bit5 != 0 }", "func (me TxsdConfidenceRating) IsHigh() bool { return me.String() == \"high\" }", "func (a *Pair) Less (b *Pair) bool {\n return a.x < b.x\n}", "func IsLowerRight(key uint32) bool {\n\treturn ((key & 0x30) == 0x30)\n}", "func LeFn(a interface{}, b interface{}) bool {\n\treturn a.(float64) <= b.(float64)\n}", "func (hp theHeap) Less(i, j int) bool {\n\treturn hp[i].d > hp[j].d\n}", "func (v *RelaxedVersion) LessThan(u *RelaxedVersion) bool {\n\treturn v.CompareTo(u) < 0\n}", "func (id Identifier) IsLarger(b Identifier) bool {\n\treturn bytes.Compare(id, b) == 1\n}", "func opUI16Lt(prgrm *CXProgram) {\n\texpr := prgrm.GetExpr()\n\tfp := prgrm.GetFramePointer()\n\n\toutV0 := ReadUI16(fp, expr.Inputs[0]) < ReadUI16(fp, expr.Inputs[1])\n\tWriteBool(GetFinalOffset(fp, expr.Outputs[0]), outV0)\n}", "func (s FeedItems) Less(i, j int) bool {\n\treturn s[i].Score < s[i].Score\n}", "func isNodeWithLowUtilization(usage NodeUsage) bool {\n\tfor name, nodeValue := range usage.usage {\n\t\t// usage.lowResourceThreshold[name] < nodeValue\n\t\tif usage.lowResourceThreshold[name].Cmp(*nodeValue) == -1 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func LE(x float64, y float64) bool {\n\treturn (x < y+e)\n}", "func (p *ProgramHeader) IsLX() bool {\n\treturn p.Signature[0] == 'L' && p.Signature[1] == 'X'\n}", "func (p *Pairs)Less(i, j int) bool {\n\treturn p.pairs[i][0] + p.pairs[i][1] > p.pairs[j][0] + p.pairs[j][1]\n}", "func isLeftHand(k int) bool { return k < 21 }", "func (t toc) Less(i, j int) bool {\n\treturn t[i].value < t[j].value\n}", "func softfloat_le128(a64, a0, b64, b0 uint64) bool {\n\treturn (a64 < b64) || ((a64 == b64) && (a0 <= b0))\n}", "func (tp *TextPos) IsLess(cmp TextPos) bool {\n\tswitch {\n\tcase tp.Ln < cmp.Ln:\n\t\treturn true\n\tcase tp.Ln == cmp.Ln:\n\t\treturn tp.Ch < cmp.Ch\n\tdefault:\n\t\treturn false\n\t}\n}", "func (a *_Atom) isHydroxyl() bool {\n\treturn a.atNum == 8 && a.hCount == 1\n}", "func isLt(fl FieldLevel) bool {\n\tfield := fl.Field()\n\tparam := fl.Param()\n\n\tswitch field.Kind() {\n\n\tcase reflect.String:\n\t\tp := asInt(param)\n\n\t\treturn int64(utf8.RuneCountInString(field.String())) < p\n\n\tcase reflect.Slice, reflect.Map, reflect.Array:\n\t\tp := asInt(param)\n\n\t\treturn int64(field.Len()) < p\n\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\tp := asIntFromType(field.Type(), param)\n\n\t\treturn field.Int() < p\n\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\tp := asUint(param)\n\n\t\treturn field.Uint() < p\n\n\tcase reflect.Float32, reflect.Float64:\n\t\tp := asFloat(param)\n\n\t\treturn field.Float() < p\n\n\tcase reflect.Struct:\n\n\t\tif field.Type().ConvertibleTo(timeType) {\n\n\t\t\treturn field.Convert(timeType).Interface().(time.Time).Before(time.Now().UTC())\n\t\t}\n\t}\n\n\tpanic(fmt.Sprintf(\"Bad field type %T\", field.Interface()))\n}", "func (k KernSubtable) IsHorizontal() bool {\n\treturn k.coverage&kerxVertical == 0\n}", "func (v *intChain) IsLess(comp int) IntChainer {\n f := func() bool { \n return v.Num < comp\n }\n v.chains = append(v.chains, f)\n\n return v\n}", "func LTInt(v2, v1 int) bool {\n\treturn v2 < v1\n}" ]
[ "0.5621557", "0.5612528", "0.5612528", "0.55929005", "0.5556854", "0.54670167", "0.54621255", "0.54328775", "0.54264414", "0.53702646", "0.53523916", "0.52703273", "0.5261488", "0.5219022", "0.51695013", "0.5155582", "0.51494825", "0.51494825", "0.51494825", "0.5135328", "0.5134709", "0.5133051", "0.51253647", "0.5107417", "0.5104107", "0.50998366", "0.5088262", "0.5079019", "0.5077033", "0.5064268", "0.50621426", "0.5037708", "0.50373", "0.50187415", "0.5006607", "0.50004685", "0.4998081", "0.49963585", "0.49963325", "0.4995592", "0.49934545", "0.49932894", "0.4989313", "0.4985889", "0.49760878", "0.49724296", "0.49524722", "0.49524722", "0.494709", "0.49367565", "0.493608", "0.49312654", "0.49292728", "0.49248406", "0.49213386", "0.49109298", "0.491034", "0.49057657", "0.49013627", "0.49009004", "0.48995084", "0.48988402", "0.48919904", "0.48906672", "0.4884127", "0.48831207", "0.48825932", "0.48761296", "0.4875139", "0.48747295", "0.48708272", "0.48681015", "0.4863497", "0.48626122", "0.48613608", "0.48555598", "0.48501575", "0.48445255", "0.48409984", "0.48359317", "0.48261076", "0.48260185", "0.4821951", "0.48212978", "0.48198488", "0.4812018", "0.4811629", "0.48040304", "0.48024982", "0.48022076", "0.47960502", "0.47897893", "0.47854835", "0.4785109", "0.4783745", "0.47804636", "0.477969", "0.47783676", "0.4776891", "0.47674382" ]
0.5042559
31
Returns True if this Tuple is elementwise less than other
func (this *Tuple) Lt(other *Tuple) bool { tlen, olen := this.Len(), other.Len() var n int if tlen < olen { n = tlen } else { n = olen } for i := 0; i < n; i++ { lhsi, rhsi := this.Get(i), other.Get(i) if TupleElemLt(lhsi, rhsi) { return true } else if !TupleElemEq(lhsi, rhsi) { return false } } // if we get here then they matched up to n if tlen < olen { return true } return false }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a *Pair) Less (b *Pair) bool {\n return a.x < b.x\n}", "func TupleElemLt(lhsi interface{}, rhsi interface{}) bool {\n\tlhsv, rhsv := reflect.ValueOf(lhsi), reflect.ValueOf(rhsi)\n\tif lhsv.IsValid() && !rhsv.IsValid() {\n\t\t// zero value is considered least\n\t\treturn false\n\t}\n\tswitch lhsi.(type) {\n\tcase nil:\n\t\tif rhsv.IsValid() {\n\t\t\treturn true\n\t\t}\n\tcase string:\n\t\tif lhsi.(string) < rhsi.(string) {\n\t\t\treturn true\n\t\t}\n\tcase int, int8, int16, int32, int64:\n\t\tif lhsv.Int() < rhsv.Int() {\n\t\t\treturn true\n\t\t}\n\tcase uint, uintptr, uint8, uint16, uint32, uint64:\n\t\tif lhsv.Uint() < rhsv.Uint() {\n\t\t\treturn true\n\t\t}\n\tcase float32, float64:\n\t\tif lhsv.Float() < rhsv.Float() {\n\t\t\treturn true\n\t\t}\n\tcase *Tuple:\n\t\tif lhsi.(*Tuple).Lt(rhsi.(*Tuple)) {\n\t\t\treturn true\n\t\t}\n\tdefault:\n\t\t// TODO: allow user-defined callback for unsupported types\n\t\tpanic(fmt.Sprintf(\"unsupported type %#v for Lt in Tuple\", lhsi))\n\t}\n\treturn false\n}", "func (this *Tuple) Le(other *Tuple) bool {\n\treturn this.Lt(other) || this.Eq(other)\n}", "func (k *joinKey) less(other joinKey) bool {\n\ta, b := k, other\n\tfor i := 0; i < len(k.values); i++ {\n\t\tif b.values[i].IsNull() {\n\t\t\treturn true\n\t\t} else if a.values[i].IsNull() {\n\t\t\treturn false\n\t\t}\n\n\t\tswitch a.columns[i].Type {\n\t\tcase flux.TBool:\n\t\t\tif av, bv := a.values[i].Bool(), b.values[i].Bool(); av != bv {\n\t\t\t\treturn bv\n\t\t\t}\n\t\tcase flux.TInt:\n\t\t\tif av, bv := a.values[i].Int(), b.values[i].Int(); av != bv {\n\t\t\t\treturn av < bv\n\t\t\t}\n\t\tcase flux.TUInt:\n\t\t\tif av, bv := a.values[i].UInt(), b.values[i].UInt(); av != bv {\n\t\t\t\treturn av < bv\n\t\t\t}\n\t\tcase flux.TFloat:\n\t\t\tif av, bv := a.values[i].Float(), b.values[i].Float(); av != bv {\n\t\t\t\treturn av < bv\n\t\t\t}\n\t\tcase flux.TString:\n\t\t\tif av, bv := a.values[i].Str(), b.values[i].Str(); av != bv {\n\t\t\t\treturn av < bv\n\t\t\t}\n\t\tcase flux.TTime:\n\t\t\tif av, bv := a.values[i].Time(), b.values[i].Time(); av != bv {\n\t\t\t\treturn av < bv\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func (a Vec2) Less(b Vec2) bool {\n\treturn a.X < b.X && a.Y < b.Y\n}", "func (p *Pairs)Less(i, j int) bool {\n\treturn p.pairs[i][0] + p.pairs[i][1] > p.pairs[j][0] + p.pairs[j][1]\n}", "func (i Int) LT(i2 Int) bool {\n\treturn lt(i.i, i2.i)\n}", "func (this *Tuple) Ge(other *Tuple) bool {\n\treturn !this.Lt(other)\n}", "func (n *Node) isLessThan(other *Node) bool {\n\treturn n.val.IsLessThan(other.val)\n}", "func (a Vec2) AnyLess(b Vec2) bool {\n\treturn a.X < b.X || a.Y < b.Y\n}", "func (i1 Int) Less(i2 freetree.Comparable) bool { return i1 < i2.(Int) }", "func (c Int32Compare) IsLess(lhs, rhs int32) bool { return c(lhs, rhs) }", "func (c UintCompare) IsLess(lhs, rhs uint) bool { return c(lhs, rhs) }", "func (x uints) Less(i, j int) bool { return x[i] < x[j] }", "func (x uints) Less(i, j int) bool { return x[i] < x[j] }", "func (x uints) Less(i, j int) bool { return x[i] < x[j] }", "func (t toc) Less(i, j int) bool {\n\treturn t[i].value < t[j].value\n}", "func (h PerformanceHeap) Less(i, j int) bool {\n\treturn h.items[i].event.Timestamp.Before(h.items[j].event.Timestamp)\n}", "func (v ResourceNodes) Less(i, j int) bool {\n\treturn v[i].Tokens.LT(v[j].Tokens)\n}", "func (h tsHeap) Less(i, j int) bool {\n\treturn h[i].ts.Less(h[j].ts)\n}", "func (b buffer) Less(i, j int) bool {\n\treturn compareByFirstOrNextValue(b[i], b[j]) < 0\n}", "func (eps Accuracy) Less(a, b float64) bool {\n\treturn math.Max(a, b) == b && math.Abs(a-b) > eps()\n}", "func (e *ConstantExpr) Slt(other *ConstantExpr) *ConstantExpr {\n\tswitch e.Width {\n\tcase Width8:\n\t\treturn NewBoolConstantExpr(int8(e.Value) < int8(other.Value))\n\tcase Width16:\n\t\treturn NewBoolConstantExpr(int16(e.Value) < int16(other.Value))\n\tcase Width32:\n\t\treturn NewBoolConstantExpr(int32(e.Value) < int32(other.Value))\n\tcase Width64:\n\t\treturn NewBoolConstantExpr(int64(e.Value) < int64(other.Value))\n\tdefault:\n\t\tpanic(\"slt: non-standard width\")\n\t}\n}", "func (h ReqHeap) Less(i, j int) bool { return h[i].Timestamp.Before(h[j].Timestamp) }", "func (i *info) less(b *info) bool {\n\tswitch t := i.Val.(type) {\n\tcase int64:\n\t\treturn t < b.Val.(int64)\n\tcase float64:\n\t\treturn t < b.Val.(float64)\n\tcase string:\n\t\treturn t < b.Val.(string)\n\tdefault:\n\t\tif ord, ok := i.Val.(util.Ordered); ok {\n\t\t\treturn ord.Less(b.Val.(util.Ordered))\n\t\t}\n\t\tlog.Fatalf(\"unhandled info value type: %s\", t)\n\t}\n\treturn false\n}", "func (a Balance) Less(b Balance) bool {\n\tfor i, valA := range a {\n\t\tvalB := b[i]\n\t\tif valA < valB {\n\t\t\treturn true\n\t\t}\n\t\tif valB < valA {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn false\n}", "func (es Events) Less(i, j int) bool {\n\treturn es[i].Time < es[j].Time\n}", "func (b timeOrd) Less(i, j int) bool {\n\tif b[i].next.IsZero() {\n\t\treturn false\n\t}\n\tif b[j].next.IsZero() {\n\t\treturn true\n\t}\n\treturn b[i].next.Before(b[j].next)\n}", "func (p byPoints) Less(i, j int) bool {\n\t// 4 is actually less than anything else\n\tif p[i] == 4 {\n\t\treturn true\n\t}\n\treturn p[i] < p[j]\n}", "func (ce ChangesetEvents) Less(i, j int) bool {\n\treturn ce[i].Timestamp().Before(ce[j].Timestamp())\n}", "func (t Targets) IsLess(o Targets) bool {\n\tif len(t) < len(o) {\n\t\treturn true\n\t}\n\tif len(t) > len(o) {\n\t\treturn false\n\t}\n\n\tsort.Sort(t)\n\tsort.Sort(o)\n\n\tfor i, e := range t {\n\t\tif e != o[i] {\n\t\t\treturn e < o[i]\n\t\t}\n\t}\n\treturn false\n}", "func (h *Heap) Less(i, j int) bool {\n\t// We have a minHeap, which means top record is a record with a lowest distance\n\treturn h.slice[i].distance < h.slice[j].distance\n}", "func LT(x float64, y float64) bool {\n\treturn (x < y-e)\n}", "func (s Migrations) Less(i, j int) bool {\n\tiTag, err := semver.Make(s[i].Tag)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tjTag, err := semver.Make(s[j].Tag)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn iTag.LT(jTag)\n}", "func (qt QueryTimes) Less(i, j int) bool { return qt[i] < qt[j] }", "func (id NodeID) Less(other NodeID) bool {\n\tfor k, v := range id {\n\t\tif v < other[k] {\n\t\t\treturn true\n\t\t} else if v > other[k] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn false\n}", "func (elems Elements) Less(i, j int) bool {\n\tif elems[i].Pos.Less(elems[j].Pos) {\n\t\treturn true\n\t}\n\tif elems[i].Pos.Equals(elems[j].Pos) {\n\t\treturn elems[i].Kind < elems[j].Kind\n\t}\n\treturn false\n}", "func (a point) Less(b point) bool {\n\tcmp := a.ip.Compare(b.ip)\n\tif cmp != 0 {\n\t\treturn cmp < 0\n\t}\n\tif a.want != b.want {\n\t\tif a.start == b.start {\n\t\t\treturn !a.want\n\t\t}\n\t\treturn a.start\n\t}\n\tif a.start != b.start {\n\t\treturn a.start\n\t}\n\treturn false\n}", "func (gdt *Vector3) OperatorLess(b Vector3) Bool {\n\targ0 := gdt.getBase()\n\targ1 := b.getBase()\n\n\tret := C.go_godot_vector3_operator_less(GDNative.api, arg0, arg1)\n\n\treturn Bool(ret)\n}", "func (s VectorClock) LessThan(otherClock VectorClock) bool {\n\tpanic(\"todo\")\n}", "func (pq priorityQueue) Less(i, j int) bool {\n\treturn pq[i].time.Before(pq[j].time)\n}", "func (es Envelopes) Less(i, j int) bool {\n\treturn (es[i].w < es[j].w) || (es[i].w == es[j].w && es[i].h >= es[j].h)\n}", "func less(c1, c2 cost) bool {\n\tswitch {\n\tcase c1.opCode != c2.opCode:\n\t\treturn c1.opCode < c2.opCode\n\tcase c1.isUnique == c2.isUnique:\n\t\treturn c1.vindexCost <= c2.vindexCost\n\tdefault:\n\t\treturn c1.isUnique\n\t}\n}", "func (b *Bucket) less(r *Bucket) bool {\n\tif b.First || r.First {\n\t\treturn b.First\n\t}\n\treturn b.Signature.less(&r.Signature)\n}", "func (e *ConstantExpr) Ult(other *ConstantExpr) *ConstantExpr {\n\tswitch e.Width {\n\tcase Width8:\n\t\treturn NewBoolConstantExpr(uint8(e.Value) < uint8(other.Value))\n\tcase Width16:\n\t\treturn NewBoolConstantExpr(uint16(e.Value) < uint16(other.Value))\n\tcase Width32:\n\t\treturn NewBoolConstantExpr(uint32(e.Value) < uint32(other.Value))\n\tcase Width64:\n\t\treturn NewBoolConstantExpr(uint64(e.Value) < uint64(other.Value))\n\tdefault:\n\t\tpanic(\"ult: non-standard width\")\n\t}\n}", "func (pq PriorityQueue) Less(i, j int) bool {\n\treturn pq[i].diff > pq[j].diff\n}", "func (o *OrderedSynchronizer) Less(i, j int) bool {\n\treturn o.compareRow(o.heap[i], o.heap[j]) < 0\n}", "func (e *Edge) Less(other Edge) bool {\n\treturn e.weight < other.weight\n}", "func (c *comparables) Less(i, j int) bool {\n\treturn c.IsLess(c.values[i], c.values[j])\n}", "func (k KeyTok) Less(other KeyTok) bool {\n\tif k.Kind < other.Kind {\n\t\treturn true\n\t} else if k.Kind > other.Kind {\n\t\treturn false\n\t}\n\ta, b := k.ID(), other.ID()\n\treturn a.Less(&b)\n}", "func (s *GoSort) LessThan(i, j int) bool {\n return s.comparator(s.values[i], s.values[j]) == -1\n}", "func (x circle) Less(i, j int) bool { return x[i] < x[j] }", "func (ei *ByIntervalTicks) Less(i, j int) bool {\n\tcursorI := i * ei.recordLength\n\tcursorJ := j * ei.recordLength\n\n\tintervalTicksI := io.ToUInt32(ei.buffer[cursorI+ei.recordLength-4 : cursorI+ei.recordLength])\n\tintervalTicksJ := io.ToUInt32(ei.buffer[cursorJ+ei.recordLength-4 : cursorJ+ei.recordLength])\n\n\treturn intervalTicksI < intervalTicksJ\n}", "func (ei *ByIntervalTicks) Less(i, j int) bool {\n\tcursor_i := i * ei.recordLength\n\tcursor_j := j * ei.recordLength\n\n\tintervalTicks_i := io.ToUInt32(ei.buffer[cursor_i+ei.recordLength-4 : cursor_i+ei.recordLength])\n\tintervalTicks_j := io.ToUInt32(ei.buffer[cursor_j+ei.recordLength-4 : cursor_j+ei.recordLength])\n\n\treturn intervalTicks_i < intervalTicks_j\n}", "func (a Value) Less(b Value) bool {\n\treturn a.Compare(b) < 0\n}", "func lessWordPair(x, y interface{}) bool\t{ return x.(*wordPair).canon < y.(*wordPair).canon }", "func lessByDelta(i, j BenchCmp, calcDelta func(BenchCmp) Delta) bool {\n\tiDelta, jDelta := calcDelta(i).mag(), calcDelta(j).mag()\n\tif iDelta != jDelta {\n\t\treturn iDelta < jDelta\n\t}\n\treturn i.Name() < j.Name()\n}", "func (v Set) Less(i, j int) bool { return v[i].Cmp(v[j]) < 0 }", "func (a Uint64) Less(b btree.Item) bool {\n\treturn a < b.(Uint64)\n}", "func (b Buildings) Less(i, j int) bool {\n\treturn b[i].Left < b[j].Left\n}", "func (es entries) Less(i, j int) bool {\n\treturn es[i].int > es[j].int\n}", "func (c UintEnumCompare) IsLess(nLHS int, lhs uint, nRHS int, rhs uint) bool {\n\treturn c(nLHS, lhs, nRHS, rhs)\n}", "func (rows byLatency) Less(i, j int) bool {\n\treturn rows[i].SumTimerWait > rows[j].SumTimerWait\n}", "func LE(x float64, y float64) bool {\n\treturn (x < y+e)\n}", "func tsLess(a, b types.TS) bool { return bytes.Compare(a[:], b[:]) < 0 }", "func (iheap IntegerHeap) Less(i, j int) bool {\n\treturn iheap[i] < iheap[j]\n}", "func (iheap IntegerHeap) Less(i, j int) bool {\n\treturn iheap[i] < iheap[j]\n}", "func (a Vertex) Less(b Vertex) bool {\n\tfor i := range a.pos {\n\t\tswitch {\n\t\tcase a.pos[i] < b.pos[i]:\n\t\t\treturn true\n\t\tcase a.pos[i] > b.pos[i]:\n\t\t\treturn false\n\t\t}\n\t}\n\tfor i := range a.color {\n\t\tswitch {\n\t\tcase a.color[i] < b.color[i]:\n\t\t\treturn true\n\t\tcase a.color[i] > b.color[i]:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn false\n}", "func (tiles Tiles) Less(i, j int) bool {\n\ttile1 := tiles[i]\n\ttile2 := tiles[j]\n\treturn CompareTiles(tile1, tile2) < 0\n}", "func (durs ByFirstEntered) Less(i, j int) bool {\n\treturn durs[i].FirstEntered.Before(durs[j].FirstEntered)\n}", "func (me TComparator) IsLessThan() bool { return me.String() == \"LessThan\" }", "func (s ElementSlice) Less (i, j int) bool {\n return (&s[i]).Less(&s[j])\n}", "func (h *Queue) Less(i, j int) bool {\n\t// We have a minHeap, which means top record is a record with a lowest distance\n\treturn h.slice[i].Estimate < h.slice[j].Estimate\n}", "func (s FeedItems) Less(i, j int) bool {\n\treturn s[i].Score < s[i].Score\n}", "func (ca ComparableArray) Less(i, j int) bool { return ca[i].Less(ca[j]) }", "func (s *SortableStruct) Less(other interface{}) bool {\n\totherss, ok := other.(*SortableStruct)\n\tif !ok {\n\t\tlog.Printf(\"Type assertion failed in SortableStruct; got other of type %#v\", other)\n\t\treturn true\n\t}\n\tres := s.Val < otherss.Val\n\treturn res\n}", "func (this FeedQueue) Less(i, j int) bool {\n\treturn this[i].score > this[j].score\n}", "func (order Order) LessThan(other Order) bool {\n\treturn order.Price < other.Price\n}", "func (n Interviews) Less(i, j int) bool {\n\treturn n[i].Time.Before(n[j].Time)\n}", "func EntryLess(i, j *spb.Entry) bool {\n\treturn EntryCompare(i, j) == LT\n}", "func (h minPath) Less(i, j int) bool {\n\treturn h[i].value < h[j].value\n}", "func (h nodeList) Less(i, j int) bool {\n\treturn h[i].hash < h[j].hash\n}", "func (pq PrioQueue) Less(i, j int) bool {\n\treturn pq[j].IsLongerThan(pq[i])\n}", "func (r *PartitionItem) Less(other btree.Item) bool {\n\tleft := r.partition.StartSlot\n\tright := other.(*PartitionItem).partition.StartSlot\n\t//return bytes.Compare(left, right) > 0\n\treturn left > right\n}", "func (r RuneList) Less(i int, j int) bool {\n\treturn r[i] < r[j]\n}", "func (t stakeTicketSorter) Less(i, j int) bool {\n\tiHash := t[i].tx.CachedTxHash()[:]\n\tjHash := t[j].tx.CachedTxHash()[:]\n\treturn bytes.Compare(iHash, jHash) < 0\n}", "func (pq PriorityQueue) Less(i, j int) bool {\n\t// If risks are different, use that for comparisons first.\n\tif pq[i].MinCost != pq[j].MinCost {\n\t\treturn pq[i].MinCost < pq[j].MinCost\n\t}\n\t// Use x + y values now.\n\tdi := pq[i].Loc.X + pq[i].Loc.Y\n\tdj := pq[j].Loc.X + pq[j].Loc.Y\n\tif di != dj {\n\t\treturn di < dj\n\t}\n\t// further left first, then further up.\n\treturn pq[i].Loc.X < pq[j].Loc.X || pq[i].Loc.Y < pq[j].Loc.Y\n}", "func (s MsgFormats) Less(i, j int) bool {\n\treturn s[i].SendTime < s[j].SendTime\n}", "func (t Task) IsLessThan(t2 Task) bool {\n if t.IsDoneNow() && !t2.IsDoneNow() {\n return false\n } else if !t.IsDoneNow() && t2.IsDoneNow() {\n return true\n }\n\n switch {\n case t.UserDueDate != t2.UserDueDate:\n return t.UserDueDate.Before(t2.UserDueDate)\n case t.Group != t2.Group:\n return t.Group < t2.Group\n default:\n return t.Name < t2.Name\n }\n}", "func (q *taskQueue) Less(i, j int) bool {\n\treturn q.tasks[i].RelativeTimestamp < q.tasks[j].RelativeTimestamp\n}", "func (a Int) Less(b Item) bool {\n return a < b.(Int)\n}", "func lt(lhs, rhs semantic.Expression) semantic.Expression {\n\treturn &semantic.BinaryOp{Type: semantic.BoolType, LHS: lhs, Operator: ast.OpLT, RHS: rhs}\n}", "func (p priorities) Less(i, j int) bool { return p[i] < p[j] }", "func (l DNA8List) Less(i, j int) bool { return l[i].Cmp(l[j]) < 0 }", "func (sr ScoredRange) Less(i, j int) bool { return sr[i].Score < sr[j].Score }", "func (a nodesInRequestOrder) Less(i, j int) bool { return a[i] < a[j] }", "func (pq priorityQueue) Less(i, j int) bool {\n\treturn pq[i].key < pq[j].key\n}", "func (a Tags) Less(i, j int) bool { return a[i].Version.GT(a[j].Version) }", "func (p *IntVector) Less(i, j int) bool\t{ return p.At(i) < p.At(j) }", "func (s *PointArrayMem) Less(i, j int) bool {\n\treturn s.points[i].Vals[s.byDim] < s.points[j].Vals[s.byDim]\n}" ]
[ "0.7582022", "0.7109866", "0.6894591", "0.6656535", "0.6587677", "0.65269125", "0.6474057", "0.6442686", "0.6441735", "0.6368265", "0.6335162", "0.63168746", "0.6275633", "0.6260398", "0.6260398", "0.6260398", "0.62527585", "0.62508184", "0.62507343", "0.62478435", "0.61915374", "0.6170371", "0.616981", "0.6164599", "0.61629", "0.61559314", "0.61337894", "0.61021084", "0.6071712", "0.60689056", "0.6064339", "0.6060495", "0.6059488", "0.60544324", "0.6032784", "0.599914", "0.59882945", "0.59798485", "0.59792006", "0.5973786", "0.59585226", "0.59514946", "0.5945506", "0.59366715", "0.5933275", "0.59225756", "0.5918867", "0.59186757", "0.5913915", "0.58968955", "0.589315", "0.58879197", "0.58857197", "0.5882234", "0.5881363", "0.58802813", "0.58749866", "0.5864259", "0.5862335", "0.58607906", "0.58428425", "0.5830869", "0.5826431", "0.58181745", "0.5807869", "0.57955545", "0.57955545", "0.5795324", "0.57895184", "0.57839704", "0.5776155", "0.57717466", "0.5771712", "0.57567525", "0.5751306", "0.5747127", "0.5746106", "0.5744014", "0.574395", "0.5741225", "0.57219344", "0.57172006", "0.57110846", "0.57084274", "0.569803", "0.5696704", "0.5689533", "0.5686941", "0.56776994", "0.56675327", "0.5664855", "0.56617516", "0.5650084", "0.56499803", "0.56483996", "0.56429946", "0.5642915", "0.56345606", "0.563169", "0.56310314" ]
0.6120704
27
Returns True if this Tuple is elementwise less than or equal to other
func (this *Tuple) Le(other *Tuple) bool { return this.Lt(other) || this.Eq(other) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a *Pair) Less (b *Pair) bool {\n return a.x < b.x\n}", "func TupleElemLt(lhsi interface{}, rhsi interface{}) bool {\n\tlhsv, rhsv := reflect.ValueOf(lhsi), reflect.ValueOf(rhsi)\n\tif lhsv.IsValid() && !rhsv.IsValid() {\n\t\t// zero value is considered least\n\t\treturn false\n\t}\n\tswitch lhsi.(type) {\n\tcase nil:\n\t\tif rhsv.IsValid() {\n\t\t\treturn true\n\t\t}\n\tcase string:\n\t\tif lhsi.(string) < rhsi.(string) {\n\t\t\treturn true\n\t\t}\n\tcase int, int8, int16, int32, int64:\n\t\tif lhsv.Int() < rhsv.Int() {\n\t\t\treturn true\n\t\t}\n\tcase uint, uintptr, uint8, uint16, uint32, uint64:\n\t\tif lhsv.Uint() < rhsv.Uint() {\n\t\t\treturn true\n\t\t}\n\tcase float32, float64:\n\t\tif lhsv.Float() < rhsv.Float() {\n\t\t\treturn true\n\t\t}\n\tcase *Tuple:\n\t\tif lhsi.(*Tuple).Lt(rhsi.(*Tuple)) {\n\t\t\treturn true\n\t\t}\n\tdefault:\n\t\t// TODO: allow user-defined callback for unsupported types\n\t\tpanic(fmt.Sprintf(\"unsupported type %#v for Lt in Tuple\", lhsi))\n\t}\n\treturn false\n}", "func (k *joinKey) less(other joinKey) bool {\n\ta, b := k, other\n\tfor i := 0; i < len(k.values); i++ {\n\t\tif b.values[i].IsNull() {\n\t\t\treturn true\n\t\t} else if a.values[i].IsNull() {\n\t\t\treturn false\n\t\t}\n\n\t\tswitch a.columns[i].Type {\n\t\tcase flux.TBool:\n\t\t\tif av, bv := a.values[i].Bool(), b.values[i].Bool(); av != bv {\n\t\t\t\treturn bv\n\t\t\t}\n\t\tcase flux.TInt:\n\t\t\tif av, bv := a.values[i].Int(), b.values[i].Int(); av != bv {\n\t\t\t\treturn av < bv\n\t\t\t}\n\t\tcase flux.TUInt:\n\t\t\tif av, bv := a.values[i].UInt(), b.values[i].UInt(); av != bv {\n\t\t\t\treturn av < bv\n\t\t\t}\n\t\tcase flux.TFloat:\n\t\t\tif av, bv := a.values[i].Float(), b.values[i].Float(); av != bv {\n\t\t\t\treturn av < bv\n\t\t\t}\n\t\tcase flux.TString:\n\t\t\tif av, bv := a.values[i].Str(), b.values[i].Str(); av != bv {\n\t\t\t\treturn av < bv\n\t\t\t}\n\t\tcase flux.TTime:\n\t\t\tif av, bv := a.values[i].Time(), b.values[i].Time(); av != bv {\n\t\t\t\treturn av < bv\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func (p *Pairs)Less(i, j int) bool {\n\treturn p.pairs[i][0] + p.pairs[i][1] > p.pairs[j][0] + p.pairs[j][1]\n}", "func (this *Tuple) Ge(other *Tuple) bool {\n\treturn !this.Lt(other)\n}", "func (a Vec2) Less(b Vec2) bool {\n\treturn a.X < b.X && a.Y < b.Y\n}", "func (i Int) LT(i2 Int) bool {\n\treturn lt(i.i, i2.i)\n}", "func (n *Node) isLessThan(other *Node) bool {\n\treturn n.val.IsLessThan(other.val)\n}", "func (i1 Int) Less(i2 freetree.Comparable) bool { return i1 < i2.(Int) }", "func (a Vec2) AnyLess(b Vec2) bool {\n\treturn a.X < b.X || a.Y < b.Y\n}", "func (c Int32Compare) IsLess(lhs, rhs int32) bool { return c(lhs, rhs) }", "func (c UintCompare) IsLess(lhs, rhs uint) bool { return c(lhs, rhs) }", "func (a Balance) Less(b Balance) bool {\n\tfor i, valA := range a {\n\t\tvalB := b[i]\n\t\tif valA < valB {\n\t\t\treturn true\n\t\t}\n\t\tif valB < valA {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn false\n}", "func (t toc) Less(i, j int) bool {\n\treturn t[i].value < t[j].value\n}", "func (e *ConstantExpr) Slt(other *ConstantExpr) *ConstantExpr {\n\tswitch e.Width {\n\tcase Width8:\n\t\treturn NewBoolConstantExpr(int8(e.Value) < int8(other.Value))\n\tcase Width16:\n\t\treturn NewBoolConstantExpr(int16(e.Value) < int16(other.Value))\n\tcase Width32:\n\t\treturn NewBoolConstantExpr(int32(e.Value) < int32(other.Value))\n\tcase Width64:\n\t\treturn NewBoolConstantExpr(int64(e.Value) < int64(other.Value))\n\tdefault:\n\t\tpanic(\"slt: non-standard width\")\n\t}\n}", "func (eps Accuracy) Less(a, b float64) bool {\n\treturn math.Max(a, b) == b && math.Abs(a-b) > eps()\n}", "func (x uints) Less(i, j int) bool { return x[i] < x[j] }", "func (x uints) Less(i, j int) bool { return x[i] < x[j] }", "func (x uints) Less(i, j int) bool { return x[i] < x[j] }", "func (b buffer) Less(i, j int) bool {\n\treturn compareByFirstOrNextValue(b[i], b[j]) < 0\n}", "func (h tsHeap) Less(i, j int) bool {\n\treturn h[i].ts.Less(h[j].ts)\n}", "func (i *info) less(b *info) bool {\n\tswitch t := i.Val.(type) {\n\tcase int64:\n\t\treturn t < b.Val.(int64)\n\tcase float64:\n\t\treturn t < b.Val.(float64)\n\tcase string:\n\t\treturn t < b.Val.(string)\n\tdefault:\n\t\tif ord, ok := i.Val.(util.Ordered); ok {\n\t\t\treturn ord.Less(b.Val.(util.Ordered))\n\t\t}\n\t\tlog.Fatalf(\"unhandled info value type: %s\", t)\n\t}\n\treturn false\n}", "func (v ResourceNodes) Less(i, j int) bool {\n\treturn v[i].Tokens.LT(v[j].Tokens)\n}", "func (this *Tuple) Lt(other *Tuple) bool {\n\ttlen, olen := this.Len(), other.Len()\n\tvar n int\n\tif tlen < olen {\n\t\tn = tlen\n\t} else {\n\t\tn = olen\n\t}\n\tfor i := 0; i < n; i++ {\n\t\tlhsi, rhsi := this.Get(i), other.Get(i)\n\t\tif TupleElemLt(lhsi, rhsi) {\n\t\t\treturn true\n\t\t} else if !TupleElemEq(lhsi, rhsi) {\n\t\t\treturn false\n\t\t}\n\t}\n\t// if we get here then they matched up to n\n\tif tlen < olen {\n\t\treturn true\n\t}\n\treturn false\n}", "func (h PerformanceHeap) Less(i, j int) bool {\n\treturn h.items[i].event.Timestamp.Before(h.items[j].event.Timestamp)\n}", "func (elems Elements) Less(i, j int) bool {\n\tif elems[i].Pos.Less(elems[j].Pos) {\n\t\treturn true\n\t}\n\tif elems[i].Pos.Equals(elems[j].Pos) {\n\t\treturn elems[i].Kind < elems[j].Kind\n\t}\n\treturn false\n}", "func (h ReqHeap) Less(i, j int) bool { return h[i].Timestamp.Before(h[j].Timestamp) }", "func (es Events) Less(i, j int) bool {\n\treturn es[i].Time < es[j].Time\n}", "func (id NodeID) Less(other NodeID) bool {\n\tfor k, v := range id {\n\t\tif v < other[k] {\n\t\t\treturn true\n\t\t} else if v > other[k] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn false\n}", "func (qt QueryTimes) Less(i, j int) bool { return qt[i] < qt[j] }", "func (b timeOrd) Less(i, j int) bool {\n\tif b[i].next.IsZero() {\n\t\treturn false\n\t}\n\tif b[j].next.IsZero() {\n\t\treturn true\n\t}\n\treturn b[i].next.Before(b[j].next)\n}", "func (c *comparables) Less(i, j int) bool {\n\treturn c.IsLess(c.values[i], c.values[j])\n}", "func (s VectorClock) LessThan(otherClock VectorClock) bool {\n\tpanic(\"todo\")\n}", "func (s Migrations) Less(i, j int) bool {\n\tiTag, err := semver.Make(s[i].Tag)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tjTag, err := semver.Make(s[j].Tag)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn iTag.LT(jTag)\n}", "func Equal(t, other Tuplelike) bool {\n\tfor idx, value := range t.Values() {\n\t\tif !inEpsilon(value, other.At(idx)) {\n\t\t\treturn false\n\t\t}\n\n\t}\n\treturn true\n}", "func (p byPoints) Less(i, j int) bool {\n\t// 4 is actually less than anything else\n\tif p[i] == 4 {\n\t\treturn true\n\t}\n\treturn p[i] < p[j]\n}", "func (o *OrderedSynchronizer) Less(i, j int) bool {\n\treturn o.compareRow(o.heap[i], o.heap[j]) < 0\n}", "func (a Value) Less(b Value) bool {\n\treturn a.Compare(b) < 0\n}", "func (e *ConstantExpr) Ult(other *ConstantExpr) *ConstantExpr {\n\tswitch e.Width {\n\tcase Width8:\n\t\treturn NewBoolConstantExpr(uint8(e.Value) < uint8(other.Value))\n\tcase Width16:\n\t\treturn NewBoolConstantExpr(uint16(e.Value) < uint16(other.Value))\n\tcase Width32:\n\t\treturn NewBoolConstantExpr(uint32(e.Value) < uint32(other.Value))\n\tcase Width64:\n\t\treturn NewBoolConstantExpr(uint64(e.Value) < uint64(other.Value))\n\tdefault:\n\t\tpanic(\"ult: non-standard width\")\n\t}\n}", "func (h *Heap) Less(i, j int) bool {\n\t// We have a minHeap, which means top record is a record with a lowest distance\n\treturn h.slice[i].distance < h.slice[j].distance\n}", "func (s *GoSort) LessThan(i, j int) bool {\n return s.comparator(s.values[i], s.values[j]) == -1\n}", "func (t Targets) IsLess(o Targets) bool {\n\tif len(t) < len(o) {\n\t\treturn true\n\t}\n\tif len(t) > len(o) {\n\t\treturn false\n\t}\n\n\tsort.Sort(t)\n\tsort.Sort(o)\n\n\tfor i, e := range t {\n\t\tif e != o[i] {\n\t\t\treturn e < o[i]\n\t\t}\n\t}\n\treturn false\n}", "func (es Envelopes) Less(i, j int) bool {\n\treturn (es[i].w < es[j].w) || (es[i].w == es[j].w && es[i].h >= es[j].h)\n}", "func (pq priorityQueue) Less(i, j int) bool {\n\treturn pq[i].time.Before(pq[j].time)\n}", "func (ce ChangesetEvents) Less(i, j int) bool {\n\treturn ce[i].Timestamp().Before(ce[j].Timestamp())\n}", "func LT(x float64, y float64) bool {\n\treturn (x < y-e)\n}", "func (pq PriorityQueue) Less(i, j int) bool {\n\treturn pq[i].diff > pq[j].diff\n}", "func less(c1, c2 cost) bool {\n\tswitch {\n\tcase c1.opCode != c2.opCode:\n\t\treturn c1.opCode < c2.opCode\n\tcase c1.isUnique == c2.isUnique:\n\t\treturn c1.vindexCost <= c2.vindexCost\n\tdefault:\n\t\treturn c1.isUnique\n\t}\n}", "func (c UintEnumCompare) IsLess(nLHS int, lhs uint, nRHS int, rhs uint) bool {\n\treturn c(nLHS, lhs, nRHS, rhs)\n}", "func (v Set) Less(i, j int) bool { return v[i].Cmp(v[j]) < 0 }", "func (k KeyTok) Less(other KeyTok) bool {\n\tif k.Kind < other.Kind {\n\t\treturn true\n\t} else if k.Kind > other.Kind {\n\t\treturn false\n\t}\n\ta, b := k.ID(), other.ID()\n\treturn a.Less(&b)\n}", "func (iheap IntegerHeap) Less(i, j int) bool {\n\treturn iheap[i] < iheap[j]\n}", "func (iheap IntegerHeap) Less(i, j int) bool {\n\treturn iheap[i] < iheap[j]\n}", "func (es entries) Less(i, j int) bool {\n\treturn es[i].int > es[j].int\n}", "func (s *SortableStruct) Less(other interface{}) bool {\n\totherss, ok := other.(*SortableStruct)\n\tif !ok {\n\t\tlog.Printf(\"Type assertion failed in SortableStruct; got other of type %#v\", other)\n\t\treturn true\n\t}\n\tres := s.Val < otherss.Val\n\treturn res\n}", "func (s ElementSlice) Less (i, j int) bool {\n return (&s[i]).Less(&s[j])\n}", "func (b Buildings) Less(i, j int) bool {\n\treturn b[i].Left < b[j].Left\n}", "func (e *Edge) Less(other Edge) bool {\n\treturn e.weight < other.weight\n}", "func (bi Int) LessThanEqual(o Int) bool {\n\treturn bi.LessThan(o) || bi.Equals(o)\n}", "func (a Uint64) Less(b btree.Item) bool {\n\treturn a < b.(Uint64)\n}", "func LE(x float64, y float64) bool {\n\treturn (x < y+e)\n}", "func (ca ComparableArray) Less(i, j int) bool { return ca[i].Less(ca[j]) }", "func (ei *ByIntervalTicks) Less(i, j int) bool {\n\tcursor_i := i * ei.recordLength\n\tcursor_j := j * ei.recordLength\n\n\tintervalTicks_i := io.ToUInt32(ei.buffer[cursor_i+ei.recordLength-4 : cursor_i+ei.recordLength])\n\tintervalTicks_j := io.ToUInt32(ei.buffer[cursor_j+ei.recordLength-4 : cursor_j+ei.recordLength])\n\n\treturn intervalTicks_i < intervalTicks_j\n}", "func (a point) Less(b point) bool {\n\tcmp := a.ip.Compare(b.ip)\n\tif cmp != 0 {\n\t\treturn cmp < 0\n\t}\n\tif a.want != b.want {\n\t\tif a.start == b.start {\n\t\t\treturn !a.want\n\t\t}\n\t\treturn a.start\n\t}\n\tif a.start != b.start {\n\t\treturn a.start\n\t}\n\treturn false\n}", "func (order Order) LessThan(other Order) bool {\n\treturn order.Price < other.Price\n}", "func (ei *ByIntervalTicks) Less(i, j int) bool {\n\tcursorI := i * ei.recordLength\n\tcursorJ := j * ei.recordLength\n\n\tintervalTicksI := io.ToUInt32(ei.buffer[cursorI+ei.recordLength-4 : cursorI+ei.recordLength])\n\tintervalTicksJ := io.ToUInt32(ei.buffer[cursorJ+ei.recordLength-4 : cursorJ+ei.recordLength])\n\n\treturn intervalTicksI < intervalTicksJ\n}", "func (x circle) Less(i, j int) bool { return x[i] < x[j] }", "func (pq PriorityQueue) Less(i, j int) bool {\n\t// If risks are different, use that for comparisons first.\n\tif pq[i].MinCost != pq[j].MinCost {\n\t\treturn pq[i].MinCost < pq[j].MinCost\n\t}\n\t// Use x + y values now.\n\tdi := pq[i].Loc.X + pq[i].Loc.Y\n\tdj := pq[j].Loc.X + pq[j].Loc.Y\n\tif di != dj {\n\t\treturn di < dj\n\t}\n\t// further left first, then further up.\n\treturn pq[i].Loc.X < pq[j].Loc.X || pq[i].Loc.Y < pq[j].Loc.Y\n}", "func (rows byLatency) Less(i, j int) bool {\n\treturn rows[i].SumTimerWait > rows[j].SumTimerWait\n}", "func (s *GoSort) LessEqualsThan(i, j int) bool {\n return (s.comparator(s.values[i], s.values[j]) == -1 || s.comparator(s.values[i], s.values[j]) == 0)\n}", "func (sr ScoredRange) Less(i, j int) bool { return sr[i].Score < sr[j].Score }", "func (h *Queue) Less(i, j int) bool {\n\t// We have a minHeap, which means top record is a record with a lowest distance\n\treturn h.slice[i].Estimate < h.slice[j].Estimate\n}", "func (tiles Tiles) Less(i, j int) bool {\n\ttile1 := tiles[i]\n\ttile2 := tiles[j]\n\treturn CompareTiles(tile1, tile2) < 0\n}", "func (b *Bucket) less(r *Bucket) bool {\n\tif b.First || r.First {\n\t\treturn b.First\n\t}\n\treturn b.Signature.less(&r.Signature)\n}", "func (a Vertex) Less(b Vertex) bool {\n\tfor i := range a.pos {\n\t\tswitch {\n\t\tcase a.pos[i] < b.pos[i]:\n\t\t\treturn true\n\t\tcase a.pos[i] > b.pos[i]:\n\t\t\treturn false\n\t\t}\n\t}\n\tfor i := range a.color {\n\t\tswitch {\n\t\tcase a.color[i] < b.color[i]:\n\t\t\treturn true\n\t\tcase a.color[i] > b.color[i]:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn false\n}", "func (pq PrioQueue) Less(i, j int) bool {\n\treturn pq[j].IsLongerThan(pq[i])\n}", "func (a Tags) Less(i, j int) bool { return a[i].Version.GT(a[j].Version) }", "func (me TComparator) IsLessThan() bool { return me.String() == \"LessThan\" }", "func (pq priorityQueue) Less(i, j int) bool {\n\treturn pq[i].key < pq[j].key\n}", "func (elems ElementsNR) Less(i, j int) bool {\n\tif elems[i].Pos.Less(elems[j].Pos) {\n\t\treturn true\n\t}\n\tif elems[i].Pos.Equals(elems[j].Pos) {\n\t\treturn elems[i].Kind < elems[j].Kind\n\t}\n\treturn false\n}", "func (this *Tuple) Eq(other *Tuple) bool {\n\tif this.Len() != other.Len() {\n\t\treturn false\n\t}\n\t//return reflect.DeepEqual(this.data, other.data)\n\tfor i := 0; i < this.Len(); i++ {\n\t\tlhsi, rhsi := this.Get(i), other.Get(i)\n\t\tif !TupleElemEq(lhsi, rhsi) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (h minPath) Less(i, j int) bool {\n\treturn h[i].value < h[j].value\n}", "func tsLess(a, b types.TS) bool { return bytes.Compare(a[:], b[:]) < 0 }", "func (ms *MultiKeySorter) Less(i, j int) bool {\n\tp, q := ms.List[i], ms.List[j]\n\t// Try all but the last comparison.\n\t// based on the sort implementation last\n\t// element is the pivot for quick sort\n\t// so it goes till second last element.\n\tvar k int\n\tfor k = 0; k < len(ms.less)-1; k++ {\n\t\tless := ms.less[k]\n\t\tswitch {\n\t\tcase less(p, q):\n\t\t\t// p < q, so we have a decision.\n\t\t\treturn true\n\t\tcase less(q, p):\n\t\t\t// p > q, so we have a decision.\n\t\t\t// that p greater then q\n\t\t\treturn false\n\t\t}\n\t\t// p == q; try the next comparison.\n\t}\n\t// All comparisons to here said \"equal\", so just return whatever\n\t// the final comparison reports.\n\treturn ms.less[k](p, q)\n}", "func (c Int32EnumCompare) IsLess(nLHS int, lhs int32, nRHS int, rhs int32) bool {\n\treturn c(nLHS, lhs, nRHS, rhs)\n}", "func (gdt *Vector3) OperatorLess(b Vector3) Bool {\n\targ0 := gdt.getBase()\n\targ1 := b.getBase()\n\n\tret := C.go_godot_vector3_operator_less(GDNative.api, arg0, arg1)\n\n\treturn Bool(ret)\n}", "func (pq MinPQueue) Less(i, j int) bool {\n\t// min heap -- lower the value, higher the priority\n\treturn pq[i].priority < pq[j].priority\n}", "func (c *comparables) IsLess(a, b interface{}) bool {\n\treturn c.isLess(a, b)\n}", "func (this FeedQueue) Less(i, j int) bool {\n\treturn this[i].score > this[j].score\n}", "func (c Conditions) Less(i, j int) bool {\n\treturn c[i].CanIterate() && c[i].Len() < c[j].Len()\n}", "func (h nodeList) Less(i, j int) bool {\n\treturn h[i].hash < h[j].hash\n}", "func (me Int64Key) LessThan(other binarytree.Comparable) bool {\n\treturn me < other.(Int64Key)\n}", "func (r RuneList) Less(i int, j int) bool {\n\treturn r[i] < r[j]\n}", "func lessWordPair(x, y interface{}) bool\t{ return x.(*wordPair).canon < y.(*wordPair).canon }", "func (me TComparator) IsLessThanOrEqualTo() bool { return me.String() == \"LessThanOrEqualTo\" }", "func (s FeedItems) Less(i, j int) bool {\n\treturn s[i].Score < s[i].Score\n}", "func (durs ByFirstEntered) Less(i, j int) bool {\n\treturn durs[i].FirstEntered.Before(durs[j].FirstEntered)\n}", "func (s *GoSort) Less(i, j int) bool {\n return s.comparator(s.values[i], s.values[j]) == -1\n}", "func (p priorities) Less(i, j int) bool { return p[i] < p[j] }", "func less(kA, kB, vA, vB reflect.Value) bool {\n\tswitch kA.Kind() {\n\tcase reflect.Bool:\n\t\treturn !kA.Bool() && kB.Bool()\n\tcase reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:\n\t\treturn kA.Int() < kB.Int()\n\tcase reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:\n\t\treturn kA.Uint() < kB.Uint()\n\tcase reflect.Float32, reflect.Float64:\n\t\tif vA.IsValid() && vB.IsValid() && math.IsNaN(kA.Float()) && math.IsNaN(kB.Float()) {\n\t\t\treturn less(vA, vB, reflect.Value{}, reflect.Value{})\n\t\t}\n\t\treturn math.IsNaN(kA.Float()) || kA.Float() < kB.Float()\n\tcase reflect.String:\n\t\treturn kA.String() < kB.String()\n\tcase reflect.Uintptr:\n\t\treturn kA.Uint() < kB.Uint()\n\tcase reflect.Array:\n\t\t// Compare the contents of both arrays.\n\t\tl := kA.Len()\n\t\tfor i := 0; i < l; i++ {\n\t\t\tav := kA.Index(i)\n\t\t\tbv := kB.Index(i)\n\t\t\tif av.Interface() == bv.Interface() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn less(av, bv, vA, vB)\n\t\t}\n\t\treturn less(vA, vB, reflect.Value{}, reflect.Value{})\n\t}\n\treturn fmt.Sprint(kA) < fmt.Sprint(kB)\n}" ]
[ "0.7385708", "0.6908471", "0.6578247", "0.64186805", "0.64105165", "0.63843644", "0.63113457", "0.63012135", "0.6258522", "0.6246853", "0.62063974", "0.6198956", "0.61527395", "0.61383474", "0.6114954", "0.6096506", "0.6092556", "0.6092556", "0.6092556", "0.6070504", "0.60629797", "0.60404885", "0.6021951", "0.6005649", "0.597734", "0.5965449", "0.59405065", "0.5937759", "0.5934702", "0.59217066", "0.5910952", "0.5908014", "0.5902819", "0.58972126", "0.5882552", "0.5876892", "0.5871719", "0.58614004", "0.58577764", "0.5856464", "0.58554393", "0.58536404", "0.5851832", "0.5848882", "0.5835749", "0.5822061", "0.57998216", "0.5797663", "0.57964665", "0.579194", "0.5789183", "0.5731456", "0.5731456", "0.57279295", "0.5716912", "0.5713138", "0.5698476", "0.56957185", "0.5695232", "0.5694353", "0.5692121", "0.5691045", "0.5686227", "0.5685555", "0.56803167", "0.56787515", "0.565328", "0.56382406", "0.563017", "0.56154627", "0.5605394", "0.56046027", "0.56030196", "0.5601932", "0.5595884", "0.55954283", "0.55924124", "0.5587145", "0.558502", "0.5581158", "0.5578949", "0.5578463", "0.5572949", "0.5570532", "0.55628705", "0.5562543", "0.5556598", "0.5549893", "0.5549726", "0.55406326", "0.55405045", "0.55394953", "0.5537044", "0.553221", "0.5530344", "0.55253655", "0.5523928", "0.5523781", "0.5520744", "0.55138713" ]
0.67197317
2
Returns True if this Tuple is elementwise greater than other
func (this *Tuple) Gt(other *Tuple) bool { return !this.Le(other) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a Vec2) AnyGreater(b Vec2) bool {\n\treturn a.X > b.X || a.Y > b.Y\n}", "func (a Vec2) Greater(b Vec2) bool {\n\treturn a.X > b.X && a.Y > b.Y\n}", "func (n *Node) isGreaterThan(other *Node) bool {\n\treturn n.val.IsGreaterThan(other.val)\n}", "func (this *Tuple) Ge(other *Tuple) bool {\n\treturn !this.Lt(other)\n}", "func greaterThan(x1, x2, y1, y2 Word) bool {\n\treturn x1 > y1 || x1 == y1 && x2 > y2\n}", "func (a *Pair) Less (b *Pair) bool {\n return a.x < b.x\n}", "func (c *Comparison) IsBigger() bool {\n\treturn (c.First.Start.Before(c.Second.Start) && c.First.End.After(c.Second.End)) || (c.First.Start.Equal(c.Second.Start) && c.First.End.After(c.Second.End)) || (c.First.Start.Before(c.Second.Start) && c.First.End.Equal(c.Second.End))\n}", "func (eps Accuracy) Greater(a, b float64) bool {\n\treturn math.Max(a, b) == a && math.Abs(a-b) > eps()\n}", "func (s *GoSort) GreaterThan(i, j int) bool {\n return s.comparator(s.values[i], s.values[j]) == 1\n}", "func GT(x float64, y float64) bool {\n\treturn (x > y+e)\n}", "func (i Int) GT(i2 Int) bool {\n\treturn gt(i.i, i2.i)\n}", "func (this *Tuple) Le(other *Tuple) bool {\n\treturn this.Lt(other) || this.Eq(other)\n}", "func gt(o1, o2 interface{}) (bool, bool) {\n\n\tf1, ok := ToFloat(o1)\n\tif !ok {\n\t\treturn false, false\n\t}\n\n\tf2, ok := ToFloat(o2)\n\tif !ok {\n\t\treturn false, false\n\t}\n\n\treturn f1 > f2, true\n}", "func (me TComparator) IsGreaterThan() bool { return me.String() == \"GreaterThan\" }", "func (me Int64Key) GreaterThan(other binarytree.Comparable) bool {\n\treturn me > other.(Int64Key)\n}", "func (s *GoSort) GreaterEqualsThan(i, j int) bool {\n return (s.comparator(s.values[i], s.values[j]) == 1 || s.comparator(s.values[i], s.values[j]) == 0)\n}", "func Lesser(x, y *big.Float) bool {\n\treturn x.Cmp(y) == -1\n}", "func (id ID) GreaterThan(other ID) bool {\n\treturn !id.LesserThan(other)\n}", "func Greater(first *Message, second *Message) bool {\n\treturn first.DeliveryTime > second.DeliveryTime\n}", "func (me TComparator) IsGreaterThanOrEqualTo() bool { return me.String() == \"GreaterThanOrEqualTo\" }", "func (id ID) LesserThan(other ID) bool {\n\treturn bytes.Compare(id[:], other[:]) == -1\n}", "func (tc *TestConfig) IsGreater(source interface{}, target interface{}) bool {\n\tvar a, b float64\n\n\tswitch source.(type) {\n\tcase int:\n\t\ta = float64(source.(int))\n\tcase float64:\n\t\ta = float64(source.(float64))\n\tdefault:\n\t\treturn false\n\t}\n\n\tswitch target.(type) {\n\tcase int:\n\t\tb = float64(target.(int))\n\tcase float64:\n\t\tb = float64(target.(float64))\n\tdefault:\n\t\treturn false\n\t}\n\n\treturn a > b\n}", "func (f Fixed) GreaterThan(f0 Fixed) bool {\n\treturn f.Cmp(f0) == 1\n}", "func (f Fixed) GreaterThan(f0 Fixed) bool {\n\treturn f.Cmp(f0) == 1\n}", "func GreaterThan(x interface{}, y interface{}) (bool, error) {\n\trx := reflect.ValueOf(x)\n\try := reflect.ValueOf(y)\n\t// if reflect.TypeOf(x).Kind() != reflect.TypeOf(y).Kind() {\n\t// \treturn false, fmt.Errorf(\"mismatch %s <-> %s\", rx.Kind(), ry.Kind())\n\t// }\n\tswitch rx.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\treturn rx.Int() > ry.Convert(rx.Type()).Int(), nil\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\treturn rx.Uint() > ry.Convert(rx.Type()).Uint(), nil\n\tcase reflect.Float32, reflect.Float64:\n\t\treturn rx.Float() > ry.Convert(rx.Type()).Float(), nil\n\tcase reflect.String:\n\t\treturn rx.String() > ry.Convert(rx.Type()).String(), nil\n\tdefault:\n\t\treturn false, fmt.Errorf(\"unexpected %s\", rx.Kind())\n\t}\n}", "func (a Vec2) AnyLess(b Vec2) bool {\n\treturn a.X < b.X || a.Y < b.Y\n}", "func TupleElemLt(lhsi interface{}, rhsi interface{}) bool {\n\tlhsv, rhsv := reflect.ValueOf(lhsi), reflect.ValueOf(rhsi)\n\tif lhsv.IsValid() && !rhsv.IsValid() {\n\t\t// zero value is considered least\n\t\treturn false\n\t}\n\tswitch lhsi.(type) {\n\tcase nil:\n\t\tif rhsv.IsValid() {\n\t\t\treturn true\n\t\t}\n\tcase string:\n\t\tif lhsi.(string) < rhsi.(string) {\n\t\t\treturn true\n\t\t}\n\tcase int, int8, int16, int32, int64:\n\t\tif lhsv.Int() < rhsv.Int() {\n\t\t\treturn true\n\t\t}\n\tcase uint, uintptr, uint8, uint16, uint32, uint64:\n\t\tif lhsv.Uint() < rhsv.Uint() {\n\t\t\treturn true\n\t\t}\n\tcase float32, float64:\n\t\tif lhsv.Float() < rhsv.Float() {\n\t\t\treturn true\n\t\t}\n\tcase *Tuple:\n\t\tif lhsi.(*Tuple).Lt(rhsi.(*Tuple)) {\n\t\t\treturn true\n\t\t}\n\tdefault:\n\t\t// TODO: allow user-defined callback for unsupported types\n\t\tpanic(fmt.Sprintf(\"unsupported type %#v for Lt in Tuple\", lhsi))\n\t}\n\treturn false\n}", "func greaterThan(expected float64, actual float64) assert.Comparison {\n\treturn assert.Comparison(func () bool {\n\t\treturn actual > expected\n\t})\n}", "func (tc *TestConfig) IsGreaterEqual(source interface{}, target interface{}) bool {\n\treturn tc.Equal(source, target) || tc.IsGreater(source, target)\n}", "func (ver *Version) GreaterThan(otherVer *Version) bool {\n if ver.Major > otherVer.Major {\n return true\n }\n if ver.Major < otherVer.Major {\n return false\n }\n\n /* same major */\n if ver.Minor > otherVer.Minor {\n return true\n }\n if ver.Minor < otherVer.Minor {\n return false\n }\n\n /* same minor */\n return ver.Patch > otherVer.Patch\n}", "func (a Vec2) Less(b Vec2) bool {\n\treturn a.X < b.X && a.Y < b.Y\n}", "func (v *RelaxedVersion) GreaterThan(u *RelaxedVersion) bool {\n\treturn v.CompareTo(u) > 0\n}", "func isMateriallyGreater(a, b float64) bool {\n\treturn (a - b) > 0.001\n}", "func Greaterf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool {\n\tif h, ok := t.(tHelper); ok {\n\t\th.Helper()\n\t}\n\treturn Greater(t, e1, e2, append([]interface{}{msg}, args...)...)\n}", "func (bi Int) GreaterThan(o Int) bool {\n\treturn Cmp(bi, o) > 0\n}", "func (this *Tuple) Lt(other *Tuple) bool {\n\ttlen, olen := this.Len(), other.Len()\n\tvar n int\n\tif tlen < olen {\n\t\tn = tlen\n\t} else {\n\t\tn = olen\n\t}\n\tfor i := 0; i < n; i++ {\n\t\tlhsi, rhsi := this.Get(i), other.Get(i)\n\t\tif TupleElemLt(lhsi, rhsi) {\n\t\t\treturn true\n\t\t} else if !TupleElemEq(lhsi, rhsi) {\n\t\t\treturn false\n\t\t}\n\t}\n\t// if we get here then they matched up to n\n\tif tlen < olen {\n\t\treturn true\n\t}\n\treturn false\n}", "func (self *FieldValue) GreaterOrEqual(other *FieldValue) bool {\n\tif self.BoolValue != nil {\n\t\tif other.BoolValue == nil {\n\t\t\treturn false\n\t\t}\n\t\t// true >= false, false >= false\n\t\treturn *self.BoolValue || !*other.BoolValue\n\t}\n\tif self.Int64Value != nil {\n\t\tif other.Int64Value == nil {\n\t\t\treturn other.BoolValue != nil\n\t\t}\n\t\treturn *self.Int64Value >= *other.Int64Value\n\t}\n\tif self.DoubleValue != nil {\n\t\tif other.DoubleValue == nil {\n\t\t\treturn other.BoolValue != nil || other.Int64Value != nil\n\t\t}\n\t\treturn *self.DoubleValue >= *other.DoubleValue\n\t}\n\tif self.StringValue != nil {\n\t\tif other.StringValue == nil {\n\t\t\treturn other.BoolValue != nil || other.Int64Value != nil || other.DoubleValue != nil\n\t\t}\n\t\treturn *self.StringValue >= *other.StringValue\n\t}\n\treturn true\n}", "func (i1 Int) Less(i2 freetree.Comparable) bool { return i1 < i2.(Int) }", "func (src Version) IsGreaterThan(des Version) bool {\n\treturn src.compareWith(des) == Greater\n}", "func Equal(t, other Tuplelike) bool {\n\tfor idx, value := range t.Values() {\n\t\tif !inEpsilon(value, other.At(idx)) {\n\t\t\treturn false\n\t\t}\n\n\t}\n\treturn true\n}", "func OpTimeGreaterThan(lhs OpTime, rhs OpTime) bool {\n\tif lhs.Term != nil && rhs.Term != nil {\n\t\tif *lhs.Term == *rhs.Term {\n\t\t\treturn util.TimestampGreaterThan(lhs.Timestamp, rhs.Timestamp)\n\t\t}\n\t\treturn *lhs.Term > *rhs.Term\n\t}\n\n\treturn util.TimestampGreaterThan(lhs.Timestamp, rhs.Timestamp)\n}", "func moreOrLessEqual(a, b, err float64) bool {\n\treturn math.Abs(a-b) < err\n}", "func Lt(val, max any) bool { return valueCompare(val, max, \"<\") }", "func (this FeedQueue) Less(i, j int) bool {\n\treturn this[i].score > this[j].score\n}", "func (d Decimal) GreaterThan(d2 Decimal) bool {\n\treturn d.Cmp(d2) == 1\n}", "func (d Decimal) GreaterThan(d2 Decimal) bool {\n\treturn d.Cmp(d2) == 1\n}", "func Gt(x, y int) bool {\n\treturn x > y\n}", "func (p *Pairs)Less(i, j int) bool {\n\treturn p.pairs[i][0] + p.pairs[i][1] > p.pairs[j][0] + p.pairs[j][1]\n}", "func (eps Accuracy) GreaterOrEqual(a, b float64) bool {\n\treturn math.Max(a, b) == a || math.Abs(a-b) < eps()\n}", "func (pq PriorityQueue) Less(i, j int) bool {\n\treturn pq[i].diff > pq[j].diff\n}", "func (this *TimeInterval) IsAfter(other *TimeInterval) bool {\n\n\treturn this.Ts.Sub(other.Te) >= 0\n}", "func GreaterThanAssert(v1,v2 int) bool{\n\tif v1 > v2 {\n\t\treturn true\n\t} else {\n\t\tif show == true {\n\t\t\tfmt.Printf(\"Failed! %d isn't greater than %d : \\n\",v1,v2)\n\t\t}\n\t\treturn false\n\t}\n}", "func GreaterThanEqual(x interface{}, y interface{}) (bool, error) {\n\trx := reflect.ValueOf(x)\n\try := reflect.ValueOf(y)\n\n\tswitch rx.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\treturn rx.Int() >= ry.Convert(rx.Type()).Int(), nil\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\treturn rx.Uint() >= ry.Convert(rx.Type()).Uint(), nil\n\tcase reflect.Float32, reflect.Float64:\n\t\treturn rx.Float() >= ry.Convert(rx.Type()).Float(), nil\n\tcase reflect.String:\n\t\treturn rx.String() >= ry.Convert(rx.Type()).String(), nil\n\tcase reflect.Bool:\n\t\treturn rx.Bool() == ry.Convert(rx.Type()).Bool(), nil\n\tdefault:\n\t\treturn reflect.DeepEqual(rx, ry), nil\n\t}\n}", "func (x uints) Less(i, j int) bool { return x[i] < x[j] }", "func (x uints) Less(i, j int) bool { return x[i] < x[j] }", "func (x uints) Less(i, j int) bool { return x[i] < x[j] }", "func (h tsHeap) Less(i, j int) bool {\n\treturn h[i].ts.Less(h[j].ts)\n}", "func (eps Accuracy) Less(a, b float64) bool {\n\treturn math.Max(a, b) == b && math.Abs(a-b) > eps()\n}", "func (u UUID) GreaterThan(n UUID) bool {\n\tif u.Equal(n) {\n\t\treturn u.Tick > n.Tick\n\t}\n\n\treturn false\n}", "func (x IntSlice) Bigger(i,j int) bool{\n if x[i]>x[j]{// comparing two int\n return true\n }\n return false\n }", "func (b buffer) Less(i, j int) bool {\n\treturn compareByFirstOrNextValue(b[i], b[j]) < 0\n}", "func (this *Tuple) Ne(other *Tuple) bool {\n\treturn !this.Eq(other)\n}", "func (b *Builder) IsGreaterThan(rhs interface{}) *predicate.Predicate {\n\tb.p.RegisterPredicate(impl.IsGreaterThan(rhs))\n\tif b.t != nil {\n\t\tb.t.Helper()\n\t\tEvaluate(b)\n\t}\n\treturn &b.p\n}", "func (k *joinKey) less(other joinKey) bool {\n\ta, b := k, other\n\tfor i := 0; i < len(k.values); i++ {\n\t\tif b.values[i].IsNull() {\n\t\t\treturn true\n\t\t} else if a.values[i].IsNull() {\n\t\t\treturn false\n\t\t}\n\n\t\tswitch a.columns[i].Type {\n\t\tcase flux.TBool:\n\t\t\tif av, bv := a.values[i].Bool(), b.values[i].Bool(); av != bv {\n\t\t\t\treturn bv\n\t\t\t}\n\t\tcase flux.TInt:\n\t\t\tif av, bv := a.values[i].Int(), b.values[i].Int(); av != bv {\n\t\t\t\treturn av < bv\n\t\t\t}\n\t\tcase flux.TUInt:\n\t\t\tif av, bv := a.values[i].UInt(), b.values[i].UInt(); av != bv {\n\t\t\t\treturn av < bv\n\t\t\t}\n\t\tcase flux.TFloat:\n\t\t\tif av, bv := a.values[i].Float(), b.values[i].Float(); av != bv {\n\t\t\t\treturn av < bv\n\t\t\t}\n\t\tcase flux.TString:\n\t\t\tif av, bv := a.values[i].Str(), b.values[i].Str(); av != bv {\n\t\t\t\treturn av < bv\n\t\t\t}\n\t\tcase flux.TTime:\n\t\t\tif av, bv := a.values[i].Time(), b.values[i].Time(); av != bv {\n\t\t\t\treturn av < bv\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func Greater(t *testing.T, a, b int) {\n\tt.Helper()\n\n\tif !(a > b) {\n\t\tt.Errorf(`%s: %d should be greater than %d`, t.Name(), a, b)\n\t}\n}", "func Gt(val, min any) bool { return valueCompare(val, min, \">\") }", "func greaterThanOrEqual(expected float64, actual float64) assert.Comparison {\n\treturn assert.Comparison(func () bool {\n\t\treturn actual >= expected\n\t})\n}", "func (f Fixed8) GreaterThan(g Fixed8) bool {\n\treturn f > g\n}", "func (h ReqHeap) Less(i, j int) bool { return h[i].Timestamp.Before(h[j].Timestamp) }", "func (p Point2) GreaterOf(ps ...Point2) Point2 {\n\tfor _, p2 := range ps {\n\t\tp[0] = math.Max(p[0], p2[0])\n\t\tp[1] = math.Max(p[1], p2[1])\n\t}\n\treturn p\n}", "func (bi Int) GreaterThanEqual(o Int) bool {\n\treturn bi.GreaterThan(o) || bi.Equals(o)\n}", "func (firstDate Nakamura) GreaterThan(secondDate Nakamura) bool {\n\treturn GreaterThan(firstDate, secondDate, secondDate.format)\n}", "func IsGreaterThan(timeLeft time.Time, timeRight time.Time) bool {\n\tdurDelta := timeLeft.Sub(timeRight)\n\tif durZero, _ := time.ParseDuration(\"0ns\"); durDelta > durZero {\n\t\treturn true\n\t}\n\treturn false\n}", "func (pq priorityQueue) Less(i, j int) bool {\n\treturn pq[i].time.Before(pq[j].time)\n}", "func (t toc) Less(i, j int) bool {\n\treturn t[i].value < t[j].value\n}", "func (qt QueryTimes) Less(i, j int) bool { return qt[i] < qt[j] }", "func (r *RID) OperatorGreater(rid *RID) bool {\n\tif !r.OperatorEqual(rid) && !r.OperatorLess(rid) {\n\t\treturn true\n\t}\n\treturn false\n}", "func (s NodeSlice) Less(i, j int) bool {\n\treturn s[i].MemFree > s[j].MemFree\n}", "func (a Balance) Less(b Balance) bool {\n\tfor i, valA := range a {\n\t\tvalB := b[i]\n\t\tif valA < valB {\n\t\t\treturn true\n\t\t}\n\t\tif valB < valA {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn false\n}", "func compare(x, y Tuple) int {\n\txn := x.Size()\n\tyn := y.Size()\n\tfor i := 0; i < xn && i < yn; i++ {\n\t\tcmp := bytes.Compare(x.GetRaw(i), y.GetRaw(i))\n\t\tif cmp != 0 {\n\t\t\treturn cmp\n\t\t}\n\t}\n\treturn ints.Compare(xn, yn)\n}", "func (r *rankImpl) Greater(a, b string) bool {\n\treturn !r.Equal(a, b) && !r.Less(a, b)\n}", "func (h PerformanceHeap) Less(i, j int) bool {\n\treturn h.items[i].event.Timestamp.Before(h.items[j].event.Timestamp)\n}", "func (a result) beats(b result) bool {\n\treturn a.n < b.n || (a.n == b.n && a.s < b.s)\n}", "func (pq PrioQueue) Less(i, j int) bool {\n\treturn pq[j].IsLongerThan(pq[i])\n}", "func Greater(v1, v2 string) (bool, error) {\n\tif v1 == \"\" && v2 != \"\" {\n\t\treturn false, nil\n\t}\n\tif v1 != \"\" && v2 == \"\" {\n\t\treturn false, nil\n\t}\n\tsv1, err := semver.Make(v1)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tsv2, err := semver.Make(v2)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn sv1.GTE(sv2), nil\n}", "func (coin Coin) IsGT(other Coin) bool {\n\treturn coin.Amount.GT(other.Amount)\n}", "func (es entries) Less(i, j int) bool {\n\treturn es[i].int > es[j].int\n}", "func (a Uint64) Less(b btree.Item) bool {\n\treturn a < b.(Uint64)\n}", "func (hp theHeap) Less(i, j int) bool {\n\treturn hp[i].d > hp[j].d\n}", "func Gtr(x, y reflect.Value) reflect.Value {\n\tmustSameType(x, y)\n\tz := reflect.New(reflect.TypeOf(false)).Elem()\n\tswitch x.Type().Kind() {\n\tcase reflect.Int:\n\t\txx := int(x.Int())\n\t\tyy := int(y.Int())\n\t\tzz := xx > yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Int8:\n\t\txx := int8(x.Int())\n\t\tyy := int8(y.Int())\n\t\tzz := xx > yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Int16:\n\t\txx := int16(x.Int())\n\t\tyy := int16(y.Int())\n\t\tzz := xx > yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Int32:\n\t\txx := int32(x.Int())\n\t\tyy := int32(y.Int())\n\t\tzz := xx > yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Int64:\n\t\txx := int64(x.Int())\n\t\tyy := int64(y.Int())\n\t\tzz := xx > yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Uint:\n\t\txx := uint(x.Uint())\n\t\tyy := uint(y.Uint())\n\t\tzz := xx > yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Uint8:\n\t\txx := uint8(x.Uint())\n\t\tyy := uint8(y.Uint())\n\t\tzz := xx > yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Uint16:\n\t\txx := uint16(x.Uint())\n\t\tyy := uint16(y.Uint())\n\t\tzz := xx > yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Uint32:\n\t\txx := uint32(x.Uint())\n\t\tyy := uint32(y.Uint())\n\t\tzz := xx > yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Uint64:\n\t\txx := uint64(x.Uint())\n\t\tyy := uint64(y.Uint())\n\t\tzz := xx > yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Uintptr:\n\t\txx := uintptr(x.Uint())\n\t\tyy := uintptr(y.Uint())\n\t\tzz := xx > yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Float32:\n\t\txx := float32(x.Float())\n\t\tyy := float32(y.Float())\n\t\tzz := xx > yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.Float64:\n\t\txx := float64(x.Float())\n\t\tyy := float64(y.Float())\n\t\tzz := xx > yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\tcase reflect.String:\n\t\txx := string(x.String())\n\t\tyy := string(y.String())\n\t\tzz := xx > yy\n\t\tz.SetBool(zz)\n\t\treturn z\n\t}\n\tpanic(fmt.Sprintf(\"operator > not defined on %v\", x.Type()))\n}", "func GreaterThan(a cty.Value, b cty.Value) (cty.Value, error) {\n\treturn GreaterThanFunc.Call([]cty.Value{a, b})\n}", "func gt(lhs, rhs semantic.Expression) semantic.Expression {\n\treturn &semantic.BinaryOp{Type: semantic.BoolType, LHS: lhs, Operator: ast.OpGT, RHS: rhs}\n}", "func (a Tags) Less(i, j int) bool { return a[i].Version.GT(a[j].Version) }", "func (h *Queue) Less(i, j int) bool {\n\t// We have a minHeap, which means top record is a record with a lowest distance\n\treturn h.slice[i].Estimate < h.slice[j].Estimate\n}", "func (t *Type) IsComparable() bool", "func (b *Builder) IsGreaterOrEqualTo(rhs interface{}) *predicate.Predicate {\n\tb.p.RegisterPredicate(impl.IsGreaterOrEqualTo(rhs))\n\tif b.t != nil {\n\t\tb.t.Helper()\n\t\tEvaluate(b)\n\t}\n\treturn &b.p\n}", "func (this *Tuple) Eq(other *Tuple) bool {\n\tif this.Len() != other.Len() {\n\t\treturn false\n\t}\n\t//return reflect.DeepEqual(this.data, other.data)\n\tfor i := 0; i < this.Len(); i++ {\n\t\tlhsi, rhsi := this.Get(i), other.Get(i)\n\t\tif !TupleElemEq(lhsi, rhsi) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (t Tuple) EqualApprox(o Tuple) bool {\n\treturn floats.EqualApprox(t.X, o.X, floats.Epsilon) &&\n\t\tfloats.EqualApprox(t.Y, o.Y, floats.Epsilon) &&\n\t\tfloats.EqualApprox(t.Z, o.Z, floats.Epsilon) &&\n\t\tfloats.EqualApprox(t.W, o.W, floats.Epsilon)\n}", "func (s *GoSort) EqualsThan(i, j int) bool {\n return s.comparator(s.values[i], s.values[j]) == 0\n}", "func (t byDiffDesc) Less(i, j int) bool {\n\treturn t[i].diff() > t[j].diff() ||\n\t\t(t[i].diff() == t[j].diff() && t[i].weight > t[j].weight)\n}" ]
[ "0.69344044", "0.68843794", "0.6558815", "0.6527433", "0.6401499", "0.63991106", "0.63838917", "0.6331737", "0.62254304", "0.6183774", "0.61705154", "0.6000766", "0.59986115", "0.5961094", "0.5937788", "0.5928268", "0.5914721", "0.58384776", "0.58122534", "0.5744468", "0.57161754", "0.571311", "0.57104874", "0.57104874", "0.5693758", "0.5653411", "0.5639295", "0.5606172", "0.5573598", "0.5573191", "0.55689764", "0.55589736", "0.55211824", "0.5513041", "0.5509306", "0.5501778", "0.54877794", "0.54795015", "0.54660565", "0.5451759", "0.54469585", "0.5437672", "0.54306173", "0.5425824", "0.5421098", "0.5421098", "0.54171157", "0.54127264", "0.53992933", "0.5388591", "0.5377317", "0.53723145", "0.537015", "0.53673565", "0.53673565", "0.53673565", "0.53579086", "0.5350762", "0.5342651", "0.5335279", "0.53326", "0.5328589", "0.531926", "0.528752", "0.5276923", "0.5267423", "0.5262901", "0.52563864", "0.5243604", "0.5233528", "0.52335036", "0.5232041", "0.52316767", "0.5228155", "0.52206737", "0.51788235", "0.51761854", "0.5165983", "0.5164925", "0.5164657", "0.5148547", "0.5144305", "0.5135035", "0.51255435", "0.51243836", "0.51239073", "0.51116014", "0.5110118", "0.51094365", "0.51079124", "0.51040673", "0.5101287", "0.509992", "0.50975907", "0.5095689", "0.5095119", "0.50868636", "0.5082941", "0.5076579", "0.50764364" ]
0.5762057
19
Returns True if this Tuple is elementwise greater than or equal to other
func (this *Tuple) Ge(other *Tuple) bool { return !this.Lt(other) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a Vec2) AnyGreater(b Vec2) bool {\n\treturn a.X > b.X || a.Y > b.Y\n}", "func (a Vec2) Greater(b Vec2) bool {\n\treturn a.X > b.X && a.Y > b.Y\n}", "func (a *Pair) Less (b *Pair) bool {\n return a.x < b.x\n}", "func (n *Node) isGreaterThan(other *Node) bool {\n\treturn n.val.IsGreaterThan(other.val)\n}", "func (c *Comparison) IsBigger() bool {\n\treturn (c.First.Start.Before(c.Second.Start) && c.First.End.After(c.Second.End)) || (c.First.Start.Equal(c.Second.Start) && c.First.End.After(c.Second.End)) || (c.First.Start.Before(c.Second.Start) && c.First.End.Equal(c.Second.End))\n}", "func (eps Accuracy) Greater(a, b float64) bool {\n\treturn math.Max(a, b) == a && math.Abs(a-b) > eps()\n}", "func greaterThan(x1, x2, y1, y2 Word) bool {\n\treturn x1 > y1 || x1 == y1 && x2 > y2\n}", "func (s *GoSort) GreaterThan(i, j int) bool {\n return s.comparator(s.values[i], s.values[j]) == 1\n}", "func (this *Tuple) Le(other *Tuple) bool {\n\treturn this.Lt(other) || this.Eq(other)\n}", "func (i Int) GT(i2 Int) bool {\n\treturn gt(i.i, i2.i)\n}", "func (s *GoSort) GreaterEqualsThan(i, j int) bool {\n return (s.comparator(s.values[i], s.values[j]) == 1 || s.comparator(s.values[i], s.values[j]) == 0)\n}", "func GT(x float64, y float64) bool {\n\treturn (x > y+e)\n}", "func Equal(t, other Tuplelike) bool {\n\tfor idx, value := range t.Values() {\n\t\tif !inEpsilon(value, other.At(idx)) {\n\t\t\treturn false\n\t\t}\n\n\t}\n\treturn true\n}", "func (self *FieldValue) GreaterOrEqual(other *FieldValue) bool {\n\tif self.BoolValue != nil {\n\t\tif other.BoolValue == nil {\n\t\t\treturn false\n\t\t}\n\t\t// true >= false, false >= false\n\t\treturn *self.BoolValue || !*other.BoolValue\n\t}\n\tif self.Int64Value != nil {\n\t\tif other.Int64Value == nil {\n\t\t\treturn other.BoolValue != nil\n\t\t}\n\t\treturn *self.Int64Value >= *other.Int64Value\n\t}\n\tif self.DoubleValue != nil {\n\t\tif other.DoubleValue == nil {\n\t\t\treturn other.BoolValue != nil || other.Int64Value != nil\n\t\t}\n\t\treturn *self.DoubleValue >= *other.DoubleValue\n\t}\n\tif self.StringValue != nil {\n\t\tif other.StringValue == nil {\n\t\t\treturn other.BoolValue != nil || other.Int64Value != nil || other.DoubleValue != nil\n\t\t}\n\t\treturn *self.StringValue >= *other.StringValue\n\t}\n\treturn true\n}", "func (me Int64Key) GreaterThan(other binarytree.Comparable) bool {\n\treturn me > other.(Int64Key)\n}", "func gt(o1, o2 interface{}) (bool, bool) {\n\n\tf1, ok := ToFloat(o1)\n\tif !ok {\n\t\treturn false, false\n\t}\n\n\tf2, ok := ToFloat(o2)\n\tif !ok {\n\t\treturn false, false\n\t}\n\n\treturn f1 > f2, true\n}", "func (me TComparator) IsGreaterThanOrEqualTo() bool { return me.String() == \"GreaterThanOrEqualTo\" }", "func (me TComparator) IsGreaterThan() bool { return me.String() == \"GreaterThan\" }", "func (id ID) GreaterThan(other ID) bool {\n\treturn !id.LesserThan(other)\n}", "func (tc *TestConfig) IsGreaterEqual(source interface{}, target interface{}) bool {\n\treturn tc.Equal(source, target) || tc.IsGreater(source, target)\n}", "func Lesser(x, y *big.Float) bool {\n\treturn x.Cmp(y) == -1\n}", "func (eps Accuracy) GreaterOrEqual(a, b float64) bool {\n\treturn math.Max(a, b) == a || math.Abs(a-b) < eps()\n}", "func GreaterThan(x interface{}, y interface{}) (bool, error) {\n\trx := reflect.ValueOf(x)\n\try := reflect.ValueOf(y)\n\t// if reflect.TypeOf(x).Kind() != reflect.TypeOf(y).Kind() {\n\t// \treturn false, fmt.Errorf(\"mismatch %s <-> %s\", rx.Kind(), ry.Kind())\n\t// }\n\tswitch rx.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\treturn rx.Int() > ry.Convert(rx.Type()).Int(), nil\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\treturn rx.Uint() > ry.Convert(rx.Type()).Uint(), nil\n\tcase reflect.Float32, reflect.Float64:\n\t\treturn rx.Float() > ry.Convert(rx.Type()).Float(), nil\n\tcase reflect.String:\n\t\treturn rx.String() > ry.Convert(rx.Type()).String(), nil\n\tdefault:\n\t\treturn false, fmt.Errorf(\"unexpected %s\", rx.Kind())\n\t}\n}", "func TupleElemLt(lhsi interface{}, rhsi interface{}) bool {\n\tlhsv, rhsv := reflect.ValueOf(lhsi), reflect.ValueOf(rhsi)\n\tif lhsv.IsValid() && !rhsv.IsValid() {\n\t\t// zero value is considered least\n\t\treturn false\n\t}\n\tswitch lhsi.(type) {\n\tcase nil:\n\t\tif rhsv.IsValid() {\n\t\t\treturn true\n\t\t}\n\tcase string:\n\t\tif lhsi.(string) < rhsi.(string) {\n\t\t\treturn true\n\t\t}\n\tcase int, int8, int16, int32, int64:\n\t\tif lhsv.Int() < rhsv.Int() {\n\t\t\treturn true\n\t\t}\n\tcase uint, uintptr, uint8, uint16, uint32, uint64:\n\t\tif lhsv.Uint() < rhsv.Uint() {\n\t\t\treturn true\n\t\t}\n\tcase float32, float64:\n\t\tif lhsv.Float() < rhsv.Float() {\n\t\t\treturn true\n\t\t}\n\tcase *Tuple:\n\t\tif lhsi.(*Tuple).Lt(rhsi.(*Tuple)) {\n\t\t\treturn true\n\t\t}\n\tdefault:\n\t\t// TODO: allow user-defined callback for unsupported types\n\t\tpanic(fmt.Sprintf(\"unsupported type %#v for Lt in Tuple\", lhsi))\n\t}\n\treturn false\n}", "func GreaterThanEqual(x interface{}, y interface{}) (bool, error) {\n\trx := reflect.ValueOf(x)\n\try := reflect.ValueOf(y)\n\n\tswitch rx.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\treturn rx.Int() >= ry.Convert(rx.Type()).Int(), nil\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\treturn rx.Uint() >= ry.Convert(rx.Type()).Uint(), nil\n\tcase reflect.Float32, reflect.Float64:\n\t\treturn rx.Float() >= ry.Convert(rx.Type()).Float(), nil\n\tcase reflect.String:\n\t\treturn rx.String() >= ry.Convert(rx.Type()).String(), nil\n\tcase reflect.Bool:\n\t\treturn rx.Bool() == ry.Convert(rx.Type()).Bool(), nil\n\tdefault:\n\t\treturn reflect.DeepEqual(rx, ry), nil\n\t}\n}", "func (a Vec2) AnyLess(b Vec2) bool {\n\treturn a.X < b.X || a.Y < b.Y\n}", "func (f Fixed) GreaterThan(f0 Fixed) bool {\n\treturn f.Cmp(f0) == 1\n}", "func (f Fixed) GreaterThan(f0 Fixed) bool {\n\treturn f.Cmp(f0) == 1\n}", "func (this *Tuple) Eq(other *Tuple) bool {\n\tif this.Len() != other.Len() {\n\t\treturn false\n\t}\n\t//return reflect.DeepEqual(this.data, other.data)\n\tfor i := 0; i < this.Len(); i++ {\n\t\tlhsi, rhsi := this.Get(i), other.Get(i)\n\t\tif !TupleElemEq(lhsi, rhsi) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (tc *TestConfig) IsGreater(source interface{}, target interface{}) bool {\n\tvar a, b float64\n\n\tswitch source.(type) {\n\tcase int:\n\t\ta = float64(source.(int))\n\tcase float64:\n\t\ta = float64(source.(float64))\n\tdefault:\n\t\treturn false\n\t}\n\n\tswitch target.(type) {\n\tcase int:\n\t\tb = float64(target.(int))\n\tcase float64:\n\t\tb = float64(target.(float64))\n\tdefault:\n\t\treturn false\n\t}\n\n\treturn a > b\n}", "func Greater(first *Message, second *Message) bool {\n\treturn first.DeliveryTime > second.DeliveryTime\n}", "func (this *Tuple) Gt(other *Tuple) bool {\n\treturn !this.Le(other)\n}", "func (this *Tuple) Lt(other *Tuple) bool {\n\ttlen, olen := this.Len(), other.Len()\n\tvar n int\n\tif tlen < olen {\n\t\tn = tlen\n\t} else {\n\t\tn = olen\n\t}\n\tfor i := 0; i < n; i++ {\n\t\tlhsi, rhsi := this.Get(i), other.Get(i)\n\t\tif TupleElemLt(lhsi, rhsi) {\n\t\t\treturn true\n\t\t} else if !TupleElemEq(lhsi, rhsi) {\n\t\t\treturn false\n\t\t}\n\t}\n\t// if we get here then they matched up to n\n\tif tlen < olen {\n\t\treturn true\n\t}\n\treturn false\n}", "func moreOrLessEqual(a, b, err float64) bool {\n\treturn math.Abs(a-b) < err\n}", "func (v *RelaxedVersion) GreaterThan(u *RelaxedVersion) bool {\n\treturn v.CompareTo(u) > 0\n}", "func (ver *Version) GreaterThan(otherVer *Version) bool {\n if ver.Major > otherVer.Major {\n return true\n }\n if ver.Major < otherVer.Major {\n return false\n }\n\n /* same major */\n if ver.Minor > otherVer.Minor {\n return true\n }\n if ver.Minor < otherVer.Minor {\n return false\n }\n\n /* same minor */\n return ver.Patch > otherVer.Patch\n}", "func (id ID) LesserThan(other ID) bool {\n\treturn bytes.Compare(id[:], other[:]) == -1\n}", "func (a Vec2) Less(b Vec2) bool {\n\treturn a.X < b.X && a.Y < b.Y\n}", "func (bi Int) GreaterThan(o Int) bool {\n\treturn Cmp(bi, o) > 0\n}", "func (p *Pairs)Less(i, j int) bool {\n\treturn p.pairs[i][0] + p.pairs[i][1] > p.pairs[j][0] + p.pairs[j][1]\n}", "func (i1 Int) Less(i2 freetree.Comparable) bool { return i1 < i2.(Int) }", "func greaterThanOrEqual(expected float64, actual float64) assert.Comparison {\n\treturn assert.Comparison(func () bool {\n\t\treturn actual >= expected\n\t})\n}", "func greaterThan(expected float64, actual float64) assert.Comparison {\n\treturn assert.Comparison(func () bool {\n\t\treturn actual > expected\n\t})\n}", "func (k *joinKey) less(other joinKey) bool {\n\ta, b := k, other\n\tfor i := 0; i < len(k.values); i++ {\n\t\tif b.values[i].IsNull() {\n\t\t\treturn true\n\t\t} else if a.values[i].IsNull() {\n\t\t\treturn false\n\t\t}\n\n\t\tswitch a.columns[i].Type {\n\t\tcase flux.TBool:\n\t\t\tif av, bv := a.values[i].Bool(), b.values[i].Bool(); av != bv {\n\t\t\t\treturn bv\n\t\t\t}\n\t\tcase flux.TInt:\n\t\t\tif av, bv := a.values[i].Int(), b.values[i].Int(); av != bv {\n\t\t\t\treturn av < bv\n\t\t\t}\n\t\tcase flux.TUInt:\n\t\t\tif av, bv := a.values[i].UInt(), b.values[i].UInt(); av != bv {\n\t\t\t\treturn av < bv\n\t\t\t}\n\t\tcase flux.TFloat:\n\t\t\tif av, bv := a.values[i].Float(), b.values[i].Float(); av != bv {\n\t\t\t\treturn av < bv\n\t\t\t}\n\t\tcase flux.TString:\n\t\t\tif av, bv := a.values[i].Str(), b.values[i].Str(); av != bv {\n\t\t\t\treturn av < bv\n\t\t\t}\n\t\tcase flux.TTime:\n\t\t\tif av, bv := a.values[i].Time(), b.values[i].Time(); av != bv {\n\t\t\t\treturn av < bv\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func (eps Accuracy) Less(a, b float64) bool {\n\treturn math.Max(a, b) == b && math.Abs(a-b) > eps()\n}", "func (bi Int) GreaterThanEqual(o Int) bool {\n\treturn bi.GreaterThan(o) || bi.Equals(o)\n}", "func isMateriallyGreater(a, b float64) bool {\n\treturn (a - b) > 0.001\n}", "func (d Decimal) GreaterThan(d2 Decimal) bool {\n\treturn d.Cmp(d2) == 1\n}", "func (d Decimal) GreaterThan(d2 Decimal) bool {\n\treturn d.Cmp(d2) == 1\n}", "func (src Version) IsGreaterThan(des Version) bool {\n\treturn src.compareWith(des) == Greater\n}", "func Lt(val, max any) bool { return valueCompare(val, max, \"<\") }", "func (a Balance) Less(b Balance) bool {\n\tfor i, valA := range a {\n\t\tvalB := b[i]\n\t\tif valA < valB {\n\t\t\treturn true\n\t\t}\n\t\tif valB < valA {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn false\n}", "func OpTimeGreaterThan(lhs OpTime, rhs OpTime) bool {\n\tif lhs.Term != nil && rhs.Term != nil {\n\t\tif *lhs.Term == *rhs.Term {\n\t\t\treturn util.TimestampGreaterThan(lhs.Timestamp, rhs.Timestamp)\n\t\t}\n\t\treturn *lhs.Term > *rhs.Term\n\t}\n\n\treturn util.TimestampGreaterThan(lhs.Timestamp, rhs.Timestamp)\n}", "func GreaterThanAssert(v1,v2 int) bool{\n\tif v1 > v2 {\n\t\treturn true\n\t} else {\n\t\tif show == true {\n\t\t\tfmt.Printf(\"Failed! %d isn't greater than %d : \\n\",v1,v2)\n\t\t}\n\t\treturn false\n\t}\n}", "func (pq PriorityQueue) Less(i, j int) bool {\n\treturn pq[i].diff > pq[j].diff\n}", "func (f Fixed8) GreaterThan(g Fixed8) bool {\n\treturn f > g\n}", "func (u UUID) GreaterThan(n UUID) bool {\n\tif u.Equal(n) {\n\t\treturn u.Tick > n.Tick\n\t}\n\n\treturn false\n}", "func (this *Tuple) Ne(other *Tuple) bool {\n\treturn !this.Eq(other)\n}", "func (d Decimal) GreaterThanOrEqual(d2 Decimal) bool {\n\tcmp := d.Cmp(d2)\n\treturn cmp == 1 || cmp == 0\n}", "func (d Decimal) GreaterThanOrEqual(d2 Decimal) bool {\n\tcmp := d.Cmp(d2)\n\treturn cmp == 1 || cmp == 0\n}", "func (t *Type) IsComparable() bool", "func (t Tuple) EqualApprox(o Tuple) bool {\n\treturn floats.EqualApprox(t.X, o.X, floats.Epsilon) &&\n\t\tfloats.EqualApprox(t.Y, o.Y, floats.Epsilon) &&\n\t\tfloats.EqualApprox(t.Z, o.Z, floats.Epsilon) &&\n\t\tfloats.EqualApprox(t.W, o.W, floats.Epsilon)\n}", "func (td TupleDesc) Equals(other TupleDesc) bool {\n\tif len(td.Types) != len(other.Types) {\n\t\treturn false\n\t}\n\tfor i, typ := range td.Types {\n\t\tif typ != other.Types[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (b buffer) Less(i, j int) bool {\n\treturn compareByFirstOrNextValue(b[i], b[j]) < 0\n}", "func Gt(val, min any) bool { return valueCompare(val, min, \">\") }", "func (this *TimeInterval) IsAfter(other *TimeInterval) bool {\n\n\treturn this.Ts.Sub(other.Te) >= 0\n}", "func (x uints) Less(i, j int) bool { return x[i] < x[j] }", "func (x uints) Less(i, j int) bool { return x[i] < x[j] }", "func (x uints) Less(i, j int) bool { return x[i] < x[j] }", "func (h tsHeap) Less(i, j int) bool {\n\treturn h[i].ts.Less(h[j].ts)\n}", "func (this FeedQueue) Less(i, j int) bool {\n\treturn this[i].score > this[j].score\n}", "func (b *Builder) IsGreaterOrEqualTo(rhs interface{}) *predicate.Predicate {\n\tb.p.RegisterPredicate(impl.IsGreaterOrEqualTo(rhs))\n\tif b.t != nil {\n\t\tb.t.Helper()\n\t\tEvaluate(b)\n\t}\n\treturn &b.p\n}", "func (pq priorityQueue) Less(i, j int) bool {\n\treturn pq[i].time.Before(pq[j].time)\n}", "func Greaterf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool {\n\tif h, ok := t.(tHelper); ok {\n\t\th.Helper()\n\t}\n\treturn Greater(t, e1, e2, append([]interface{}{msg}, args...)...)\n}", "func (s *GoSort) EqualsThan(i, j int) bool {\n return s.comparator(s.values[i], s.values[j]) == 0\n}", "func (f Fixed) GreaterThanOrEqual(f0 Fixed) bool {\n\tcmp := f.Cmp(f0)\n\treturn cmp == 1 || cmp == 0\n}", "func (f Fixed) GreaterThanOrEqual(f0 Fixed) bool {\n\tcmp := f.Cmp(f0)\n\treturn cmp == 1 || cmp == 0\n}", "func (b *Builder) IsGreaterThan(rhs interface{}) *predicate.Predicate {\n\tb.p.RegisterPredicate(impl.IsGreaterThan(rhs))\n\tif b.t != nil {\n\t\tb.t.Helper()\n\t\tEvaluate(b)\n\t}\n\treturn &b.p\n}", "func (v *APIVersion) GreaterOrEquals(other APIVersion) bool {\n\tif v.Major < other.Major {\n\t\treturn false\n\t}\n\treturn v.Major > other.Major || v.Minor >= other.Minor\n}", "func Gt(x, y int) bool {\n\treturn x > y\n}", "func (s NodeSlice) Less(i, j int) bool {\n\treturn s[i].MemFree > s[j].MemFree\n}", "func (r *rankImpl) Greater(a, b string) bool {\n\treturn !r.Equal(a, b) && !r.Less(a, b)\n}", "func (c UintCompare) IsLess(lhs, rhs uint) bool { return c(lhs, rhs) }", "func EqualsValTuple(a, b ValTuple) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(a); i++ {\n\t\tif !EqualsExpr(a[i], b[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (t toc) Less(i, j int) bool {\n\treturn t[i].value < t[j].value\n}", "func EQ(x float64, y float64) bool {\n\treturn (y-e < x) && (x < y+e)\n}", "func IsGreaterThan(timeLeft time.Time, timeRight time.Time) bool {\n\tdurDelta := timeLeft.Sub(timeRight)\n\tif durZero, _ := time.ParseDuration(\"0ns\"); durDelta > durZero {\n\t\treturn true\n\t}\n\treturn false\n}", "func Greater(v1, v2 string) (bool, error) {\n\tif v1 == \"\" && v2 != \"\" {\n\t\treturn false, nil\n\t}\n\tif v1 != \"\" && v2 == \"\" {\n\t\treturn false, nil\n\t}\n\tsv1, err := semver.Make(v1)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tsv2, err := semver.Make(v2)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn sv1.GTE(sv2), nil\n}", "func GreaterThanOrEqual(v1 interface{}, v2 interface{}) bool {\n\treturn GreaterThan(v1, v2) || v1 == v2\n}", "func (x IntSlice) Bigger(i,j int) bool{\n if x[i]>x[j]{// comparing two int\n return true\n }\n return false\n }", "func (qt QueryTimes) Less(i, j int) bool { return qt[i] < qt[j] }", "func (c *GreaterEqual) CompatibleWith(c2 Constraint) (bool, error) {\n\tswitch c2.Type() {\n\tcase TypeGreater, TypeGreaterEqual, TypeOneOf:\n\t\treturn false, nil\n\tcase TypeLess:\n\t\treturn c.val.Less(c2.Param().(value.Single))\n\tcase TypeLessEqual:\n\t\treturn c.val.LessEqual(c2.Param().(value.Single))\n\t}\n\n\treturn true, nil\n}", "func Greater(t *testing.T, a, b int) {\n\tt.Helper()\n\n\tif !(a > b) {\n\t\tt.Errorf(`%s: %d should be greater than %d`, t.Name(), a, b)\n\t}\n}", "func TupleElemEq(lhsi interface{}, rhsi interface{}) bool {\n\tlhsv, rhsv := reflect.ValueOf(lhsi), reflect.ValueOf(rhsi)\n\t// IsNil panics if type is not interface-y, so use IsValid instead\n\tif lhsv.IsValid() != rhsv.IsValid() {\n\t\treturn false\n\t}\n\t// TODO: this currently blows up if lhs can't be converted to same\n\t// type as rhs (e.g. int vs. string)\n\tswitch lhsi.(type) {\n\tcase nil:\n\t\tif rhsv.IsValid() {\n\t\t\treturn false\n\t\t}\n\tcase string:\n\t\tif lhsi.(string) != rhsi.(string) {\n\t\t\treturn false\n\t\t}\n\tcase int, int8, int16, int32, int64:\n\t\tif lhsv.Int() != rhsv.Int() {\n\t\t\treturn false\n\t\t}\n\tcase uint, uintptr, uint8, uint16, uint32, uint64:\n\t\tif lhsv.Uint() != rhsv.Uint() {\n\t\t\treturn false\n\t\t}\n\tcase float32, float64:\n\t\tif lhsv.Float() != rhsv.Float() {\n\t\t\treturn false\n\t\t}\n\tcase *Tuple:\n\t\tif lhsi.(*Tuple).Ne(rhsi.(*Tuple)) {\n\t\t\treturn false\n\t\t}\n\tdefault:\n\t\t//if !lhsv.IsValid() && !rhsv.IsValid() {\n\t\t//return false\n\t\t//}\n\t\t// TODO: allow user-defined callback for unsupported types\n\t\tpanic(fmt.Sprintf(\"unsupported type %#v for Eq in Tuple\", lhsi))\n\t}\n\treturn true\n}", "func (self Mset) Geq (other Mset) bool {\n\tif self.size < other.size {\n\t\treturn false\n\t}\n\tfor iter, key, val := other.h.Iter(); key != nil; key, val = iter.Next() {\n\t\tk, v := self.h.Get(*key)\n\t\tif k == nil {\n\t\t\treturn false\n\t\t} else if (*v).(uint64) < (*val).(uint64) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (v *RelaxedVersion) GreaterThanOrEqual(u *RelaxedVersion) bool {\n\treturn v.CompareTo(u) >= 0\n}", "func (pq PrioQueue) Less(i, j int) bool {\n\treturn pq[j].IsLongerThan(pq[i])\n}", "func (a Uint64) Less(b btree.Item) bool {\n\treturn a < b.(Uint64)\n}", "func (firstDate Nakamura) GreaterThan(secondDate Nakamura) bool {\n\treturn GreaterThan(firstDate, secondDate, secondDate.format)\n}", "func (h ReqHeap) Less(i, j int) bool { return h[i].Timestamp.Before(h[j].Timestamp) }" ]
[ "0.67103213", "0.6682943", "0.6405361", "0.6349489", "0.6347604", "0.6269906", "0.6263092", "0.6047359", "0.6021726", "0.6013786", "0.59681875", "0.5929761", "0.58839434", "0.5878891", "0.5847747", "0.5798595", "0.57832897", "0.5777936", "0.5768222", "0.57614046", "0.57372475", "0.570907", "0.5699963", "0.5684249", "0.56579304", "0.56517273", "0.5651222", "0.5651222", "0.56512153", "0.56511706", "0.56491184", "0.5637903", "0.55692816", "0.55677044", "0.5560568", "0.55492055", "0.55474776", "0.5532193", "0.5507634", "0.5502908", "0.54703355", "0.5464068", "0.54604477", "0.5451933", "0.54439926", "0.54423976", "0.54385483", "0.54379106", "0.54379106", "0.5431815", "0.54235387", "0.5386505", "0.53755033", "0.53680474", "0.5339522", "0.5329179", "0.5321928", "0.5309525", "0.52971226", "0.52971226", "0.52967817", "0.5296535", "0.5278399", "0.5275252", "0.52691376", "0.5262859", "0.526052", "0.526052", "0.526052", "0.52555954", "0.52436966", "0.52344185", "0.52338994", "0.52302897", "0.52287865", "0.5212025", "0.5212025", "0.5208903", "0.51771057", "0.516922", "0.51677924", "0.5162243", "0.5156277", "0.51515454", "0.5151185", "0.51493156", "0.5148906", "0.5145223", "0.51413417", "0.5134687", "0.51317674", "0.5129376", "0.5117923", "0.51148754", "0.5111774", "0.51039994", "0.5103167", "0.5103016", "0.5102261", "0.5101366" ]
0.6474378
2
Returns the position of item in the tuple. The search starts from position start. Returns 1 if item is not found
func (this *Tuple) Index(item interface{}, start int) int { for i := start; i < this.Len(); i++ { if TupleElemEq(this.Get(i), item) { return i } } return -1 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func getIndItem (items [] string, finder string) int {\n\tfor i := 0; i < len(items); i++ {\n\t\tif items[i] == finder {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func findPosition(value int, data []int) int {\n\tif len(data) == 0 {\n\t\treturn -1\n\t}\n\tfor index := 0; index < len(data); index++ {\n\t\tif data[index] == value {\n\t\t\treturn index\n\t\t}\n\t}\n\treturn -1\n}", "func (s items) find(item Item, ctx interface{}) (index int, found bool) {\n\ti, j := 0, len(s)\n\tfor i < j {\n\t\th := i + (j-i)/2\n\t\tif !item.Less(s[h], ctx) {\n\t\t\ti = h + 1\n\t\t} else {\n\t\t\tj = h\n\t\t}\n\t}\n\tif i > 0 && !s[i-1].Less(item, ctx) {\n\t\treturn i - 1, true\n\t}\n\treturn i, false\n}", "func (list *List) FindPositionofElement(data int) int {\n // 1. Get the current head of list\n current := list.Head()\n\n // 2. Set position integer to 1\n position := 1\n\n // 3. Loop over the list until requested element is found and keep track of position\n for current != nil {\n if current.data == data {\n return position\n }\n current = current.next\n position++\n }\n\n // 4. Return -1 if the requested element is not found\n return -1\n\n}", "func (slice stringSlice) pos(value string) int {\n\tfor p, v := range slice {\n\t\tif v == value {\n\t\t\treturn p\n\t\t}\n\t}\n\n\treturn -1\n}", "func find(slice []int, value int) int {\n\tfor i, item := range slice {\n\t\tif item == value {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func FindInt(slice []int, val int) (int, bool) {\n for i, item := range slice {\n if item == val {\n return i, true\n }\n\t}\n return -1, false\n}", "func FindPosition(nums []int, target int) int {\n\tfor i := range nums {\n\t\tif target == nums[i] {\n\t\t\treturn i\n\t\t} else if target < nums[i] {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn len(nums)\n}", "func indexOf(list []int, valueToBeFound int) int {\n\tfor i, value := range list {\n\t\tif value == valueToBeFound {\n\t\t\treturn i\n\t\t}\n\t}\n\n\treturn -1\n}", "func Find(slice []string, val string) (int, bool) {\n for i, item := range slice {\n if item == val {\n return i, true\n }\n }\n return -1, false\n}", "func posString(slice []string, element string) int {\n\tfor index, elem := range slice {\n\t\tif elem == element {\n\t\t\treturn index\n\t\t}\n\t}\n\treturn -1\n}", "func posString(slice []string, element string) int {\n\tfor index, elem := range slice {\n\t\tif elem == element {\n\t\t\treturn index\n\t\t}\n\t}\n\treturn -1\n}", "func posString(slice []string, element string) int {\n\tfor index, elem := range slice {\n\t\tif elem == element {\n\t\t\treturn index\n\t\t}\n\t}\n\treturn -1\n}", "func posString(slice []string, element string) int {\n\tfor index, elem := range slice {\n\t\tif elem == element {\n\t\t\treturn index\n\t\t}\n\t}\n\treturn -1\n}", "func posString(slice []string, element string) int {\n\tfor index, elem := range slice {\n\t\tif elem == element {\n\t\t\treturn index\n\t\t}\n\t}\n\treturn -1\n}", "func IntIndexOf(sorted []int, item int, lt IntLessThan) int {\n\ti := IntBinarySearch(sorted, item, lt)\n\tif !lt(sorted[i], item) && !lt(item, sorted[i]) {\n\t\treturn i\n\t}\n\treturn -1\n}", "func index(slice []string, item string) int {\n\tfor i := range slice {\n\t\tif slice[i] == item {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func findItemInSequence(sequenceKey string, findVal *goyaml.Node, sequenceNode *goyaml.Node) int {\n\tchildren := sequenceNode.Content\n\tfor i, val := range children {\n\t\tif sequenceItemMatch(sequenceKey, val, findVal) {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func Find(slice []string, val string) (int, bool) {\n for i, item := range slice {\n if item == val {\n return i, true\n }\n\t}\n return -1, false\n}", "func Find(a []string, x string) int {\n\tfor i, n := range a {\n\t\tif x == n {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func getOccurrencePosition(arr []int, key, firstPos, lastPos, res int, findFirstOccr bool) int {\n\n\tif firstPos <= lastPos {\n\t\tmidIdx := (firstPos+lastPos)/2\n\t\tif arr[midIdx] == key {\n\t\t\tres = midIdx\n\t\t\tif findFirstOccr {\n\t\t\t\treturn getOccurrencePosition(arr, key, firstPos, midIdx-1, res, findFirstOccr)\n\t\t\t} else {\n\t\t\t\treturn getOccurrencePosition(arr, key, midIdx+1, lastPos, res, findFirstOccr)\n\t\t\t}\n\t\t} else if arr[midIdx] < key {\n\t\t\t// search in right hand side of array in case array is sorted in ascending order\n\t\t\treturn getOccurrencePosition(arr, key, midIdx+1, lastPos, res, findFirstOccr)\n\t\t} else {\n\t\t\t// arr[midIdx] > key, i.e. search in first half of the array\n\t\t\treturn getOccurrencePosition(arr, key, firstPos, midIdx-1, res, findFirstOccr)\n\t\t}\n\t}\n\treturn res\n}", "func searchLinear(nums []uint, n uint) int {\n\tfor i := 0; i < len(nums); i++ {\n\t\tif nums[i] == n {\n\t\t\treturn int(n)\n\t\t}\n\t}\n\treturn -1\n}", "func (v IntVec) Find(find func(e int) bool) (idx int, res int) {\n\tfor i, e := range v {\n\t\tif find(e) {\n\t\t\treturn i, e\n\t\t}\n\t}\n\n\tidx = -1\n\treturn\n}", "func search(s []int, e int) int {\n\tstart := 0\n\tend := len(s)\n\tfor start < end {\n\t\ti := start + (end - start)/2\n\t\tif e > s[i] {\n\t\t\tstart = i+1\n\t\t} else if e < s[i] {\n\t\t\tend = i\n\t\t} else {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func findInsertionIndex(list []int, item int) int {\n\tif len(list) == 0 {\n\t\treturn 0\n\t}\n\n\thigh := len(list) - 1\n\tlow := 0\n\tmid := len(list) / 2\n\n\tfor {\n\t\tif item < list[mid] {\n\t\t\tif mid == 0 || item >= list[mid-1] {\n\t\t\t\treturn mid\n\t\t\t} else if mid-low == 1 {\n\t\t\t\tmid = low\n\t\t\t} else {\n\t\t\t\thigh, mid = mid, mid-((mid-low)/2)\n\t\t\t}\n\t\t} else if item > list[mid] {\n\t\t\tif mid == len(list)-1 || item <= list[mid+1] {\n\t\t\t\treturn mid + 1\n\t\t\t} else if high-mid == 1 {\n\t\t\t\tmid = high\n\t\t\t} else {\n\t\t\t\tlow, mid = mid, mid+((high-mid)/2)\n\t\t\t}\n\t\t} else {\n\t\t\treturn mid\n\t\t}\n\t}\n}", "func findIndexByItem(keyName string, items []string) (int, bool) {\n\n\tfor index := range items {\n\t\tif keyName == items[index] {\n\t\t\treturn index, true\n\t\t}\n\t}\n\n\treturn -1, false\n}", "func (rl RangeList) findPosition(number int) int {\n\tif len(rl.list) <= 0 {\n\t\treturn -1\n\t}\n\n\tleft := 0\n\tright := len(rl.list) - 1\n\tfor left <= right {\n\t\tmid := (left + right) / 2\n\t\tif number < rl.list[mid][leftIdx] {\n\t\t\tright = mid - 1\n\t\t}\n\t\tif number > rl.list[mid][leftIdx] {\n\t\t\tleft = mid + 1\n\t\t}\n\t\tif number == rl.list[mid][leftIdx] {\n\t\t\treturn mid\n\t\t}\n\t}\n\n\tif left < right {\n\t\treturn left\n\t} else {\n\t\treturn right\n\t}\n}", "func find(slice []string, val string) (int, bool) {\n\tfor i, item := range slice {\n\t\tif item == val {\n\t\t\treturn i, true\n\t\t}\n\t}\n\treturn -1, false\n}", "func find(slice []string, val string) (int, bool) {\n\tfor i, item := range slice {\n\t\tif item == val {\n\t\t\treturn i, true\n\t\t}\n\t}\n\treturn -1, false\n}", "func find(slice []string, val string) (int, bool) {\n\tfor i, item := range slice {\n\t\tif item == val {\n\t\t\treturn i, true\n\t\t}\n\t}\n\treturn -1, false\n}", "func LinearSearch(list []int, key int) int {\n\tfor index, element := range list {\n\t\tif key == element {\n\t\t\treturn index\n\t\t}\n\t}\n\n\treturn -1\n}", "func (iter *Iterator) Position() uint64 { return iter.impl.Value() }", "func (ts TagSet) Find(tag string) int {\n\tfor i := range ts {\n\t\tif ts[i] == tag {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func Find(a []string, x string) int {\n\tfor index, value := range a {\n\t\tif x == value {\n\t\t\treturn index\n\t\t}\n\t}\n\treturn len(a)\n}", "func (this *Tuple) Count(item interface{}, start int) int {\n\tctr := 0\n\tfor i := start; i < this.Len(); i++ {\n\t\tif TupleElemEq(this.Get(i), item) {\n\t\t\tctr += 1\n\t\t}\n\t}\n\treturn ctr\n}", "func (l *list) FindIndex(fn EachElementCallback) int {\n\tvar i = -1\n\n\tfor k, v := range l.elements {\n\t\tres := fn(k, v)\n\t\tif nil != res {\n\t\t\ti = k\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn i\n}", "func find(s []string, pattern string) (int, bool) {\n for i, item := range s {\n if item == pattern {\n return i, true\n }\n }\n return -1, false\n}", "func (list *ArrayList[T]) IndexOf(ele T) int {\n\tfor i := 0; i < list.Size(); i++ {\n\t\tif ele == list.elems[i] {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func (s *GoSort) FindMinElementAndIndex() (interface{}, int) {\n var index = 0\n \n for i := 1; i < s.Len(); i++ {\n if s.LessThan(i, index) {\n index = i\n }\n }\n return s.values[index], index\n}", "func (l *LinkedList) Search(val int) int {\n if l.Root == nil {\n return -1\n }\n\n n := l.Root\n\n for i := 0; n != nil; i++ {\n if n.Value == val {\n return i\n }\n\n n = n.Next\n }\n return -1\n}", "func find(a []string, x string) int {\n\tfor i, n := range a {\n\t\tif x == n {\n\t\t\treturn i\n\t\t}\n\n\t}\n\treturn len(a)\n}", "func (s *nodeBlock) find(key uint128) (index int, found bool) {\n\ti := sort.Search(int(s.itemsSize), func(i int) bool {\n\t\treturn key.less(s.items[i].key)\n\t})\n\tif i > 0 && s.items[i-1].key == key {\n\t\treturn i - 1, true\n\t}\n\treturn i, false\n}", "func getTaskPosition(id interface{}) (int, bool) {\n\tfor i, v := range tasks {\n\t\tif v == id {\n\t\t\treturn i, true\n\t\t}\n\t}\n\n\treturn 0, false\n}", "func (ll *LinkedList) IndexOf(t Item) int {\n\tll.lock.RLock()\n\tdefer ll.lock.RUnlock()\n\n\tif ll.head == nil {\n\t\treturn 0\n\t}\n\n\tnode := ll.head\n\tj := 0\n\n\tfor {\n\t\tif node.content == t {\n\t\t\treturn j\n\t\t}\n\n\t\tif node.next == nil {\n\t\t\treturn -1\n\t\t}\n\t\tnode = node.next\n\t\tj++\n\t}\n}", "func (l *Leaf) locate(key []byte) int {\n\ti := 0\n\tsize := len(l.Keys)\n\tfor {\n\t\tmid := (i + size) / 2\n\t\tif i == size {\n\t\t\tbreak\n\t\t}\n\t\tif bytes.Compare(l.Keys[mid], key) <= 0 {\n\t\t\ti = mid + 1\n\t\t} else {\n\t\t\tsize = mid\n\t\t}\n\t}\n\treturn i\n}", "func index(vs []int, t int) int {\n\tfor i, v := range vs {\n\t\tif v == t {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func (t tagSet) Search(key string) int {\n\ti, j := 0, len(t)\n\tfor i < j {\n\t\th := (i + j) / 2\n\t\tif t[h].key < key {\n\t\t\ti = h + 1\n\t\t} else {\n\t\t\tj = h\n\t\t}\n\t}\n\treturn i\n}", "func (enum Enum) Index(findValue string) int {\n\tfor idx, item := range enum.items {\n\t\tif findValue == item.value {\n\t\t\treturn idx\n\t\t}\n\t}\n\treturn -1\n}", "func searchByPos(idarr []identifier, pos token.Position) (identifier, bool) {\n\tvar ret identifier\n\n\tfor _, id := range idarr {\n\t\tif id.pos == pos {\n\t\t\treturn id, true\n\t\t}\n\t}\n\treturn ret, false\n}", "func find(element string, data []string) (int) {\n\tfor k, v := range data {\n\t\tif element == v {\n\t\t\treturn k\n\t\t}\n\t}\n\treturn -1\n}", "func (s strings) Find(in []string, what string) int {\n\tfor i, entry := range in {\n\t\tif entry == what {\n\t\t\treturn i\n\t\t}\n\t}\n\n\treturn -1\n}", "func FindIndex(arr []string, value string) int {\n\tfor index, item := range arr {\n\t\tif item == value {\n\t\t\treturn index\n\t\t}\n\t}\n\n\treturn -1\n}", "func (l ObjectList) find(obj Object) (int, bool) {\n\n\t// Check if the vertex exists in the list and return its index if it does\n\tfor i := 0; i < len(l); i++ {\n\t\tif l[i] == obj {\n\t\t\treturn i, true\n\t\t}\n\t}\n\n\t// If not, indicate non-existence and return negative index\n\treturn indexNoExist, false\n}", "func Index(ss []string, s string) int {\n\tfor i, b := range ss {\n\t\tif b == s {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func PyTuple_GetItem(o *PyObject, pos int) *PyObject {\n\treturn c2go(C.__PyTuple_GetItem(go2c(o), C.Py_ssize_t(pos)))\n}", "func findIndex(v []string, s string, i int) int {\n\tif s == \"\" {\n\t\tif i < len(v) {\n\t\t\treturn i\n\t\t}\n\t\treturn -1\n\t}\n\treturn indexOf(v, s)\n}", "func (t Table) GetPos(d Data) (int64, error) {\n\tdb, err := openDB(t.Config)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer db.Close()\n\tdirection := \"\"\n\tif d.DescOrder {\n\t\tdirection = \"DESC\"\n\t}\n\tsqlQuery := fmt.Sprintf(`SELECT ROW_NUMBER FROM (SELECT ROW_NUMBER() OVER (ORDER BY %s %s), %s FROM %s) x WHERE %s=$1`, d.OrderBy, direction, d.Key, t.Name, d.Key)\n\trow := db.QueryRow(sqlQuery, d.KeyVal)\n\tvar position int64\n\terr = row.Scan(&position)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn position, nil\n}", "func find(slice [][]rune, val []rune) int {\n\tfor i, item := range slice {\n\t\tif utils.Equal(item, val) {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func (invertedIndex *InvertedIndex) FindItem(Term uint64) int {\n\tfor index, item := range invertedIndex.Items {\n\t\tif item.Term == Term {\n\t\t\treturn index\n\t\t}\n\t}\n\t\n\tpanic(\"Not Found\")\n}", "func (v Int32Vec) Find(find func(e int32) bool) (idx int, res int32) {\n\tfor i, e := range v {\n\t\tif find(e) {\n\t\t\treturn i, e\n\t\t}\n\t}\n\n\tidx = -1\n\treturn\n}", "func Find(slice []string, val string) (int, bool) {\n\tfor i, item := range slice {\n\t\tif item == val {\n\t\t\treturn i, true\n\t\t}\n\t}\n\treturn -1, false\n}", "func Find(slice []string, val string) (int, bool) {\n\tfor i, item := range slice {\n\t\tif item == val {\n\t\t\treturn i, true\n\t\t}\n\t}\n\treturn -1, false\n}", "func Find(slice []string, val string) (int, bool) {\n\tfor i, item := range slice {\n\t\tif item == val {\n\t\t\treturn i, true\n\t\t}\n\t}\n\treturn -1, false\n}", "func Find(slice []string, val string) (int, bool) {\n\tfor i, item := range slice {\n\t\tif item == val {\n\t\t\treturn i, true\n\t\t}\n\t}\n\treturn -1, false\n}", "func search(nums []int, target int) int {\n\tfor i,v := range nums {\n\t\tif v == target {\n\t\t\treturn i\n\t\t}\n\t}\n\n\treturn -1\n}", "func IntBinarySearch(sorted []int, item int, lt IntLessThan) int {\n\t// Define f(-1) == false and f(n) == true.\n\t// Invariant: f(i-1) == false, f(j) == true.\n\ti, j := 0, len(sorted)-1\n\tfor i < j {\n\t\th := int(uint(i+j) >> 1) // avoid overflow when computing h\n\t\t// i ≤ h < j\n\t\tif lt(sorted[h], item) {\n\t\t\ti = h + 1 // preserves f(i-1) == false\n\t\t} else {\n\t\t\tj = h // preserves f(j) == true\n\t\t}\n\t}\n\t// i == j, f(i-1) == false, and f(j) (= f(i)) == true => answer is i.\n\treturn i\n}", "func (t *Indexed) Find(x int) (value int, exists bool) {\n\tn := t.find(t.root, x)\n\tif n == nil {\n\t\treturn 0, false\n\t}\n\treturn n.value, true\n}", "func search(numbers []int, value int) (int, error) {\n\tfor i := range numbers {\n\t\tif numbers[i] == value {\n\t\t\treturn i, nil\n\t\t}\n\t}\n\n\treturn 0, errors.New(\"Not found\")\n}", "func (i *Iter) Pos() int {\n\treturn i.p\n}", "func IntExist(needle int, haystack []int) (int, bool) {\n\tvar (\n\t\texist bool\n\t\tindex int\n\t)\n\n\tfor i, n := range haystack {\n\t\tif n == needle {\n\t\t\texist = true\n\t\t\tindex = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn index, exist\n}", "func (n *bTreeNode) find(e IndexElem) uint {\n\ti := sort.Search(len(n.elems), func(i int) bool {\n\t\treturn e.Less(n.elems[i])\n\t})\n\tif i < 0 {\n\t\tpanic(fmt.Sprintf(\"i cannot be < 0, got %d\", i))\n\t}\n\treturn uint(i)\n}", "func (q *memQueue) position(datum []byte) (pos int, err error) {\n\tfor pos, candidate := range q.q {\n\t\tif bytes.Equal(candidate, datum) {\n\t\t\treturn pos, nil\n\t\t}\n\t}\n\n\treturn -1, nil\n}", "func (gc *GisCache) GetPosition(typ string, name string) (*Position, error) {\n\tkey := gc.baseKey + posKey + typ + \":\" + name\n\n\t// Create position map\n\tpositionMap := make(map[string]*Position)\n\n\t// Get all position entry details\n\terr := gc.rc.ForEachEntry(key, getPosition, &positionMap)\n\tif err != nil {\n\t\tlog.Error(\"Failed to get all entries with error: \", err.Error())\n\t\treturn nil, err\n\t}\n\n\t// only one result, so return the first one\n\tfor _, position := range positionMap {\n\t\treturn position, nil\n\t}\n\treturn nil, nil\n}", "func (s *String) BitPos(bit, begin, end int) (int, error) {\n\tbegin, end = initCursor(begin, end, len(s.Meta.Value))\n\t// For empty ranges (start > end) we return -1 as an empty range does\n\t// not contain a 0 nor a 1.\n\tif begin > end {\n\t\treturn -1, nil\n\t}\n\treturn redisBitpos(s.Meta.Value[begin:end+1], bit), nil\n}", "func (list *List) IndexOf(value interface{}) int {\n\tif list.size == 0 {\n\t\treturn -1\n\t}\n\tfor index, element := range list.Values() {\n\t\tif element == value {\n\t\t\treturn index\n\t\t}\n\t}\n\treturn -1\n}", "func (l *LinkedList) Search(val interface{}) int {\n\tptr := l.head\n\tfor i := 0; i < l.len; i++ {\n\t\tif ptr.data == val {\n\t\t\treturn i\n\t\t}\n\t\tptr = ptr.next\n\t}\n\treturn -1\n}", "func Search(s string, list []string) int {\n\tfor i, sl := range list {\n\t\tif sl == s {\n\t\t\treturn i\n\t\t}\n\t}\n\n\treturn -1\n}", "func (v Set) indexOf(iPk *big.Int) (int, bool) {\n\t// use binary search to get the index of the element\n\tidx := sort.Search(len(v), func(i int) bool {\n\t\treturn v[i].Cmp(iPk) >= 0\n\t})\n\n\tif idx < len(v) && iPk.Cmp(v[idx]) == 0 {\n\t\t// the element is actually found at the index\n\t\treturn idx, true\n\t}\n\n\t// the element wasn't found\n\treturn idx, false\n}", "func (s *S43_SmallSetOfIntegers) SEARCH(n int) int {\n\tfor i := 0; i < s.size; i++ {\n\t\tif s.content[i] != n {\n\t\t\tcontinue\n\t\t}\n\t\treturn i\n\t}\n\treturn s.size\n}", "func (n *Node) locate(key []byte) int {\n\ti := 0\n\tsize := len(n.Keys)\n\tfor {\n\t\tmid := (i + size) / 2\n\t\tif i == size {\n\t\t\tbreak\n\t\t}\n\t\tif bytes.Compare(n.Keys[mid], key) <= 0 {\n\t\t\ti = mid + 1\n\t\t} else {\n\t\t\tsize = mid\n\t\t}\n\t}\n\treturn i\n}", "func (this *activitiesStruct) searchActivity(begin time.Time) (int, bool) {\n\tgroups := this.groups\n\tnumGroups := len(groups)\n\tidxLeft := int(0)\n\n\t/*\n\t * The case that there are no groups requires special handling.\n\t */\n\tif numGroups > 0 {\n\t\tidxRight := numGroups - 1\n\n\t\t/*\n\t\t * Binary search algorithm.\n\t\t */\n\t\tfor idxLeft <= idxRight {\n\t\t\tdiff := idxRight - idxLeft\n\t\t\tdiffHalf := diff / 2\n\t\t\tidxPivot := idxLeft + diffHalf\n\t\t\tpivot := groups[idxPivot]\n\t\t\tpivotBegin := pivot.begin\n\n\t\t\t/*\n\t\t\t * Check if we have to continue searching in left or\n\t\t\t * right half.\n\t\t\t */\n\t\t\tif pivotBegin.After(begin) {\n\t\t\t\tidxRight = idxPivot - 1\n\n\t\t\t\t/*\n\t\t\t\t * Prevent underflow.\n\t\t\t\t */\n\t\t\t\tif idxRight > idxPivot {\n\t\t\t\t\tidxRight = idxPivot\n\t\t\t\t}\n\n\t\t\t} else if pivotBegin.Before(begin) {\n\t\t\t\tidxLeft = idxPivot + 1\n\n\t\t\t\t/*\n\t\t\t\t * Prevent overflow.\n\t\t\t\t */\n\t\t\t\tif idxLeft < idxPivot {\n\t\t\t\t\tidxLeft = idxPivot\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\treturn idxPivot, true\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\treturn idxLeft, false\n}", "func (n *node) find(key int) (int, bool) {\n\tidx := sort.Search(n.count, func(i int) bool {\n\t\treturn n.keys[i] >= key\n\t})\n\n\tif idx < n.count && key == n.keys[idx] {\n\t\treturn idx, true\n\t}\n\treturn idx, false\n}", "func IndexOf(data interface{}, search interface{}, args ...int) (int, error) {\n\tvar err error\n\n\tresult := func(err *error) int {\n\t\tdefer catch(err)\n\n\t\tif !isNonNilData(err, \"data\", data) {\n\t\t\treturn -1\n\t\t}\n\n\t\tdataValue, _, _, dataValueLen := inspectData(data)\n\n\t\tif !isSlice(err, \"data\", dataValue) {\n\t\t\treturn -1\n\t\t}\n\n\t\tstartIndex := 0\n\t\tif len(args) > 0 {\n\t\t\tstartIndex = args[0]\n\t\t}\n\n\t\tif startIndex >= dataValueLen {\n\t\t\treturn -1\n\t\t}\n\n\t\tif dataValueLen == 0 {\n\t\t\treturn -1\n\t\t}\n\n\t\tresult := -1\n\n\t\tforEachSliceStoppable(dataValue, dataValueLen, func(each reflect.Value, i int) bool {\n\t\t\tif startIndex > -1 {\n\t\t\t\tif startIndex > 0 && i < startIndex {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\t\tif each.Interface() == search && result == -1 {\n\t\t\t\t\tresult = i\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif i > (startIndex*-1)-1 {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\t\tiFromRight := dataValueLen - i - 1\n\t\t\t\teachFromRight := dataValue.Index(iFromRight)\n\n\t\t\t\tif eachFromRight.Interface() == search {\n\t\t\t\t\tresult = iFromRight\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn true\n\t\t})\n\n\t\treturn result\n\t}(&err)\n\n\treturn result, err\n}", "func TestLinearSearch(t *testing.T) {\n\ta := []int{23, 45, 67, 27, 32, 87, 90, 12}\n\tposition := LinearSearch(a, 67)\n\n\tassert.Equal(t, 3, position, \"Oops.. linear search didn't work!!\")\n}", "func getStartIndex(st int32, a []int32) int {\n\tif st <= a[0] {\n\t\treturn 0 // st a[0]......a[len(a) - 1]\n\t}\n\tif st == a[len(a)-1] {\n\t\treturn len(a) - 1\n\t}\n\tif st > a[len(a)-1] {\n\t\treturn -1 // a[0]......a[len(a) - 1] st\n\t}\n\treturn sort.Search(len(a), func(i int) bool {\n\t\treturn a[i] >= st // a[0], a[1], st, a[2], a[3]....a[len(a) - 1]\n\t})\n}", "func (s *Set) Index(v string) (int, bool) {\n\tslot, found := s.findSlot(v)\n\tif !found {\n\t\treturn 0, false\n\t}\n\n\tindexPlusOne := s.table[slot]\n\treturn int(indexPlusOne - 1), true\n}", "func (f intFinder) find(rid int) (int, bool) {\n\tline, ok := f.m[rid]\n\treturn line, ok\n}", "func (list List) Index(element interface{}) int {\n\tfor k, v := range list {\n\t\tif element == v {\n\t\t\treturn k\n\t\t}\n\t}\n\treturn -1\n}", "func (q *QQwry) searchIndex(ip uint32) uint32 {\n\theader := q.readData(8, 0)\n\n\tstart := binary.LittleEndian.Uint32(header[:4])\n\tend := binary.LittleEndian.Uint32(header[4:])\n\n\tbuf := make([]byte, INDEX_LEN)\n\tmid := uint32(0)\n\t_ip := uint32(0)\n\n\tfor {\n\t\tmid = q.getMiddleOffset(start, end)\n\t\tbuf = q.readData(INDEX_LEN, int64(mid))\n\t\t_ip = binary.LittleEndian.Uint32(buf[:4])\n\n\t\tif end-start == INDEX_LEN {\n\t\t\toffset := byte3ToUInt32(buf[4:])\n\t\t\tbuf = q.readData(INDEX_LEN)\n\t\t\tif ip < binary.LittleEndian.Uint32(buf[:4]) {\n\t\t\t\treturn offset\n\t\t\t}\n\t\t\treturn 0\n\t\t}\n\n\t\t// greater than ip, so move before\n\t\tif _ip > ip {\n\t\t\tend = mid\n\t\t} else if _ip < ip { // less than ip, so move after\n\t\t\tstart = mid\n\t\t} else if _ip == ip {\n\t\t\treturn byte3ToUInt32(buf[4:])\n\t\t}\n\t}\n}", "func contains(array []int32, item int32) int {\n\tfor index, currentItem := range array {\n\t\tif currentItem == item {\n\t\t\treturn index\n\t\t}\n\t}\n\treturn -1\n}", "func Index(s, t string) int {\n\tx := 0\n\ty := 0\n\tfor _, c := range s {\n\t\tif c == c {\n\t\t\tx++\n\t\t}\n\t}\n\tfor _, c := range t {\n\t\tif c == c {\n\t\t\ty++\n\t\t}\n\t}\n\tfor i := 0; i < x; i++ {\n\t\tif y != 0 && s[i] == t[0] {\n\t\t\tok := true\n\t\t\tmok := 0\n\t\t\tfor j := 0; j < y; j++ {\n\t\t\t\tif i+mok >= x || t[j] != s[i+mok] {\n\t\t\t\t\tok = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tmok++\n\t\t\t}\n\t\t\tif ok == true {\n\t\t\t\treturn i\n\t\t\t}\n\t\t}\n\t}\n\treturn -1\n}", "func LinearSearch(arr []int, v int) int {\n\tfor i, val := range arr {\n\t\tif val == v {\n\t\t\treturn i\n\t\t}\n\t}\n\n\treturn -1\n}", "func (a Slice[T]) Index(element T) int {\n\tfor i, o := range a {\n\t\tif o == element {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func FindInSlice(slice []string, val string) (int, bool) {\r\n\tfor i, item := range slice {\r\n\t\tif item == val {\r\n\t\t\treturn i, true\r\n\t\t}\r\n\t}\r\n\treturn -1, false\r\n}", "func (li *List) ItemPosition(item IPanel) int {\n\n\tfor pos := 0; pos < len(li.items); pos++ {\n\t\tif li.items[pos].(*ListItem).item == item {\n\t\t\treturn pos\n\t\t}\n\t}\n\treturn -1\n}", "func findString(list []string, p string) (bool, int){\n\tfor ind, l := range list{\n\t\tif l == p {\n\t\t\treturn true, ind\n\t\t}\n\t}\n\treturn false, -1\n}", "func FindIndex(text, pat string) int {\n\tlsp := LspTable(pat)\n\ti, j := 0, 0\n\n\tfor ; i < len(text) && j < len(pat); {\n\t\tif text[i] == pat[j] {\n\t\t\tif j == len(pat)-1 {\n\t\t\t\treturn i - (len(pat) - 1)\n\t\t\t}\n\t\t\ti++\n\t\t\tj++\n\t\t} else {\n\t\t\tj--\n\t\t\tif j < 0 {\n\t\t\t\tj = 0\n\t\t\t\ti++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tj = lsp[j]\n\t\t}\n\t}\n\treturn -1\n}", "func IndexOf(slice []int, val int) int {\n\tfor i := 0; i < len(slice); i++ {\n\t\tif slice[i] == val {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func (rs Ranges) search(r Range) int {\n\treturn sort.Search(len(rs), func(i int) bool {\n\t\treturn rs[i].Pos >= r.Pos\n\t})\n}", "func (a *StringArray) search(v int64) int {\n\t// Define: f(x) → a.Timestamps[x] < v\n\t// Define: f(-1) == true, f(n) == false\n\t// Invariant: f(lo-1) == true, f(hi) == false\n\tlo := 0\n\thi := a.Len()\n\tfor lo < hi {\n\t\tmid := int(uint(lo+hi) >> 1)\n\t\tif a.Timestamps[mid] < v {\n\t\t\tlo = mid + 1 // preserves f(lo-1) == true\n\t\t} else {\n\t\t\thi = mid // preserves f(hi) == false\n\t\t}\n\t}\n\n\t// lo == hi\n\treturn lo\n}" ]
[ "0.6777817", "0.6646685", "0.6631839", "0.6475447", "0.63192135", "0.62363327", "0.6098243", "0.6074247", "0.6062774", "0.6061379", "0.60531753", "0.60531753", "0.60531753", "0.60531753", "0.60531753", "0.60161793", "0.6008917", "0.6006638", "0.5988918", "0.5973541", "0.5956409", "0.5940044", "0.5936692", "0.5933368", "0.5904672", "0.58852494", "0.5879135", "0.58664", "0.58664", "0.58664", "0.58489674", "0.58463496", "0.58206564", "0.58048266", "0.579767", "0.57917655", "0.5767237", "0.5755893", "0.57548964", "0.57260144", "0.57223326", "0.5721303", "0.5719893", "0.5715271", "0.57044613", "0.5702301", "0.56963384", "0.56945246", "0.56794655", "0.5671495", "0.5663351", "0.56504697", "0.5647139", "0.5638082", "0.56348485", "0.56256115", "0.5616133", "0.56028473", "0.5601801", "0.5594531", "0.5593155", "0.5593155", "0.5593155", "0.5593155", "0.5585005", "0.5578455", "0.55468535", "0.5545941", "0.5538977", "0.5534586", "0.55338997", "0.55279195", "0.5524261", "0.55196106", "0.5517999", "0.5517579", "0.5512221", "0.551126", "0.55097616", "0.5495814", "0.5494232", "0.54896647", "0.548834", "0.54839444", "0.54774785", "0.5473921", "0.5470105", "0.54571676", "0.5456122", "0.5444599", "0.5442703", "0.54407835", "0.543422", "0.54224116", "0.5415682", "0.5414796", "0.5407093", "0.54054534", "0.54053336", "0.5403297" ]
0.74833435
0
Returns the number of occurrences of item in the tuple, given starting position start.
func (this *Tuple) Count(item interface{}, start int) int { ctr := 0 for i := start; i < this.Len(); i++ { if TupleElemEq(this.Get(i), item) { ctr += 1 } } return ctr }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func countingValleys(n int32, s string) int32 {\n\tstartAr := []int32{0}\n\tvar start int32\n\tvar valleyPoint int32 = 1\n\tfor _, elem := range s {\n\t\tchar := string(elem)\n\t\tcheckInt := true\n\t\tcheckInt = math.Signbit(float64(start))\n\t\tif char == \"D\" {\n\t\t\tstart = start - 1\n\t\t} else {\n\t\t\tstart = start + 1\n\t\t}\n\n\t\tif start == 0 {\n\t\t\tif checkInt == true {\n\t\t\t\tvalleyPoint = valleyPoint + 1\n\t\t\t}\n\t\t}\n\t\tstartAr = append(startAr, start)\n\t}\n\tfmt.Println(startAr)\n\tvalley := valleyPoint - 1\n\treturn valley\n}", "func CountFrom(start, step int) Stream {\n return &count{start, step}\n}", "func (this *Tuple) Index(item interface{}, start int) int {\n\tfor i := start; i < this.Len(); i++ {\n\t\tif TupleElemEq(this.Get(i), item) {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func countInitialOccurrences(s []byte, x byte) int {\n\tfor i, c := range s {\n\t\tif c != x {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn len(s)\n}", "func (sm *scoreMemberMap) count(min, max float64) int {\n\tn := 0\n\tfor cur := sm.head; cur != nil && cur.score <= max; cur = cur.next {\n\t\tif cur.score >= min {\n\t\t\tn += len(cur.members)\n\t\t}\n\t}\n\treturn n\n}", "func (q *quartileIndex) Count(from int, to int) int {\n\tif from == 0 {\n\t\treturn q.zeroCount(to)\n\t}\n\treturn q.zeroCount(to) - q.zeroCount(from)\n}", "func (r *baseNsRange) Start() int { return r.start }", "func getTotalCount(a map[string]int) int {\n\tvar result int\n\tfor _, v := range a {\n\t\tresult += v\n\t}\n\treturn result\n}", "func (c CounterSnapshot) Count() int64 { return int64(c) }", "func NumOccurrences(s string, c byte) int {\n\tvar n int\n\tfor i := 0; i < len(s); i++ {\n\t\tif s[i] == c {\n\t\t\tn++\n\t\t}\n\t}\n\treturn n\n}", "func (r *Record) Start() int {\n\treturn r.Pos\n}", "func Count(s, substr string) int {\n\treturn strings.Count(s, substr)\n}", "func (sc gloomList) countArgs() (int, error) {\n\t// Extract all \"arg characters\" in the list\n\targs := []int{}\n\tfor _, arg := range sc.Elems {\n\t\tif v, ok := arg.(argument); ok {\n\t\t\targs = append(args, int(v))\n\t\t}\n\t}\n\n\t// Early exit for no-args case\n\tif len(args) == 0 {\n\t\treturn 0, nil\n\t}\n\n\t// Sort the argument numbers in ascending order\n\tsort.Ints(args)\n\tif args[0] == 0 {\n\t\treturn 0, fmt.Errorf(\"invalid argument `$0`\")\n\t}\n\n\t// Check that we're not \"skipping\" arguments\n\tlast := 0\n\tfor _, argIdx := range args {\n\t\tif argIdx != last && argIdx != last+1 {\n\t\t\treturn 0, fmt.Errorf(\"missing argument `$%d`\", last+1)\n\t\t}\n\n\t\tlast = argIdx\n\t}\n\n\treturn last, nil\n}", "func countWordLenCallByReference(count []int, ss []string) []int {\n\tif len(ss) == 0 {\n\t\treturn count\n\t}\n\treturn countWordLenCallByReference(append(count, len(ss[0])), ss[1:])\n}", "func countOccurences(cards []string, thing string) int {\n\tcount := 0\n\tfor _, item := range cards {\n\t\tif item == thing {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count\n}", "func countRepetitions(strand Strand, length, limit int) int {\n\tcurrLen := 0\n\treps := 0\n\tvar prev rune\n\tfor _, r := range strand {\n\t\tif prev != r {\n\t\t\tcurrLen = 0\n\t\t}\n\t\tcurrLen++\n\t\tif currLen >= length {\n\t\t\treps++ // sequences can overlap\n\t\t}\n\t\tif limit > 0 && reps >= limit {\n\t\t\tbreak\n\t\t}\n\t\tprev = r\n\t}\n\n\treturn reps\n}", "func Count(str, substr string) int {\n\treturn strings.Count(str, substr)\n}", "func length(s *Skiplist) int {\n\tcount := 0\n\n\tvar it Iterator\n\tit.Init(s)\n\n\tfor it.SeekToFirst(); it.Valid(); it.Next() {\n\t\tcount++\n\t}\n\n\treturn count\n}", "func countRangeSum1(nums []int, lower int, upper int) int {\n\trst := 0\n\tfor i := 0; i < len(nums); i++ {\n\t\tfor j := i; j < len(nums); j++ {\n\t\t\ttmp := 0\n\t\t\tfor k := i; k <= j; k++ { // s(i,j)\n\t\t\t\ttmp += nums[k]\n\t\t\t}\n\t\t\tif tmp <= upper && tmp >= lower {\n\t\t\t\trst++\n\t\t\t}\n\t\t}\n\t}\n\treturn rst\n}", "func FindOccurences(source, char string, occur int) int {\n\tcount := 0\n\tfor i := 0; i < len(source); i++ {\n\t\tif source[i:i+1] == char {\n\t\t\tcount++\n\t\t\tif count == occur {\n\t\t\t\treturn i\n\t\t\t}\n\t\t}\n\t}\n\treturn len(source)\n}", "func GetListItemCount(list *List) uint64 {\n return list.itemCount;\n}", "func countTotal(P []int, x int, y int) int {\n return P[y+1] - P[x]\n}", "func getNumberOfRecords(c *bolt.Cursor) (i int) {\n\tfor k, _ := c.First(); k != nil; k, _ = c.Next() {\n\t\ti++\n\t}\n\treturn i\n}", "func getCountAndMin(currentCount int, currentMin int, incomingCount int, incomingMin int) (int, int) {\n\tif incomingMin == currentMin {\n\t\treturn currentCount + incomingCount, incomingMin\n\t} else if incomingMin < currentMin {\n\t\treturn incomingCount, incomingMin\n\t} else {\n\t\treturn currentCount, currentMin\n\t}\n}", "func getOccurrencePosition(arr []int, key, firstPos, lastPos, res int, findFirstOccr bool) int {\n\n\tif firstPos <= lastPos {\n\t\tmidIdx := (firstPos+lastPos)/2\n\t\tif arr[midIdx] == key {\n\t\t\tres = midIdx\n\t\t\tif findFirstOccr {\n\t\t\t\treturn getOccurrencePosition(arr, key, firstPos, midIdx-1, res, findFirstOccr)\n\t\t\t} else {\n\t\t\t\treturn getOccurrencePosition(arr, key, midIdx+1, lastPos, res, findFirstOccr)\n\t\t\t}\n\t\t} else if arr[midIdx] < key {\n\t\t\t// search in right hand side of array in case array is sorted in ascending order\n\t\t\treturn getOccurrencePosition(arr, key, midIdx+1, lastPos, res, findFirstOccr)\n\t\t} else {\n\t\t\t// arr[midIdx] > key, i.e. search in first half of the array\n\t\t\treturn getOccurrencePosition(arr, key, firstPos, midIdx-1, res, findFirstOccr)\n\t\t}\n\t}\n\treturn res\n}", "func Count(spin string) int {\n\tcount := 1\n\tmatches := re.FindAllString(spin, -1)\n\tfor _, match := range matches {\n\t\tparts := strings.Split(match[1:len(match)-1], \"|\")\n\t\tif len(parts) >= 1 {\n\t\t\tcount *= len(parts)\n\t\t}\n\t}\n\treturn count\n}", "func (t *SimpleChaincode) getNumberOfLocs (stub *shim.ChaincodeStub, args []string) ([]byte, error){\n \tvalAsbytes, err := stub.GetState(\"counter\");\n \t\n \tif err != nil {\n\t\treturn nil, err\n\t}\n \t\n //s := strconv.Itoa(counter) ;\n //ret_s := []byte(s);\n return valAsbytes, nil;\n }", "func (m *RecurrenceRange) GetNumberOfOccurrences()(*int32) {\n val, err := m.GetBackingStore().Get(\"numberOfOccurrences\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}", "func countingValleys(n int32, s string) int32 {\n\n l, v := 0, 0\n s = strings.ToLower(s)\n for _, r := range s {\n\n if r == 'u' {\n if l < 0 && l+1 == 0 {\n v++\n }\n l++\n\n } else {\n l--\n }\n }\n return int32(v)\n}", "func (x *intSet) count() int {\n\tn := 0\n\ty := *x\n\tfor y != 0 {\n\t\ty &= (y - 1)\n\t\tn++\n\t}\n\treturn n\n}", "func (m MultiSet) Count (val string) int {\n\tcount := 0\n\tfor _, num := range m {\n\t\tint_val, _ := strconv.Atoi(val)\n\t\tif num == int_val {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count\n}", "func GetSize(matches []logol.Match) int {\n\tstart := 0\n\tend := 0\n\tif len(matches) > 0 {\n\t\tstart = matches[0].Start\n\t\tend = matches[len(matches)-1].End\n\t}\n\treturn end - start\n}", "func getStartIndex(st int32, a []int32) int {\n\tif st <= a[0] {\n\t\treturn 0 // st a[0]......a[len(a) - 1]\n\t}\n\tif st == a[len(a)-1] {\n\t\treturn len(a) - 1\n\t}\n\tif st > a[len(a)-1] {\n\t\treturn -1 // a[0]......a[len(a) - 1] st\n\t}\n\treturn sort.Search(len(a), func(i int) bool {\n\t\treturn a[i] >= st // a[0], a[1], st, a[2], a[3]....a[len(a) - 1]\n\t})\n}", "func fileCount(startPath string) (totalCount int64) {\n\terr := filepath.WalkDir(startPath,\n\t\tfunc(path string, entry os.DirEntry, err error) error {\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !entry.IsDir() && gallery.IsValidMedia(path) {\n\t\t\t\ttotalCount += 1\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\tif err != nil {\n\t\tlogger.Print(err)\n\t}\n\treturn\n}", "func (set *lalrSet) size() (count int) {\n\tfor _, list := range(set.items) {\n\t\tcount = count + len(list)\n\t}\n\treturn\n}", "func (s *shard) len() uint64 {\n\ts.rwMutex.RLock()\n\tlength := uint64(len(s.entryIndexes))\n\ts.rwMutex.RUnlock()\n\n\treturn length\n}", "func (oupq *OrgUnitPositionQuery) Count(ctx context.Context) (int, error) {\n\tif err := oupq.prepareQuery(ctx); err != nil {\n\t\treturn 0, err\n\t}\n\treturn oupq.sqlCount(ctx)\n}", "func countApplesAndOranges(s int32, t int32, a int32, b int32, apples []int32, oranges []int32) {\n\tvar hitApples, hitOranges int32\n\tfor _, apple := range apples {\n\t\tplace := a + apple\n\t\tif s <= place && place <= t {\n\t\t\thitApples++\n\t\t}\n\t}\n\tfor _, orange := range oranges {\n\t\tplace := b + orange\n\t\tif s <= place && place <= t {\n\t\t\thitOranges++\n\t\t}\n\t}\n\tfmt.Println(hitApples)\n\tfmt.Println(hitOranges)\n}", "func (td TupleDesc) Count() int {\n\treturn len(td.Types)\n}", "func (t *txLookUp) Count() int {\n\tt.mu.RLock()\n\tdefer t.mu.RUnlock()\n\n\treturn t.count()\n}", "func (vs variableSet) count() int {\n\tc := 0\n\tif vs[0] != nil {\n\t\tc++\n\t}\n\tif vs[1] != nil {\n\t\tc++\n\t}\n\tif vs[2] != nil {\n\t\tc++\n\t}\n\tif vs[3] != nil {\n\t\tc++\n\t}\n\treturn c\n}", "func countRegexFrequency(matcher, text string) int {\n\tregex := regexp.MustCompile(matcher)\n\tmatches := regex.FindAllStringSubmatch(text, -1)\n\n\treturn len(matches)\n}", "func (bm BitMap) BitCount(ctx context.Context, start, end int64) (int64, error) {\n\treq := newRequest(\"*4\\r\\n$8\\r\\nBITCOUNT\\r\\n$\")\n\treq.addStringInt2(bm.name, start, end)\n\treturn bm.c.cmdInt(ctx, req)\n}", "func (l *line) len() int {\n\tvar n int\n\tfor i := range l.spans {\n\t\tn += len(l.spans[i].text)\n\t}\n\treturn n\n}", "func (db *DB) CountPrefixTx(tx *bolt.Tx, prefix interface{}, value interface{}, count *int) error {\n\t*count = 0\n\tbb := db.bucket(value)\n\tb := tx.Bucket(bb)\n\tif b == nil {\n\t\treturn nil\n\t}\n\n\tpb, err := db.encode(prefix)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc := b.Cursor()\n\tfor k, _ := c.Seek(pb); k != nil && bytes.HasPrefix(k, pb); k, _ = c.Next() {\n\t\t*count++\n\t}\n\treturn nil\n}", "func (this *HitCounter) GetHits(timestamp int) int {\n\tif this.tail == nil {\n\t\treturn 0\n\t}\n\tstart := this.tail\n\tcount := 0\n\tfor start != nil && (timestamp - start.Key) < 300{\n\t\tif start.Key <= timestamp{\n\t\t\tcount += start.Count\n\t\t}\n\t\tstart = start.Prev\n\t}\n\treturn count\n}", "func (s IntSet) Count() int {\n\treturn len(s)\n}", "func (l *Layer) Count(value int) int {\n\tcount := 0\n\tfor _, b := range l.Bytes {\n\t\tif b == value {\n\t\t\tcount++\n\t\t}\n\t}\n\n\treturn count\n}", "func (this *activitiesStruct) searchActivity(begin time.Time) (int, bool) {\n\tgroups := this.groups\n\tnumGroups := len(groups)\n\tidxLeft := int(0)\n\n\t/*\n\t * The case that there are no groups requires special handling.\n\t */\n\tif numGroups > 0 {\n\t\tidxRight := numGroups - 1\n\n\t\t/*\n\t\t * Binary search algorithm.\n\t\t */\n\t\tfor idxLeft <= idxRight {\n\t\t\tdiff := idxRight - idxLeft\n\t\t\tdiffHalf := diff / 2\n\t\t\tidxPivot := idxLeft + diffHalf\n\t\t\tpivot := groups[idxPivot]\n\t\t\tpivotBegin := pivot.begin\n\n\t\t\t/*\n\t\t\t * Check if we have to continue searching in left or\n\t\t\t * right half.\n\t\t\t */\n\t\t\tif pivotBegin.After(begin) {\n\t\t\t\tidxRight = idxPivot - 1\n\n\t\t\t\t/*\n\t\t\t\t * Prevent underflow.\n\t\t\t\t */\n\t\t\t\tif idxRight > idxPivot {\n\t\t\t\t\tidxRight = idxPivot\n\t\t\t\t}\n\n\t\t\t} else if pivotBegin.Before(begin) {\n\t\t\t\tidxLeft = idxPivot + 1\n\n\t\t\t\t/*\n\t\t\t\t * Prevent overflow.\n\t\t\t\t */\n\t\t\t\tif idxLeft < idxPivot {\n\t\t\t\t\tidxLeft = idxPivot\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\treturn idxPivot, true\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\treturn idxLeft, false\n}", "func Count(diagrama []string) int {\n\n\t\n\taltura := len(diagrama)\n\n\tif altura == 0 {\n\t\treturn 0\n\t}\n\n\tlargura, count := len(diagrama[0]), 0\n\n\t\n\tfor y := 0; y < altura-1; y++ {\n\t\tfor x := 0; x < largura-1; x++ {\n\t\t\tif diagrama[y][x] == '+' {\n\t\t\t\t\n\t\t\t\tcount += Search(x, y, largura, altura, diagrama)\n\t\t\t}\n\t\t}\n\t}\n\treturn count\n}", "func (s SearchResultReference) size() (size int) {\n\tfor _, uri := range s {\n\t\tsize += uri.size()\n\t}\n\tsize += sizeTagAndLength(tagSequence, size)\n\treturn\n}", "func (_Contracts *ContractsCaller) PositionsCount(opts *bind.CallOpts, _proposal *big.Int) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Contracts.contract.Call(opts, out, \"positionsCount\", _proposal)\n\treturn *ret0, err\n}", "func (s *String) BitCount(begin, end int) (int, error) {\n\tbegin, end = initCursor(begin, end, len(s.Meta.Value))\n\tif begin > end {\n\t\treturn 0, nil\n\t}\n\treturn redisPopcount(s.Meta.Value[begin : end+1]), nil\n}", "func GetNumElements(results []string) int {\n\ti := 0\n for _, _ = range results {\n\t\t\ti++\n }\n return i\n}", "func Count() AggregateFunc {\n\treturn func(start, end string) (string, *dsl.Traversal) {\n\t\tif end == \"\" {\n\t\t\tend = DefaultCountLabel\n\t\t}\n\t\treturn end, __.As(start).Count(dsl.Local).As(end)\n\t}\n}", "func (oupgb *OrgUnitPositionGroupBy) Int(ctx context.Context) (_ int, err error) {\n\tvar v []int\n\tif v, err = oupgb.Ints(ctx); err != nil {\n\t\treturn\n\t}\n\tswitch len(v) {\n\tcase 1:\n\t\treturn v[0], nil\n\tcase 0:\n\t\terr = &NotFoundError{orgunitposition.Label}\n\tdefault:\n\t\terr = fmt.Errorf(\"ent: OrgUnitPositionGroupBy.Ints returned %d results when one was expected\", len(v))\n\t}\n\treturn\n}", "func countElements(arr []int) int {\n\tcount := 0\n\tif len(arr) == 1 {\n\t\treturn 0\n\t}\n\tfor i := 1; i < len(arr); i++ {\n\t\tif arr[i] == arr[i-1]+1 {\n\t\t\tcount++\n\t\t}\n\t}\n\n\treturn count\n}", "func (s SearchResultDone) size() int {\n\treturn LDAPResult(s).sizeTagged(TagSearchResultDone)\n}", "func findCount (item []Items) [] Items{\n\tbuffer := make( [] Items, 0);\n\tvar prev string\n\tfor i := 0; i < len(item); i++ {\n\t\tif (item[i].Itemid_string != prev) {\n\t\t\tbuffer = append(buffer, Items {\n\t\t\t\titem[i].Itemid_string,\n\t\t\t\t1,\n\t\t\t})\n\t\t} else {\n\t\t\tbuffer[len(buffer) - 1].Itemid_count++\n\t\t}\n\t\tprev = item[i].Itemid_string\n\t}\n\treturn buffer\n}", "func XMLSegsCount(xml string) (count int) {\n\ts := Str(xml)\n\tmarkS, markE1, markE2 := '<', '<', '/'\n\n\tlevel, inflag, To := 0, false, s.L()-1\n\ti := 0\n\tfor _, c := range s {\n\t\tif i < To {\n\t\t\tif c == markS && s.C(i+1) != markE2 {\n\t\t\t\tlevel++\n\t\t\t}\n\t\t\tif c == markE1 && s.C(i+1) == markE2 {\n\t\t\t\tlevel--\n\t\t\t\tif level == 0 {\n\t\t\t\t\tinflag = false\n\t\t\t\t}\n\t\t\t}\n\t\t\tif level == 1 {\n\t\t\t\tif !inflag {\n\t\t\t\t\tcount++\n\t\t\t\t\tinflag = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ti++\n\t}\n\treturn count\n}", "func countSub(x, y uint32) int {\n\t// x-y is 32-bit signed or 30-bit signed; sign-extend to 32 bits and convert to int.\n\treturn int(int32(x-y) << 2 >> 2)\n}", "func count_X(x, y, z byte) int {\n\tcount := 0;\n\t// 'x' = 120\n\tif ( x == 120) {\n\t\tcount = count + 1\n\t}\n\tif ( y == 120) {\n\t\tcount = count + 1\n\t}\n\tif ( z == 120) {\n\t\tcount = count + 1\n\t}\n\treturn count\n}", "func (d *Driver) Count(ctx context.Context, prefix string) (revRet int64, count int64, err error) {\n\tstart := time.Now()\n\tdefer func() {\n\t\tdur := time.Since(start)\n\t\tfStr := \"COUNT %s => rev=%d, count=%d, err=%v, duration=%s\"\n\t\td.logMethod(dur, fStr, prefix, revRet, count, err, dur)\n\t}()\n\n\tentries, err := d.getKeys(ctx, prefix, false)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\t// current revision\n\tcurrentRev, err := d.currentRevision()\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\treturn currentRev, int64(len(entries)), nil\n}", "func countIter(n int) int {\n\tcount := 0\n\n\tfor n != 0 {\n\t\tcount += n & 1\n\t\tn >>= 1\n\t}\n\n\treturn count\n}", "func initialPosition(ctx, sub string, loc []int) (int, string) {\n\tidx := strings.Index(ctx, sub)\n\tif idx < 0 {\n\t\t// Fall back to the JaroWinkler distance. This should only happen if\n\t\t// we're in a scope that contains inline markup (e.g., a sentence with\n\t\t// code spans).\n\t\treturn JaroWinkler(ctx, sub)\n\t}\n\tpat := `(?:^|\\b|_)` + regexp.QuoteMeta(sub) + `(?:\\b|_|$)`\n\ttxt := strings.TrimSpace(ctx[Max(idx-1, 0):Min(idx+len(sub)+1, len(ctx))])\n\tif match, err := regexp.MatchString(pat, txt); err != nil || !match {\n\t\t// If there's more than one, we take the first bounded option.\n\t\t// For example, given that we're looking for \"very\", \"every\" => nested\n\t\t// and \" very \" => bounded.\n\t\tsloc := regexp.MustCompile(pat).FindStringIndex(ctx)\n\t\tif len(sloc) > 0 {\n\t\t\tidx = sloc[0]\n\t\t\tif strings.HasPrefix(ctx[idx:], \"_\") {\n\t\t\t\tidx++ // We don't want to include the underscore boundary.\n\t\t\t}\n\t\t}\n\t}\n\treturn utf8.RuneCountInString(ctx[:idx]) + 1, sub\n}", "func (dna DNA) Count(nucleotide string) (int, error) {\n\tnucleotides := map[string]bool{\"A\": true, \"T\": true, \"G\": true, \"C\": true}\n\n\tif !nucleotides[nucleotide] {\n\t\treturn 0, fmt.Errorf(\"INVALID NUCLEOTIDE ENTRY: %s\", nucleotide)\n\t}\n\n\tcumsum := 0\n\tfor _, value := range dna.sequence {\n\t\tif nucleotide == string(value) {\n\t\t\tcumsum++\n\t\t}\n\t}\n\treturn cumsum, nil\n}", "func (s *Store) Count(key storage.Key) (int, error) {\n\tkeys := util.BytesPrefix([]byte(key.Namespace() + separator))\n\titer := s.db.NewIterator(keys, nil)\n\n\tvar c int\n\tfor iter.Next() {\n\t\tc++\n\t}\n\n\titer.Release()\n\n\treturn c, iter.Error()\n}", "func (h *peerStore) count(ih InfoHash) int {\n\tpeers := h.get(ih)\n\tif peers == nil {\n\t\treturn 0\n\t}\n\treturn peers.Size()\n}", "func (m match) Len() int {\n\treturn m.n\n}", "func (idx *Tree) Count(searchPrefix []byte) (nodes, leaves int) {\n\treturn NewCounter(idx).Count(searchPrefix)\n}", "func Count(itr Iterator) int {\n\tconst mask = ^Word(0)\n\tcount := 0\n\tfor {\n\t\tw, n := itr.Next()\n\t\tif n == 0 {\n\t\t\tbreak\n\t\t}\n\t\tif n < bitLength-1 {\n\t\t\tw &= mask >> uint(bitLength-n)\n\t\t}\n\t\tcount += bits.OnesCount(uint(w))\n\t}\n\treturn count\n}", "func NumMatchingSubseq(S string, words []string) int {\n\tvar l int = len(S)\n\tvar res int = 0\n\tfor _,word := range words{\n\t\tword_len := len(word)\n\t\tif word_len > l{\n\t\t\tcontinue\n\t\t}\n\t\tvar i int = 0\n\t\tvar j int = 0\n\t\tfor i < word_len && j < l{\n\t\t\tif word[i] == S[j] {\n\t\t\t\ti++\n\t\t\t\tj++\n\t\t\t}else{\n\t\t\t\tj++\n\t\t\t}\n\t\t}\n\t\tif i == word_len{\n\t\t\tres++\n\t\t}\n\t}\n\treturn res\n}", "func (s *Sparse) inc(start uint, dx int32) {\n\tfor i := start + 1; i < uint(len(s.count)); i++ {\n\t\ts.count[i] += dx\n\t}\n}", "func countSubstrings(s string) int {\n\tl := len(s)\n\tif l <= 0 {\n\t\treturn 0\n\t}\n\n\tcount := 0\n\n\textend := func(left int, right int) {\n\t\tfor left >= 0 && right < l && s[left] == s[right] {\n\t\t\tleft--\n\t\t\tright++\n\t\t\tcount++\n\t\t}\n\t}\n\n\tfor mid := 0; mid < l; mid++ {\n\t\textend(mid, mid)\n\t\textend(mid, mid+1)\n\t}\n\n\treturn count\n}", "func getTracesCount(ctx context.Context, xrayClient XrayClient, from time.Time, to time.Time, groupName *string) (int64, error) {\n\tlog.DefaultLogger.Debug(\"getTracesCount\", \"from\", from, \"to\", to, \"groupName\", groupName)\n\tinput := &xray.GetTimeSeriesServiceStatisticsInput{\n\t\tStartTime: aws.Time(from),\n\t\tEndTime: aws.Time(to),\n\t\tGroupName: groupName,\n\t\tPeriod: aws.Int64(60),\n\t}\n\n\tcount := int64(0)\n\terr := xrayClient.GetTimeSeriesServiceStatisticsPagesWithContext(ctx, input, func(output *xray.GetTimeSeriesServiceStatisticsOutput, b bool) bool {\n\t\tfor _, stats := range output.TimeSeriesServiceStatistics {\n\t\t\t// Not sure if this can return ServiceSummaryStatistics. It should be returned only if a service filter expression\n\t\t\t// is defined for a particular service but I would assume a Group can also trigger this.\n\t\t\tif stats.ServiceSummaryStatistics != nil {\n\t\t\t\tcount += *stats.ServiceSummaryStatistics.TotalCount\n\t\t\t} else if stats.EdgeSummaryStatistics != nil {\n\t\t\t\tcount += *stats.EdgeSummaryStatistics.TotalCount\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n\n\treturn count, err\n}", "func findNumberOfLIS(nums []int) int {\n\tx := 0\n\tsize := len(nums)\n\tfor i := 1; i < size-1; i++ {\n\t\tcrt := nums[i]\n\t\tpre := nums[i-1]\n\t\tif pre <= crt {\n\t\t\tcontinue\n\t\t}\n\t}\n\n\treturn x\n}", "func wordBegin(bytes []byte, r0Pos int) int {\n\tr0, r1Delta := wFirstSequence(bytes[r0Pos:])\n\tr1, _ := wFirstSequence(bytes[r0Pos+r1Delta:])\n\tl0, l0Pos := wLastSequence(bytes[:r0Pos])\n\n\tfor r0Pos >= 0 {\n\t\tl1, l1Pos := wLastSequence(bytes[:l0Pos])\n\t\tlOddRI := wIsOpenRI(bytes[:l1Pos], l1, l0)\n\t\tif wDecision(l1, l0, lOddRI, r0, r1) {\n\t\t\treturn r0Pos\n\t\t}\n\t\tr1 = r0\n\t\tr0 = l0\n\t\tl0 = l1\n\t\tr0Pos = l0Pos\n\t\tl0Pos = l1Pos\n\t}\n\n\treturn 0\n}", "func getStartsWithIndices(str string, strSize int, c *Chunk) []int {\n\tif strings.ToLower(string(c.Data[0])) == str {\n\t\treturn []int{0, strSize}\n\t}\n\tfirstOcc := 1\n\tfor i, s := range c.Data {\n\t\tif strings.ToLower(string(s)) == str {\n\t\t\tfirstOcc = i\n\t\t\tbreak\n\t\t}\n\t}\n\treturn []int{firstOcc, firstOcc + strSize}\n}", "func findstart(a []int) int {\n\tfmt.Println(a)\n\tif len(a) == 0 {\n\t\treturn -1\n\t}\n\tif len(a) == 1 {\n\t\treturn a[0]\n\t}\n\n\tmid := len(a) / 2 //7/2 = mid = 3, a[3] = 7\n\tstart := 0\n\tend := len(a) - 1\n\n\tif a[mid-1] > a[mid] && a[mid] < a[(mid+1)%len(a)] {\n\t\treturn a[mid]\n\t} else if a[mid] > a[start] && a[mid] > a[end] {\n\t\treturn findstart(a[mid:])\n\t} else if a[mid] < a[start] && a[mid] < a[end] {\n\t\treturn findstart(a[start:mid])\n\t}\n\n\tif (a[mid] > a[start]) && mid > start {\n\t\treturn findstart(a[start:mid])\n\t}\n\n\tif a[mid] < a[start] && mid < end {\n\t\treturn findstart(a[mid:])\n\t}\n\treturn -1\n\n}", "func (it MyString) MyCount() int {\n\treturn len(it)\n}", "func (o SecurityPolicyRuleResponseOutput) RuleTupleCount() pulumi.IntOutput {\n\treturn o.ApplyT(func(v SecurityPolicyRuleResponse) int { return v.RuleTupleCount }).(pulumi.IntOutput)\n}", "func OnesCountBefore(n uint, iBit uint) int {\n\tif UintSize == 32 {\n\t\treturn gobits.OnesCount32(uint32(n) & ((uint32(1) << iBit) - 1))\n\t}\n\treturn gobits.OnesCount64(uint64(n) & ((uint64(1) << iBit) - 1))\n}", "func (i *IntCounter) CountLE(value int64) int64 {\n\tif value < i.lastCall {\n\t\tpanic(kValueLessThanLastCall)\n\t}\n\ti.lastCall = value\n\tfor i.lastTaken < value {\n\t\tnextTaken, ok := i.stream.Next()\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\ti.lastTaken = nextTaken\n\t\ti.numTaken++\n\t}\n\tif i.lastTaken <= value {\n\t\treturn i.numTaken\n\t}\n\treturn i.numTaken - 1\n}", "func Count(v Value) int {\n\tif c, ok := v.(CountedSequence); ok {\n\t\treturn c.Count()\n\t}\n\tpanic(ErrStr(ExpectedCounted, v))\n}", "func (r *SlidingWindow) Count() int {return r.count}", "func (s *Storey) OccupancyCount() int {\n\tif s.slotList == nil {\n\t\treturn 0\n\t}\n\n\treturn s.slotList.CountSelf()\n}", "func genNumTreesRecur(start, end int) int {\n\tif start >= end {\n\t\treturn 1\n\t}\n\tcount := 0\n\tfor i := start; i <= end; i++ {\n\t\tleftCount := genNumTreesRecur(start, i-1)\n\t\trightCount := genNumTreesRecur(i+1, end)\n\t\tcount += leftCount * rightCount\n\t}\n\treturn count\n}", "func CountArgs(args MyType) int {\n\treturn len(args)\n}", "func numIdenticalPairs(nums []int) int {\n\tvar pairs int\n\thm := make(map[int]int)\n\n\t//find count of number occurences of number then store in map\n\tfor _, n := range nums {\n\t\tpairs += hm[n]\n\t\thm[n]++\n\t\tfmt.Println(\"pairs: \", pairs, \"hm:\", hm) //final hm in ex.: 1:3, 2:1, 3:2\n\t}\n\treturn pairs\n}", "func (db *DB) CountPrefix(prefix interface{}, value interface{}, count *int) error {\n\treturn db.bolt.View(func(tx *bolt.Tx) error {\n\t\treturn db.CountPrefixTx(tx, prefix, value, count)\n\t})\n}", "func Count(str string, pattern string) int {\n\treturn xstrings.Count(str, pattern)\n}", "func PopCount(x uint64) int {\n result := 0\n for i := 0; i <= 8; i++ {\n result += int(pc[byte(x>>(i*8))])\n }\n return result\n /*\n return int(pc[byte(x>>(0*8))] +\n pc[byte(x>>(1*8))] +\n pc[byte(x>>(2*8))] +\n pc[byte(x>>(3*8))] +\n pc[byte(x>>(4*8))] +\n pc[byte(x>>(5*8))] +\n pc[byte(x>>(6*8))] +\n pc[byte(x>>(7*8))])*/\n}", "func (l LinkedList) Count(val datatype) (c int) {\n\tif l.head == nil {\n\t\treturn 0\n\t}\n\n\tcur := l.head\n\tc = 0\n\tfor {\n\t\tif cur.data == val {\n\t\t\tc++\n\t\t}\n\t\tif cur.next == nil {\n\t\t\tbreak\n\t\t} else {\n\t\t\tcur = cur.next\n\t\t}\n\t}\n\treturn c\n}", "func Count(str, operand string) int { return strings.Count(operand, str) }", "func CountOf(val bool, slice []bool) int {\n\tcount := 0\n\tfor _, el := range slice {\n\t\tif val == el {\n\t\t\tcount = count + 1\n\t\t}\n\t}\n\treturn count\n}", "func (store *EntryStore) Count() int64 {\n\tprop := store.db.GetProperty(\"rocksdb.estimate-num-keys\")\n\tc, _ := strconv.ParseInt(prop, 10, 64)\n\treturn c\n}", "func (mr *MockMetricsMockRecorder) CountStart() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CountStart\", reflect.TypeOf((*MockMetrics)(nil).CountStart))\n}", "func (s *SliceInt) Count() int {\n\treturn len(s.data)\n}", "func tallyRangesUpTo(ranger []Range, upTo int) int {\n\ttotalUpTo := 0\n\tfor _, r := range ranger {\n\t\tif r.Start >= upTo {\n\t\t\tbreak\n\t\t}\n\t\tif r.Start+r.Length >= upTo {\n\t\t\ttotalUpTo += upTo - r.Start\n\t\t\tbreak\n\t\t}\n\t\ttotalUpTo += r.Length\n\t}\n\treturn totalUpTo\n}", "func findMatchingClosingParen(runes []rune, openLoc, end int) int {\n\tnestedTracker := 0\n\tfor i := openLoc + 1; i < end; i++ {\n\t\tswitch runes[i] {\n\t\tcase openParen:\n\t\t\tnestedTracker++\n\t\tcase closeParen:\n\t\t\tif nestedTracker > 0 {\n\t\t\t\tnestedTracker--\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}" ]
[ "0.5463875", "0.5387405", "0.5212348", "0.5128807", "0.50549966", "0.49670365", "0.4928032", "0.4916265", "0.48942822", "0.4891153", "0.47932094", "0.47927457", "0.47873327", "0.47757578", "0.47515303", "0.47440237", "0.47414726", "0.47373933", "0.47335076", "0.4721766", "0.47200114", "0.47017437", "0.46846884", "0.4668828", "0.46524236", "0.46452108", "0.4642338", "0.46326402", "0.46321085", "0.46223968", "0.46216178", "0.46186784", "0.4615917", "0.45805302", "0.45769966", "0.45671514", "0.4563707", "0.4561525", "0.45531282", "0.45261088", "0.45255038", "0.45247245", "0.45241228", "0.4518445", "0.45096296", "0.4505755", "0.45030355", "0.4499863", "0.4496171", "0.44960448", "0.44906223", "0.44850096", "0.4484115", "0.44837645", "0.44829404", "0.44779757", "0.44776618", "0.44765922", "0.44631055", "0.44625697", "0.44583797", "0.4458015", "0.44498557", "0.44474834", "0.4444961", "0.44427946", "0.4437836", "0.44370165", "0.44326487", "0.44320202", "0.44220117", "0.44219053", "0.44176358", "0.44134057", "0.44112983", "0.44075727", "0.440455", "0.44030336", "0.44022697", "0.4398299", "0.4396981", "0.4395098", "0.4394563", "0.43939653", "0.4393648", "0.43905014", "0.4388239", "0.4386873", "0.43819672", "0.43790984", "0.43757486", "0.43658674", "0.43650493", "0.43595016", "0.4355401", "0.43473068", "0.43430734", "0.43377307", "0.43302816", "0.43300158" ]
0.7639275
0
Inserts data from other table into this, starting at offset start
func (this *Tuple) Insert(start int, other *Tuple) { this.InsertItems(start, other.data...) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func insertIntoTable(ctx context.Context, sd StationData) error {\n\t// Get the current application ID, which is the same as the project ID.\n\t//projectID := appengine.AppID(ctx)\n\t//fmt.Println(projectID)\n\n\t// Create the BigQuery service.\n\tbq, err := bigquery.NewClient(ctx, \"pdxbike\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not create service: %v\", err)\n\t}\n\n\titems := []*Station{}\n\tfor _, st := range sd.Data.Stations {\n\t\tfmt.Println(st)\n\t\titems = append(items, &st)\n\t}\n\tu := bq.Dataset(\"StationData\").Table(\"testing1\").Uploader()\n\tif err := u.Put(ctx, items); err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (this *Tuple) InsertItems(start int, items ...interface{}) {\n\tstart = this.Offset(start)\n\trhs := this.Copy().data[start:]\n\tthis.data = append(this.data[:start], items...)\n\tthis.data = append(this.data, rhs...)\n}", "func (driver) InsertOffset(\n\tctx context.Context,\n\ttx *sql.Tx,\n\tak, sk string,\n\tn uint64,\n) (_ bool, err error) {\n\tdefer sqlx.Recover(&err)\n\n\treturn sqlx.TryExecRow(\n\t\tctx,\n\t\ttx,\n\t\t`INSERT INTO stream_offset SET\n\t\t\tapp_key = ?,\n\t\t\tsource_app_key = ?,\n\t\t\tnext_offset = ?\n\t\tON DUPLICATE KEY UPDATE\n\t\t\tapp_key = app_key`, // do nothing\n\t\tak,\n\t\tsk,\n\t\tn,\n\t), nil\n}", "func (s *DB) InsertInto(table string, data interface{}, params ...Params) (res sql.Result, err error) {\n\n\tp := Params{}\n\tif params != nil {\n\t\tp = params[0]\n\t}\n\n\tv := reflect.ValueOf(data)\n\tfor v.Kind() == reflect.Ptr {\n\t\tdata = reflect.ValueOf(data).Elem().Interface()\n\t\tv = reflect.ValueOf(data)\n\t}\n\tif v.Kind() != reflect.Struct {\n\t\treturn nil, errors.New(`sqlez.InsertInto: 'data' must be struct, got ` + v.Kind().String())\n\t}\n\n\tlabels, interfaces, err := s.scanStruct(v, false, p.SkipEmpty, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar columns string\n\tvar values string\n\n\tfor i, v := range labels {\n\t\tcolumns += v\n\t\tvalues += \"?\"\n\t\tif i < len(labels)-1 {\n\t\t\tcolumns += \", \"\n\t\t\tvalues += \", \"\n\t\t}\n\t}\n\n\tquery := \"INSERT INTO \"\n\tif p.OrIgnore {\n\t\tquery = \"INSERT OR IGNORE INTO \"\n\t}\n\n\tquery = query + table + \" (\" + columns + \") VALUES (\" + values + \")\"\n\ts.LastQuery = query\n\treturn s.DB.Exec(query, interfaces...)\n}", "func (conn *Conn) Insert(dataSet map[int][]string) {\n\tdb := conn.db\n\tshardMap := make(map[int][]Pair)\n\tfor userid, emails := range dataSet {\n\t\tshardMap[modId(userid)] = append(shardMap[modId(userid)], Pair{userid, emails})\n\t}\n\tvar sqlStrings []SqlStrVal\n\n\tfor tabNum, pairs := range shardMap {\n\t\ttableName := \"unsub_\" + strconv.Itoa(tabNum)\n\t\tsqlStr := \"INSERT INTO \" + tableName + \"(user_id, email, ts) VALUES \"\n\t\tvar vals []interface{}\n\t\tcounter := 0\n\n\t\tfor p := range pairs {\n\t\t\tfor e := range pairs[p].emails {\n\t\t\t\tsqlStr += \"(?, ?, CURRENT_TIMESTAMP), \"\n\t\t\t\tvals = append(vals, pairs[p].id, pairs[p].emails[e])\n\t\t\t\tcounter += 1\n\t\t\t\tif counter >= 32000 {\n\t\t\t\t\tsqlStrings = append(sqlStrings, SqlStrVal{sqlStr, vals[0:len(vals)]})\n\t\t\t\t\tsqlStr = \"INSERT INTO \" + tableName + \"(user_id, email, ts) VALUES \"\n\t\t\t\t\tvals = make([]interface{}, 0)\n\t\t\t\t\tcounter = 0\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(vals) != 0 {\n\t\t\tsqlStrings = append(sqlStrings, SqlStrVal{sqlStr, vals[0:len(vals)]})\n\t\t}\n\n\t}\n\n\tfor i := range sqlStrings {\n\t\tstmt, err := db.Prepare(sqlStrings[i].sqlStr[0 : len(sqlStrings[i].sqlStr)-2])\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error preparing statement: %v\\n\", err)\n\t\t\treturn\n\t\t}\n\t\t_, err = stmt.Exec(sqlStrings[i].val...)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error executing statement: %v\\n\", err)\n\t\t\treturn\n\t\t}\n\t}\n}", "func insertIntoPosition(data []string, insertion string) []string {\n\t// I am really sorry for this loop. I have not figured out why slice concatenation doesn't work\n\tvar newData []string\n\tdataLength := len(data)\n\tposition := pickNumberRange(dataLength + 1)\n\tif position == dataLength {\n\t\tnewData = append(data, []string{insertion}...)\n\t} else {\n\t\tfor i, entry := range data {\n\t\t\tif i == position {\n\t\t\t\tnewData = append(newData, []string{insertion}...)\n\t\t\t}\n\t\t\tnewData = append(newData, entry)\n\t\t}\n\t}\n\treturn newData\n}", "func (t *strideTable[T]) insert(addr uint8, prefixLen int, val *T) {\n\tidx := prefixIndex(addr, prefixLen)\n\told := t.entries[idx].value\n\toldIdx := t.entries[idx].prefixIndex\n\tif oldIdx == idx && old == val {\n\t\t// This exact prefix+value is already in the table.\n\t\treturn\n\t}\n\tt.allot(idx, oldIdx, idx, val)\n\tif oldIdx != idx {\n\t\t// This route entry was freshly created (not just updated), that's a new\n\t\t// reference.\n\t\tt.refs++\n\t}\n\treturn\n}", "func MoveData(table string, source, destination *sql.DB, clause string) error {\n\n\tqueryStmt := fmt.Sprintf(\"SELECT * FROM %s\", table)\n\tif clause != \"\" {\n\t\tqueryStmt = queryStmt + \" WHERE \" + clause\n\t}\n\trows, err := source.Query(queryStmt)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer rows.Close()\n\n\tcols, err := rows.Columns()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfields := strings.Join(cols, \", \")\n\tvar args []string\n\tfor i := range cols {\n\t\targs = append(args, fmt.Sprintf(\"$%d\", i+1))\n\t}\n\n\tparams := strings.Join(args, \", \")\n\tinsertStmt := fmt.Sprintf(\"INSERT INTO %s (%s) VALUES (%s)\", table, fields, params)\n\tdestInsert, err := destination.Prepare(insertStmt)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvals := make([]interface{}, len(cols))\n\tfor i := range vals {\n\t\tvals[i] = new(interface{})\n\t}\n\ttimeToRead := 0.0\n\ttimeToWrite := 0.0\n\n\tnum := 0\n\tdestination.Exec(\"BEGIN TRANSACTION\")\n\n\tfor rows.Next() {\n\t\tstart := time.Now()\n\t\tif err = rows.Scan(vals...); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tend := time.Now()\n\t\ttimeToRead += float64(end.Sub(start)) / float64(time.Microsecond)\n\t\tstart = time.Now()\n\t\tif _, err := destInsert.Exec(vals...); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tend = time.Now()\n\t\ttimeToWrite += float64(end.Sub(start)) / float64(time.Microsecond)\n\t\tnum++\n\n\t\tif num%10000 == 0 {\n\t\t\tdestination.Exec(\"END TRANSACTION\")\n\t\t\tdestination.Exec(\"BEGIN TRANSACTION\")\n\t\t}\n\t}\n\tdestination.Exec(\"END TRANSACTION\")\n\n\tlogging.Info(\"Time to read %s (%d rows): %6.3f us (%6.3f us/row) Time to write %6.3f us (%6.3f us/row)\",\n\t\ttable, num,\n\t\ttimeToRead, timeToRead/float64(num),\n\t\ttimeToWrite, timeToWrite/float64(num))\n\treturn nil\n}", "func (d DB) InsertIntoWfDataTable(ctx context.Context, req *pb.UpdateWorkflowDataRequest) error {\n\tif req.WorkflowID == workflowForErr {\n\t\treturn errors.New(\"INSERT Into workflow_data\")\n\t}\n\treturn nil\n}", "func (d TinkDB) InsertIntoWfDataTable(ctx context.Context, req *pb.UpdateWorkflowDataRequest) error {\n\tversion, err := getLatestVersionWfData(ctx, d.instance, req.GetWorkflowId())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//increment version\n\tversion = version + 1\n\ttx, err := d.instance.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"BEGIN transaction\")\n\t}\n\n\t_, err = tx.Exec(`\n\tINSERT INTO\n\t\tworkflow_data (workflow_id, version, metadata, data)\n\tVALUES\n\t\t($1, $2, $3, $4);\n\t`, req.GetWorkflowId(), version, string(req.GetMetadata()), string(req.GetData()))\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"INSERT Into workflow_data\")\n\t}\n\n\tif version > int32(maxVersions) {\n\t\tcleanVersion := version - int32(maxVersions)\n\t\t_, err = tx.Exec(`\n\t\tUPDATE workflow_data\n\t\tSET\n\t\t\tdata = NULL\n\t\tWHERE\n\t\t\tworkflow_id = $1 AND version = $2;\n\t\t`, req.GetWorkflowId(), cleanVersion)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"UPDATE\")\n\t\t}\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"COMMIT\")\n\t}\n\treturn nil\n}", "func InsertIntoDb(data []interface{}, dataType interface{}, tableName string, db *sql.DB) error {\n\n\t_, err := db.Exec(InsertQuery(tableName, dataType), data...)\n\tif err != nil {\n\t\t//fmt.Println(err)\n\t\treturn err\n\t}\n\treturn nil\n\n}", "func (m *MockIPTables) Insert(table string, chain string, pos int, rulespec ...string) error {\n\tm.Rules = m.prependRule(m.Rules, IPtableRule{\n\t\tTable: table,\n\t\tChain: chain,\n\t\tRuleSpec: rulespec,\n\t})\n\treturn nil\n}", "func BulkInsertTo(name int, db *sql.DB, records []Record) {\n\tlog.Printf(\"new batch: %v\", name)\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\tlog.Fatalln(\"could not init transaction:\", err)\n\t}\n\tstmt, err := tx.Prepare(pq.CopyIn(\"record\", \"seq_id\", \"datetime\", \"email\", \"ipv4\", \"mac\", \"country_code\", \"user_agent\"))\n\tif err != nil {\n\t\tlog.Fatalln(\"could not prepare statment\")\n\t}\n\tfor _, r := range records {\n\t\t_, err := stmt.Exec(r.ID, r.Timestamp, r.Email, r.IP, r.Mac, r.CountryCode, r.UserAgent)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"could not\")\n\t\t}\n\t}\n\t_, err = stmt.Exec()\n\tif err != nil {\n\t\tlog.Fatalln(\"unable to flush data:\", err)\n\t}\n\terr = stmt.Close()\n\tif err != nil {\n\t\tlog.Fatalln(\"unable to close prepared statment:\", err)\n\t}\n\terr = tx.Commit()\n\tif err != nil {\n\t\tlog.Fatalln(\"unable to commit:\", err)\n\t}\n\tlog.Printf(\"end batch: %v\", name)\n}", "func InsertBytes(dest *[]byte, pos int, src ...[]byte) {\n\tfor _, part := range src {\n\t\tdestLen, partLen := len(*dest), len(part)\n\t\tif pos < 0 || pos > destLen {\n\t\t\tmod.Error(\"Position\", pos, \"out of range; len(*dest):\", destLen)\n\t\t} else if partLen != 0 {\n\t\t\t*dest = append(*dest, part...) // grow destination\n\t\t\tcopy((*dest)[pos+partLen:], (*dest)[pos:]) // shift to make space\n\t\t\tcopy((*dest)[pos:], part) // copy source to dest.\n\t\t}\n\t\tpos += len(part)\n\t}\n}", "func (s *Session) Insert(dest interface{}) (int64, error) {\n\ts.initStatemnt()\n\ts.statement.Insert()\n\tscanner, err := NewScanner(dest)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer scanner.Close()\n\tif s.statement.table == \"\" {\n\t\ts.statement.From(scanner.GetTableName())\n\t}\n\tinsertFields := make([]string, 0)\n\tfor n, f := range scanner.Model.Fields {\n\t\tif !f.IsReadOnly {\n\t\t\tinsertFields = append(insertFields, n)\n\t\t}\n\t}\n\ts.Columns(insertFields...)\n\tif scanner.entityPointer.Kind() == reflect.Slice {\n\t\tfor i := 0; i < scanner.entityPointer.Len(); i++ {\n\t\t\tval := make([]interface{}, 0)\n\t\t\tsub := scanner.entityPointer.Index(i)\n\t\t\tif sub.Kind() == reflect.Ptr {\n\t\t\t\tsubElem := sub.Elem()\n\t\t\t\tfor _, fn := range insertFields {\n\t\t\t\t\tf, ok := scanner.Model.Fields[fn]\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tfv := subElem.Field(f.idx)\n\t\t\t\t\tval = append(val, fv.Interface())\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tfor _, fn := range insertFields {\n\t\t\t\t\tf, ok := scanner.Model.Fields[fn]\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tfv := sub.Field(f.idx)\n\t\t\t\t\tval = append(val, fv.Interface())\n\t\t\t\t}\n\t\t\t}\n\t\t\ts.statement.Values(val)\n\t\t}\n\n\t} else if scanner.entityPointer.Kind() == reflect.Struct {\n\t\tval := make([]interface{}, 0)\n\t\tfor _, fn := range insertFields {\n\t\t\tf, ok := scanner.Model.Fields[fn]\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfv := scanner.entityPointer.Field(f.idx)\n\t\t\tval = append(val, fv.Interface())\n\t\t}\n\t\ts.statement.Values(val)\n\t} else {\n\t\treturn 0, InsertExpectSliceOrStruct\n\t}\n\tsql, args, err := s.statement.ToSQL()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ts.logger.Debugf(\"[Session Insert] sql: %s, args: %v\", sql, args)\n\ts.initCtx()\n\tsResult, err := s.ExecContext(s.ctx, sql, args...)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn sResult.RowsAffected()\n}", "func (sd *SelectDataset) Insert() *InsertDataset {\n\ti := newInsertDataset(sd.dialect.Dialect(), sd.queryFactory).\n\t\tPrepared(sd.isPrepared)\n\tif sd.clauses.HasSources() {\n\t\ti = i.Into(sd.GetClauses().From().Columns()[0])\n\t}\n\tc := i.clauses\n\tfor _, ce := range sd.clauses.CommonTables() {\n\t\tc = c.CommonTablesAppend(ce)\n\t}\n\ti.clauses = c\n\treturn i\n}", "func insertIntoLeaf(leaf *Node, key []byte, pointer *Record) {\n\ti := 0\n\tfor i < leaf.KeysNum {\n\t\tif compare(key, leaf.Keys[i]) > 0 {\n\t\t\ti++\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfor j := leaf.KeysNum; j > i; j-- {\n\t\tleaf.Keys[j] = leaf.Keys[j-1]\n\t\tleaf.pointers[j] = leaf.pointers[j-1]\n\t}\n\n\tleaf.Keys[i] = key\n\tleaf.pointers[i] = pointer\n\tleaf.KeysNum++\n}", "func (self *DBSteward) doXmlDataInsert(defFile string, dataFile string) {\n\t// TODO(go,xmlutil) verify this behavior is correct, add tests. need to change fatals to returns\n\tself.Info(\"Automatic insert data into %s from %s\", defFile, dataFile)\n\tdefDoc, err := GlobalXmlParser.LoadDefintion(defFile)\n\tself.FatalIfError(err, \"Failed to load %s\", defFile)\n\n\tdataDoc, err := GlobalXmlParser.LoadDefintion(dataFile)\n\tself.FatalIfError(err, \"Failed to load %s\", dataFile)\n\n\tfor _, dataSchema := range dataDoc.Schemas {\n\t\tdefSchema, err := defDoc.GetSchemaNamed(dataSchema.Name)\n\t\tself.FatalIfError(err, \"while searching %s\", defFile)\n\t\tfor _, dataTable := range dataSchema.Tables {\n\t\t\tdefTable, err := defSchema.GetTableNamed(dataTable.Name)\n\t\t\tself.FatalIfError(err, \"while searching %s\", defFile)\n\n\t\t\tdataRows := dataTable.Rows\n\t\t\tif dataRows == nil {\n\t\t\t\tself.Fatal(\"table %s in %s does not have a <rows> element\", dataTable.Name, dataFile)\n\t\t\t}\n\n\t\t\tif len(dataRows.Columns) == 0 {\n\t\t\t\tself.Fatal(\"Unexpected: no rows[columns] found in table %s in file %s\", dataTable.Name, dataFile)\n\t\t\t}\n\n\t\t\tif len(dataRows.Rows) > 1 {\n\t\t\t\tself.Fatal(\"Unexpected: more than one rows->row found in table %s in file %s\", dataTable.Name, dataFile)\n\t\t\t}\n\n\t\t\tif len(dataRows.Rows[0].Columns) != len(dataRows.Columns) {\n\t\t\t\tself.Fatal(\"Unexpected: Table %s in %s defines %d colums but has %d <col> elements\",\n\t\t\t\t\tdataTable.Name, dataFile, len(dataRows.Columns), len(dataRows.Rows[0].Columns))\n\t\t\t}\n\n\t\t\tfor i, newColumn := range dataRows.Columns {\n\t\t\t\tself.Info(\"Adding rows column %s to definition table %s\", newColumn, defTable.Name)\n\n\t\t\t\tif defTable.Rows == nil {\n\t\t\t\t\tdefTable.Rows = &model.DataRows{}\n\t\t\t\t}\n\t\t\t\terr = defTable.Rows.AddColumn(newColumn, dataRows.Columns[i])\n\t\t\t\tself.FatalIfError(err, \"Could not add column %s to %s in %s\", newColumn, dataTable.Name, dataFile)\n\t\t\t}\n\t\t}\n\t}\n\n\tdefFileModified := defFile + \".xmldatainserted\"\n\tself.Notice(\"Saving modified dbsteward definition as %s\", defFileModified)\n\tGlobalXmlParser.SaveDoc(defFileModified, defDoc)\n}", "func (b *Book) insertOrderAtLimit(limit *InfoAtLimit, order *Order) {\n elem := limit.OrderList.PushBack(order)\n b.OrderMap.insertOrderIntoMap(order)\n limit.Size += order.NumberOfShares\n limit.UserOrderMap[order.UserId].PushToList(elem)\n}", "func (t *BPTree) insertIntoNode(node *Node, leftIndex int, key []byte, right *Node) error {\n\tfor i := node.KeysNum; i > leftIndex; i-- {\n\t\tnode.Keys[i] = node.Keys[i-1]\n\t\tnode.pointers[i+1] = node.pointers[i]\n\t}\n\n\tnode.Keys[leftIndex] = key\n\tnode.pointers[leftIndex+1] = right\n\tnode.KeysNum++\n\n\treturn nil\n}", "func (sq *testQueryService) addGeneratedRows(from, to int) {\n\tvar rows [][]sqltypes.Value\n\t// ksids has keyspace ids which are covered by the shard key ranges -40 and 40-80.\n\tksids := []uint64{0x2000000000000000, 0x6000000000000000}\n\n\tfor id := from; id < to; id++ {\n\t\t// Only return the rows which are covered by this shard.\n\t\tshardIndex := id % 2\n\t\tif sq.shardCount == 1 || shardIndex == sq.shardIndex {\n\t\t\tidValue := sqltypes.NewInt64(int64(id))\n\n\t\t\trow := []sqltypes.Value{\n\t\t\t\tidValue,\n\t\t\t\tsqltypes.NewVarBinary(fmt.Sprintf(\"Text for %v\", id)),\n\t\t\t}\n\t\t\tif !sq.omitKeyspaceID {\n\t\t\t\trow = append(row, sqltypes.NewVarBinary(fmt.Sprintf(\"%v\", ksids[shardIndex])))\n\t\t\t}\n\t\t\trows = append(rows, row)\n\t\t}\n\t}\n\n\tif sq.rows == nil {\n\t\tsq.rows = rows\n\t} else {\n\t\tsq.rows = append(sq.rows, rows...)\n\t}\n}", "func GenerateInitialData(db *sql.DB) {\n var teams []string\n\n db.Exec(\"TRUNCATE TABLE game\")\n db.Exec(\"DELETE FROM team\")\n for i := 0; i < 30; i++ {\n id := pgtype.UUID{}\n err := db.QueryRow(fmt.Sprintf(`INSERT INTO team(name) VALUES ('Team %d') RETURNING id;`, i + 1)).Scan(&id)\n if err != nil {\n println(err.Error())\n }\n idStr, _ := id.EncodeText(nil, nil)\n teams = append(teams, string(idStr))\n }\n for i := 0; i < len(teams); i += 2 {\n _, err := db.Exec(fmt.Sprintf(`INSERT INTO game(location, team_a, team_b) VALUES ('Location %d', '%s', '%s') RETURNING id;`, i + 1, teams[i], teams[i + 1]))\n if err != nil {\n println(err.Error())\n }\n }\n\n}", "func TransferColumnBasedInsertDataToRowBased(data *InsertData) (\n\tTimestamps []uint64,\n\tRowIDs []int64,\n\tRowData []*commonpb.Blob,\n\terr error,\n) {\n\tif !checkTsField(data) {\n\t\treturn nil, nil, nil,\n\t\t\terrors.New(\"cannot get timestamps from insert data\")\n\t}\n\n\tif !checkRowIDField(data) {\n\t\treturn nil, nil, nil,\n\t\t\terrors.New(\"cannot get row ids from insert data\")\n\t}\n\n\ttss := data.Data[common.TimeStampField].(*Int64FieldData)\n\trowIds := data.Data[common.RowIDField].(*Int64FieldData)\n\n\tls := fieldDataList{}\n\tfor fieldID := range data.Data {\n\t\tif fieldID == common.TimeStampField || fieldID == common.RowIDField {\n\t\t\tcontinue\n\t\t}\n\n\t\tls.IDs = append(ls.IDs, fieldID)\n\t\tls.datas = append(ls.datas, data.Data[fieldID])\n\t}\n\n\t// checkNumRows(tss, rowIds, ls.datas...) // don't work\n\tall := []FieldData{tss, rowIds}\n\tall = append(all, ls.datas...)\n\tif !checkNumRows(all...) {\n\t\treturn nil, nil, nil,\n\t\t\terrors.New(\"columns of insert data have different length\")\n\t}\n\n\tsortFieldDataList(ls)\n\n\tnumRows := tss.RowNum()\n\trows := make([]*commonpb.Blob, numRows)\n\tfor i := 0; i < numRows; i++ {\n\t\tblob := &commonpb.Blob{}\n\t\tvar buffer bytes.Buffer\n\n\t\tfor j := 0; j < ls.Len(); j++ {\n\t\t\td := ls.datas[j].GetRow(i)\n\t\t\terr := binary.Write(&buffer, common.Endian, d)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, nil,\n\t\t\t\t\tfmt.Errorf(\"failed to get binary row, err: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\tblob.Value = buffer.Bytes()\n\t\trows[i] = blob\n\t}\n\n\tutss := make([]uint64, tss.RowNum())\n\tfor i := 0; i < tss.RowNum(); i++ {\n\t\tutss[i] = uint64(tss.Data[i])\n\t}\n\n\treturn utss, rowIds.Data, rows, nil\n}", "func (s *BasePlSqlParserListener) EnterMulti_table_insert(ctx *Multi_table_insertContext) {}", "func (store *Db2Store) InsertData(sqlStr string, maxID int32, homeDetail *models.HomeDetail) error {\n\tstmt, err := store.Db.Prepare(sqlStr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Print(\"Executin insert statement\")\n\tres, err := stmt.Exec(\n\t\tmaxID,\n\t\thomeDetail.LotArea,\n\t\thomeDetail.BldgType,\n\t\thomeDetail.HouseStyle,\n\t\thomeDetail.OverallCond,\n\t\thomeDetail.YearBuilt,\n\t\thomeDetail.RoofStyle,\n\t\thomeDetail.ExterCond,\n\t\thomeDetail.Foundation,\n\t\thomeDetail.BsmtCond,\n\t\thomeDetail.Heating,\n\t\thomeDetail.HeatingQC,\n\t\thomeDetail.CentralAir,\n\t\thomeDetail.Electrical,\n\t\thomeDetail.FullBath,\n\t\thomeDetail.HalfBath,\n\t\thomeDetail.BedroomAbvGr,\n\t\thomeDetail.KitchenAbvGr,\n\t\thomeDetail.KitchenQual,\n\t\thomeDetail.TotRmsAbvGrd,\n\t\thomeDetail.Fireplaces,\n\t\thomeDetail.FireplaceQu,\n\t\thomeDetail.GarageType,\n\t\thomeDetail.GarageFinish,\n\t\thomeDetail.GarageCars,\n\t\thomeDetail.GarageCond,\n\t\thomeDetail.PoolArea,\n\t\thomeDetail.PoolQC,\n\t\thomeDetail.Fence,\n\t\thomeDetail.MoSold,\n\t\thomeDetail.YrSold)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Print(\"Rows Affected\")\n\trowCnt, err := res.RowsAffected()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"affected = %d\\n\", rowCnt)\n\treturn nil\n}", "func (w *dbWrapper) insertMigrationData(version time.Time, appliedAtTs time.Time, executor executor) error {\n\tif executor == nil {\n\t\texecutor = w.db\n\t}\n\n\t_, err := executor.Exec(w.setPlaceholders(fmt.Sprintf(\"INSERT INTO %s (version, applied_at) VALUES (?, ?)\", w.MigrationsTable)),\n\t\tversion.UTC().Format(TimestampFormat), appliedAtTs.UTC().Format(TimestampFormat))\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"can't insert migration\")\n\t}\n\n\treturn nil\n}", "func (m *Memory) AddChunkAhead(fp string, data []byte, offset int64, t time.Duration) error {\n\tkey := fp + \"-\" + strconv.FormatInt(offset, 10)\n\tm.db.Set(key, data, cache.DefaultExpiration)\n\n\treturn nil\n}", "func WithOffset(a *gorm.DB, offset int) *gorm.DB {\n\tstore := a\n\tif offset != 0 {\n\t\tstore = store.Offset(offset)\n\t}\n\treturn store\n}", "func (b *BTree) insertInNodeAtIdx(n *memNode, item *Item, i int) {\n\ts := n.node.Items\n\ts = append(s, nil)\n\tif i < len(s) {\n\t\tcopy(s[i+1:], s[i:])\n\t}\n\ts[i] = item\n\tn.node.Items = s\n}", "func SliceInsert(sl *[]Ki, k Ki, idx int) {\n\tkl := len(*sl)\n\tif idx < 0 {\n\t\tidx = kl + idx\n\t}\n\tif idx < 0 { // still?\n\t\tidx = 0\n\t}\n\tif idx > kl { // last position allowed for insert\n\t\tidx = kl\n\t}\n\t// this avoids extra garbage collection\n\t*sl = append(*sl, nil)\n\tif idx < kl {\n\t\tcopy((*sl)[idx+1:], (*sl)[idx:kl])\n\t}\n\t(*sl)[idx] = k\n}", "func (c Client) InsertInto(entity interface{}, ptrResult interface{}, collectionName string) error {\n\n\tif !isStruct(entity) {\n\t\treturn fmt.Errorf(\"entity must be a struct\")\n\t}\n\n\tif !isPointerOfStruct(ptrResult) {\n\t\treturn fmt.Errorf(\"result must be a pointer\")\n\t}\n\n\tcollection := c.getCollection(collectionName)\n\n\tinsertResult, err := collection.InsertOne(context.TODO(), entity)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.FindByIDFrom(insertResult.InsertedID, ptrResult, collectionName)\n}", "func (e *ObservableEditableBuffer) InsertAt(rp0 int, rs []rune) {\n\tp0 := e.f.RuneTuple(rp0)\n\ts, nr := RunesToBytes(rs)\n\n\te.Insert(p0, s, nr)\n}", "func (d *dbBase) InsertMulti(ctx context.Context, q dbQuerier, mi *modelInfo, sind reflect.Value, bulk int, tz *time.Location) (int64, error) {\n\tvar (\n\t\tcnt int64\n\t\tnums int\n\t\tvalues []interface{}\n\t\tnames []string\n\t)\n\n\t// typ := reflect.Indirect(mi.addrField).Type()\n\n\tlength, autoFields := sind.Len(), make([]string, 0, 1)\n\n\tfor i := 1; i <= length; i++ {\n\n\t\tind := reflect.Indirect(sind.Index(i - 1))\n\n\t\t// Is this needed ?\n\t\t// if !ind.Type().AssignableTo(typ) {\n\t\t// \treturn cnt, ErrArgs\n\t\t// }\n\n\t\tif i == 1 {\n\t\t\tvar (\n\t\t\t\tvus []interface{}\n\t\t\t\terr error\n\t\t\t)\n\t\t\tvus, autoFields, err = d.collectValues(mi, ind, mi.fields.dbcols, false, true, &names, tz)\n\t\t\tif err != nil {\n\t\t\t\treturn cnt, err\n\t\t\t}\n\t\t\tvalues = make([]interface{}, bulk*len(vus))\n\t\t\tnums += copy(values, vus)\n\t\t} else {\n\t\t\tvus, _, err := d.collectValues(mi, ind, mi.fields.dbcols, false, true, nil, tz)\n\t\t\tif err != nil {\n\t\t\t\treturn cnt, err\n\t\t\t}\n\n\t\t\tif len(vus) != len(names) {\n\t\t\t\treturn cnt, ErrArgs\n\t\t\t}\n\n\t\t\tnums += copy(values[nums:], vus)\n\t\t}\n\n\t\tif i > 1 && i%bulk == 0 || length == i {\n\t\t\tnum, err := d.InsertValue(ctx, q, mi, true, names, values[:nums])\n\t\t\tif err != nil {\n\t\t\t\treturn cnt, err\n\t\t\t}\n\t\t\tcnt += num\n\t\t\tnums = 0\n\t\t}\n\t}\n\n\tvar err error\n\tif len(autoFields) > 0 {\n\t\terr = d.ins.setval(ctx, q, mi, autoFields)\n\t}\n\n\treturn cnt, err\n}", "func insertMetadata(db *sql.DB, b *block.Block, bLen uint32, pos int64) error {\n\tbHeight := b.Height\n\tbHash := block.HashBlock(*b)\n\n\tsqlQuery := sqlstatements.INSERT_VALUES_INTO_METADATA\n\t_, err := db.Exec(sqlQuery, bHeight, pos, bLen, bHash)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to execute statement: %s\", err.Error())\n\t\treturn errors.New(\"Failed to execute statement\")\n\t}\n\n\treturn nil\n}", "func (l *leaf) insert(x, y float64, elems []interface{}, inPtr *subtree, r *root) {\n\tfor i := range l.ps {\n\t\tif l.ps[i].zeroed() {\n\t\t\tl.ps[i].x = x\n\t\t\tl.ps[i].y = y\n\t\t\tl.ps[i].elems = elems\n\t\t\treturn\n\t\t}\n\t\tif l.ps[i].sameLoc(x, y) {\n\t\t\tl.ps[i].elems = append(l.ps[i].elems, elems...)\n\t\t\treturn\n\t\t}\n\t}\n\t// This leaf is full we need to create an intermediary node to divide it up\n\tnewIntNode(x, y, elems, inPtr, l, r)\n}", "func (mod *Modifier) insertSource(source []byte) (from, to int) {\n\troot := mod.Root()\n\torgLen := len(root.source)\n\tfrom, to = orgLen, orgLen+len(source)\n\tif from < to {\n\t\troot.source = append(root.source, source...)\n\t} else {\n\t\tto = from\n\t}\n\treturn\n}", "func (tm *TableManager) Append(i Index, ts *Table) error {\n\tif ts == nil {\n\t\treturn log.Error(\"csdb.TableManager.Init\", \"err\", errgo.Newf(\"Table pointer cannot be nil for Index %d\", i))\n\t}\n\ttm.mu.Lock()\n\ttm.ts[i] = ts\n\ttm.mu.Unlock() // use defer once there are multiple returns\n\treturn nil\n}", "func (t *TablesType) Insert(f ...qb.Field) *qb.InsertBuilder {\n\treturn t.table.Insert(f)\n}", "func (d *Database) Insert(db DB, table string, src interface{}) error {\n\tpkName, pkValue, err := d.PrimaryKey(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif pkName != \"\" && pkValue != 0 {\n\t\treturn fmt.Errorf(\"meddler.Insert: primary key must be zero\")\n\t}\n\n\t// gather the query parts\n\tnamesPart, err := d.ColumnsQuoted(src, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvaluesPart, err := d.PlaceholdersString(src, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvalues, err := d.Values(src, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// run the query\n\tq := fmt.Sprintf(\"INSERT INTO %s (%s) VALUES (%s)\", d.quoted(table), namesPart, valuesPart)\n\tif d.UseReturningToGetID && pkName != \"\" {\n\t\tq += \" RETURNING \" + d.quoted(pkName)\n\t\tvar newPk int64\n\t\terr := db.QueryRow(q, values...).Scan(&newPk)\n\t\tif err != nil {\n\t\t\treturn &dbErr{msg: \"meddler.Insert: DB error in QueryRow\", err: err}\n\t\t}\n\t\tif err = d.SetPrimaryKey(src, newPk); err != nil {\n\t\t\treturn fmt.Errorf(\"meddler.Insert: Error saving updated pk: %v\", err)\n\t\t}\n\t} else if pkName != \"\" {\n\t\tresult, err := db.Exec(q, values...)\n\t\tif err != nil {\n\t\t\treturn &dbErr{msg: \"meddler.Insert: DB error in Exec\", err: err}\n\t\t}\n\n\t\t// save the new primary key\n\t\tnewPk, err := result.LastInsertId()\n\t\tif err != nil {\n\t\t\treturn &dbErr{msg: \"meddler.Insert: DB error getting new primary key value\", err: err}\n\t\t}\n\t\tif err = d.SetPrimaryKey(src, newPk); err != nil {\n\t\t\treturn fmt.Errorf(\"meddler.Insert: Error saving updated pk: %v\", err)\n\t\t}\n\t} else {\n\t\t// no primary key, so no need to lookup new value\n\t\t_, err := db.Exec(q, values...)\n\t\tif err != nil {\n\t\t\treturn &dbErr{msg: \"meddler.Insert: DB error in Exec\", err: err}\n\t\t}\n\t}\n\n\treturn nil\n}", "func BenchmarkTableInsert(b *testing.B) {\n\tfor size := 1; size <= 10000; size *= 10 {\n\t\tb.Run(fmt.Sprintf(\"%.05d\", size), func(b *testing.B) {\n\t\t\tvar fb document.FieldBuffer\n\n\t\t\tfor i := int64(0); i < 10; i++ {\n\t\t\t\tfb.Add(fmt.Sprintf(\"name-%d\", i), types.NewIntegerValue(i))\n\t\t\t}\n\n\t\t\tb.ResetTimer()\n\t\t\tb.StopTimer()\n\t\t\tfor i := 0; i < b.N; i++ {\n\t\t\t\ttb, cleanup := newTestTable(b)\n\n\t\t\t\tb.StartTimer()\n\t\t\t\tfor j := 0; j < size; j++ {\n\t\t\t\t\ttb.Insert(&fb)\n\t\t\t\t}\n\t\t\t\tb.StopTimer()\n\t\t\t\tcleanup()\n\t\t\t}\n\t\t})\n\t}\n}", "func (t *BPTree) insertIntoParent(left *Node, key []byte, right *Node) error {\n\t// Check if the parent of the leaf node is nil or not\n\t// if nil means the leaf is root node.\n\tif left.parent == nil {\n\t\treturn t.insertIntoNewRoot(left, key, right)\n\t}\n\n\t// Get the left index.\n\tleftIndex := 0\n\tfor leftIndex <= left.parent.KeysNum {\n\t\tif left == left.parent.pointers[leftIndex] {\n\t\t\tbreak\n\t\t} else {\n\t\t\tleftIndex++\n\t\t}\n\t}\n\n\t// Check if the parent of left node is full or not\n\t// if not full,then insert into the parent node.\n\tif left.parent.KeysNum < order-1 {\n\t\treturn t.insertIntoNode(left.parent, leftIndex, key, right)\n\t}\n\n\t// The the parent of left node is full, split the parent node.\n\treturn t.splitParent(left.parent, leftIndex, key, right)\n}", "func insert(array []int8, val int8, pos int) []int8 {\r\n\tvar length = len(array)\r\n\tvar tempArray = make([]int8, length+1)\r\n\tfmt.Printf(\"\\n\")\r\n\r\n\t// copy each value from start to position\r\n\t// leave the pos we want to fill empty and copy each value after that\r\n\t// eg at pos 3: 1 2 3 x 4 5 6 7 -> 1 2 3 21 4 5 6 7\r\n\r\n\tfor i := 0; i < length; i++ {\r\n\t\tif i < pos {\r\n\t\t\ttempArray[i] = array[i]\r\n\t\t} else {\r\n\t\t\ttempArray[i+1] = array[i]\r\n\t\t}\r\n\t}\r\n\r\n\ttempArray[pos] = val\r\n\treturn tempArray\r\n}", "func (v *Data) InsertSlice(idx int, val []PicData) {\n\tdv := *v\n\t*v = append(append(append(make(Data, 0, len(dv)+1), dv[:idx]...), val...), dv[idx:]...)\n}", "func (db *DB) InsertRows(rows Rows) error {\n\tdb.partitionsLock.Lock()\n\tdefer db.partitionsLock.Unlock()\n\n\tpartitionMults := map[int]partition{}\n\n\tmaxTSInDB := 0\n\n\tfor i, part := range db.partitions {\n\t\tif i == 0 {\n\t\t\tmaxTSInDB = int(part.maxTimestamp())\n\t\t}\n\n\t\tkey := int(part.maxTimestamp()) / db.partitionModulus\n\t\tpartitionMults[key] = part\n\n\t\tif int(part.maxTimestamp()) > maxTSInDB {\n\t\t\tmaxTSInDB = int(part.maxTimestamp())\n\t\t}\n\t}\n\n\tkeyToRows := map[int]Rows{}\n\n\tfor _, row := range rows {\n\t\tkey := int(row.Timestamp) / db.partitionModulus\n\t\tkeyToRows[key] = append(keyToRows[key], row)\n\t}\n\n\tfor key, _ := range keyToRows {\n\t\tif part := partitionMults[key]; part != nil && part.readOnly() {\n\t\t\treturn errors.New(\"catena: insert into read-only partition(s)\")\n\t\t}\n\t}\n\n\tkeys := []int{}\n\tfor key := range keyToRows {\n\t\tkeys = append(keys, key)\n\t}\n\tsort.Ints(keys)\n\n\tfor _, key := range keys {\n\t\tpart := partitionMults[key]\n\t\tif part == nil {\n\n\t\t\t// make sure the new keys are strictly\n\t\t\t// larger than the largest timestamp\n\t\t\tfor _, row := range keyToRows[key] {\n\t\t\t\tif int(row.Timestamp) < maxTSInDB && len(db.partitions) > 0 {\n\t\t\t\t\treturn errors.New(\"catena: row being inserted is too old\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// create a new memory partition\n\t\t\tdb.lastPartitionID++\n\n\t\t\tlogger.Println(\"creating new partition with ID\", db.lastPartitionID, \"for key\", key)\n\t\t\twalFileName := filepath.Join(db.baseDir,\n\t\t\t\tfmt.Sprintf(\"%d.wal\", db.lastPartitionID))\n\t\t\tlog, err := newFileWAL(walFileName)\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tlogger.Println(\"created new WAL:\", walFileName)\n\n\t\t\tmp, err := newMemoryPartition(log)\n\t\t\tif err != nil {\n\t\t\t\tlog.close()\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tpart = mp\n\t\t\tdb.partitions = append(db.partitions, part)\n\n\t\t\tgo db.compactPartitions()\n\t\t}\n\n\t\trows := keyToRows[key]\n\t\terr := part.put(rows)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func insertKeyAndPtr(target *Node, key string, n *Node) {\n\tvar i int\n\tvar r Record\n\tfor i, r = range target.records {\n\t\tif key < r.key {\n\t\t\tbreak\n\t\t}\n\t}\n\n\trtmp := make([]Record, 0)\n\tctmp := make([]*Node, 0)\n\n\tswitch {\n\tcase key > r.key:\n\t\ttarget.records = append(target.records, Record{key: key, value: \"\"})\n\t\ttarget.childPtrs = append(target.childPtrs, n)\n\tcase i == 0:\n\t\trtmp = make([]Record, 1)\n\t\tctmp = make([]*Node, 1)\n\t\trtmp[0] = Record{key: key, value: \"\"}\n\t\trtmp = append(rtmp, target.records...)\n\n\t\tctmp[0] = target.childPtrs[0]\n\t\tctmp = append(ctmp, n)\n\t\tctmp = append(ctmp, target.childPtrs[1:]...)\n\t\ttarget.records = rtmp\n\t\ttarget.childPtrs = ctmp\n\tdefault:\n\t\trtmp = append(rtmp, target.records[:i]...)\n\t\trtmp = append(rtmp, Record{key: key, value: \"\"})\n\t\trtmp = append(rtmp, target.records[i:]...)\n\n\t\ti++ // Since we have more ptrs than records.\n\t\tctmp = append(ctmp, target.childPtrs[:i]...)\n\t\tctmp = append(ctmp, n)\n\t\tctmp = append(ctmp, target.childPtrs[i:]...)\n\t\ttarget.records = rtmp\n\t\ttarget.childPtrs = ctmp\n\n\t}\n}", "func (self *averageCache) insert(dataPoints []*whisper.TimeSeriesPoint) {\n\tlog.WithFields(log.Fields{\n\t\t\"cache\": self.name,\n\t}).Debug(\"Internal Insert\")\n\tvar timeSlot int\n\tvar cs *cacheSlot\n\tvar exists bool\n\tfor _, dataPoint := range dataPoints {\n\t\ttimeSlot = dataPoint.Time - (dataPoint.Time % 10) // TODO: Custom interval\n\t\tif cs, exists = self.cache[timeSlot]; exists {\n\t\t\tcs.Value += dataPoint.Value\n\t\t\tcs.Count += 1\n\t\t\tcs.LastUpdated = int(time.Now().Unix())\n\t\t} else {\n\t\t\tself.cache[timeSlot] = &cacheSlot{dataPoint.Value, 1, int(time.Now().Unix())}\n\t\t}\n\t}\n}", "func (d DB) InsertIntoWorkflowEventTable(ctx context.Context, wfEvent *pb.WorkflowActionStatus, time time.Time) error {\n\treturn nil\n}", "func (memtable *Memtable) Insert(data Comparable) (err error) {\n\tif memtable.Root, err = insert(memtable.Root, data); err == nil {\n\t\tmemtable.size++\n\t}\n\treturn err\n}", "func (s *nodeBlock) insertItemAt(index int, item Metadata) {\n\t_ = s.items[maxItems-1-s.itemsSize]\n\tcopy(s.items[index+1:], s.items[index:])\n\ts.items[index] = item\n\ts.itemsSize++\n\ts.markDirty()\n}", "func (b *Buffer) Insert(o, n int) {\n\tp := make([]*Tile, n)\n\tb.Tiles = append(b.Tiles[:o], append(p, b.Tiles[o:]...)...)\n}", "func (o TenantSlice) InsertAll(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error {\n\tln := int64(len(o))\n\tif ln == 0 {\n\t\treturn nil\n\t}\n\tvar sql string\n\tvals := []interface{}{}\n\tfor i, row := range o {\n\t\tif !boil.TimestampsAreSkipped(ctx) {\n\t\t\tcurrTime := time.Now().In(boil.GetLocation())\n\n\t\t\tif row.CreatedAt.IsZero() {\n\t\t\t\trow.CreatedAt = currTime\n\t\t\t}\n\t\t\tif row.UpdatedAt.IsZero() {\n\t\t\t\trow.UpdatedAt = currTime\n\t\t\t}\n\t\t}\n\n\t\tif err := row.doBeforeInsertHooks(ctx, exec); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnzDefaults := queries.NonZeroDefaultSet(tenantColumnsWithDefault, row)\n\t\twl, _ := columns.InsertColumnSet(\n\t\t\ttenantAllColumns,\n\t\t\ttenantColumnsWithDefault,\n\t\t\ttenantColumnsWithoutDefault,\n\t\t\tnzDefaults,\n\t\t)\n\t\tif i == 0 {\n\t\t\tsql = \"INSERT INTO `tenants` \" + \"(`\" + strings.Join(wl, \"`,`\") + \"`)\" + \" VALUES \"\n\t\t}\n\t\tsql += strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), len(vals)+1, len(wl))\n\t\tif i != len(o)-1 {\n\t\t\tsql += \",\"\n\t\t}\n\t\tvalMapping, err := queries.BindMapping(tenantType, tenantMapping, wl)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvalue := reflect.Indirect(reflect.ValueOf(row))\n\t\tvals = append(vals, queries.ValuesFromMapping(value, valMapping)...)\n\t}\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, vals...)\n\t}\n\n\t_, err := exec.ExecContext(ctx, sql, vals...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"dbmodel: unable to insert into tenants\")\n\t}\n\n\treturn nil\n}", "func (s *BasePlSqlParserListener) EnterSingle_table_insert(ctx *Single_table_insertContext) {}", "func (m *MySQL) Insert(p *packet.Packet, interval time.Duration, t time.Time) {\n\t_, err := m.stmt.Exec(p.Interface, p.Bytes, p.SrcName, p.DstName, p.Hostname, p.Proto, p.SrcPort, p.DstPort, int(interval.Seconds()), t)\n\tif err != nil {\n\t\tlog.Println(\"sql err:\", err)\n\t\tlog.Println(\"Time:\", t.Unix())\n\t\tspew.Dump(p)\n\t}\n}", "func (s *session) Insert(tables ...Table) error {\n\tfor _, table := range tables {\n\t\taction, err := s.update(table, true)\n\t\tif err != nil {\n\t\t\treturn s.catch(\"Insert: \"+action, err)\n\t\t}\n\t}\n\treturn nil\n}", "func TownInsert(data interface{}, key Key) error {\n\terr := wErr(tblTown.Insert(data).RunWrite(session))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tct := &cacheTown{townKey: key, data: data}\n\tct.refresh()\n\n\treturn nil\n}", "func (stmt *statement) InsertInto(tableName string) Statement {\n\tstmt.addPart(posInsert, \"INSERT INTO\", tableName, nil, \", \")\n\tstmt.addPart(posInsertFields-1, \"(\", \"\", nil, \"\")\n\tstmt.addPart(posValues-1, \") VALUES (\", \"\", nil, \"\")\n\tstmt.addPart(posValues+1, \")\", \"\", nil, \"\")\n\tstmt.position = posInsertFields\n\treturn stmt\n}", "func (r *TableEventHandler) insert2ProtoBytes(ev *replication.BinlogEvent) error {\n\tre := ev.Event.(*replication.RowsEvent)\n\tfor i, row := range re.Rows {\n\t\tafter := &pb.BytePair{\n\t\t\tKey: []byte(r.genKey(row)),\n\t\t\tColumnBitmap: re.ColumnBitmap1,\n\t\t}\n\t\tafter.Value = genValue(i, ev)\n\n\t\tif r.SecDb != nil {\n\t\t\t// second db\n\t\t\tif err := handleInsertOnDb(r.SecDb, after); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tif r.MinDb != nil {\n\t\t\t// minute db\n\t\t\tif err := handleInsertOnDb(r.MinDb, after); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tif r.HourDb != nil {\n\t\t\t// hour db\n\t\t\tif err := handleInsertOnDb(r.HourDb, after); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// day db\n\t\tif err := handleInsertOnDb(r.DayDb, after); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (t *ATrains) Insert(train *Train) {\n\tif train.ID() >= 1 && train.ID() <= len(t.trains) {\n\t\tt.trains[train.ID() - 1] = train\n\t}\n}", "func (cl *Client) addOffsetsToTxn(ctx context.Context, group string) error {\n\tid, epoch, err := cl.producerID()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcl.cfg.logger.Log(LogLevelInfo, \"issuing AddOffsetsToTxn\",\n\t\t\"txn\", *cl.cfg.txnID,\n\t\t\"producerID\", id,\n\t\t\"producerEpoch\", epoch,\n\t\t\"group\", group,\n\t)\n\tresp, err := (&kmsg.AddOffsetsToTxnRequest{\n\t\tTransactionalID: *cl.cfg.txnID,\n\t\tProducerID: id,\n\t\tProducerEpoch: epoch,\n\t\tGroup: group,\n\t}).RequestWith(ctx, cl)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn kerr.ErrorForCode(resp.ErrorCode)\n}", "func newRowIterator(tbl *DoltTable, ctx *sql.Context, partition *doltTablePartition) (*doltTableRowIter, error) {\n\trowData, err := tbl.table.GetRowData(ctx)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar mapIter types.MapIterator\n\tvar end types.LesserValuable\n\tif partition == nil {\n\t\tmapIter, err = rowData.BufferedIterator(ctx)\n\t} else {\n\t\tendIter, err := rowData.IteratorAt(ctx, partition.end)\n\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn nil, err\n\t\t} else if err == nil {\n\t\t\tkeyTpl, _, err := endIter.Next(ctx)\n\n\t\t\tif err != nil && err != io.EOF {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif keyTpl != nil {\n\t\t\t\tend, err = keyTpl.(types.Tuple).AsSlice()\n\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\n\t\tmapIter, err = rowData.BufferedIteratorAt(ctx, partition.start)\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &doltTableRowIter{table: tbl, rowData: rowData, ctx: ctx, nomsIter: mapIter, end: end, nbf: rowData.Format()}, nil\n}", "func (m *DBMem) Insert(data Person) {\n m.Lock()\n defer m.Unlock()\n\n\tid := len(m.data)\n m.data[id] = data\n m.history.Append(\"INSERT\", id, data)\n}", "func (o *Operation) insertMarker(m *Marker) error {\n\t_, err := db.Exec(\"INSERT INTO marker (ID, opID, PortalID, type, comment) VALUES (?, ?, ?, ?, ?)\",\n\t\tm.ID, o.ID, m.PortalID, m.Type, m.Comment)\n\tif err != nil {\n\t\tLog.Error(err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func InsertInto(table string) *InsertBuilder {\n\treturn NewInsertBuilder(table)\n}", "func (d *DirectAddress) Insert(key int, value interface{}) {\n\tif err := d.validateKey(key); err != nil {\n\t\treturn\n\t}\n\td.array[key-d.uMin] = value\n}", "func (tv *TextView) InsertAtCursor(txt []byte) {\n\twupdt := tv.TopUpdateStart()\n\tdefer tv.TopUpdateEnd(wupdt)\n\tif tv.HasSelection() {\n\t\ttbe := tv.DeleteSelection()\n\t\ttv.CursorPos = tbe.AdjustPos(tv.CursorPos, AdjustPosDelStart) // move to start if in reg\n\t}\n\ttbe := tv.Buf.InsertText(tv.CursorPos, txt, true, true)\n\tif tbe == nil {\n\t\treturn\n\t}\n\tpos := tbe.Reg.End\n\tif len(txt) == 1 && txt[0] == '\\n' {\n\t\tpos.Ch = 0 // sometimes it doesn't go to the start..\n\t}\n\ttv.SetCursorShow(pos)\n\ttv.SetCursorCol(tv.CursorPos)\n}", "func buildXRefTableStartingAt(ctx *model.Context, offset *int64) error {\n\n\tlog.Read.Println(\"buildXRefTableStartingAt: begin\")\n\n\trs := ctx.Read.RS\n\tconf := ctx.Configuration\n\thv, eolCount, err := headerVersion(rs, conf.HeaderBufSize)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx.HeaderVersion = hv\n\tctx.Read.EolCount = eolCount\n\toffs := map[int64]bool{}\n\txrefSectionCount := 0\n\n\tfor offset != nil {\n\n\t\tif offs[*offset] {\n\t\t\toffset, err = offsetLastXRefSection(ctx, ctx.Read.FileSize-*offset)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif offs[*offset] {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\toffs[*offset] = true\n\n\t\toff, err := tryXRefSection(ctx, rs, offset, &xrefSectionCount)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif off == nil || *off != 0 {\n\t\t\toffset = off\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Read.Println(\"buildXRefTableStartingAt: found xref stream\")\n\t\tctx.Read.UsingXRefStreams = true\n\t\trd, err := newPositionedReader(rs, offset)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif offset, err = parseXRefStream(rd, offset, ctx); err != nil {\n\t\t\tlog.Read.Printf(\"bypassXRefSection after %v\\n\", err)\n\t\t\t// Try fix for corrupt single xref section.\n\t\t\treturn bypassXrefSection(ctx)\n\t\t}\n\n\t}\n\n\tpostProcess(ctx, xrefSectionCount)\n\n\tlog.Read.Println(\"buildXRefTableStartingAt: end\")\n\n\treturn nil\n}", "func (o *Source) Insert(exec boil.Executor, whitelist ...string) error {\n\tif o == nil {\n\t\treturn errors.New(\"mdbmdbmodels: no sources provided for insertion\")\n\t}\n\n\tvar err error\n\n\tnzDefaults := queries.NonZeroDefaultSet(sourceColumnsWithDefault, o)\n\n\tkey := makeCacheKey(whitelist, nzDefaults)\n\tsourceInsertCacheMut.RLock()\n\tcache, cached := sourceInsertCache[key]\n\tsourceInsertCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl, returnColumns := strmangle.InsertColumnSet(\n\t\t\tsourceColumns,\n\t\t\tsourceColumnsWithDefault,\n\t\t\tsourceColumnsWithoutDefault,\n\t\t\tnzDefaults,\n\t\t\twhitelist,\n\t\t)\n\n\t\tcache.valueMapping, err = queries.BindMapping(sourceType, sourceMapping, wl)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcache.retMapping, err = queries.BindMapping(sourceType, sourceMapping, returnColumns)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(wl) != 0 {\n\t\t\tcache.query = fmt.Sprintf(\"INSERT INTO \\\"sources\\\" (\\\"%s\\\") %%sVALUES (%s)%%s\", strings.Join(wl, \"\\\",\\\"\"), strmangle.Placeholders(dialect.IndexPlaceholders, len(wl), 1, 1))\n\t\t} else {\n\t\t\tcache.query = \"INSERT INTO \\\"sources\\\" DEFAULT VALUES\"\n\t\t}\n\n\t\tvar queryOutput, queryReturning string\n\n\t\tif len(cache.retMapping) != 0 {\n\t\t\tqueryReturning = fmt.Sprintf(\" RETURNING \\\"%s\\\"\", strings.Join(returnColumns, \"\\\",\\\"\"))\n\t\t}\n\n\t\tif len(wl) != 0 {\n\t\t\tcache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning)\n\t\t}\n\t}\n\n\tvalue := reflect.Indirect(reflect.ValueOf(o))\n\tvals := queries.ValuesFromMapping(value, cache.valueMapping)\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, cache.query)\n\t\tfmt.Fprintln(boil.DebugWriter, vals)\n\t}\n\n\tif len(cache.retMapping) != 0 {\n\t\terr = exec.QueryRow(cache.query, vals...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...)\n\t} else {\n\t\t_, err = exec.Exec(cache.query, vals...)\n\t}\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"mdbmdbmodels: unable to insert into sources\")\n\t}\n\n\tif !cached {\n\t\tsourceInsertCacheMut.Lock()\n\t\tsourceInsertCache[key] = cache\n\t\tsourceInsertCacheMut.Unlock()\n\t}\n\n\treturn nil\n}", "func (fdb *fdbSlice) insert(k Key, v Value, workerId int) {\n\n\tvar err error\n\tvar oldkey Key\n\n\tcommon.Tracef(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Set Key - %s \"+\n\t\t\"Value - %s\", fdb.id, fdb.idxInstId, k, v)\n\n\t//check if the docid exists in the back index\n\tif oldkey, err = fdb.getBackIndexEntry(v.Docid(), workerId); err != nil {\n\t\tfdb.checkFatalDbError(err)\n\t\tcommon.Errorf(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Error locating \"+\n\t\t\t\"backindex entry %v\", fdb.id, fdb.idxInstId, err)\n\t\treturn\n\t} else if oldkey.EncodedBytes() != nil {\n\t\t//TODO: Handle the case if old-value from backindex matches with the\n\t\t//new-value(false mutation). Skip It.\n\n\t\t//there is already an entry in main index for this docid\n\t\t//delete from main index\n\t\tif err = fdb.main[workerId].DeleteKV(oldkey.EncodedBytes()); err != nil {\n\t\t\tfdb.checkFatalDbError(err)\n\t\t\tcommon.Errorf(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Error deleting \"+\n\t\t\t\t\"entry from main index %v\", fdb.id, fdb.idxInstId, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t//If secondary-key is nil, no further processing is required. If this was a KV insert,\n\t//nothing needs to be done. If this was a KV update, only delete old back/main index entry\n\tif v.KeyBytes() == nil {\n\t\tcommon.Errorf(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Received NIL secondary key. \"+\n\t\t\t\"Skipped Key %s. Value %s.\", fdb.id, fdb.idxInstId, k, v)\n\t\treturn\n\t}\n\n\t//set the back index entry <docid, encodedkey>\n\tif err = fdb.back[workerId].SetKV([]byte(v.Docid()), k.EncodedBytes()); err != nil {\n\t\tfdb.checkFatalDbError(err)\n\t\tcommon.Errorf(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Error in Back Index Set. \"+\n\t\t\t\"Skipped Key %s. Value %s. Error %v\", fdb.id, fdb.idxInstId, v, k, err)\n\t\treturn\n\t}\n\n\t//set in main index\n\tif err = fdb.main[workerId].SetKV(k.EncodedBytes(), v.EncodedBytes()); err != nil {\n\t\tfdb.checkFatalDbError(err)\n\t\tcommon.Errorf(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Error in Main Index Set. \"+\n\t\t\t\"Skipped Key %s. Value %s. Error %v\", fdb.id, fdb.idxInstId, k, v, err)\n\t\treturn\n\t}\n\n}", "func (self *Cache) InsertBatch(keys []interface{}, values []interface{}, sizesBytes []uint64) int {\n\tif len(keys) != len(values) {\n\t\tpanic(fmt.Sprintf(\"keys and values are not the same len. %d keys, %d values\", len(keys), len(values)))\n\t}\n\tvalues = values[:len(keys)]\n\tself.insertLock.Lock()\n\tdefer self.insertLock.Unlock()\n\n\tfor idx := range keys {\n\t\tvar inserted bool\n\t\tkeys[idx], values[idx], inserted = self.insert(keys[idx], values[idx], sizesBytes[idx])\n\t\tif !inserted {\n\t\t\treturn idx\n\t\t}\n\t}\n\treturn len(keys)\n}", "func (d *DB) insertIntoNode(cursor Cursor, kv *Pair) (bool, error) {\n\tnode := cursor.Node\n\tif node == nil {\n\t\tlog.Panic(\"try to insert into nil node!\")\n\t}\n\tif d.isFull(node) {\n\t\tlog.Printf(\"try to insert into a full node: %v, kv: %v\", node, kv)\n\t\tlog.Panic(\"insert into a full node.\")\n\t}\n\tidx := cursor.Index\n\t// TODO\t check node.Cells[idx].Child == nil\n\t// move cells\n\t//log.Printf(\"+ node: %v\\n\", node)\n\tfor i := node.Used + 1; i > idx; i-- {\n\t\tnode.Cells[i] = node.Cells[i-1]\n\t}\n\t// set cell\n\tnode.Cells[idx].KeyVal = *kv\n\t// set used\n\tnode.Used++\n\t// check full\n\tif d.isFull(node) {\n\t\td.split(node)\n\t}\n\treturn true, nil\n}", "func (m *CassandraDB) moveRecordToTable(\n\tctx context.Context,\n\tid, initiator, src_table, src_prefix, dst_table, dst_prefix string,\n\tttl int32) error {\n\tvar member *membersys.MembershipAgreement = new(membersys.MembershipAgreement)\n\tvar qstmt *gocql.Query\n\tvar batch *gocql.Batch\n\tvar encodedProto []byte\n\n\tvar err error\n\n\tqstmt = m.sess.Query(\n\t\t\"SELECT pb_data FROM \"+src_table+\" WHERE key = ?\",\n\t\tappend([]byte(src_prefix), []byte(id)...)).WithContext(ctx).\n\t\tConsistency(gocql.Quorum)\n\tdefer qstmt.Release()\n\n\terr = qstmt.Scan(&encodedProto)\n\tif err == gocql.ErrNotFound {\n\t\treturn grpc.Errorf(codes.NotFound, \"No such %s \\\"%s\\\" in records\",\n\t\t\tsrc_table, id)\n\t}\n\tif err != nil {\n\t\treturn grpc.Errorf(codes.Internal, \"Error looking up key \\\"%s\\\" in %s: %s\",\n\t\t\tid, src_table, err.Error())\n\t}\n\n\terr = proto.Unmarshal(encodedProto, member)\n\tif err != nil {\n\t\treturn grpc.Errorf(codes.DataLoss, \"Error parsing member data: %s\",\n\t\t\terr.Error())\n\t}\n\n\tif dst_table == \"membership_queue\" && len(member.AgreementPdf) == 0 {\n\t\treturn grpc.Errorf(codes.Internal,\n\t\t\t\"No membership agreement scan has been uploaded\")\n\t}\n\n\t// Fill in details concerning the approval.\n\tmember.Metadata.ApproverUid = proto.String(initiator)\n\tmember.Metadata.ApprovalTimestamp = proto.Uint64(uint64(time.Now().Unix()))\n\n\tencodedProto, err = proto.Marshal(member)\n\tif err != nil {\n\t\treturn grpc.Errorf(codes.Internal,\n\t\t\t\"Error encoding member data for deletion: %s\", err.Error())\n\t}\n\n\tbatch = gocql.NewBatch(gocql.LoggedBatch).WithContext(ctx)\n\tbatch.SetConsistency(gocql.Quorum)\n\tbatch.Query(\"INSERT INTO \"+dst_table+\" (key, pb_data) VALUES (?, ?)\",\n\t\tappend([]byte(dst_prefix), []byte(id)...), encodedProto)\n\tbatch.Query(\"DELETE FROM \"+src_table+\" WHERE key = ?\",\n\t\tappend([]byte(src_prefix), []byte(id)...))\n\n\terr = m.sess.ExecuteBatch(batch)\n\tif err != nil {\n\t\treturn grpc.Errorf(codes.Internal,\n\t\t\t\"Error moving membership record to %s in Cassandra database: %s\",\n\t\t\tdst_table, err.Error())\n\t}\n\n\treturn nil\n}", "func (t Table) Insert(document ...interface{}) error {\n\treturn t.collection.Insert(document...)\n}", "func (p *planner) CopyData(n CopyDataBlock, autoCommit bool) (planNode, error) {\n\t// When this many rows are in the copy buffer, they are inserted.\n\tconst copyRowSize = 100\n\n\tcf := p.copyFrom\n\n\t// Only do work if we have lots of rows or this is the end.\n\tif ln := len(cf.rows); ln == 0 || (ln < copyRowSize && !n.Done) {\n\t\treturn &emptyNode{}, nil\n\t}\n\n\tvc := &parser.ValuesClause{Tuples: cf.rows}\n\t// Reuse the same backing array once the Insert is complete.\n\tcf.rows = cf.rows[:0]\n\tcf.rowsMemAcc.Wtxn(p.session).Clear()\n\n\tin := parser.Insert{\n\t\tTable: cf.table,\n\t\tColumns: cf.columns,\n\t\tRows: &parser.Select{\n\t\t\tSelect: vc,\n\t\t},\n\t}\n\treturn p.Insert(&in, nil, autoCommit)\n}", "func (w *QueryWrapper) ToBatchInsert(data interface{}) (string, []interface{}) {\n\tv := reflect.Indirect(reflect.ValueOf(data))\n\n\tswitch v.Kind() {\n\tcase reflect.Slice:\n\t\tif v.Len() == 0 {\n\t\t\treturn \"\", nil\n\t\t}\n\n\t\te := v.Type().Elem()\n\n\t\tswitch e.Kind() {\n\t\tcase reflect.Map:\n\t\t\tx, ok := data.([]X)\n\n\t\t\tif !ok {\n\t\t\t\tlogger.Error(\"yiigo: invalid data type for batch insert, expects []struct, []*struct, []yiigo.X\")\n\n\t\t\t\treturn \"\", nil\n\t\t\t}\n\n\t\t\tw.batchInsertWithMap(x)\n\t\tcase reflect.Struct:\n\t\t\tw.batchInsertWithStruct(v)\n\t\tcase reflect.Ptr:\n\t\t\tif e.Elem().Kind() != reflect.Struct {\n\t\t\t\tlogger.Error(\"yiigo: invalid data type for batch insert, expects []struct, []*struct, []yiigo.X\")\n\n\t\t\t\treturn \"\", nil\n\t\t\t}\n\n\t\t\tw.batchInsertWithStruct(v)\n\t\tdefault:\n\t\t\tlogger.Error(\"yiigo: invalid data type for batch insert, expects []struct, []*struct, []yiigo.X\")\n\n\t\t\treturn \"\", nil\n\t\t}\n\tdefault:\n\t\tlogger.Error(\"yiigo: invalid data type for batch insert, expects []struct, []*struct, []yiigo.X\")\n\n\t\treturn \"\", nil\n\t}\n\n\tclauses := []string{\"INSERT\", \"INTO\", w.table, fmt.Sprintf(\"(%s)\", strings.Join(w.columns, \", \")), \"VALUES\", strings.Join(w.values, \", \")}\n\n\tquery := sqlx.Rebind(sqlx.BindType(string(w.driver)), strings.Join(clauses, \" \"))\n\n\tif debug {\n\t\tlogger.Info(query, zap.Any(\"binds\", w.binds))\n\t}\n\n\treturn query, w.binds\n}", "func (database *Database) bulkInsert(tx *sql.Tx, unsavedRows []StatsEntry) error {\n\tvalueStrings := make([]string, 0, 1000)\n\tvalueArgs := make([]interface{}, 0, 12000)\n\ti := 0\n\tvar prep *sql.Stmt\n\tvar err error\n\tfor _, row := range unsavedRows {\n\t\tif prep == nil {\n\t\t\tvalueStrings = append(valueStrings, fmt.Sprintf(\"($%d, $%d, $%d, $%d, $%d, $%d, $%d, $%d, $%d, $%d, $%d, $%d)\", i*12+1, i*12+2, i*12+3, i*12+4, i*12+5, i*12+6, i*12+7, i*12+8, i*12+9, i*12+10, i*12+11, i*12+12))\n\t\t}\n\t\tvalueArgs = append(valueArgs, row.time)\n\t\tvalueArgs = append(valueArgs, row.src)\n\t\tvalueArgs = append(valueArgs, row.dst)\n\t\tvalueArgs = append(valueArgs, row.proto)\n\t\tvalueArgs = append(valueArgs, row.port)\n\t\tvalueArgs = append(valueArgs, row.srcPackets)\n\t\tvalueArgs = append(valueArgs, row.srcBytes)\n\t\tvalueArgs = append(valueArgs, row.dstPackets)\n\t\tvalueArgs = append(valueArgs, row.dstBytes)\n\t\tvalueArgs = append(valueArgs, row.connectionTimes)\n\t\tvalueArgs = append(valueArgs, row.connectionCount)\n\t\tvalueArgs = append(valueArgs, row.openConnections)\n\t\ti++\n\t\tif i == 500 { // bulk size\n\t\t\tif prep == nil {\n\t\t\t\tstmt := fmt.Sprintf(\"INSERT INTO vpn_traffic (\\\"time\\\", src, dst, proto, port, src_packets, src_bytes, dst_packets, dst_bytes, connection_times, connection_count, open_connections) VALUES %s ON CONFLICT DO NOTHING\", strings.Join(valueStrings, \",\"))\n\t\t\t\tprep, err = tx.Prepare(stmt)\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\t_, err = prep.Exec(valueArgs...)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\ti = 0\n\t\t\tvalueArgs = make([]interface{}, 0, 12000)\n\t\t}\n\t}\n\tif len(valueArgs) > 0 {\n\t\tstmt := fmt.Sprintf(\"INSERT INTO vpn_traffic (\\\"time\\\", src, dst, proto, port, src_packets, src_bytes, dst_packets, dst_bytes, connection_times, connection_count, open_connections) VALUES %s ON CONFLICT DO NOTHING\", strings.Join(valueStrings[:len(valueArgs)/12], \",\"))\n\t\t_, err := database.db.Exec(stmt, valueArgs...)\n\t\treturn err\n\t} else {\n\t\treturn nil\n\t}\n}", "func InsertIntoSlice(slice []interface{}, index int, value interface{}) []interface{} {\n\tvar newSlice []interface{}\n\n\t// Grow the slice by one element.\n\tif cap(slice) == len(slice) {\n\t\tnewSlice = make([]interface{}, len(slice)+1)\n\t\tcopy(newSlice[0:index], slice[0:index])\n\t} else {\n\t\tnewSlice = slice[0 : len(slice)+1]\n\t}\n\n\t// Use copy to move the upper part of the slice out of the way and open a hole.\n\tcopy(newSlice[index+1:], slice[index:])\n\t// Store the new value.\n\tnewSlice[index] = value\n\t// Return the result.\n\treturn newSlice\n}", "func insertMetadata(data []byte, metadata []byte, n int) []byte {\n\tnumMetadata := int(math.Ceil(float64(len(data) / n)))\n\n\tbufSize := len(metadata)*numMetadata + len(data)\n\tbuf := make([]byte, bufSize)\n\n\tfor i, j := 0, 0; i < len(data); i = i + n {\n\t\tdataStart := i\n\t\tdataEnd := i + n\n\t\tif dataEnd >= len(data) {\n\t\t\tdataEnd = len(data)\n\t\t}\n\n\t\tbufStart := j * (len(metadata) + n)\n\t\tbufEnd := bufStart + (dataEnd - dataStart)\n\n\t\tcopy(buf[bufStart:bufEnd], data[dataStart:dataEnd])\n\t\tcopy(buf[bufEnd:], metadata)\n\n\t\tj++\n\t}\n\treturn buf\n}", "func (m *MockRepository) InsertInto(tag *models.RestTag) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InsertInto\", tag)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (o *Source) Insert(exec boil.Executor, columns boil.Columns) error {\n\tif o == nil {\n\t\treturn errors.New(\"mdbmodels: no sources provided for insertion\")\n\t}\n\n\tvar err error\n\n\tnzDefaults := queries.NonZeroDefaultSet(sourceColumnsWithDefault, o)\n\n\tkey := makeCacheKey(columns, nzDefaults)\n\tsourceInsertCacheMut.RLock()\n\tcache, cached := sourceInsertCache[key]\n\tsourceInsertCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl, returnColumns := columns.InsertColumnSet(\n\t\t\tsourceAllColumns,\n\t\t\tsourceColumnsWithDefault,\n\t\t\tsourceColumnsWithoutDefault,\n\t\t\tnzDefaults,\n\t\t)\n\n\t\tcache.valueMapping, err = queries.BindMapping(sourceType, sourceMapping, wl)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcache.retMapping, err = queries.BindMapping(sourceType, sourceMapping, returnColumns)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(wl) != 0 {\n\t\t\tcache.query = fmt.Sprintf(\"INSERT INTO \\\"sources\\\" (\\\"%s\\\") %%sVALUES (%s)%%s\", strings.Join(wl, \"\\\",\\\"\"), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1))\n\t\t} else {\n\t\t\tcache.query = \"INSERT INTO \\\"sources\\\" %sDEFAULT VALUES%s\"\n\t\t}\n\n\t\tvar queryOutput, queryReturning string\n\n\t\tif len(cache.retMapping) != 0 {\n\t\t\tqueryReturning = fmt.Sprintf(\" RETURNING \\\"%s\\\"\", strings.Join(returnColumns, \"\\\",\\\"\"))\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning)\n\t}\n\n\tvalue := reflect.Indirect(reflect.ValueOf(o))\n\tvals := queries.ValuesFromMapping(value, cache.valueMapping)\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, cache.query)\n\t\tfmt.Fprintln(boil.DebugWriter, vals)\n\t}\n\n\tif len(cache.retMapping) != 0 {\n\t\terr = exec.QueryRow(cache.query, vals...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...)\n\t} else {\n\t\t_, err = exec.Exec(cache.query, vals...)\n\t}\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"mdbmodels: unable to insert into sources\")\n\t}\n\n\tif !cached {\n\t\tsourceInsertCacheMut.Lock()\n\t\tsourceInsertCache[key] = cache\n\t\tsourceInsertCacheMut.Unlock()\n\t}\n\n\treturn nil\n}", "func (s *Service) batchInsertDiffs(c context.Context, table string, wch chan []*model.Diff) (err error) {\n\tvar (\n\t\tbuff = make([]*model.Diff, _limit)\n\t\tbuffEnd = 0\n\t)\n\tfor ds := range wch {\n\t\tfor _, d := range ds {\n\t\t\tbuff[buffEnd] = d\n\t\t\tbuffEnd++\n\t\t\tif buffEnd >= _limit {\n\t\t\t\tvalues := diffValues(buff[:buffEnd])\n\t\t\t\tbuffEnd = 0\n\t\t\t\t_, err = s.dao.InsertTrend(c, table, values)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif buffEnd > 0 {\n\t\t\tvalues := diffValues(buff[:buffEnd])\n\t\t\tbuffEnd = 0\n\t\t\t_, err = s.dao.InsertTrend(c, table, values)\n\t\t}\n\t}\n\treturn\n}", "func (list *Linked_List) Insert_Before_At(index int, data interface{}) {\n\tlist.Insert_Before(list.At(index), data)\n}", "func (r *Rope) InsertBytes(point int, data []byte) (err error) {\n\tif point > r.runes {\n\t\tpoint = r.runes\n\t}\n\n\t// search for the Knot where we'll insert\n\tvar k *knot\n\ts := skiplist{r: r}\n\tif k, err = s.find2(point); err != nil {\n\t\treturn err\n\t}\n\treturn s.insert(k, data)\n}", "func insert(nums int) {\n\ttimeStart := util.Microsecond()\n\tfor i := 0; i < nums; i++ {\n\t\tkey := []byte(\"key_\" + strconv.Itoa(i)) // 10 bytes\n\t\tvalue := []byte(\"value_\" + strconv.Itoa(i)) //12 bytes\n\t\tbDB.Update(func(tx *bolt.Tx) error {\n\t\t\tb := tx.Bucket([]byte(\"copernicus\"))\n\t\t\terr := b.Put(key, value)\n\t\t\treturn err\n\t\t})\n\t}\n\tfmt.Println(\"insert time is :\", util.Microsecond()-timeStart)\n}", "func (this *Array) InsertToTail(v int) error{\n\treturn this.Insert(this.Len(), v)\n}", "func (a Slice[T]) Insert(index int, elements ...T) Slice[T] {\n\tresult := Slice[T]{}\n\tresult = append(result, a[0:index]...)\n\tresult = append(result, elements...)\n\tresult = append(result, a[index:]...)\n\treturn result\n}", "func copyOuterRows(innerColOffset, outerColOffset int, src *Chunk, numRows int, dst *Chunk) {\n\ttrace_util_0.Count(_chunk_util_00000, 17)\n\tif numRows <= 0 {\n\t\ttrace_util_0.Count(_chunk_util_00000, 20)\n\t\treturn\n\t}\n\ttrace_util_0.Count(_chunk_util_00000, 18)\n\trow := src.GetRow(0)\n\tvar srcCols []*column\n\tif innerColOffset == 0 {\n\t\ttrace_util_0.Count(_chunk_util_00000, 21)\n\t\tsrcCols = src.columns[outerColOffset:]\n\t} else {\n\t\ttrace_util_0.Count(_chunk_util_00000, 22)\n\t\t{\n\t\t\tsrcCols = src.columns[:innerColOffset]\n\t\t}\n\t}\n\ttrace_util_0.Count(_chunk_util_00000, 19)\n\tfor i, srcCol := range srcCols {\n\t\ttrace_util_0.Count(_chunk_util_00000, 23)\n\t\tdstCol := dst.columns[outerColOffset+i]\n\t\tdstCol.appendMultiSameNullBitmap(!srcCol.isNull(row.idx), numRows)\n\t\tdstCol.length += numRows\n\t\tif srcCol.isFixed() {\n\t\t\ttrace_util_0.Count(_chunk_util_00000, 24)\n\t\t\telemLen := len(srcCol.elemBuf)\n\t\t\tstart := row.idx * elemLen\n\t\t\tend := start + numRows*elemLen\n\t\t\tdstCol.data = append(dstCol.data, srcCol.data[start:end]...)\n\t\t} else {\n\t\t\ttrace_util_0.Count(_chunk_util_00000, 25)\n\t\t\t{\n\t\t\t\tstart, end := srcCol.offsets[row.idx], srcCol.offsets[row.idx+numRows]\n\t\t\t\tdstCol.data = append(dstCol.data, srcCol.data[start:end]...)\n\t\t\t\toffsets := dstCol.offsets\n\t\t\t\telemLen := srcCol.offsets[row.idx+1] - srcCol.offsets[row.idx]\n\t\t\t\tfor j := 0; j < numRows; j++ {\n\t\t\t\t\ttrace_util_0.Count(_chunk_util_00000, 27)\n\t\t\t\t\toffsets = append(offsets, int64(offsets[len(offsets)-1]+elemLen))\n\t\t\t\t}\n\t\t\t\ttrace_util_0.Count(_chunk_util_00000, 26)\n\t\t\t\tdstCol.offsets = offsets\n\t\t\t}\n\t\t}\n\t}\n}", "func (self *Ring) bulkDataSendToReplicas(maxRingPos int) {\n\n\tmin := self.KeyValTable.Min()\n\tkey := self.getKey()\n\n\t//Tree is empty\n\tif min.Equal(self.KeyValTable.Limit()) {\n\t\treturn\n\t}\n\tfor min != self.KeyValTable.Limit() {\n\t\titem := min.Item().(data.DataStore)\n if item.Key > maxRingPos {\n return\n }\n\t\tself.writeToReplicas(&item, key)\n\t\tfmt.Println(min.Item().(data.DataStore))\n\t\tmin = min.Next()\n\t}\n\n}", "func migrateDataToMergedSchema(ctx *sql.Context, tm *TableMerger, vm *valueMerger, mergedSch schema.Schema) error {\n\tlr, err := tm.leftTbl.GetRowData(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tleftRows := durable.ProllyMapFromIndex(lr)\n\tmut := leftRows.Rewriter(mergedSch.GetKeyDescriptor(), mergedSch.GetValueDescriptor())\n\tmapIter, err := mut.IterAll(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tleftSch, err := tm.leftTbl.GetSchema(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvalueDescriptor := leftSch.GetValueDescriptor()\n\n\tfor {\n\t\tkeyTuple, valueTuple, err := mapIter.Next(ctx)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnewValueTuple, err := remapTupleWithColumnDefaults(ctx, keyTuple, valueTuple, valueDescriptor, vm.leftMapping, tm, mergedSch, vm.syncPool)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = mut.Put(ctx, keyTuple, newValueTuple)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tm, err := mut.Map(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnewIndex := durable.IndexFromProllyMap(m)\n\tnewTable, err := tm.leftTbl.UpdateRows(ctx, newIndex)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttm.leftTbl = newTable\n\n\t// TODO: for now... we don't actually need to migrate any of the data held in secondary indexes (yet).\n\t// We're currently dealing with column adds/drops/renames/reorders, but none of those directly affect\n\t// secondary indexes. Columns drops *should*, but currently Dolt just drops any index referencing the\n\t// dropped column, so there's nothing to do currently.\n\t// https://github.com/dolthub/dolt/issues/5641\n\t// Once we start handling type changes changes or primary key changes, or fix the bug above,\n\t// then we will need to start migrating secondary index data, too.\n\n\treturn nil\n}", "func (t *Table) Push(values ...interface{}) {\n\tfor i, value := range values {\n\t\t// TODO: bounds checking\n\t\tt.columns[i].Push(value)\n\t}\n\tt.numRows++\n}", "func (d *Database) Insert(db DB, table string, src interface{}) error {\n\treturn d.InsertContext(context.Background(), db, table, src)\n}", "func (d TinkDB) InsertIntoWorkflowEventTable(ctx context.Context, wfEvent *pb.WorkflowActionStatus, time time.Time) error {\n\ttx, err := d.instance.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"BEGIN transaction\")\n\t}\n\n\t// TODO \"created_at\" field should be set in worker and come in the request\n\t_, err = tx.Exec(`\n\tINSERT INTO\n\t\tworkflow_event (workflow_id, worker_id, task_name, action_name, execution_time, message, status, created_at)\n\tVALUES\n\t\t($1, $2, $3, $4, $5, $6, $7, $8);\n\t`, wfEvent.WorkflowId, wfEvent.WorkerId, wfEvent.TaskName, wfEvent.ActionName, wfEvent.Seconds, wfEvent.Message, wfEvent.ActionStatus, time)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"INSERT in to workflow_event\")\n\t}\n\terr = tx.Commit()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"COMMIT\")\n\t}\n\treturn nil\n}", "func (s *BaseMySqlParserListener) EnterTableSourceBase(ctx *TableSourceBaseContext) {}", "func (r *batchRangeVectorIterator) load(start, end int64) {\n\tfor lbs, sample, hasNext := r.iter.Peek(); hasNext; lbs, sample, hasNext = r.iter.Peek() {\n\t\tif sample.Timestamp > end {\n\t\t\t// not consuming the iterator as this belong to another range.\n\t\t\treturn\n\t\t}\n\t\t// the lower bound of the range is not inclusive\n\t\tif sample.Timestamp <= start {\n\t\t\t_ = r.iter.Next()\n\t\t\tcontinue\n\t\t}\n\t\t// adds the sample.\n\t\tvar series *promql.Series\n\t\tvar ok bool\n\t\tseries, ok = r.window[lbs]\n\t\tif !ok {\n\t\t\tvar metric labels.Labels\n\t\t\tif metric, ok = r.metrics[lbs]; !ok {\n\t\t\t\tvar err error\n\t\t\t\tmetric, err = promql_parser.ParseMetric(lbs)\n\t\t\t\tif err != nil {\n\t\t\t\t\t_ = r.iter.Next()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tr.metrics[lbs] = metric\n\t\t\t}\n\n\t\t\tseries = getSeries()\n\t\t\tseries.Metric = metric\n\t\t\tr.window[lbs] = series\n\t\t}\n\t\tp := promql.Point{\n\t\t\tT: sample.Timestamp,\n\t\t\tV: sample.Value,\n\t\t}\n\t\tseries.Points = append(series.Points, p)\n\t\t_ = r.iter.Next()\n\t}\n}", "func tabInsert(ls *LuaState) int {\n\te := _auxGetN(ls, 1, TAB_RW) + 1 /* first empty element */\n\tvar pos int64 /* where to insert new element */\n\tswitch luaGetTop(ls) {\n\tcase 2: /* called with only 2 arguments */\n\t\tpos = e /* insert new element at the end */\n\tcase 3:\n\t\tpos = ls.CheckInteger(2) /* 2nd argument is the position */\n\t\tls.ArgCheck(1 <= pos && pos <= e, 2, \"position out of bounds\")\n\t\tfor i := e; i > pos; i-- { /* move up elements */\n\t\t\tluaGetI(ls, 1, i-1)\n\t\t\tluaSetI(ls, 1, i) /* t[i] = t[i - 1] */\n\t\t}\n\tdefault:\n\t\treturn ls.Error2(\"wrong number of arguments to 'insert'\")\n\t}\n\tluaSetI(ls, 1, pos) /* t[pos] = v */\n\treturn 0\n}", "func (db *ChainDb) insertBlockData(batch storage.Batch, sha *wire.Hash, prevSha *wire.Hash, buf []byte) (uint64, error) {\n\toBlkHeight, err := db.getBlkLoc(prevSha)\n\tif err != nil {\n\t\tvar zeroHash = wire.Hash{}\n\t\tif *prevSha != zeroHash {\n\t\t\treturn 0, err\n\t\t}\n\t\toBlkHeight = UnknownHeight\n\t}\n\n\tblkHeight := oBlkHeight + 1\n\tsetBlk(batch, sha, blkHeight, buf)\n\tnewStorageMeta := dbStorageMeta{\n\t\tcurrentHeight: blkHeight,\n\t\tcurrentHash: *sha,\n\t}\n\tbatch.Put(dbStorageMetaDataKey, encodeDBStorageMetaData(newStorageMeta))\n\n\treturn blkHeight, nil\n}", "func (m Manager) AddTo(schema *Schema) error {\n\treturn schema.Add(m.TableElem)\n}", "func (d *dbBase) Insert(ctx context.Context, q dbQuerier, mi *modelInfo, ind reflect.Value, tz *time.Location) (int64, error) {\n\tnames := make([]string, 0, len(mi.fields.dbcols))\n\tvalues, autoFields, err := d.collectValues(mi, ind, mi.fields.dbcols, false, true, &names, tz)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tid, err := d.InsertValue(ctx, q, mi, false, names, values)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif len(autoFields) > 0 {\n\t\terr = d.ins.setval(ctx, q, mi, autoFields)\n\t}\n\treturn id, err\n}", "func (o *CurrentChartDataMinutely) Insert(exec boil.Executor, columns boil.Columns) error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no current_chart_data_minutely provided for insertion\")\n\t}\n\n\tvar err error\n\tcurrTime := time.Now().In(boil.GetLocation())\n\n\tif o.CreatedAt.IsZero() {\n\t\to.CreatedAt = currTime\n\t}\n\tif o.UpdatedAt.IsZero() {\n\t\to.UpdatedAt = currTime\n\t}\n\n\tif err := o.doBeforeInsertHooks(exec); err != nil {\n\t\treturn err\n\t}\n\n\tnzDefaults := queries.NonZeroDefaultSet(currentChartDataMinutelyColumnsWithDefault, o)\n\n\tkey := makeCacheKey(columns, nzDefaults)\n\tcurrentChartDataMinutelyInsertCacheMut.RLock()\n\tcache, cached := currentChartDataMinutelyInsertCache[key]\n\tcurrentChartDataMinutelyInsertCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl, returnColumns := columns.InsertColumnSet(\n\t\t\tcurrentChartDataMinutelyColumns,\n\t\t\tcurrentChartDataMinutelyColumnsWithDefault,\n\t\t\tcurrentChartDataMinutelyColumnsWithoutDefault,\n\t\t\tnzDefaults,\n\t\t)\n\n\t\tcache.valueMapping, err = queries.BindMapping(currentChartDataMinutelyType, currentChartDataMinutelyMapping, wl)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcache.retMapping, err = queries.BindMapping(currentChartDataMinutelyType, currentChartDataMinutelyMapping, returnColumns)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(wl) != 0 {\n\t\t\tcache.query = fmt.Sprintf(\"INSERT INTO \\\"current_chart_data_minutely\\\" (\\\"%s\\\") %%sVALUES (%s)%%s\", strings.Join(wl, \"\\\",\\\"\"), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1))\n\t\t} else {\n\t\t\tcache.query = \"INSERT INTO \\\"current_chart_data_minutely\\\" %sDEFAULT VALUES%s\"\n\t\t}\n\n\t\tvar queryOutput, queryReturning string\n\n\t\tif len(cache.retMapping) != 0 {\n\t\t\tqueryReturning = fmt.Sprintf(\" RETURNING \\\"%s\\\"\", strings.Join(returnColumns, \"\\\",\\\"\"))\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning)\n\t}\n\n\tvalue := reflect.Indirect(reflect.ValueOf(o))\n\tvals := queries.ValuesFromMapping(value, cache.valueMapping)\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, cache.query)\n\t\tfmt.Fprintln(boil.DebugWriter, vals)\n\t}\n\n\tif len(cache.retMapping) != 0 {\n\t\terr = exec.QueryRow(cache.query, vals...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...)\n\t} else {\n\t\t_, err = exec.Exec(cache.query, vals...)\n\t}\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to insert into current_chart_data_minutely\")\n\t}\n\n\tif !cached {\n\t\tcurrentChartDataMinutelyInsertCacheMut.Lock()\n\t\tcurrentChartDataMinutelyInsertCache[key] = cache\n\t\tcurrentChartDataMinutelyInsertCacheMut.Unlock()\n\t}\n\n\treturn o.doAfterInsertHooks(exec)\n}", "func (db *DB) fillWithValues(recordDescription *recordDescription, pointersGetter pointersGetter, columns []string, rows *sql.Rows) (int, error) {\n\trowsCount := 0\n\trecordLength := recordDescription.len()\n\tfor rows.Next() {\n\t\trowsCount++\n\t\tif rowsCount > recordLength {\n\t\t\treturn 0, fmt.Errorf(\"there are more rows returned than the target size : %v\", recordLength)\n\t\t}\n\t\tinstancePtr := recordDescription.index(rowsCount - 1)\n\n\t\tpointers, err := pointersGetter(instancePtr, columns)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\terr = rows.Scan(pointers...)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\treturn rowsCount, nil\n}", "func (m *PgDbSyncer) insertUpstreamData(mdata *types.ModemData) {\n\tusFreqList := make(map[int64]nothing)\n\n\tfor _, us := range mdata.UpStreams {\n\t\tif us.Freq == 0 {\n\t\t\t// some modems do report the upstream frequency wrong\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := usFreqList[int64(us.Freq)]; ok {\n\t\t\t// and some report the same frequency twice\n\t\t\t// this check prevents a duplicate key entry in the database\n\t\t\tcontinue\n\t\t}\n\t\tm.copyUpstreams.Insert(mdata.DbModemId, mdata.Timestamp,\n\t\t\tus.Freq, us.TimingOffset, us.TxPower)\n\t\tusFreqList[int64(us.Freq)] = nothing{}\n\t}\n}" ]
[ "0.5563809", "0.55390996", "0.5367466", "0.52960044", "0.52340716", "0.5105631", "0.5099199", "0.50528187", "0.50201684", "0.49987578", "0.4963444", "0.49634376", "0.49370745", "0.49369252", "0.4891936", "0.4813999", "0.48111808", "0.47809646", "0.4778556", "0.47260755", "0.4721869", "0.47209877", "0.47182995", "0.47142687", "0.46998703", "0.46950388", "0.46824074", "0.466633", "0.46648622", "0.465623", "0.46512872", "0.46468538", "0.46446732", "0.46301693", "0.46231726", "0.46122015", "0.46114436", "0.46087784", "0.46056947", "0.45989886", "0.45961013", "0.45863166", "0.45843792", "0.45642582", "0.45541748", "0.45454535", "0.45433277", "0.45422414", "0.4533035", "0.45319512", "0.45279926", "0.45186624", "0.45098072", "0.45018774", "0.45008835", "0.45006794", "0.44940397", "0.4487881", "0.44874611", "0.4486881", "0.44842187", "0.44805762", "0.44717336", "0.4466651", "0.44549388", "0.44536522", "0.4451889", "0.44500116", "0.4448317", "0.4444538", "0.444341", "0.44407704", "0.4439993", "0.44314852", "0.4419973", "0.44189477", "0.4418246", "0.44178075", "0.44172764", "0.44157276", "0.44111156", "0.44025567", "0.44009504", "0.4396093", "0.4395326", "0.43950167", "0.43910316", "0.43882284", "0.43877062", "0.43855438", "0.43748993", "0.43669063", "0.43581104", "0.43535382", "0.43462956", "0.43438163", "0.4342262", "0.4341038", "0.4336175", "0.43345085" ]
0.57182276
0
Inserts items into this tuple, starting from offset start
func (this *Tuple) InsertItems(start int, items ...interface{}) { start = this.Offset(start) rhs := this.Copy().data[start:] this.data = append(this.data[:start], items...) this.data = append(this.data, rhs...) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *Tuple) Insert(start int, other *Tuple) {\n\tthis.InsertItems(start, other.data...)\n}", "func (s *items) insertAt(index int, item Item) {\n\t*s = append(*s, nil)\n\tif index < len(*s) {\n\t\tcopy((*s)[index+1:], (*s)[index:])\n\t}\n\t(*s)[index] = item\n}", "func insertIntoPosition(data []string, insertion string) []string {\n\t// I am really sorry for this loop. I have not figured out why slice concatenation doesn't work\n\tvar newData []string\n\tdataLength := len(data)\n\tposition := pickNumberRange(dataLength + 1)\n\tif position == dataLength {\n\t\tnewData = append(data, []string{insertion}...)\n\t} else {\n\t\tfor i, entry := range data {\n\t\t\tif i == position {\n\t\t\t\tnewData = append(newData, []string{insertion}...)\n\t\t\t}\n\t\t\tnewData = append(newData, entry)\n\t\t}\n\t}\n\treturn newData\n}", "func insert(a []interface{}, c interface{}, i int) []interface{} {\n\treturn append(a[:i], append([]interface{}{c}, a[i:]...)...)\n}", "func (t *StringSlice) InsertAt(i int, s string) *StringSlice {\n\tif i < 0 || i >= len(t.items) {\n\t\treturn t\n\t}\n\tres := []string{}\n\tres = append(res, t.items[:0]...)\n\tres = append(res, s)\n\tres = append(res, t.items[i:]...)\n\tt.items = res\n\treturn t\n}", "func (s *nodeBlock) insertItemAt(index int, item Metadata) {\n\t_ = s.items[maxItems-1-s.itemsSize]\n\tcopy(s.items[index+1:], s.items[index:])\n\ts.items[index] = item\n\ts.itemsSize++\n\ts.markDirty()\n}", "func (a Slice[T]) Insert(index int, elements ...T) Slice[T] {\n\tresult := Slice[T]{}\n\tresult = append(result, a[0:index]...)\n\tresult = append(result, elements...)\n\tresult = append(result, a[index:]...)\n\treturn result\n}", "func (list *Linked_List) Insert_Before_At(index int, data interface{}) {\n\tlist.Insert_Before(list.At(index), data)\n}", "func SliceInsert(sl *[]Ki, k Ki, idx int) {\n\tkl := len(*sl)\n\tif idx < 0 {\n\t\tidx = kl + idx\n\t}\n\tif idx < 0 { // still?\n\t\tidx = 0\n\t}\n\tif idx > kl { // last position allowed for insert\n\t\tidx = kl\n\t}\n\t// this avoids extra garbage collection\n\t*sl = append(*sl, nil)\n\tif idx < kl {\n\t\tcopy((*sl)[idx+1:], (*sl)[idx:kl])\n\t}\n\t(*sl)[idx] = k\n}", "func PrependItems(slice []int, values ...int) []int {\n\treturn append(values, slice...)\n}", "func InsertBytes(dest *[]byte, pos int, src ...[]byte) {\n\tfor _, part := range src {\n\t\tdestLen, partLen := len(*dest), len(part)\n\t\tif pos < 0 || pos > destLen {\n\t\t\tmod.Error(\"Position\", pos, \"out of range; len(*dest):\", destLen)\n\t\t} else if partLen != 0 {\n\t\t\t*dest = append(*dest, part...) // grow destination\n\t\t\tcopy((*dest)[pos+partLen:], (*dest)[pos:]) // shift to make space\n\t\t\tcopy((*dest)[pos:], part) // copy source to dest.\n\t\t}\n\t\tpos += len(part)\n\t}\n}", "func (e *ObservableEditableBuffer) InsertAt(rp0 int, rs []rune) {\n\tp0 := e.f.RuneTuple(rp0)\n\ts, nr := RunesToBytes(rs)\n\n\te.Insert(p0, s, nr)\n}", "func insert(array []int8, val int8, pos int) []int8 {\r\n\tvar length = len(array)\r\n\tvar tempArray = make([]int8, length+1)\r\n\tfmt.Printf(\"\\n\")\r\n\r\n\t// copy each value from start to position\r\n\t// leave the pos we want to fill empty and copy each value after that\r\n\t// eg at pos 3: 1 2 3 x 4 5 6 7 -> 1 2 3 21 4 5 6 7\r\n\r\n\tfor i := 0; i < length; i++ {\r\n\t\tif i < pos {\r\n\t\t\ttempArray[i] = array[i]\r\n\t\t} else {\r\n\t\t\ttempArray[i+1] = array[i]\r\n\t\t}\r\n\t}\r\n\r\n\ttempArray[pos] = val\r\n\treturn tempArray\r\n}", "func (b *Buffer) Insert(o, n int) {\n\tp := make([]*Tile, n)\n\tb.Tiles = append(b.Tiles[:o], append(p, b.Tiles[o:]...)...)\n}", "func BenchmarkSliceInsert(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\ts := []string{\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"g\"}\n\t\tindex := i % len(s)\n\t\t_ = SliceInsert(&s, index, \"0\")\n\t}\n}", "func (i *Iter) Prepend(v ...uint64) {\n\ti.v = append(v, i.v...)\n}", "func (e *ObservableEditableBuffer) Insert(p0 OffsetTuple, s []byte, nr int) {\n\tbefore := e.getTagStatus()\n\tdefer e.notifyTagObservers(before)\n\n\te.f.Insert(p0, s, nr, e.seq)\n\tif e.seq < 1 {\n\t\te.f.FlattenHistory()\n\t}\n\te.inserted(p0, s, nr)\n}", "func (p *SliceOfMap) Insert(i int, obj interface{}) ISlice {\n\tif p == nil || len(*p) == 0 {\n\t\treturn p.ConcatM(obj)\n\t}\n\n\t// Insert the item before j if pos and after j if neg\n\tj := i\n\tif j = absIndex(len(*p), j); j == -1 {\n\t\treturn p\n\t}\n\tif i < 0 {\n\t\tj++\n\t}\n\tif elems, err := ToSliceOfMapE(obj); err == nil {\n\t\tif j == 0 {\n\t\t\t*p = append(*elems, *p...)\n\t\t} else if j < len(*p) {\n\t\t\t*p = append(*p, *elems...) // ensures enough space exists\n\t\t\tcopy((*p)[j+len(*elems):], (*p)[j:]) // shifts right elements drop added\n\t\t\tcopy((*p)[j:], *elems) // set new in locations vacated\n\t\t} else {\n\t\t\t*p = append(*p, *elems...)\n\t\t}\n\t}\n\treturn p\n}", "func (l *List) Prepend(items ...Item) (err error) {\n\tl.value = append(items, l.value...)\n\treturn nil\n}", "func InsertToSlice(nums []int, v, pos int) []int {\n\tif pos > len(nums) || pos < 0 {\n\t\treturn nil\n\t}\n\tvar ret []int\n\tret = append(ret, nums[0:pos]...)\n\tret = append(ret, v)\n\tret = append(ret, nums[pos:]...)\n\treturn ret\n}", "func (s Byte) Insert(items ...byte) Byte {\n\tfor _, item := range items {\n\t\ts[item] = Empty{}\n\t}\n\treturn s\n}", "func (nl *nodeList) insert(i int, n *Node) {\n\t// Add a nil value to the end of the slice, to make room for the new Node.\n\tnl.elements = append(nl.elements, nil)\n\t// Copy values from the insertion point to the right by one\n\tcopy(nl.elements[i+1:], nl.elements[i:])\n\t// Set the value at the insertion point\n\tnl.elements[i] = n\n}", "func InsertIntoSlice(slice []interface{}, index int, value interface{}) []interface{} {\n\tvar newSlice []interface{}\n\n\t// Grow the slice by one element.\n\tif cap(slice) == len(slice) {\n\t\tnewSlice = make([]interface{}, len(slice)+1)\n\t\tcopy(newSlice[0:index], slice[0:index])\n\t} else {\n\t\tnewSlice = slice[0 : len(slice)+1]\n\t}\n\n\t// Use copy to move the upper part of the slice out of the way and open a hole.\n\tcopy(newSlice[index+1:], slice[index:])\n\t// Store the new value.\n\tnewSlice[index] = value\n\t// Return the result.\n\treturn newSlice\n}", "func (b *BTree) insertInNodeAtIdx(n *memNode, item *Item, i int) {\n\ts := n.node.Items\n\ts = append(s, nil)\n\tif i < len(s) {\n\t\tcopy(s[i+1:], s[i:])\n\t}\n\ts[i] = item\n\tn.node.Items = s\n}", "func (sl *stringList) insert(i int, aString string) {\n\t// Add a empty string value to the end of the slice, to make room for the new element.\n\tsl.elements = append(sl.elements, \"\")\n\t// Copy values from the insertion point to the right by one\n\tcopy(sl.elements[i+1:], sl.elements[i:])\n\t// Set the value at the insertion point\n\tsl.elements[i] = aString\n}", "func (idxer *Indexes) Insert(item *item, to ...string) {\n\tfor _, index := range idxer.storage {\n\t\tif idxer.fit(index.name, to) && match.Match(string(item.key), index.pattern) {\n\t\t\tindex.insert(item)\n\t\t}\n\t}\n}", "func (ref Ref) Insert(x *Term, pos int) Ref {\n\tswitch {\n\tcase pos == len(ref):\n\t\treturn ref.Append(x)\n\tcase pos > len(ref)+1:\n\t\tpanic(\"illegal index\")\n\t}\n\tcpy := make(Ref, len(ref)+1)\n\tcopy(cpy, ref[:pos])\n\tcpy[pos] = x\n\tcopy(cpy[pos+1:], ref[pos:])\n\treturn cpy\n}", "func (q *quartileIndex) Insert(n int, at int) error {\n\tif n%4 != 0 {\n\t\tpanic(\"can only extend by nibbles (multiples of 4)\")\n\t}\n\terr := q.bits.Insert(n, at)\n\tif err != nil {\n\t\treturn err\n\t}\n\tnewlen := q.bits.Len()\n\tfor i := 0; i < 3; i++ {\n\t\tq.adjust(i, n, at, (newlen * (i + 1) / 4))\n\t}\n\treturn nil\n}", "func Insert(pts PTslice, pt *PT) PTslice {\n\ti := pts.locate(pt.Time)\n\tnpts := append(pts, &PT{})\n\tcopy(npts[i+1:], npts[i:])\n\tnpts[i] = pt\n\treturn npts\n}", "func (a Args) SetBefore(cursor interface{}) { a[3] = &cursor }", "func (d *Data) Insert(items ...interface{}) {\n\tfor _, value := range items {\n\t\td.Lock()\n\t\tv, ok := d.m[value]\n\t\td.Unlock()\n\t\tif ok {\n\t\t\td.Lock()\n\t\t\td.m[value] = v + 1\n\t\t\td.Unlock()\n\t\t\tcontinue\n\t\t}\n\t\td.Lock()\n\t\td.m[value] = 1\n\t\td.Unlock()\n\t}\n}", "func insert(slice []int, index, value int) []int {\n // Grow the slice by one element.\n slice = slice[0 : len(slice)+1]\n // Use copy to move the upper part of the slice out of the way and open a hole.\n copy(slice[index+1:], slice[index:])\n // Store the new value.\n slice[index] = value\n // Return the result.\n return slice\n}", "func (sl *Slice) Insert(k Ki, idx int) {\n\tSliceInsert((*[]Ki)(sl), k, idx)\n}", "func (s *SliceInt) Prepend(elems ...int) *SliceInt {\n\tif s == nil {\n\t\treturn nil\n\t}\n\ts.data = append(elems, s.data...)\n\treturn s\n}", "func (l *List) InsertInMiddle(value interface{}) {\n\tl = GetHead(l)\n\tlistSize := l.ListSize()\n\tmiddleIndex := listSize / 2\n\tfor i := 0; i <= middleIndex; i++ {\n\t\tl = l.next\n\t}\n\tnewElement := List{value: value, next: l, prev: l.prev}\n\tl.prev.next = &newElement\n\tl.prev = &newElement\n}", "func (list *List) PrependToBeginning(data int) {\n // 1. Create a new node\n newNode := &Node{data: data, next: nil}\n\n // 2. Point the new node's next to current head\n newNode.next = list.Head()\n\n // 3. Update the list's head as the new node\n list.head = newNode\n\n // 4. Increment the list size\n list.size++\n}", "func (h *binaryHeap) Insert(items ...int) {\n\tif h.size+len(items) >= len(h.items) {\n\t\th.resize(len(items))\n\t}\n\tfor _, element := range items {\n\t\th.items[h.size] = element\n\t\th.size++\n\t\th.siftup(h.size - 1)\n\t}\n}", "func IntInsert(sorted []int, item int, lt IntLessThan) []int {\n\ti := IntBinarySearch(sorted, item, lt)\n\tif i == len(sorted)-1 && lt(sorted[i], item) {\n\t\treturn append(sorted, item)\n\t}\n\treturn append(sorted[:i], append([]int{item}, sorted[i:]...)...)\n}", "func (l *List) Prepend(i interface{}) {\n\tl = GetHead(l)\n\tl.prev = &List{next: l, value: i}\n}", "func (v *Data) InsertSlice(idx int, val []PicData) {\n\tdv := *v\n\t*v = append(append(append(make(Data, 0, len(dv)+1), dv[:idx]...), val...), dv[idx:]...)\n}", "func (list *List) Prepend(values ...interface{}) {\n\t// in reverse to keep passed order i.e. [\"c\",\"d\"] -> Prepend([\"a\",\"b\"]) -> [\"a\",\"b\",\"c\",d\"]\n\tfor v := len(values) - 1; v >= 0; v-- {\n\t\tnewElement := &element{value: values[v], next: list.first}\n\t\tlist.first = newElement\n\t\tif list.size == 0 {\n\t\t\tlist.last = newElement\n\t\t}\n\t\tlist.size++\n\t}\n}", "func insert(x []int, index, value int) []int {\n\t// Grow the slice by one element.\n\tx = x[0 : len(x)+1]\n\t// Create room for new element.\n\tcopy(x[index+1:], x[index:])\n\t// Insert the new element.\n\tx[index] = value\n\treturn x\n}", "func TestPrepend(t *T) {\n\t// Normal case\n\tintl := []interface{}{3, 2, 1, 0}\n\tl := NewList(intl...)\n\tnl := l.Prepend(4)\n\tassertSaneList(l, t)\n\tassertSaneList(nl, t)\n\tassertSeqContents(l, intl, t)\n\tassertSeqContents(nl, []interface{}{4, 3, 2, 1, 0}, t)\n\n\t// Degenerate case\n\tl = NewList()\n\tnl = l.Prepend(0)\n\tassertEmpty(l, t)\n\tassertSaneList(nl, t)\n\tassertSeqContents(nl, []interface{}{0}, t)\n}", "func (s *children) insertAt(index int, n *node) {\n\t*s = append(*s, nil)\n\tif index < len(*s) {\n\t\tcopy((*s)[index+1:], (*s)[index:])\n\t}\n\t(*s)[index] = n\n}", "func (p *SliceOfMap) Prepend(elem interface{}) ISlice {\n\treturn p.Insert(0, elem)\n}", "func (l SList) InsertBefore(prev, off int64) error {\n\tn, err := l.OpenSList(off)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif prev != 0 {\n\t\tp, err := l.OpenSList(prev)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := p.setNext(l.Off); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn l.setNext(n.Off)\n}", "func (list *List) Insert(index int, values ...interface{}) {\n\n\tif !list.withinRange(index) {\n\t\t// Append\n\t\tif index == list.size {\n\t\t\tlist.Add(values...)\n\t\t}\n\t\treturn\n\t}\n\n\tlist.size += len(values)\n\n\tvar beforeElement *element\n\tfoundElement := list.first\n\tfor e := 0; e != index; e, foundElement = e+1, foundElement.next {\n\t\tbeforeElement = foundElement\n\t}\n\n\tif foundElement == list.first {\n\t\toldNextElement := list.first\n\t\tfor i, value := range values {\n\t\t\tnewElement := &element{value: value}\n\t\t\tif i == 0 {\n\t\t\t\tlist.first = newElement\n\t\t\t} else {\n\t\t\t\tbeforeElement.next = newElement\n\t\t\t}\n\t\t\tbeforeElement = newElement\n\t\t}\n\t\tbeforeElement.next = oldNextElement\n\t} else {\n\t\toldNextElement := beforeElement.next\n\t\tfor _, value := range values {\n\t\t\tnewElement := &element{value: value}\n\t\t\tbeforeElement.next = newElement\n\t\t\tbeforeElement = newElement\n\t\t}\n\t\tbeforeElement.next = oldNextElement\n\t}\n}", "func (s Int64) Insert(items ...int64) Int64 {\n\treturn Int64(cast(s).Insert(items...))\n}", "func (l *SliceList[T]) Prepend(v ...T) {\n\t*l = append(v, (*l)...)\n}", "func insert(a []map[string]interface{}, c map[string]interface{}, i int) []map[string]interface{} {\n\treturn append(a[:i], append([]map[string]interface{}{c}, a[i:]...)...)\n}", "func (hat *HashedArrayTree) Prepend(values ...interface{}) error {\n\tlenValues := len(values)\n\tnewSize := hat.size + lenValues\n\tif err := hat.resize(newSize); err != nil {\n\t\treturn err\n\t}\n\t// Move items in the buffer by the length of values\n\tfor i := hat.size - 1; i >= 0; i-- {\n\t\tbti, bli := hat.topIndex(i), hat.leafIndex(i)\n\t\tati, ali := hat.topIndex(i+lenValues), hat.leafIndex(i+lenValues)\n\t\that.top[ati][ali] = hat.top[bti][bli]\n\t}\n\tfor i := 0; i < lenValues; i++ {\n\t\tti, li := hat.topIndex(i), hat.leafIndex(i)\n\t\that.top[ti][li] = values[i]\n\t}\n\that.size = newSize\n\treturn nil\n}", "func InsertBeginning(list List, newNode *Node) List {\n\tnewNode.Next = list.FirstNode\n\tlist.FirstNode = newNode\n\treturn list\n}", "func (t *strideTable[T]) insert(addr uint8, prefixLen int, val *T) {\n\tidx := prefixIndex(addr, prefixLen)\n\told := t.entries[idx].value\n\toldIdx := t.entries[idx].prefixIndex\n\tif oldIdx == idx && old == val {\n\t\t// This exact prefix+value is already in the table.\n\t\treturn\n\t}\n\tt.allot(idx, oldIdx, idx, val)\n\tif oldIdx != idx {\n\t\t// This route entry was freshly created (not just updated), that's a new\n\t\t// reference.\n\t\tt.refs++\n\t}\n\treturn\n}", "func (l *leaf) insert(x, y float64, elems []interface{}, inPtr *subtree, r *root) {\n\tfor i := range l.ps {\n\t\tif l.ps[i].zeroed() {\n\t\t\tl.ps[i].x = x\n\t\t\tl.ps[i].y = y\n\t\t\tl.ps[i].elems = elems\n\t\t\treturn\n\t\t}\n\t\tif l.ps[i].sameLoc(x, y) {\n\t\t\tl.ps[i].elems = append(l.ps[i].elems, elems...)\n\t\t\treturn\n\t\t}\n\t}\n\t// This leaf is full we need to create an intermediary node to divide it up\n\tnewIntNode(x, y, elems, inPtr, l, r)\n}", "func (o *Outline) Insert(index uint, item *OutlineItem) {\n\tl := uint(len(o.items))\n\tif index > l {\n\t\tindex = l\n\t}\n\n\to.items = append(o.items[:index], append([]*OutlineItem{item}, o.items[index:]...)...)\n}", "func (this *Tuple) AppendItems(items ...interface{}) {\n\tthis.data = append(this.data, items...)\n}", "func (e *ObservableEditableBuffer) inserted(q0 OffsetTuple, b []byte, nr int) {\n\te.treatasclean = false\n\tfor observer := range e.observers {\n\t\tobserver.Inserted(q0, b, nr)\n\t}\n}", "func (v *IntVec) Insert(idx int, val ...int) {\n\tdv := *v\n\tdv = append(dv, val...)\n\tcopy(dv[idx+len(val):], dv[idx:])\n\tcopy(dv[idx:], val)\n\t*v = dv\n}", "func (mod *Modifier) insertSource(source []byte) (from, to int) {\n\troot := mod.Root()\n\torgLen := len(root.source)\n\tfrom, to = orgLen, orgLen+len(source)\n\tif from < to {\n\t\troot.source = append(root.source, source...)\n\t} else {\n\t\tto = from\n\t}\n\treturn\n}", "func prepend(arr []Message, item Message) []Message {\n\treturn append([]Message{item}, arr...)\n}", "func (this *ActivityStreamsImageProperty) PrependActivityStreamsMention(v vocab.ActivityStreamsMention) {\n\tthis.properties = append([]*ActivityStreamsImagePropertyIterator{{\n\t\tactivitystreamsMentionMember: v,\n\t\talias: this.alias,\n\t\tmyIdx: 0,\n\t\tparent: this,\n\t}}, this.properties...)\n\tfor i := 1; i < this.Len(); i++ {\n\t\t(this.properties)[i].myIdx = i\n\t}\n}", "func (driver) InsertOffset(\n\tctx context.Context,\n\ttx *sql.Tx,\n\tak, sk string,\n\tn uint64,\n) (_ bool, err error) {\n\tdefer sqlx.Recover(&err)\n\n\treturn sqlx.TryExecRow(\n\t\tctx,\n\t\ttx,\n\t\t`INSERT INTO stream_offset SET\n\t\t\tapp_key = ?,\n\t\t\tsource_app_key = ?,\n\t\t\tnext_offset = ?\n\t\tON DUPLICATE KEY UPDATE\n\t\t\tapp_key = app_key`, // do nothing\n\t\tak,\n\t\tsk,\n\t\tn,\n\t), nil\n}", "func (l *littr) InsertImports(imports *[]string, start, end int) {\n\t// Take out imports\n\tl.code = l.code[:start] + l.code[end+1:]\n\n\t// Init import string and generate it by cycling through necessary imports\n\timportStr := \"\\n\\nimport (\\n\"\n\tfor _, im := range *imports {\n\t\timportStr += \"\\t\" + im + \"\\n\"\n\t}\n\timportStr += \")\\n\"\n\n\t// Insert the import at the first \\n (which should be after package line)\n\tinsertAt := strings.Index(l.code, \"\\n\")\n\n\tl.code = l.code[:insertAt] + importStr + l.code[insertAt:]\n}", "func tabInsert(ls *LuaState) int {\n\te := _auxGetN(ls, 1, TAB_RW) + 1 /* first empty element */\n\tvar pos int64 /* where to insert new element */\n\tswitch luaGetTop(ls) {\n\tcase 2: /* called with only 2 arguments */\n\t\tpos = e /* insert new element at the end */\n\tcase 3:\n\t\tpos = ls.CheckInteger(2) /* 2nd argument is the position */\n\t\tls.ArgCheck(1 <= pos && pos <= e, 2, \"position out of bounds\")\n\t\tfor i := e; i > pos; i-- { /* move up elements */\n\t\t\tluaGetI(ls, 1, i-1)\n\t\t\tluaSetI(ls, 1, i) /* t[i] = t[i - 1] */\n\t\t}\n\tdefault:\n\t\treturn ls.Error2(\"wrong number of arguments to 'insert'\")\n\t}\n\tluaSetI(ls, 1, pos) /* t[pos] = v */\n\treturn 0\n}", "func (t *Trie) Insert(word ...string) {\n\tfor _, w := range word {\n\t\tt.insertWord(w)\n\t}\n}", "func (list *List) Insert(idx int, element interface{}) error {\n\tif list.Length() < idx || idx < 0 {\n\t\treturn fmt.Errorf(\"index out of range\")\n\t}\n\tlist_ := []interface{}(*list)\n\t*list = append(list_[:idx], append([]interface{}{element}, list_[idx:]...)...)\n\treturn nil\n}", "func (oi *OutlineItem) Insert(index uint, item *OutlineItem) {\n\tl := uint(len(oi.items))\n\tif index > l {\n\t\tindex = l\n\t}\n\n\toi.items = append(oi.items[:index], append([]*OutlineItem{item}, oi.items[index:]...)...)\n}", "func (this *ActivityStreamsImageProperty) InsertActivityStreamsMention(idx int, v vocab.ActivityStreamsMention) {\n\tthis.properties = append(this.properties, nil)\n\tcopy(this.properties[idx+1:], this.properties[idx:])\n\tthis.properties[idx] = &ActivityStreamsImagePropertyIterator{\n\t\tactivitystreamsMentionMember: v,\n\t\talias: this.alias,\n\t\tmyIdx: idx,\n\t\tparent: this,\n\t}\n\tfor i := idx; i < this.Len(); i++ {\n\t\t(this.properties)[i].myIdx = i\n\t}\n}", "func (tv *TextView) InsertAtCursor(txt []byte) {\n\twupdt := tv.TopUpdateStart()\n\tdefer tv.TopUpdateEnd(wupdt)\n\tif tv.HasSelection() {\n\t\ttbe := tv.DeleteSelection()\n\t\ttv.CursorPos = tbe.AdjustPos(tv.CursorPos, AdjustPosDelStart) // move to start if in reg\n\t}\n\ttbe := tv.Buf.InsertText(tv.CursorPos, txt, true, true)\n\tif tbe == nil {\n\t\treturn\n\t}\n\tpos := tbe.Reg.End\n\tif len(txt) == 1 && txt[0] == '\\n' {\n\t\tpos.Ch = 0 // sometimes it doesn't go to the start..\n\t}\n\ttv.SetCursorShow(pos)\n\ttv.SetCursorCol(tv.CursorPos)\n}", "func (blink *Blink) Insert(keys ...Key) Keys {\n\tif len(keys) > numberOfItemsBeforeMultithread {\n\t\treturn blink.multithreadedInsert(keys)\n\t}\n\toverwritten := make(Keys, 0, len(keys))\n\tstack := make(nodes, 0, blink.Ary)\n\tfor _, k := range keys {\n\t\toverwritten = append(overwritten, blink.insert(k, &stack))\n\t\tstack.reset()\n\t}\n\n\treturn overwritten\n}", "func (s *SliceInt) Insert(index, value int) *SliceInt {\n\t// Grow the slice by one element.\n\ts.data = s.data[0 : len(s.data)+1]\n\t// Use copy to move the upper part of the slice out of the way and open a hole.\n\tcopy(s.data[index+1:], s.data[index:])\n\t// Store the new value.\n\ts.data[index] = value\n\t// Return the result.\n\treturn s\n}", "func (this *Selection) InsertBefore(futureNextSib *Selection) *Selection {\n\tparent := futureNextSib.Node().Parent // TODO: this is a nilref bug, come up with a better way of finding the parent\n\tfor _, n := range this.Nodes {\n\t\tif futureNextSib == nil || len(futureNextSib.Nodes) == 0 {\n\t\t\tparent.AppendChild(n)\n\t\t} else {\n\t\t\tparent.InsertBefore(n, futureNextSib.Node())\n\t\t}\n\t}\n\treturn this\n}", "func (store Storage) BeginWithStartTS(startTS uint64) (kv.Transaction, error) {\n\treturn Transaction{}, nil\n}", "func (ll *LinkedList) InsertAt(t Item, pos int) error {\n\tll.lock.RLock()\n\tdefer ll.lock.RUnlock()\n\n\tif ll.head == nil || pos < 0 || ll.count < pos {\n\t\treturn fmt.Errorf(\"Index out of bounds\")\n\t}\n\n\tnewNode := Node{t, nil}\n\tcurrent := ll.head\n\tindex := 0\n\n\tif pos == 0 {\n\t\tnewNode.next = ll.head\n\t\tll.head = &newNode\n\t\tll.count++\n\t\treturn nil\n\t}\n\n\tfor index < pos-2 {\n\t\tindex++\n\t\tcurrent = current.next\n\t}\n\n\tnewNode.next = current.next\n\tcurrent.next = &newNode\n\tll.count++\n\treturn nil\n}", "func (li *List) InsertAt(pos int, item IPanel) *ListItem {\n\n\tlitem := newListItem(li, item)\n\tli.ItemScroller.InsertAt(pos, litem)\n\tlitem.Panel.Subscribe(OnMouseDown, litem.onMouse)\n\tlitem.Panel.Subscribe(OnCursorEnter, litem.onCursor)\n\treturn litem\n}", "func OrderInsert(s []uint64, target uint64) []uint64 {\n\treturn BinaryInsert(s, 0, len(s)-1, target)\n}", "func (v *Int32Vec) Insert(idx int, val ...int32) {\n\tdv := *v\n\tdv = append(dv, val...)\n\tcopy(dv[idx+len(val):], dv[idx:])\n\tcopy(dv[idx:], val)\n\t*v = dv\n}", "func (ll *Doubly[T]) AddAtBeg(val T) {\n\tll.lazyInit()\n\tll.insertValue(val, ll.Head)\n}", "func (l *littr) Insert(s string, i int) {\n\tl.code = l.code[:i] + s + l.code[i:]\n}", "func (node *LinkList) InsertAtPos(data, pos int) {\n\tif node == nil {\n\t\tfmt.Println(\"list is empty\")\n\t\treturn\n\t}\n\tnewNode := new(LinkList)\n\tnewNode.data = data\n\tnewNode.next = nil\n\tcount := 1\n\ttemp := node\n\tfor temp.next != nil && count < pos {\n\t\ttemp = temp.next\n\t\tcount++\n\t}\n\tif count < pos {\n\t\tfmt.Println(\"Not enough element present in the list\")\n\t\treturn\n\t}\n\tnewNode.next = temp.next\n\ttemp.next = newNode\n}", "func prepend(a []int, b int) []int {\n\ta = append(a, 0)\n\tcopy(a[1:], a)\n\ta[0] = b\n\treturn a\n}", "func (l *List) Prepend(val interface{}) *List {\n\treturn &List{\n\t\tnext: l,\n\t\tval: val,\n\t}\n}", "func (b *Skiplist) Insert(searchKey interface{}, value interface{}) {\n\tupdateList := make([]*Skipnode, b.MaxLevel)\n\tcurrentNode := b.Header\n\n\t//Quick search in forward list\n\tfor i := b.Header.Level - 1; i >= 0; i-- {\n\t\tfor currentNode.Forward[i] != nil && currentNode.Forward[i].compare(b.Comparator,searchKey) < 0 {\n\t\t\tcurrentNode = currentNode.Forward[i]\n\t\t}\n\t\tupdateList[i] = currentNode\n\t}\n\n\t//Step to next node. (which is the target insert location)\n\tcurrentNode = currentNode.Forward[0]\n\n\tif currentNode != nil && currentNode.compare(b.Comparator,searchKey) == 0 {\n\t\tcurrentNode.Val = value\n\t} else {\n\t\tnewLevel := b.RandomLevel()\n\t\tif newLevel > b.Level {\n\t\t\tfor i := b.Level + 1; i <= newLevel; i++ {\n\t\t\t\tupdateList[i-1] = b.Header\n\t\t\t}\n\t\t\tb.Level = newLevel //This is not mention in cookbook pseudo code\n\t\t\tb.Header.Level = newLevel\n\t\t}\n\n\t\tnewNode := NewNode(searchKey, value, newLevel, b.MaxLevel) //New node\n\t\tfor i := 0; i <= newLevel-1; i++ { //zero base\n\t\t\tnewNode.Forward[i] = updateList[i].Forward[i]\n\t\t}\n\t\t\n\t\t// XXXMFG: I need a write barrier (eg. Write-Cache-Flush) here badly!!!\n\t\t\n\t\tfor i := 0; i <= newLevel-1; i++ { //zero base\n\t\t\tupdateList[i].Forward[i] = newNode\n\t\t}\n\t\t\n\t\t// We assume, that\n\t\t//\tnewNode.Forward[i] = updateList[i].Forward[i]\n\t\t// is observable before\n\t\t//\tupdateList[i].Forward[i] = newNode\n\t\t//\n\t\t// If not, !BANG!\n\t}\n}", "func AppendBeginMarker(dst []byte) []byte {\n\treturn append(dst, byte(majorTypeMap|additionalTypeInfiniteCount))\n}", "func (sll *SingleLinkedList) Prepend(element interface{}) {\n\tsll.Insert(0, element)\n}", "func (o *ordering) patchForInsert() {\n\tfor i := 0; i < len(o.ordered)-1; {\n\t\te := o.ordered[i]\n\t\tlev := e.level\n\t\tn := e.next\n\t\tfor ; n != nil && len(n.elems) > 1; n = n.next {\n\t\t\tif n.level < lev {\n\t\t\t\tlev = n.level\n\t\t\t}\n\t\t\tn.skipRemove = true\n\t\t}\n\t\tfor ; o.ordered[i] != n; i++ {\n\t\t\to.ordered[i].level = lev\n\t\t\to.ordered[i].next = n\n\t\t\to.ordered[i+1].prev = e\n\t\t}\n\t}\n}", "func TestPrepend(t *T) {\n\t// Normal case\n\tintl := []interface{}{3, 2, 1, 0}\n\tl := NewList(intl...)\n\tnl := l.Prepend(4)\n\tassertSaneList(l, t)\n\tassertSaneList(nl, t)\n\tassert.Equal(t, intl, ToSlice(l))\n\tassert.Equal(t, []interface{}{4, 3, 2, 1, 0}, ToSlice(nl))\n\n\t// Degenerate case\n\tl = NewList()\n\tnl = l.Prepend(0)\n\tassert.Equal(t, 0, Size(l))\n\tassertSaneList(nl, t)\n\tassert.Equal(t, []interface{}{0}, ToSlice(nl))\n}", "func insert(a []int, index int, value int) []int {\r\n\tif len(a) == index { // nil or empty slice or after last element\r\n\t\treturn append(a, value)\r\n\t}\r\n\ta = append(a[:index+1], a[index:]...) // index < len(a)\r\n\ta[index] = value\r\n\treturn a\r\n}", "func (bids *Bids) insert(index int, Bid Bid) {\n\tif len(bids.ticks) == index { // nil or empty slice or after last element\n\t\tbids.ticks = append(bids.ticks, Bid)\n\t}\n\tbids.ticks = append(bids.ticks[:index+1], bids.ticks[index:]...) // index < len(a)\n\tbids.ticks[index] = Bid\n}", "func (o *KeyValueOrdered) Insert(key Key, idx int, value Value) {\n\to.Remove(key)\n\to.m[key] = idx\n\to.shift(idx, len(o.s), 1)\n\to.s = append(append(append(make([]KeyValueCapsule, 0, len(o.s)+1), o.s[:idx]...), KeyValueCapsule{key, value}), o.s[idx:]...)\n}", "func (p *IntVector) Insert(i int, x int)\t{ p.Vector.Insert(i, x) }", "func BinaryInsert(s []uint64, start, end int, target uint64) []uint64 {\n\t//log.Infof(\"s: %v start: %d, end: %d, target: %d\", s, start, end, target)\n\tif len(s) == 0 {\n\t\treturn append(s, target)\n\t}\n\tif target > s[end] {\n\t\treturn append(s, target)\n\t}\n\tif target < s[start] {\n\t\treturn append([]uint64{target}, s...)\n\t}\n\tif start >= end {\n\t\tlog.Errorf(\"Should not come here start: %d, end: %d, target: %d\", start, end, target)\n\t\treturn append(s, target)\n\t}\n\tif end == start+1 { //\n\t\treturn append(s[:end], append([]uint64{target}, s[end:]...)...)\n\t}\n\tm := (start + end) / 2\n\tif target < s[m] {\n\t\tend = m\n\t}\n\tif target > s[m] {\n\t\tstart = m\n\t}\n\treturn BinaryInsert(s, start, end, target)\n}", "func Insert(slice []int, index, value int) []int {\n\treturn append(slice[:index], append([]int{value}, slice[index:]...)...)\n}", "func (l *List) Insert(pos int, v interface{}) error {\n\tif pos == 0 {\n\t\tl.head = &Node{v, l.head}\n\t\treturn nil\n\t}\n\n\tp := l.head\n\ti := pos - 1\n\tfor i != 0 {\n\t\tif p.next == nil {\n\t\t\treturn fmt.Errorf(\"%v is not a valid position for a %v long list\", pos, pos-i)\n\t\t}\n\t\tp = p.next\n\t\ti--\n\t}\n\n\tp.next = &Node{v, p.next}\n\treturn nil\n}", "func (l *list) insert(i int, e string) {\n n := l.first\n\n // if the list is empty, e becomes the first item\n if n == nil {\n l.first = create(nil, nil, e)\n return\n }\n\n // does this go to the first index?\n if i <= 0 {\n m := create(nil, n, e)\n n.prev = m\n l.first = m\n return\n } \n\n // otherwise traverse to the correct position\n j := 1\n for n.next != nil && j < i {\n n = n.next\n j++\n }\n\n m := create(n, n.next, e)\n\n // add the element into the list and fix the links\n if (n.next != nil) {\n n.next.prev = m\n }\n\n n.next = m\n}", "func insertMetadata(data []byte, metadata []byte, n int) []byte {\n\tnumMetadata := int(math.Ceil(float64(len(data) / n)))\n\n\tbufSize := len(metadata)*numMetadata + len(data)\n\tbuf := make([]byte, bufSize)\n\n\tfor i, j := 0, 0; i < len(data); i = i + n {\n\t\tdataStart := i\n\t\tdataEnd := i + n\n\t\tif dataEnd >= len(data) {\n\t\t\tdataEnd = len(data)\n\t\t}\n\n\t\tbufStart := j * (len(metadata) + n)\n\t\tbufEnd := bufStart + (dataEnd - dataStart)\n\n\t\tcopy(buf[bufStart:bufEnd], data[dataStart:dataEnd])\n\t\tcopy(buf[bufEnd:], metadata)\n\n\t\tj++\n\t}\n\treturn buf\n}", "func (l *LinkedList) InsertAt(pos int, val interface{}) {\n\tn := &Node{value: val}\n\t// If the given position is lower than the list length\n\t// the element will be inserted at the end of the list\n\tswitch {\n\tcase l.length < pos:\n\t\tl.Insert(val)\n\tcase pos == 1:\n\t\tn.SetNext(l.head)\n\t\tl.head = n\n\tdefault:\n\t\tnode := l.head\n\t\t// Position - 2 since we want the element replacing the given position\n\t\tfor i := 1; i < (pos - 1); i++ {\n\t\t\tnode = node.Next()\n\t\t}\n\t\tn.SetNext(node.Next())\n\t\tnode.SetNext(n)\n\t}\n\n\tl.length = l.length + 1\n}", "func InsertIntsAt(x []int, y []int, index int) ([]int, error) {\n\tif index < 0 || index > len(x) {\n\t\treturn x, fmt.Errorf(\"out of bound\")\n\t}\n\treturn append(x[:index], append(y, x[index:]...)...), nil\n}", "func (s *WidgetBase) Insert(i int, w Widget) {\n\tif len(s.children) < i || i < 0 {\n\t\treturn\n\t}\n\n\ts.children = append(s.children, nil)\n\tcopy(s.children[i+1:], s.children[i:])\n\ts.children[i] = w\n\tw.SetParent(s)\n}", "func (rs *Ranges) Insert(r Range) {\n\tif r.IsEmpty() {\n\t\treturn\n\t}\n\tranges := *rs\n\tif len(ranges) == 0 {\n\t\tranges = append(ranges, r)\n\t\t*rs = ranges\n\t\treturn\n\t}\n\ti := ranges.search(r)\n\tif i == len(ranges) || !merge(&r, &ranges[i]) {\n\t\t// insert into the range\n\t\tranges = append(ranges, Range{})\n\t\tcopy(ranges[i+1:], ranges[i:])\n\t\tranges[i] = r\n\t\t*rs = ranges\n\t}\n\trs.coalesce(i)\n}" ]
[ "0.7017136", "0.58420914", "0.5738992", "0.5642923", "0.56324965", "0.5616734", "0.5611215", "0.55662197", "0.55369467", "0.54622537", "0.5455527", "0.54492414", "0.54408133", "0.54373574", "0.54122126", "0.5382448", "0.5360022", "0.53573275", "0.5343377", "0.53135765", "0.5304861", "0.5288978", "0.5280615", "0.52695096", "0.5247557", "0.5235641", "0.5214418", "0.5212796", "0.5204536", "0.5187745", "0.5180409", "0.51796687", "0.51679623", "0.5141536", "0.5132705", "0.5127549", "0.5125029", "0.51063216", "0.51024765", "0.50696564", "0.5061732", "0.5051662", "0.5036939", "0.5036697", "0.50148696", "0.50077736", "0.49923134", "0.49914977", "0.4990291", "0.49882028", "0.49882022", "0.49790213", "0.4976846", "0.49745238", "0.49616206", "0.49615562", "0.49601758", "0.49582255", "0.49580127", "0.49559432", "0.49526128", "0.49279678", "0.49249974", "0.49241185", "0.49131364", "0.49058565", "0.48951304", "0.48862493", "0.48842427", "0.48812875", "0.48765782", "0.48764583", "0.4873155", "0.48702458", "0.48627156", "0.48505324", "0.4848574", "0.48453507", "0.48424965", "0.48410666", "0.48337436", "0.48280025", "0.48116136", "0.48071483", "0.48056167", "0.47946286", "0.47936672", "0.47936562", "0.47917843", "0.4789763", "0.4787649", "0.47749826", "0.47696096", "0.47660035", "0.47507846", "0.47504216", "0.4745792", "0.47388777", "0.4727038", "0.47262546" ]
0.80089074
0
Appends all elements from other tuple to this
func (this *Tuple) Append(other *Tuple) { this.AppendItems(other.data...) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *Tuple) AppendItems(items ...interface{}) {\n\tthis.data = append(this.data, items...)\n}", "func Add(t, other Tuplelike) Tuplelike {\n\tresult := []float64{}\n\n\tfor idx, value := range t.Values() {\n\t\tresult = append(result, value+other.At(idx))\n\t}\n\n\treturn Tuple(result)\n}", "func (b *AppendOnlyBufferedBatch) AppendTuples(batch coldata.Batch, startIdx, endIdx int) {\n\tfor _, colIdx := range b.colsToStore {\n\t\tb.colVecs[colIdx].Append(\n\t\t\tcoldata.SliceArgs{\n\t\t\t\tSrc: batch.ColVec(colIdx),\n\t\t\t\tSel: batch.Selection(),\n\t\t\t\tDestIdx: b.length,\n\t\t\t\tSrcStartIdx: startIdx,\n\t\t\t\tSrcEndIdx: endIdx,\n\t\t\t},\n\t\t)\n\t}\n\tb.length += endIdx - startIdx\n}", "func append(first *[]interface{}, second *[]interface{}){\n for _, val := range(second){\n first.\n }\n}", "func (bs *BitStream) Append(other BitStream) {\n\tbs.bits = append(bs.bits, other.bits...)\n}", "func (n *Nodes) Append(a ...*Node)", "func (this *Tuple) Insert(start int, other *Tuple) {\n\tthis.InsertItems(start, other.data...)\n}", "func (t *Tuple) Add(o *Tuple) *Tuple {\n\treturn &Tuple{\n\t\tt.x + o.x,\n\t\tt.y + o.y,\n\t\tt.z + o.z,\n\t\tt.w + o.w,\n\t}\n}", "func (r *Result) Append(other Result) {\n\tr.UncheckedErrors = append(r.UncheckedErrors, other.UncheckedErrors...)\n}", "func (i *Iter) Append(v ...uint64) {\n\ti.v = append(i.v, v...)\n}", "func ConcatAll[T any](items ...TryNextor[T]) TryNextor[T] {\n\treturn &join[T]{\n\t\tinner: FromSlice(items),\n\t\tcurrent: empty[T]{},\n\t}\n}", "func Append(v1 Vector, v2 Vector) Vector {\n\tbaseDim := v1.Size()\n\tv1.dim = baseDim + v2.Size()\n\tfor n, d := range v2.data {\n\t\tv1.Set(baseDim+n, d)\n\t}\n\n\treturn v1\n}", "func lvalJoin(a *LVal, b *LVal) *LVal {\n\tfor len(b.Cell) > 0 {\n\t\ta = lvalAdd(a, lvalPop(b, 0))\n\t}\n\n\treturn a\n}", "func (hat *HashedArrayTree) Append(values ...interface{}) error {\n\tnewSize := hat.size + len(values)\n\tif err := hat.resize(newSize); err != nil {\n\t\treturn err\n\t}\n\tfor i, j := hat.size, 0; i < newSize; i, j = i+1, j+1 {\n\t\tti, li := hat.topIndex(i), hat.leafIndex(i)\n\t\that.top[ti][li] = values[j]\n\t}\n\that.size = newSize\n\treturn nil\n}", "func (set Int64Set) Append(more ...int64) Int64Set {\n\tunionedSet := set.Clone()\n\tfor _, v := range more {\n\t\tunionedSet.doAdd(v)\n\t}\n\treturn unionedSet\n}", "func (t Tuple) Add(o Tuple) Tuple {\n\tif t.IsPoint() && o.IsPoint() {\n\t\tpanic(\"cannot add 2 point tuples\")\n\t}\n\treturn Tuple{t.X + o.X, t.Y + o.Y, t.Z + o.Z, t.W + o.W}\n}", "func (s *Set[T]) Add(elts ...T) {\n\ts.resize(2 * len(elts))\n\tfor _, elt := range elts {\n\t\t(*s)[elt] = struct{}{}\n\t}\n}", "func (s Sequence) Append(tok Token) Sequence {\n\tv := s.Clone()\n\tv.Tokens[len(s.Tokens)] = tok\n\treturn v\n}", "func (ts *tupleSet) add(tuple seed.Tuple) {\n\tif len(tuple) != ts.numberOfColumns {\n\t\tfatal(ts.collectionName, \"expected\", ts.numberOfColumns, \"columns for\", tuple)\n\t}\n\n\tkey, err := json.Marshal(tuple[:ts.keyEnds])\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tts.tuples[string(key)] = tuple\n}", "func (ts Uint64Uint64Tuples) Append1(k uint64, v uint64) Uint64Uint64Tuples {\n\treturn append(ts, Uint64Uint64Tuple{k, v})\n}", "func (ts Uint64Uint64Tuples) Append2(k1 uint64, v1 uint64, k2 uint64, v2 uint64) Uint64Uint64Tuples {\n\treturn append(ts, Uint64Uint64Tuple{k1, v1}, Uint64Uint64Tuple{k2, v2})\n}", "func (ar *ActiveRecord) Append(other *ActiveRecord) *ActiveRecord {\n\tar.Tokens = append(ar.Tokens, other.Tokens...)\n\tar.Args = append(ar.Args, other.Args...)\n\treturn ar\n}", "func (f *FacebookMessages) Append(addition ...*FacebookMessage) *FacebookMessages {\n\tfor _, a := range addition {\n\t\t*f = append(*f, *a)\n\t}\n\treturn f\n}", "func (il *IntList) JoinUnique(other *IntList) {\n // The algorithm here is stupid. Are there better ones?\n otherLast := other.Last()\n for otherIt := other.First(); otherIt != otherLast; otherIt = otherIt.Next() {\n contained := false\n value := otherIt.Value()\n last := il.Last()\n for it := il.First(); it != last; it = it.Next() {\n if it.Value() == value {\n contained = true\n break\n }\n }\n if !contained {\n il.Append(value)\n }\n }\n}", "func (ss SliceType) Append(elements ...ElementType) SliceType {\n\t// Copy ss, to make sure no memory is overlapping between input and\n\t// output. See issue #97.\n\tresult := append(SliceType{}, ss...)\n\n\tresult = append(result, elements...)\n\treturn result\n}", "func (r *Linear[T]) Append(x, y T) {\n\tr.ax = append(r.ax, x)\n\tr.ay = append(r.ay, y)\n}", "func Append(m []interface{}, args ...interface{}) []interface{} {\n\tfor _, v := range args {\n\t\tm = append(m, v)\n\t}\n\treturn m\n}", "func (this *Tuple) Copy() *Tuple {\n\tt := NewTuple(this.Len())\n\tcopy(t.data, this.data)\n\treturn t\n}", "func With[S ~[]E, E any](s1 S, s2 ...E) S {\n\tresult := make(S, len(s1)+len(s2))\n\tcopy(result, s1)\n\tcopy(result[len(s1):], s2)\n\treturn result\n}", "func (f *Fields) Append(s ...*Field)", "func (self Mset) Add (other Mset) Mset {\n\tfor iter, key, val := other.h.Iter(); key != nil; key, val = iter.Next() {\n\t\tk, v := self.h.Get(*key)\n\t\tif k == nil {\n\t\t\tself.h.Put(*key, (*val).(uint64))\n\t\t} else {\n\t\t\tself.h.Put(*key, (*v).(uint64) + (*val).(uint64))\n\t\t}\n\t}\n\tself.size += other.size\n\treturn self\n}", "func (e *rawData) AddElements(elements ...Element) Element { return e }", "func (array Array) Concat(others ...Array) Array {\n\tconcatenatedArray := array\n\tfor _, other := range others {\n\t\tconcatenatedArray = concatenatedArray.Push(other...)\n\t}\n\treturn concatenatedArray\n}", "func (t TagSet) Merge(more TagSet) TagSet {\n\tmerged := t[:]\n\treturn append(merged, more...)\n}", "func (r *Result) Append(other Result) {\n\tr.UnusedGetterError = append(r.UnusedGetterError, other.UnusedGetterError...)\n}", "func (ls LabelSet) AppendTo(target LabelSet) LabelSet {\n\tfor _, l := range ls {\n\t\tif !l.IsZero() {\n\t\t\ttarget = append(target, l)\n\t\t}\n\t}\n\treturn target\n}", "func (v *VectorImpl) Append(item ...Value) *VectorImpl {\n\tresult := v\n\titemLen := uint(len(item))\n\tfor insertOffset := uint(0); insertOffset < itemLen; {\n\t\ttailLen := result.len - result.tailOffset()\n\t\ttailFree := nodeSize - tailLen\n\t\tif tailFree == 0 {\n\t\t\tresult = result.pushLeafNode(result.tail)\n\t\t\tresult.tail = emptyVectorImpl.tail\n\t\t\ttailFree = nodeSize\n\t\t\ttailLen = 0\n\t\t}\n\n\t\tbatchLen := uintMin(itemLen-insertOffset, tailFree)\n\t\tnewTail := make([]Value, 0, tailLen+batchLen)\n\t\tnewTail = append(newTail, result.tail...)\n\t\tnewTail = append(newTail, item[insertOffset:insertOffset+batchLen]...)\n\t\tresult = &VectorImpl{root: result.root, tail: newTail, len: result.len + batchLen, shift: result.shift}\n\t\tinsertOffset += batchLen\n\t}\n\n\treturn result\n}", "func (r StringsSet) AddAll(other StringsSet) {\n\tfor s := range other {\n\t\tr[s] = struct{}{}\n\t}\n}", "func (t T) MergedWith(that T) T {\n\tout := make(T)\n\tfor k, v := range t {\n\t\tout[k] = v\n\t}\n\n\tfor k, v := range that {\n\t\tout[k] = v\n\t}\n\n\treturn out\n}", "func addedge(from *BasicBlock, to *BasicBlock) {\n\tif from == nil {\n\t\tFatal(\"addedge: from is nil\")\n\t}\n\tif to == nil {\n\t\tFatal(\"addedge: to is nil\")\n\t}\n\tfrom.succ = append(from.succ, to)\n\tto.pred = append(to.pred, from)\n}", "func (this *Selection) Append(newKids *Selection) *Selection {\n\tfor i, node := range this.Nodes {\n\t\tif i == 0 { // move the kid(s)\n\t\t\tfor _, kid := range newKids.Nodes {\n\t\t\t\tif kid.Parent != nil {\n\t\t\t\t\tkid.Parent.RemoveChild(kid)\n\t\t\t\t}\n\t\t\t\tnode.AppendChild(kid)\n\t\t\t}\n\t\t} else { // clone the kid(s)\n\t\t\tfor _, kid := range newKids.Nodes {\n\t\t\t\tnode.AppendChild(cloneNode(kid))\n\t\t\t}\n\t\t}\n\t}\n\treturn this\n}", "func (n *Nodes) AppendNodes(n2 *Nodes)", "func join(a, b Value) Value {\n\treturn Value{\n\t\tSize: a.Size + b.Size,\n\t\tNumber: a.Number + b.Number,\n\t}\n}", "func (a Attributes) AddAll(others Attributes) Attributes {\n\tif others == nil {\n\t\treturn a\n\t}\n\tif a == nil {\n\t\ta = Attributes{}\n\t}\n\tfor k, v := range others {\n\t\ta.Set(k, v)\n\t}\n\treturn a\n}", "func (s *SliceOfUint64) Concat(items []uint64) *SliceOfUint64 {\n\ts.items = append(s.items, items...)\n\treturn s\n}", "func (this *Tuple) InsertItems(start int, items ...interface{}) {\n\tstart = this.Offset(start)\n\trhs := this.Copy().data[start:]\n\tthis.data = append(this.data[:start], items...)\n\tthis.data = append(this.data, rhs...)\n}", "func (s *SliceOfInterface) Concat(items []interface{}) *SliceOfInterface {\n\ts.items = append(s.items, items...)\n\treturn s\n}", "func (t *Tags) AppendEach(dst []byte) []byte {\n\tt.Each(func(key uint32, val []byte) {\n\t\tdst = kbin.AppendUvarint(dst, key)\n\t\tdst = kbin.AppendUvarint(dst, uint32(len(val)))\n\t\tdst = append(dst, val...)\n\t})\n\treturn dst\n}", "func (this *Vector)PushBack(x ...interface{}){\n\tthis.init()\n\tfor _,tmp:=range x{\n\t\tthis.v=append(this.v,tmp)\n\t}\n}", "func (ma *MessageAccumulator) AddAll(other *MessageAccumulator) {\n\tif other.msgs == nil {\n\t\treturn\n\t}\n\tfor _, msg := range *other.msgs {\n\t\tma.Add(msg)\n\t}\n}", "func (s Set) Union(other Set) {\n\tfor k := range other {\n\t\ts.Insert(k)\n\t}\n}", "func (b *Bag) union(c Bag) Bag {\n\tbag := make(Bag)\n\tfor k, v := range *b {\n\t\tbag[k] += v\n\t}\n\tfor k, v := range c {\n\t\tbag[k] += v\n\t}\n\treturn bag\n}", "func (s strMap) AddAll(other StrMap) StrMap {\n\tnewMap := NewStrMap()\n\n\tfor k, v := range s.s {\n\t\tnewMap.innerMap()[k] = v\n\t}\n\n\tfor ok, ov := range other.innerMap() {\n\t\tnewMap.innerMap()[ok] = ov\n\t}\n\treturn newMap\n}", "func (a *Actions) concat(o *Actions) *Actions {\n\ta.Send = append(a.Send, o.Send...)\n\ta.Commits = append(a.Commits, o.Commits...)\n\ta.Hash = append(a.Hash, o.Hash...)\n\ta.WriteAhead = append(a.WriteAhead, o.WriteAhead...)\n\tif o.StateTransfer != nil {\n\t\tif a.StateTransfer != nil {\n\t\t\tpanic(\"attempted to concatenate two concurrent state transfer requests\")\n\t\t}\n\t\ta.StateTransfer = o.StateTransfer\n\t}\n\treturn a\n}", "func (l *AttributeList) Merge(other AttributeList) AttributeList {\n\tif l.Len() == 0 {\n\t\treturn other\n\t}\n\tif other.Len() == 0 {\n\t\treturn *l\n\t}\n\tl.last.Next = other.first\n\tl.last = other.last\n\tl.length += other.Len()\n\treturn *l\n}", "func (graph *CIOperatorStepGraph) MergeFrom(from ...CIOperatorStepDetails) {\n\tfor _, step := range from {\n\t\tvar found bool\n\t\tfor idx, existing := range *graph {\n\t\t\tif step.StepName != existing.StepName {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfound = true\n\t\t\t(*graph)[idx] = mergeSteps(existing, step)\n\t\t}\n\t\tif !found {\n\t\t\t*graph = append(*graph, step)\n\t\t}\n\t}\n\n}", "func (this *Tuple) Reverse() {\n\tfor i, j := 0, this.Len()-1; i < j; i, j = i+1, j-1 {\n\t\tthis.data[i], this.data[j] = this.data[j], this.data[i]\n\t}\n}", "func (ref Ref) Extend(other Ref) Ref {\n\tdst := make(Ref, len(ref)+len(other))\n\tcopy(dst, ref)\n\n\thead := other[0].Copy()\n\thead.Value = String(head.Value.(Var))\n\toffset := len(ref)\n\tdst[offset] = head\n\n\tcopy(dst[offset+1:], other[1:])\n\treturn dst\n}", "func (l *SliceList[T]) Append(v ...T) {\n\t*l = append((*l), v...)\n}", "func (ta TableAliases) putAll(other TableAliases) {\n\tfor alias, target := range other {\n\t\tta[alias] = target\n\t}\n}", "func (a *ArrayObject) concatenateCopies(t *thread, n *IntegerObject) Object {\n\taLen := len(a.Elements)\n\tresult := make([]Object, 0, aLen*n.value)\n\n\tfor i := 0; i < n.value; i++ {\n\t\tresult = append(result, a.Elements...)\n\t}\n\n\treturn t.vm.initArrayObject(result)\n}", "func (v ExtraValues) AppendTo(body *form.Values, keyParts []string) {\n\tfor k, vs := range v.Values {\n\t\tfor _, v := range vs {\n\t\t\tbody.Add(form.FormatKey(append(keyParts, k)), v)\n\t\t}\n\t}\n}", "func Append[V any](t *T, v Var[V], x ...interface{}) {\n\trv := reflect.ValueOf(v.Get(t))\n\tvar rx []reflect.Value\n\tfor _, e := range x {\n\t\trx = append(rx, reflect.ValueOf(e))\n\t}\n\tv.Set(t, reflect.Append(rv, rx...).Interface().(V))\n}", "func (vector *Vector) Extend(j int) {\n\t*vector = append(*vector, make([]interface{}, j)...)\n}", "func (s *SliceOfUint) Concat(items []uint) *SliceOfUint {\n\ts.items = append(s.items, items...)\n\treturn s\n}", "func (p *Packed2DGenericTypeBuilder) Append(x GenericType) {\n\tif p.autoGrow && p.tail >= len(p.buf) {\n\t\tp.Grow(1)\n\t}\n\tp.buf[p.tail] = x\n\tp.tail++\n}", "func (el *Elements) Append(d Elements) {\n\tswitch el.Type {\n\tcase part3.Int32:\n\t\tel.I32 = append(el.I32, d.I32...)\n\tcase part3.Float32:\n\t\tel.F32 = append(el.F32, d.F32...)\n\tcase part3.Float64:\n\t\tel.F64 = append(el.F64, d.F64...)\n\t}\n}", "func (b *Bag) Merge(from *Bag) {\n\tb.Add(from.Items()...)\n}", "func (list *List) Append(values ...interface{}) {\n\tlist.Add(values...)\n}", "func (e *Elog) extend() {\n\t// Slightly too clever code: Double the slice if we're out,\n\t// adding the reservation for the new eo\n\tif cap((*e).Log) == len((*e).Log) {\n\t\tt := make([]ElogOperation, len((*e).Log), (cap((*e).Log)+1)*2)\n\t\tcopy(t, (*e).Log)\n\t\t(*e).Log = t\n\t}\n\t(*e).Log = (*e).Log[:len((*e).Log)+1]\n}", "func (s *internalPointBufferView) Append(\n\tslice PointBuffer,\n\telemsToAppend ...Point,\n) (PointBuffer, error) {\n\n\ttarget, allocErr := s.growIfNecessary(slice, len(elemsToAppend))\n\tif allocErr != nil {\n\t\treturn PointBuffer{}, allocErr\n\t}\n\ttarget.len = slice.len + len(elemsToAppend)\n\tresult := s.ToRef(target)\n\tcopy(result[slice.len:], elemsToAppend)\n\treturn target, nil\n}", "func (list *ArrayList) AddAll(e *ArrayList) {\n\tif list.checkDataType(e.elements[0]) == nil {\n\t\tlist.elements = append(list.elements, e.elements...)\n\t\tlist.size = len(list.elements)\n\t\tlist.cap = cap(list.elements)\n\t}\n}", "func (ns Slice) extend(a Slice) Slice {\n\tnn := make(Slice, ns.Len()+a.Len())\n\tcopy(nn, ns)\n\tcopy(nn[ns.Len():], a)\n\treturn nn.uniq()\n}", "func (q Query) Concat(q2 Query) Query {\n\treturn q.UnionAll(q2)\n}", "func (hat *HashedArrayTree) Prepend(values ...interface{}) error {\n\tlenValues := len(values)\n\tnewSize := hat.size + lenValues\n\tif err := hat.resize(newSize); err != nil {\n\t\treturn err\n\t}\n\t// Move items in the buffer by the length of values\n\tfor i := hat.size - 1; i >= 0; i-- {\n\t\tbti, bli := hat.topIndex(i), hat.leafIndex(i)\n\t\tati, ali := hat.topIndex(i+lenValues), hat.leafIndex(i+lenValues)\n\t\that.top[ati][ali] = hat.top[bti][bli]\n\t}\n\tfor i := 0; i < lenValues; i++ {\n\t\tti, li := hat.topIndex(i), hat.leafIndex(i)\n\t\that.top[ti][li] = values[i]\n\t}\n\that.size = newSize\n\treturn nil\n}", "func (s1 Sequence) Append(s2 Sequence) Sequence {\n\tif s1.IsConcurrent() {return s1.CAppend(s2)}\n\treturn s1.SAppend(s2)\n}", "func (j *jointRequest) merge(from *jointRequest) {\n\tfor _, tile := range from.tiles {\n\t\tj.tiles = append(j.tiles, tile)\n\t}\n}", "func main() {\n\n\ta := []int{1,2,3,4,5}\n\tb := []int{6,7,8,9,10}\n\n\ta = append(a, b...)\n\tfmt.Println(a)\n\n\tc := make([]int, 10, 20)\n\tcopy(c, a)\n\tc = append(c, 50,60,70)\n\tfmt.Println(c)\n\n\td := append([]int(nil), a...)\n\tfmt.Println(d)\n\n\td = append(c[:2], c[6:]...)\n\tfmt.Println(d)\n\n\n\n\n\n}", "func (s *SliceOfFloat64) Concat(items []float64) *SliceOfFloat64 {\n\ts.items = append(s.items, items...)\n\treturn s\n}", "func (peers Peers) Append(p ...string) Peers {\n\tpeers = append(peers, p...)\n\n\treturn peers.Unique()\n}", "func (v Vec) AddBy(other Vec) Vec {\n\tassertSameLen(v, other)\n\tfor i, val := range other {\n\t\tv[i] += val\n\t}\n\treturn v\n}", "func (rs *Repos) Concat(others ...Repos) {\n\tfor _, o := range others {\n\t\t*rs = append(*rs, o...)\n\t}\n}", "func f () {\r\n\tvar a1 []int\r\n\r\n\ta1 = append(a1, 2)\r\n\r\n\ta2, _ := append(a1, 1), append (a1, 3)\r\n}", "func (x *Any) Append(key string, value any) {\n\tx.makeNotNil()\n\n\tif original, ok := (*x)[key]; ok {\n\n\t\tif list, ok := original.([]any); ok {\n\t\t\t(*x)[key] = append(list, value)\n\t\t\treturn\n\t\t}\n\n\t\t(*x)[key] = []any{original, value}\n\t\treturn\n\t}\n\n\t(*x)[key] = []any{value}\n}", "func (s *Uint64) Union(other Uint64) Uint64 {\n\tres := NewUint64WithSize(s.Size() + other.Size())\n\n\tfor val := range s.m {\n\t\tres.Add(val)\n\t}\n\tfor val := range other.m {\n\t\tres.Add(val)\n\t}\n\treturn res\n}", "func (m *Matrix) AddToAll(v int64) {\n\tfor x := 0; x < m.W(); x++ {\n\t\tfor y := 0; y < m.H(); y++ {\n\t\t\tm.Add(x, y, v)\n\t\t}\n\t}\n}", "func addArr(a, b []interface{}) []interface{} {\n\treturn append(a, b...)\n}", "func (m *Matrix) Append(i, j int, v float64) {\n\tif i < 0 || m.r <= i {\n\t\tpanic(\"triplet: row index out of range\")\n\t}\n\tif j < 0 || m.c <= j {\n\t\tpanic(\"triplet: column index out of range\")\n\t}\n\tif v == 0 {\n\t\treturn\n\t}\n\tm.data = append(m.data, triplet{i, j, v})\n}", "func (p *Pair) Append(key string, val interface{}) *Pair {\n\treturn &Pair{\n\t\tprev: p,\n\t\tkey: key,\n\t\tvalue: val,\n\t}\n}", "func encodeTuple(t *tree.DTuple, appendTo []byte, colID uint32, scratch []byte) ([]byte, error) {\n\tappendTo = encoding.EncodeValueTag(appendTo, colID, encoding.Tuple)\n\tappendTo = encoding.EncodeNonsortingUvarint(appendTo, uint64(len(t.D)))\n\n\tvar err error\n\tfor _, dd := range t.D {\n\t\tappendTo, err = EncodeTableValue(appendTo, descpb.ColumnID(encoding.NoColumnID), dd, scratch)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn appendTo, nil\n}", "func (s *IntSet) UnionWith(t *IntSet) {\n\tfor i, tword := range t.words {\n\t\tif i < len(s.words) {\n\t\t\ts.words[i] |= tword\n\t\t} else {\n\t\t\ts.words = append(s.words, tword)\n\t\t}\n\t}\n}", "func (s *IntSet) UnionWith(t *IntSet) {\n\tfor i, tword := range t.words {\n\t\tif i < len(s.words) {\n\t\t\ts.words[i] |= tword\n\t\t} else {\n\t\t\ts.words = append(s.words, tword)\n\t\t}\n\t}\n}", "func (s *IntSet) UnionWith(t *IntSet) {\n\tfor i, tword := range t.words {\n\t\tif i < len(s.words) {\n\t\t\ts.words[i] |= tword\n\t\t} else {\n\t\t\ts.words = append(s.words, tword)\n\t\t}\n\t}\n}", "func (arr *Array) Append(v *Term) *Array {\n\tcpy := *arr\n\tcpy.elems = append(arr.elems, v)\n\tcpy.hashs = append(arr.hashs, v.Value.Hash())\n\tcpy.hash = arr.hash + v.Value.Hash()\n\tcpy.ground = arr.ground && v.IsGround()\n\treturn &cpy\n}", "func (s Stream) Append(it Iterator) Stream {\n\tif mr, ok := s.it.(multiIterator); ok {\n\t\tmr.iterators = append(mr.iterators, it)\n\t\ts.it = mr\n\t} else {\n\t\ts.it = multiIterator{\n\t\t\titerators: []Iterator{s, it},\n\t\t}\n\t}\n\n\treturn s\n}", "func Add(out1 *LooseFieldElement, arg1 *TightFieldElement, arg2 *TightFieldElement) {\n\tx1 := (arg1[0] + arg2[0])\n\tx2 := (arg1[1] + arg2[1])\n\tx3 := (arg1[2] + arg2[2])\n\tout1[0] = x1\n\tout1[1] = x2\n\tout1[2] = x3\n}", "func (ss MultiRenderer) Append(elements ...Renderer) MultiRenderer {\n\t// Copy ss, to make sure no memory is overlapping between input and\n\t// output. See issue #97.\n\tresult := append(MultiRenderer{}, ss...)\n\n\tresult = append(result, elements...)\n\treturn result\n}", "func (list *DoublyLinkedList) Append(values ...interface{}) {\n\tlist.Add(values...)\n}", "func (l *List) Append(values ...interface{}) {\n\tfor _, v := range values {\n\t\tif l.head == nil {\n\t\t\tl.head = &Node{v, nil}\n\t\t\tcontinue\n\t\t}\n\t\tp := l.head\n\t\tfor p.next != nil {\n\t\t\tp = p.next\n\t\t}\n\t\tp.next = &Node{v, nil}\n\t}\n}", "func Add(out1 *LooseFieldElement, arg1 *TightFieldElement, arg2 *TightFieldElement) {\n\tx1 := (arg1[0] + arg2[0])\n\tx2 := (arg1[1] + arg2[1])\n\tx3 := (arg1[2] + arg2[2])\n\tx4 := (arg1[3] + arg2[3])\n\tx5 := (arg1[4] + arg2[4])\n\tout1[0] = x1\n\tout1[1] = x2\n\tout1[2] = x3\n\tout1[3] = x4\n\tout1[4] = x5\n}" ]
[ "0.63661397", "0.58355916", "0.56410396", "0.54085696", "0.5406405", "0.53868324", "0.53644", "0.53264797", "0.53212005", "0.53112465", "0.5262726", "0.52600545", "0.52031255", "0.5199285", "0.5136459", "0.51320195", "0.51014876", "0.5095561", "0.50813615", "0.5061924", "0.5060194", "0.5024492", "0.5010495", "0.49617168", "0.49466747", "0.49461553", "0.49399823", "0.49347004", "0.49340218", "0.49301472", "0.49255395", "0.49046034", "0.48873594", "0.48746195", "0.4849042", "0.48262748", "0.4813813", "0.48095423", "0.4780849", "0.47597158", "0.47589105", "0.47555026", "0.47414017", "0.47379932", "0.4726175", "0.47219962", "0.4718618", "0.47110736", "0.4703064", "0.46990532", "0.4685188", "0.46752116", "0.46722272", "0.46705234", "0.46558553", "0.46372452", "0.46370405", "0.4636523", "0.4615991", "0.46136954", "0.46061084", "0.46018755", "0.4598399", "0.45970777", "0.4572447", "0.45710763", "0.45622754", "0.45537233", "0.4550788", "0.45351693", "0.4532296", "0.4526442", "0.45250478", "0.452177", "0.4520288", "0.4498768", "0.44943807", "0.44929212", "0.44856858", "0.44802615", "0.44728908", "0.44722345", "0.44699925", "0.44680607", "0.44677895", "0.4467439", "0.44653136", "0.44637066", "0.4462142", "0.44601703", "0.44576022", "0.44576022", "0.44576022", "0.4456485", "0.4452", "0.44498625", "0.44424114", "0.4442163", "0.4434577", "0.44286522" ]
0.74295527
0
Appends one or more items to end of data
func (this *Tuple) AppendItems(items ...interface{}) { this.data = append(this.data, items...) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Repository) append(slice []models.Command, items ...models.Command) []models.Command {\n\tfor _, item := range items {\n\t\tslice = r.extend(slice, item)\n\t}\n\treturn slice\n}", "func (arr *ArrayList) Append(item ItemType) {\n if arr.length == arr.capacity {\n arr.resize(arr.capacity * 2)\n }\n arr.data[arr.length] = item\n arr.length++\n}", "func (resp *LongviewClientsPagedResponse) appendData(r *LongviewClientsPagedResponse) {\n\tresp.Data = append(resp.Data, r.Data...)\n}", "func (hrp *HttpRequestParser) Append(data *[]byte) {\n\thrp.payload = append(hrp.payload, (*data)...)\n}", "func (resp *DomainRecordsPagedResponse) appendData(r *DomainRecordsPagedResponse) {\n\tresp.Data = append(resp.Data, r.Data...)\n}", "func (b *Builder) append(data []byte) {\n\tdst := b.allocate(len(data))\n\tutils.AssertTrue(len(data) == copy(dst, data))\n\n\t/*\n\t\tif b.currentBlock == nil {\n\t\t\tb.currentBlock = &pb.Block{\n\t\t\t\tData: make([]byte, 64*KB),\n\t\t\t\t//BlockLength: uint32(size),\n\t\t\t}\n\t\t\tb.blocks = append(b.blocks, b.currentBlock)\n\t\t}\n\t\t// Ensure we have enough spa\t to store new data.\n\t\tif uint32(len(b.currentBlock.Data)) < b.sz+uint32(len(data)) {\n\t\t\tblockGrow(b.currentBlock, uint32(len(data)))\n\t\t}\n\n\t\tcopy(b.currentBlock.Data[b.sz:], data)\n\t\tb.sz += uint32(len(data))\n\t*/\n}", "func (list *List) Append(item string) {\n\tlist.data = append(list.data, item)\n}", "func (lf *ListFile) Append(items ...string) error {\n\tif lf.IsClosed() {\n\t\treturn errors.New(\"file is already closed\")\n\t}\n\n\tlf.mu.Lock()\n\tdefer lf.mu.Unlock()\n\n\t{\n\t\t// Gather all lines into a buffer:\n\t\tbuf := new(bytes.Buffer)\n\t\tfor _, item := range items {\n\t\t\t_, err := buf.WriteString(item + \"\\n\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\t// Write the buffer to the file (in one file write):\n\t\t_, err := lf.file.Write(buf.Bytes())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor _, item := range items {\n\t\tif lf.mainIndex != nil {\n\t\t\t// add to tree to be able then to search it:\n\t\t\tlf.mainIndex.Add(item)\n\t\t}\n\t\t// add to all indexes:\n\t\tfor _, index := range lf.secondaryIndexes {\n\t\t\tindex.backfillFunc([]byte(item))\n\t\t}\n\t}\n\treturn nil\n}", "func (a *Alfred) Append(item *Item) {\n\ta.Items = append(a.Items, *item)\n}", "func (resp *IPAddressesPagedResponse) appendData(r *IPAddressesPagedResponse) {\n\tresp.Data = append(resp.Data, r.Data...)\n}", "func (s *Sorter) Append(data []byte) error {\n\tif sz := s.buf.Len(); sz > 0 && sz+len(data) > s.opt.MaxMemBuffer {\n\t\tif err := s.flush(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ts.buf.Append(data)\n\treturn nil\n}", "func (b *Builder) append(data []byte) {\n\tdst := b.allocate(len(data))\n\ty.AssertTrue(len(data) == copy(dst, data))\n}", "func (a *Array) Append(data int) {\n\ta.data = append(a.data, data)\n\ta.length++\n}", "func (b *Buffer) Add(series ...*influxdb.Series) {\n\tif b.capacity == 0 {\n\t\tb.fn(series)\n\t\treturn\n\t}\n\n\tfor _, item := range series {\n\t\tb.in <- item\n\t}\n}", "func (out *OutBuffer) Append(p ...byte) {\n\tout.Data = append(out.Data, p...)\n}", "func (list *CopyOnWriteList) AddLast(items ... interface{}) {\n\titemsLen := len(items)\n\tif itemsLen == 0 {\n\t\treturn\n\t}\n\tfor {\n\t\toldList := *(*[]interface{})(atomic.LoadPointer(&list.innerList))\n\t\toldLen := len(oldList)\n\t\tnewLen := oldLen + itemsLen\n\t\tnewList := make([]interface{}, newLen, newLen)\n\t\t// the new item is at the first\n\t\tcopy(newList, oldList)\n\t\tcopy(newList[oldLen:], items)\n\t\tnewListPtr := unsafe.Pointer(&newList)\n\t\tif atomic.CompareAndSwapPointer(&list.innerList, list.innerList, newListPtr) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (ab *AutoflushBuffer) AddMany(objs ...interface{}) {\n\tab.Lock()\n\tdefer ab.Unlock()\n\n\tfor _, obj := range objs {\n\t\tab.Contents.Enqueue(obj)\n\t\tif ab.Contents.Len() >= ab.MaxLen {\n\t\t\tab.flushUnsafeAsync(ab.Background(), ab.Contents.Drain())\n\t\t}\n\t}\n}", "func (b *eventBuffer) Append(events *structs.Events) {\n\tb.appendItem(newBufferItem(events))\n}", "func (l *List) Prepend(items ...Item) (err error) {\n\tl.value = append(items, l.value...)\n\treturn nil\n}", "func (ud *udoc) appendItem(taskid, value string) {\n\ttask := udata{ID: taskid,\n\t\tRel: []string{\"item\"},\n\t\tName: \"tasks\",\n\t\tData: []udata{\n\t\t\tudata{Rel: []string{\"complete\"}, URL: \"/tasks/complete/\", Model: fmt.Sprintf(\"id=%s\", taskid), Action: \"append\"},\n\t\t\tudata{Name: \"text\", Value: value}}}\n\n\tud.Uber.Data[1].Data = append(ud.Uber.Data[1].Data, task)\n}", "func (l *List) Append(items ...Item) (err error) {\n\tl.value = append(l.value, items...)\n\treturn nil\n}", "func (s *SliceOfFloat64) Append(item float64) *SliceOfFloat64 {\n\ts.items = append(s.items, item)\n\treturn s\n}", "func (l *Service) Append(bytes []byte) ([]byte, error) {\n\trequest := &AppendRequest{}\n\tif err := proto.Unmarshal(bytes, request); err != nil {\n\t\treturn nil, err\n\t}\n\n\tindex := len(l.values)\n\tl.values = append(l.values, request.Value)\n\n\tl.sendEvent(&ListenResponse{\n\t\tType: ListenResponse_ADDED,\n\t\tIndex: uint32(index),\n\t\tValue: request.Value,\n\t})\n\n\treturn proto.Marshal(&AppendResponse{\n\t\tStatus: ResponseStatus_OK,\n\t})\n}", "func Append(exchange string, p currency.Pair, a asset.Item, price, volume float64) {\n\tif AlreadyExists(exchange, p, a, price, volume) {\n\t\treturn\n\t}\n\n\ti := Item{\n\t\tExchange: exchange,\n\t\tPair: p,\n\t\tAssetType: a,\n\t\tPrice: price,\n\t\tVolume: volume,\n\t}\n\n\tItems = append(Items, i)\n}", "func (list *WhoWasList) Append(whowas WhoWas) {\n\tlist.accessMutex.Lock()\n\tdefer list.accessMutex.Unlock()\n\n\tif len(list.buffer) == 0 {\n\t\treturn\n\t}\n\n\tvar pos int\n\tif list.start == -1 { // empty\n\t\tpos = 0\n\t\tlist.start = 0\n\t\tlist.end = 1\n\t} else if list.start != list.end { // partially full\n\t\tpos = list.end\n\t\tlist.end = (list.end + 1) % len(list.buffer)\n\t} else if list.start == list.end { // full\n\t\tpos = list.end\n\t\tlist.end = (list.end + 1) % len(list.buffer)\n\t\tlist.start = list.end // advance start as well, overwriting first entry\n\t}\n\n\tlist.buffer[pos] = whowas\n}", "func (c *CurlCommand) append(newSlice ...string) {\n\t*c = append(*c, newSlice...)\n}", "func (l *List) Append(d sh.QData) {\n\tl.append(d)\n}", "func (s *SliceOfInterface) Append(item interface{}) *SliceOfInterface {\n\ts.items = append(s.items, item)\n\treturn s\n}", "func (s *SliceOfUint64) Append(item uint64) *SliceOfUint64 {\n\ts.items = append(s.items, item)\n\treturn s\n}", "func (p *Packet) append(typ byte, b []byte) error {\n\tif p.Len()+1+1+len(b) > MaxEIRPacketLength {\n\t\treturn ErrNotFit\n\t}\n\tp.b = append(p.b, byte(len(b)+1))\n\tp.b = append(p.b, typ)\n\tp.b = append(p.b, b...)\n\treturn nil\n}", "func (v *VectorImpl) Append(item ...Value) *VectorImpl {\n\tresult := v\n\titemLen := uint(len(item))\n\tfor insertOffset := uint(0); insertOffset < itemLen; {\n\t\ttailLen := result.len - result.tailOffset()\n\t\ttailFree := nodeSize - tailLen\n\t\tif tailFree == 0 {\n\t\t\tresult = result.pushLeafNode(result.tail)\n\t\t\tresult.tail = emptyVectorImpl.tail\n\t\t\ttailFree = nodeSize\n\t\t\ttailLen = 0\n\t\t}\n\n\t\tbatchLen := uintMin(itemLen-insertOffset, tailFree)\n\t\tnewTail := make([]Value, 0, tailLen+batchLen)\n\t\tnewTail = append(newTail, result.tail...)\n\t\tnewTail = append(newTail, item[insertOffset:insertOffset+batchLen]...)\n\t\tresult = &VectorImpl{root: result.root, tail: newTail, len: result.len + batchLen, shift: result.shift}\n\t\tinsertOffset += batchLen\n\t}\n\n\treturn result\n}", "func (s *SliceOfByte) Append(item byte) *SliceOfByte {\n\ts.items = append(s.items, item)\n\treturn s\n}", "func (list *List) AppendToEnd(data int) {\n // 1. Create a new Node\n newNode := &Node{data: data, next: nil}\n\n // 2a. If list contains no elements, set new node as head of list\n // 2b. If list contains any element, traverse till last and append new node\n if list.size == 0 {\n list.head = newNode\n } else if list.size > 0 {\n current := list.head\n for current.next != nil {\n current = current.next\n }\n current.next = newNode\n }\n\n // 3. Increment the list size\n list.size++\n}", "func (s *RedisStorage) Append(value []byte) error {\n\tpipe := s.client.TxPipeline()\n\tdefer pipe.Close()\n\thash1, hash2 := hashValue(&value)\n\tfor index, fkey := range s.filters {\n\t\tpipe.SetBit(fkey, int64(getOffset(hash1, hash2, uint(index+1), s.size)), 1)\n\t}\n\t_, err := pipe.Exec()\n\tif err != nil {\n\t\tpipe.Discard()\n\t}\n\treturn err\n}", "func Append(s []interface{}, val interface{}, grow int) []interface{} {\n\tl := len(s)\n\ttarget := s\n\tif l == cap(target) {\n\t\t// will grow by specified size instead of default cap*2\n\t\ttarget = make([]interface{}, l, l+grow)\n\t\tcopy(target, s[:])\n\t}\n\n\ttarget = append(target, val)\n\treturn target\n}", "func (m *OutMessage) Append(src []byte) {\n\tp := m.GrowNoZero(len(src))\n\tif p == nil {\n\t\tpanic(fmt.Sprintf(\"Can't grow %d bytes\", len(src)))\n\t}\n\n\tsh := (*reflect.SliceHeader)(unsafe.Pointer(&src))\n\tmemmove(p, unsafe.Pointer(sh.Data), uintptr(sh.Len))\n\n\treturn\n}", "func (p *Pes) Append(buf []byte) {\n\tp.buf = append(p.buf, buf...)\n}", "func (list *List) Append(values ...interface{}) {\n\tlist.Add(values...)\n}", "func (cs *ConcurrentSlice) Append(item interface{}) {\n\tcs.Lock()\n\tdefer cs.Unlock()\n\tcs.items = append(cs.items, item)\n}", "func (b *Bag) Add(items ...Item) {\n\tb.items = append(b.items, items...)\n}", "func (lf *ListFile) AppendBytes(items ...[]byte) error {\n\tif lf.IsClosed() {\n\t\treturn errors.New(\"file is already closed\")\n\t}\n\n\tlf.mu.Lock()\n\tdefer lf.mu.Unlock()\n\n\t{\n\t\t// Gather all lines into a buffer:\n\t\tbuf := new(bytes.Buffer)\n\t\tfor _, item := range items {\n\t\t\t_, err := buf.Write(append(item, []byte(\"\\n\")...))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\t// Write the buffer to the file (in one file write):\n\t\t_, err := lf.file.Write(buf.Bytes())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor _, item := range items {\n\t\tif lf.mainIndex != nil {\n\t\t\t// add to tree to be able then to search it:\n\t\t\tlf.mainIndex.AddFromBytes(item)\n\t\t}\n\n\t\t// add to all indexes:\n\t\tfor _, index := range lf.secondaryIndexes {\n\t\t\tindex.backfillFunc(item)\n\t\t}\n\t}\n\treturn nil\n}", "func (batch *Batch) Append(dataId common.DataID) {\n\tindices := batch.set[dataId.BundleID]\n\tif indices == nil {\n\t\tindices = []int{}\n\t}\n\tindices = append(indices, dataId.Index)\n\n\tbatch.set[dataId.BundleID] = indices\n\tbatch.Count += 1\n}", "func (jz *Jzon) Append(v *Jzon) (err error) {\n\tif jz.Type != JzTypeArr {\n\t\treturn expectTypeOf(JzTypeArr, jz.Type)\n\t}\n\n\tjz.data = append(jz.data.([]*Jzon), v)\n\treturn nil\n}", "func (que *Queue) Push(items ...string) {\n\tque.values = append(que.values, items...)\n}", "func (builder *ListBuilder) Append(c *Cons) {\n\tif builder.Head == nil {\n\t\tbuilder.Head = c\n\t} else {\n\t\tbuilder.Tail.Cdr = c\n\t}\n\n\tbuilder.Tail = c.Last()\n}", "func (w *BytesWriter) Append(args ...interface{}) {\r\n\tw.args = append(w.args, args...)\r\n}", "func (d *D) Append(name string, value interface{}) {\n\t*d = append(*d, DocItem{name, value})\n}", "func (cli *Client) OrderedListAppend(ctx context.Context, collectionName string, key infrastructure.Key, bin string, data []interface{}) (err error) {\n\n\tpolicy := aero.NewWritePolicy(0, 0)\n\tlistPolicy := aero.NewListPolicy(aero.ListOrderOrdered, aero.ListWriteFlagsDefault)\n\n\taeroKey := cli.keyPool.Get(key.Namespace, key.SetName, key.UserKey)\n\n\toperations := make([]*aero.Operation, len(data))\n\tcounter := 0\n\tfor _, value := range data {\n\t\toperations[counter] = aero.ListAppendWithPolicyOp(listPolicy, bin, value)\n\t\tcounter++\n\t}\n\n\tif _, setErr := cli.Client.Operate(policy, aeroKey, operations...); setErr != nil {\n\t\terr = errors.Wrap(setErr, \"Client Put error\")\n\t}\n\n\treturn\n}", "func (dr *DataRow) AppendItem(item DataItem) error {\n\tif len(dr.Items) >= MaxColumns {\n\t\treturn fmt.Errorf(\"append item: %w\", ErrOverMaxColumns)\n\t}\n\n\tdr.Items = append(dr.Items, item)\n\treturn nil\n}", "func (r *RSS) Append(link, title, creator, description, content string, subject []string, date int64, abs bool) {\n\tif !abs {\n\t\tlink = r.parent + link\n\t}\n\ti := &Item{\n\t\tTitle: strings.TrimSpace(title),\n\t\tLink: link,\n\t\tDescription: strings.TrimSpace(description),\n\t\tCreator: creator,\n\t\tDate: date,\n\t\tSubject: subject,\n\t\tcontent: content,\n\t}\n\tr.Feeds = append(r.Feeds, i)\n}", "func appendDataList(dataList []data.Data, mdata data.Data, respDepth uint32) []data.Data {\n\tif mdata == nil {\n\t\treturn dataList\n\t}\n\treq, ok := mdata.(*data.Request)\n\tif ok {\n\t\treq.SetDepth(respDepth + 1)\n\t}\n\treturn append(dataList, mdata)\n}", "func Append() {\n\tp := []int{1, 2, 3}\n\tfmt.Println(p)\n\tfmt.Println(p[:1])\n\n\tq := append(p[:1], 4)\n\tfmt.Println(q)\n}", "func (s *SliceOfInt8) Append(item int8) *SliceOfInt8 {\n\ts.items = append(s.items, item)\n\treturn s\n}", "func (p *Packed2DGenericTypeBuilder) Append(x GenericType) {\n\tif p.autoGrow && p.tail >= len(p.buf) {\n\t\tp.Grow(1)\n\t}\n\tp.buf[p.tail] = x\n\tp.tail++\n}", "func (s *SliceOfUint8) Append(item uint8) *SliceOfUint8 {\n\ts.items = append(s.items, item)\n\treturn s\n}", "func (i *Iter) Append(v ...uint64) {\n\ti.v = append(i.v, v...)\n}", "func Append(m []interface{}, args ...interface{}) []interface{} {\n\tfor _, v := range args {\n\t\tm = append(m, v)\n\t}\n\treturn m\n}", "func (self *Response) AddItem(data map[string]interface{}) {\n\tself.items = append(self.items, data)\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 (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 (store *Store) append(buf []byte) error {\n\t// append data uncommitted\n\t_, err := store.dataFile.Seek(store.ptr, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, err = store.dataFile.Write(buf); err != nil {\n\t\treturn err\n\t}\n\tnewptr, err := store.dataFile.Seek(0, 1)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// start committing header\n\tif _, err = store.dataFile.Seek(0, 0); err != nil {\n\t\treturn err\n\t}\n\ttmp := [8]byte{}\n\tif _, err = store.dataFile.Read(tmp[:]); err != nil {\n\t\treturn err\n\t}\n\tflag := tmp[3]\n\tbinary.BigEndian.PutUint64(tmp[:], uint64(newptr))\n\n\tif flag == 0 {\n\t\tflag = 1\n\t\t_, err = store.dataFile.Seek(10, 0)\n\t} else {\n\t\tflag = 0\n\t\t_, err = store.dataFile.Seek(4, 0)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, err = store.dataFile.Write(tmp[2:]); err != nil {\n\t\treturn err\n\t}\n\tif _, err = store.dataFile.Seek(3, 0); err != nil {\n\t\treturn err\n\t}\n\tif _, err = store.dataFile.Write([]byte{flag}); err != nil {\n\t\treturn err\n\t}\n\n\t// all clear\n\tstore.ptr = newptr\n\treturn nil\n}", "func (s *BytesWriter) Append(args ...interface{}) {\n\ts.args = append(s.args, args...)\n}", "func (s *BytesWriter) Append(args ...interface{}) {\n\ts.args = append(s.args, args...)\n}", "func (l *List) Extend(items []Object) {\n\tl.Items = append(l.Items, items...)\n}", "func (w *tWriter) append(key, value []byte) error {\n\tif w.first == nil {\n\t\tw.first = append([]byte{}, key...)\n\t}\n\tw.last = append(w.last[:0], key...)\n\treturn w.tw.Append(key, value)\n}", "func (s *SliceOfInt64) Append(item int64) *SliceOfInt64 {\n\ts.items = append(s.items, item)\n\treturn s\n}", "func (server RaftMachine) Append(cmdReq []byte) {\n\treqApp := Append{Data: cmdReq}\n\tserver.SM.CommMedium.clientCh <- reqApp\n}", "func (DummyStore) AppendSlice(key string, values ...interface{}) error {\n\treturn nil\n}", "func (this *Tuple) Append(other *Tuple) {\n\tthis.AppendItems(other.data...)\n}", "func (b *Buffer) Append(data []byte) {\n\tb.appendWithLen(data, len(data))\n}", "func (f *FacebookRequestResponses) Append(addition ...*FacebookRequestResponse) *FacebookRequestResponses {\n\tfor _, a := range addition {\n\t\t*f = append(*f, *a)\n\t}\n\treturn f\n}", "func (h *HistoricalRecords) Append(tr *TransferRecord) {\n\th.mutex.Lock()\n\th.records = append(h.records, tr)\n\th.mutex.Unlock()\n}", "func (o *Originator) Add(items []string) {\n\tfor _, item := range items {\n\t\to.data[item] = true\n\t}\n}", "func (s *SliceOfString) Append(item string) *SliceOfString {\n\ts.items = append(s.items, item)\n\treturn s\n}", "func (fi *FileIO) Append(bs [][]byte) (int, error) {\n\treturn genericAppend(fi, bs)\n}", "func (l *List) AppendItems(items []interface{}) {\n\tfor _, item := range items {\n\t\tl.AppendItem(item)\n\t}\n}", "func (this *Tuple) InsertItems(start int, items ...interface{}) {\n\tstart = this.Offset(start)\n\trhs := this.Copy().data[start:]\n\tthis.data = append(this.data[:start], items...)\n\tthis.data = append(this.data, rhs...)\n}", "func (reading_EntityInfo) AppendToSlice(slice interface{}, object interface{}) interface{} {\n\tif object == nil {\n\t\treturn append(slice.([]*Reading), nil)\n\t}\n\treturn append(slice.([]*Reading), object.(*Reading))\n}", "func (q Query) Append(item Record) Query {\n\treturn Query{\n\t\tIterate: func() Iterator {\n\t\t\tnext := q.Iterate()\n\t\t\tappended := false\n\n\t\t\treturn func(ctx Context) (Record, error) {\n\t\t\t\ti, err := next(ctx)\n\t\t\t\tif err == nil {\n\t\t\t\t\treturn i, nil\n\t\t\t\t}\n\t\t\t\tif !IsNoRows(err) {\n\t\t\t\t\treturn Record{}, err\n\t\t\t\t}\n\n\t\t\t\tif !appended {\n\t\t\t\t\tappended = true\n\t\t\t\t\treturn item, nil\n\t\t\t\t}\n\n\t\t\t\treturn Record{}, ErrNoRows\n\t\t\t}\n\t\t},\n\t}\n}", "func (e *T) append(b byte) {\n\tif e.widx >= len(e.buf) {\n\t\te.overflow = true\n\t\te.available = true\n\t\treturn\n\t}\n\te.buf[e.widx] = b\n\te.widx++\n}", "func (tb *Table) AddItems(items [][]byte) {\n\ttb.rawItems.addItems(tb, items)\n\tatomic.AddUint64(&tb.itemsAdded, uint64(len(items)))\n\tn := 0\n\tfor _, item := range items {\n\t\tn += len(item)\n\t}\n\tatomic.AddUint64(&tb.itemsAddedSizeBytes, uint64(n))\n}", "func (c *Conn) end(data []byte) {\n\tif len(data) > 0 {\n\t\tif len(data) != len(c.in) {\n\t\t\tc.in = append(c.in[:0], data...)\n\t\t}\n\t} else if len(c.in) > 0 {\n\t\tc.in = c.in[:0]\n\t}\n\n\t//if len(c.out) > 0 {\n\t//\tc.outb = c.out\n\t//\tc.out = nil\n\t//}\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 (l *TimestampedLog) Append(ts int64, data []byte) error {\n\tlatest, err := l.latest()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif ts < latest {\n\t\treturn errors.New(\"TimestampedLog.append: wrong timestamp\")\n\t}\n\n\tidx, err := l.addToSize(1)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar buf bytes.Buffer\n\tbuf.Write(util.Uint64To8Bytes(uint64(ts)))\n\tbuf.Write(data)\n\tl.kvw.Set(l.getElemKey(idx), buf.Bytes())\n\treturn nil\n}", "func (batch *BatchEncoder) Append(key []byte, value []byte) {\n\tvar keyLenByte [8]byte\n\tbinary.BigEndian.PutUint64(keyLenByte[:], uint64(len(key)))\n\tvar valueLenByte [8]byte\n\tbinary.BigEndian.PutUint64(valueLenByte[:], uint64(len(value)))\n\n\tbatch.keyBuf.Write(keyLenByte[:])\n\tbatch.keyBuf.Write(key)\n\n\tbatch.valueBuf.Write(valueLenByte[:])\n\tbatch.valueBuf.Write(value)\n}", "func (l *List) Append(val interface{}) {\n\tl.entries = append(l.entries, val)\n}", "func (ms Float64Slice) Append(elms ...float64) {\n\t*ms.getOrig() = append(*ms.getOrig(), elms...)\n}", "func (b *BookShelf) Append(book *Book) {\n\tb.books = append(b.books, book)\n\tb.last++\n}", "func (e *rawData) AddElements(elements ...Element) Element { return e }", "func (a *appender) Append(id common.ID, b []byte) error {\n\tlength, err := marshalObjectToWriter(id, b, a.writer)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ti := sort.Search(len(a.records), func(idx int) bool {\n\t\treturn bytes.Compare(a.records[idx].ID, id) == 1\n\t})\n\ta.records = append(a.records, nil)\n\tcopy(a.records[i+1:], a.records[i:])\n\ta.records[i] = &common.Record{\n\t\tID: id,\n\t\tStart: uint64(a.currentOffset),\n\t\tLength: uint32(length),\n\t}\n\n\ta.currentOffset += length\n\treturn nil\n}", "func (s *VectorImplSlice) Append(items ...Value) *VectorImplSlice {\n\tnewSlice := VectorImplSlice{vector: s.vector, start: s.start, stop: s.stop + len(items)}\n\n\t// If this is v slice that has an upper bound that is lower than the backing\n\t// vector then set the values in the backing vector to achieve some structural\n\t// sharing.\n\titemPos := 0\n\tfor ; s.stop+itemPos < s.vector.Len() && itemPos < len(items); itemPos++ {\n\t\tnewSlice.vector = newSlice.vector.Set(s.stop+itemPos, items[itemPos])\n\t}\n\n\t// For the rest just append it to the underlying vector\n\tnewSlice.vector = newSlice.vector.Append(items[itemPos:]...)\n\treturn &newSlice\n}", "func (b *ScriptBuilder) AddFullData(data []byte) *ScriptBuilder {\n\tif b.err != nil {\n\t\treturn b\n\t}\n\n\treturn b.addData(data)\n}", "func (m *MemoryLogger) Append(newEntry LogEntry) {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\tm.Entries[m.index] = newEntry\n\tm.index = (m.index + 1) % maxLogItems\n}", "func (s *SliceOfByte) Concat(items []byte) *SliceOfByte {\n\ts.items = append(s.items, items...)\n\treturn s\n}", "func (db *DataPerBuild) AppendSeriesData(obj TestData) {\n\tdb.Series = append(db.Series, obj.SeriesData)\n}", "func (l *LevelDB) Append(entries []pb.Entry) error {\n\tbatch := new(leveldb.Batch)\n\tfor _, e := range entries {\n\t\tk := make([]byte, 8)\n\t\tbinary.LittleEndian.PutUint64(k, uint64(e.Index))\n\t\tb, err := proto.Marshal(&e)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbatch.Put(k, b)\n\t}\n\n\treturn l.db.Write(batch, nil)\n}", "func (hil *HTTPServiceInfoList) AddItem(h HTTPServiceInfo) {\n\tfor i, item := range *hil {\n\t\tif h.BCSVHost == item.BCSVHost && h.ServicePort == item.ServicePort {\n\t\t\titem.Backends = append(item.Backends, h.Backends...)\n\t\t\t(*hil)[i] = item\n\t\t\treturn\n\t\t}\n\t}\n\n\t//not match data already exist\n\t*hil = append(*hil, h)\n}", "func (s *server) AppendEntries(req *AppendEntriesRequest) *AppendEntriesResponse {\n\tvar ret, _ = s.send(req)\n\tresp, _ := ret.(*AppendEntriesResponse)\n\treturn resp\n}", "func (l *Slist) Append(d interface{}) {\n\tif l.head == nil {\n\t\tl.head = &Snode{data: d}\n\t\tl.len++\n\t\treturn\n\t}\n\n\tcurrent := l.head\n\tfor current != nil {\n\t\tif current.next == nil {\n\t\t\tcurrent.next = &Snode{data: d}\n\t\t\tl.len++\n\t\t\treturn\n\t\t}\n\t\tcurrent = current.next\n\t}\n}", "func (x *List) Append(item string) {\n\tx.items = append(x.items, item)\n}" ]
[ "0.63881624", "0.6340976", "0.60832125", "0.6061933", "0.60277545", "0.6017608", "0.60159856", "0.59959954", "0.5993144", "0.5986288", "0.59482485", "0.5875957", "0.5873964", "0.5836725", "0.5813423", "0.58130157", "0.57939684", "0.5792593", "0.578395", "0.57786715", "0.57769907", "0.57510746", "0.57141", "0.56981647", "0.5695311", "0.5693924", "0.56919795", "0.56878674", "0.56843144", "0.5668278", "0.56568176", "0.56366867", "0.563584", "0.56304973", "0.56066215", "0.5598089", "0.5561244", "0.5555795", "0.55328274", "0.55115515", "0.5497472", "0.54904103", "0.5489704", "0.548797", "0.54864734", "0.5483753", "0.5466774", "0.5466249", "0.5463413", "0.54590946", "0.54565275", "0.5456141", "0.5440889", "0.54391646", "0.54351294", "0.5434303", "0.5426259", "0.5420683", "0.541693", "0.5416906", "0.5414762", "0.54117733", "0.54117733", "0.5409002", "0.54013634", "0.53974485", "0.5391034", "0.5389162", "0.53864735", "0.5370055", "0.53653455", "0.53631955", "0.5356782", "0.5353819", "0.5349495", "0.53439295", "0.53403395", "0.5338085", "0.5328948", "0.5327437", "0.53198075", "0.53101987", "0.53073037", "0.5304925", "0.5303113", "0.53015023", "0.53010505", "0.5299207", "0.5294347", "0.52916604", "0.52905625", "0.5283088", "0.52823216", "0.52822995", "0.5281533", "0.52754605", "0.52721417", "0.52670366", "0.5259369", "0.52423006" ]
0.6661583
0
LoadConfig loads the configuration stored in `~/.mktmpio.yml`, returning it as a Config type instance.
func LoadConfig() *Config { config := Config{} defConf := DefaultConfig() file := FileConfig(ConfigPath()) env := EnvConfig() return config.Apply(defConf).Apply(file).Apply(env) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func LoadConfig(confPath string) (Config, error){\n var conf Config\n _, err := toml.DecodeFile(confPath, &conf)\n return conf, err\n}", "func LoadConfig(path string) error {\n\t// Lock mutex\n\tConfig.rw.Lock()\n\tdefer Config.rw.Unlock()\n\n\t// Decode the given file to the given interface\n\tif _, err := toml.DecodeFile(path, Config.Configuration); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func LoadConfig(path string) *Config {\n\tdefaultConfig := defaultConfig()\n\tfmt.Println(path)\n\tfmt.Println(defaultConfig)\n\tif _, err := toml.DecodeFile(path, defaultConfig); err != nil {\n\t\tlog.Fatal(\"error\", err.Error())\n\t}\n\tfmt.Println(defaultConfig)\n\treturn defaultConfig\n}", "func LoadConfig(configPath string) (err error) {\n // Open config file\n file, err := os.Open(configPath)\n if err != nil {\n return\n }\n defer file.Close()\n \n // Init new YAML decode\n d := yaml.NewDecoder(file)\n\n // Start YAML decoding from file\n err = d.Decode(&Config)\n return\n}", "func LoadConfig(data []byte) *Config {\r\n\tvar config = new(Config)\r\n\terr := yaml.Unmarshal(data, &config)\r\n\tif err != nil {\r\n\t\tpanic(err.Error())\r\n\t}\r\n\treturn config\r\n}", "func LoadConfig(fname string) (m *Config) {\n\tm = &Config{}\n\tif err := LoadYaml(m, fname); err != nil {\n\t\tif isV {\n\t\t\tfmt.Println(\" File can not unmarshal.:\", fname)\n\t\t}\n\t\treturn nil\n\t}\n\treturn\n}", "func LoadConfig(configPath string) Config {\n\tb, err := ioutil.ReadFile(configPath)\n\tif err != nil {\n\t\tlog.Fatalf(\"error: %v\", err)\n\t}\n\n\tm := Config{}\n\terr = yaml.Unmarshal(b, &m)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"error: %v\", err)\n\t}\n\n\treturn m\n}", "func LoadConfig() Config {\n\tvar config Config\n\tvar usedPath string\n\tfor _, path := range ListOfConfigPath {\n\t\tif _, err := os.Stat(path); !os.IsNotExist(err) {\n\t\t\tusedPath = path\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif _, err := toml.DecodeFile(usedPath, &config); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tlog.Println(\"Loaded config :\", usedPath)\n\treturn config\n}", "func Load(path string, maxSize int64) (*Config, error) {\n\tb, readErr := store.FileRead(path, maxSize)\n\tif readErr != nil {\n\t\treturn nil, readErr\n\t}\n\tc := New()\n\tif err := yaml.Unmarshal(b, c); err != nil {\n\t\treturn nil, err\n\t}\n\treturn c, nil\n}", "func LoadConfig(file string) (c *Config, err error) {\n\tc = new(Config)\n\n\t// Check for tag\n\tsFile := checkName(file)\n\tif sFile == \"\" {\n\t\treturn c, fmt.Errorf(\"Wrong format for %s\", file)\n\t}\n\n\t// Check if there is any config file\n\tif _, err := os.Stat(sFile); err != nil {\n\t\t// No config file is no error\n\t\treturn c, nil\n\t}\n\n\t// Read it\n\tbuf, err := ioutil.ReadFile(sFile)\n\tif err != nil {\n\t\treturn c, fmt.Errorf(\"Can not read %s\", sFile)\n\t}\n\n\terr = toml.Unmarshal(buf, &c)\n\tif err != nil {\n\t\treturn c, fmt.Errorf(\"Error parsing toml %s: %v\",\n\t\t\tsFile, err)\n\t}\n\n\treturn c, nil\n}", "func LoadConfig(path string) (Config, error) {\n\tvar m Config\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn m, err\n\t}\n\terr = json.Unmarshal(data, &m)\n\treturn m, err\n}", "func LoadConfig(configFile string) {\n\tif _, err := os.Stat(configFile); os.IsNotExist(err) {\n\t\tfmt.Println(\"Config file \\\"\" + configFile + \"\\\" does not exist.\")\n\t\treturn\n\t} else if err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\n\tif _, err := toml.DecodeFile(configFile, &Config); err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n}", "func LoadConfig(configFile string) (*tomlConfig, error) {\n\tif _, err := os.Stat(configFile); os.IsNotExist(err) {\n\t\treturn nil, errors.New(\"Config File doesn not exist\")\n\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar config tomlConfig\n\n\tif _, err := toml.DecodeFile(configFile, &config); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &config, nil\n\n}", "func LoadConfig(configPtr *string) Config {\n\tbytes, err := ioutil.ReadFile(*configPtr)\n\tif err != nil {\n\t\tfmt.Println(\"Specified config file or default config file is not existing or not readable\")\n\t\tos.Exit(2)\n\t}\n\n\tconfig := Config{}\n\terr = yaml.Unmarshal(bytes, &config)\n\tif err != nil {\n\t\tfmt.Println(\"Config file is not valid\")\n\t\tos.Exit(3)\n\t}\n\n\treturn config\n}", "func LoadConfig(file string) (*Config, error) {\n\tb, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif ext := path.Ext(file); ext == \".yaml\" || ext == \".yml\" {\n\t\tb, err = yaml.YAMLToJSON(b)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tconfig := &Config{}\n\tif err = json.Unmarshal(b, config); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfixMbeanNames(config)\n\treturn config, nil\n}", "func LoadConfig(path string) {\n\tConf = *NewConfigByPath(path)\n}", "func LoadConfig(configPath string) Config {\n\tvar conf Config\n\tcontent, err := ioutil.ReadFile(configPath)\n\tif err != nil {\n\t\tfmt.Println(\"[-] Couldn't read the config file.\")\n\t\tos.Exit(1)\n\t}\n\terr = json.Unmarshal(content, &conf)\n\tif err != nil {\n\t\tfmt.Println(\"[-] Couldn't parse the config file.\", err)\n\t\tos.Exit(1)\n\t}\n\n\treturn conf\n}", "func LoadConfig(path string) (Config, error) {\n\tbuf, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn Config{}, err\n\t}\n\n\tvar config Config\n\n\terr = json.Unmarshal(buf, &config)\n\tif err != nil {\n\t\treturn Config{}, err\n\t}\n\n\treturn config, nil\n}", "func Load(path string) (*Configuration, error) {\n\n\tbytes, err := ioutil.ReadFile(path)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar c Configuration\n\terr = goyaml.Unmarshal(bytes, &c)\n\n\treturn &c, err\n}", "func LoadConfig(fpath string) (*PinoyConfig, error) {\n\tcontent, err := ioutil.ReadFile(fpath)\n\tif err != nil {\n\t\tlog.Println(\"Config:ERROR: Failed to read config file:\", err)\n\t\treturn nil, err\n\t}\n\n\tvar cfg PinoyConfig\n\terr = json.Unmarshal(content, &cfg)\n\tif err != nil {\n\t\tlog.Println(\"Config:ERROR: Failed to unmarshal config file:\", err)\n\t}\n\tcfg.NormalizeConfig()\n\treturn &cfg, nil\n}", "func loadConfig(configFile string) *utils.Config {\n\tconf := &utils.Config{}\n\tif _, err := toml.DecodeFile(configFile, &conf); err != nil {\n\t\tfmt.Println(err)\n\t}\n\treturn conf\n}", "func LoadConfig(fname string, ctx *interfaces.Context) (err error) {\n\tdoc, err := ioutil.ReadFile(fname)\n\tif err != nil {\n\t\tctx.Logger.Error().Msgf(\"Could not read config file: %s\", err.Error())\n\t\treturn\n\t}\n\n\ttoml.Unmarshal(doc, &ctx.Config)\n\tctx.Logger.Debug().Msg(spew.Sprint(ctx.Config))\n\n\treturn nil\n}", "func LoadConfig(conf interface{}, filename string) (err error) {\n\tvar decoder *json.Decoder\n\tfile := OpenFile(conf, filename)\n\tdefer file.Close()\n\tdecoder = json.NewDecoder(file)\n\tif err = decoder.Decode(conf); err != nil {\n\t\treturn\n\t}\n\tjson.Marshal(&conf)\n\treturn\n}", "func LoadConfig(path string) (*Config, error) {\n\tvar config Config\n\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := yaml.Unmarshal(b, &config); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &config, nil\n}", "func LoadConfig(filename string) (*Config, error) {\n\tif filename == \"\" {\n\t\treturn root, nil\n\t}\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn root, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\tb, err := io.ReadAll(f)\n\tf.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := yaml.Unmarshal(b, root); err != nil {\n\t\treturn nil, err\n\t}\n\treturn root, nil\n}", "func LoadConfig(path string) {\n\t// Load the config file\n\tfile, err := os.OpenFile(path, os.O_RDONLY, 0666)\n\tif err != nil {\n\t\tfmt.Println(\"error opening config file,\", err)\n\t}\n\tjson.NewDecoder(file).Decode(&Config)\n\tdefer file.Close()\n}", "func (ts *Tester) LoadConfig() (eksconfig.Config, error) {\n\treturn *ts.cfg, nil\n}", "func LoadConfig(configPath string) {\n\tsource, err := ioutil.ReadFile(configPath)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = yaml.Unmarshal(source, &Config)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (cf *Config) LoadConfig() {\n\t_, err := os.Stat(\"configs/config.yaml\")\n\tif os.IsNotExist(err) {\n\t\tlog.Panic(\"No config.yaml file found.\")\n\t}\n\tyamlFile, err := ioutil.ReadFile(\"configs/config.yaml\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\terr = yaml.Unmarshal(yamlFile, &cf)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func loadConfig() (TestingConfig, error) {\n\tvar config TestingConfig\n\n\tusr, err := user.Current()\n\tif err != nil {\n\t\tfmt.Println(\"Could not get current user.\", err)\n\t\treturn TestingConfig{}, err\n\t}\n\n\tpath := filepath.Join(usr.HomeDir, \"/.config/slackposter/config.json\")\n\n\tstr, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tfmt.Println(\"Could not read config.json. \", err)\n\t\treturn TestingConfig{}, err\n\t}\n\n\tif err := json.Unmarshal(str, &config); err != nil {\n\t\tfmt.Println(\"Failed to unmarshal config.json:\", err)\n\t\treturn config, err\n\t}\n\n\treturn config, nil\n}", "func LoadConfig(data []byte) (Configs, error) {\n\tcfg := Configs{}\n\terr := json.Unmarshal(data, &cfg)\n\n\t// TODO(mattfarina): wrap the error into something more useful if one exists\n\treturn cfg, err\n}", "func LoadConfig(structure interface{}) error {\n\tdata, err := ioutil.ReadFile(\"config.json\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal(data, structure)\n}", "func LoadConfig() error {\n\tfile, err := os.Open(\"config/config.json\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tConfig = new(Configuration)\n\tdecoder := json.NewDecoder(file)\n\terr = decoder.Decode(&Config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func LoadConfig(path string) error {\n\tfile, err := os.Open(filepath.Join(filepath.Clean(path), \"config.json\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdecoder := json.NewDecoder(file)\n\terr = decoder.Decode(&Config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func LoadConfig() error {\n\tfile, err := ioutil.ReadFile(\"config.json\")\n\terrorHandler(err, \"\")\n\tConfig = Configuration{}\n\terr = json.Unmarshal(file, &Config)\n\terrorHandler(err, \"\")\n\n\treturn nil\n}", "func LoadConfig() (*Config, error) {\n\tvar config Config\n\tvar filePath string\n\n\t// Default file location\n\tif cwd, err := os.Getwd(); err == nil {\n\t\tfilePath = filepath.Join(cwd, \"config.toml\")\n\t} else {\n\t\treturn config, fmt.Errorf(\"error getting working directory: %s\", err.Error())\n\t}\n\n\t// Check if PathEnvKey is set\n\tif val, set := os.LookupEnv(PathEnvKey); set {\n\t\t// Override filePath with custom user provided value\n\t\tfilePath = val\n\t}\n\n\t// Check if filePath exists\n\tif _, err := os.Stat(filePath); os.IsNotExist(err) {\n\t\treturn config, fmt.Errorf(\"config path does not exist: %s\", filePath)\n\t}\n\n\t// Read file contents\n\tdata, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn config, fmt.Errorf(\"error reading config file \\\"%s\\\": %s\", filePath, err.Error())\n\t}\n\n\t// Load toml\n\tif _, err := toml.Decode(string(data), &config); err != nil {\n\t\treturn config, fmt.Errorf(\"failed to parse toml config file \\\"%s\\\": %s\", filePath, err.Error())\n\t}\n\n\t// Validate\n\tif err := config.Validate(); err != nil {\n\t\treturn config, fmt.Errof(\"error verifying config: %s\", err.Error())\n\t}\n\n\t// All done, return\n\treturn config, nil\n}", "func LoadConfig(path string) error {\n\tlog.WithFields(log.Fields{\"path\": path}).Info(\"Loading config\")\n\treturn LoadConfigToVar(path, &Config)\n}", "func Load(path string, cfg *Config) error {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"faild to open configuration file\")\n\t}\n\n\terr = yaml.NewDecoder(f).Decode(cfg)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"faild to decode\")\n\t}\n\n\treturn nil\n}", "func loadConfig(path string) (*Config, error) {\n\n\tif _, err := os.Stat(path); err != nil {\n\t\treturn nil, errors.New(\"config file does not exist\")\n\t}\n\n\tinput, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot open config file: %v\", err)\n\t}\n\tdefer input.Close()\n\n\ttemp, err := ioutil.ReadAll(input)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot read config file: %v\", err)\n\t}\n\n\tvar c *Config\n\terr = yaml.Unmarshal([]byte(temp), &c)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot unmarshall config file: %v\", err)\n\t}\n\n\treturn c, nil\n}", "func LoadConfig(filePath string) (Config, error) {\n\tdata, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn Config{}, err\n\t}\n\n\tvar conf = Config{}\n\n\terr = json.Unmarshal(data, &conf)\n\n\tlog.Println(conf)\n\n\tif err != nil {\n\t\treturn Config{}, err\n\t}\n\n\tvar abs string\n\tabs, err = filepath.Abs(conf.MocksRootDir)\n\n\tif err != nil {\n\t\treturn Config{}, err\n\t}\n\n\tconf.MocksRootDir = abs\n\n\tabs, err = filepath.Abs(conf.LogsPath)\n\n\tif err != nil {\n\t\treturn Config{}, err\n\t}\n\n\tconf.LogsPath = abs\n\n\treturn conf, nil\n}", "func LoadConfig(path string) (Config, error) {\n\tconfig := Config{}\n\tcontent, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn config, fmt.Errorf(\"couldn't open file: %v\", err)\n\t}\n\tif err := json.Unmarshal(content, &config); err != nil {\n\t\treturn config, fmt.Errorf(\"couldn't parse config: %v\", err)\n\t}\n\treturn config, nil\n}", "func loadConfig(path string) (Config, error) {\n\tcfg := Config{}\n\tfilename, err := filepath.Abs(path)\n\tif err != nil {\n\t\treturn cfg, err\n\t}\n\tcontent, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn cfg, err\n\t}\n\n\terr = yaml.Unmarshal(content, &cfg)\n\tif err != nil {\n\t\treturn cfg, err\n\t}\n\n\treturn cfg, err\n}", "func LoadConfig(path string) (Config, error) {\n\tcfgBody, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn Config{}, err\n\t}\n\treturn ParseConfig(string(cfgBody))\n}", "func (c *Config) LoadConfig(path string) {\n\n\tf, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\n\tif err := json.Unmarshal(f, &c); err != nil {\n\t\tlog.Panicln(err)\n\t}\n\n}", "func LoadConfig(cf io.ReadCloser) (*Config, error) {\n\tdefer cf.Close()\n\n\tconfig, err := ParseConfig(cf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tglog.V(1).Info(\"Configuration loaded\")\n\treturn config, nil\n}", "func LoadConfig(path string) (c *Config, err error) {\n\tvar jsonFile *os.File\n\tvar byteValue []byte\n\n\tfmt.Println(\"Path \", path)\n\t// Open our jsonFile\n\tjsonFile, err = os.Open(path)\n\t// if we os.Open returns an error then handle it\n\tif err != nil {\n\t\terrors.Errorf(\": %w\", err)\n\t\treturn\n\t}\n\tfmt.Println(\"Successfully Opened json\")\n\t// defer the closing of our jsonFile so that we can parse it later on\n\tdefer jsonFile.Close()\n\n\t// read our opened xmlFile as a byte array.\n\tbyteValue, err = ioutil.ReadAll(jsonFile)\n\tif err != nil {\n\t\terrors.Errorf(\": %w\", err)\n\t\treturn\n\t}\n\tc = &Config{}\n\terr = json.Unmarshal(byteValue, c)\n\tif err != nil {\n\t\terrors.Errorf(\": %w\", err)\n\t\treturn\n\t}\n\treturn\n}", "func (f *Frontend) Loadconfig() error {\n\tcfgFile := configFile()\n\tcfgExists, err := exists(cfgFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !cfgExists {\n\t\treturn fmt.Errorf(configNotFound)\n\t}\n\tbs, err := ioutil.ReadFile(cfgFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = json.Unmarshal(bs, f.Config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tf.storage.Config = f.Config\n\tf.loader.Config = f.Config\n\treturn err\n}", "func Load(dataDirPath string) (config *Config, err error) {\n // load the config json into memory\n byteArr, err := ioutil.ReadFile(filepath.Join(dataDirPath, configFileName))\n if err != nil {\n return nil, fmt.Errorf(\"failed to read configuration file: %v\", err)\n }\n cfgJSON := &configJSON{}\n if err = json.Unmarshal(byteArr, cfgJSON); err != nil {\n return nil, fmt.Errorf(\"failed to parse configuration json: %v\", err)\n }\n\n // decode the private and public pem files\n pubPem, _ := pem.Decode([]byte(cfgJSON.PubPem))\n if pubPem == nil {\n return nil, fmt.Errorf(\"invalid public key data\")\n }\n privPem, _ := pem.Decode([]byte(cfgJSON.PrivPem))\n if privPem == nil {\n return nil, fmt.Errorf(\"invalid private key data\")\n }\n return &Config{privPem, pubPem, dataDirPath}, nil\n}", "func LoadConfig(path string) (*Config, error) {\n\tc := &Config{}\n\tcontents, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to read configuration file: %s, error: %s\", path, err)\n\t}\n\tif err = yaml.Unmarshal(contents, c); err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to parse configuration, error: %s\", err)\n\t}\n\tif err = c.validate(); err != nil {\n\t\treturn nil, fmt.Errorf(\"Invalid configuration, error: %s\", err)\n\t}\n\treturn c, nil\n}", "func LoadConfig(path string) (*tomledit.Document, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\treturn tomledit.Parse(f)\n}", "func LoadConfig(source string) (*Config, error) {\n\tjsonData, err := ioutil.ReadFile(source)\n\n\tif err != nil {\n\t\treturn nil, ErrorConfigNotFound\n\t}\n\n\tvar config Config\n\n\terr = json.Unmarshal(jsonData, &config)\n\n\tif err != nil {\n\t\treturn nil, ErrorFormatConfigNotValid\n\t}\n\n\treturn &config, nil\n}", "func LoadConfig(s string) (*Config, error) {\n\tcfg := &Config{}\n\terr := yaml.Unmarshal([]byte(s), cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.V(1).Infof(\"Loaded config:\\n%+v\", cfg)\n\treturn cfg, nil\n}", "func LoadConfig() (map[string]interface{}, error) {\n\treturn ReadConfig(\"\", \"\")\n}", "func LoadConfig(path string) (*Config, error) {\n\tif path == \"\" {\n\t\tex, _ := os.Executable()\n\t\texePath := filepath.Dir(ex)\n\t\tpath = exePath + \"/conf.json\"\n\t}\n\n\tdat, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar config Config\n\tif err := json.Unmarshal(dat, &config); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !config.IsValid() {\n\t\treturn nil, errors.New(\"config file is invalid\")\n\t}\n\n\tLog(\"load config file...\", path, config)\n\treturn &config, nil\n}", "func Load(path string) (Config, error) {\n\tcontents, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn Config{}, errors.Wrap(err, \"reading file\")\n\t}\n\tvar c Config\n\tif err := yaml.Unmarshal(contents, &c); err != nil {\n\t\treturn Config{}, errors.Wrap(err, \"unmarshaling config YAML\")\n\t}\n\treturn c, nil\n}", "func loadConfig() (*provider.Config, error) {\n\t// Gets the config file path.\n\tpath := os.Getenv(configFile)\n\tif path == \"\" {\n\t\tpath = defaultConfigFilePath\n\t}\n\n\tlogger.WithField(\"filename\", path).Info(\"Parsing config file\")\n\n\t// Reads config file.\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"cannot read config file\")\n\t}\n\n\tvar c *provider.Config\n\n\t// Unmarshals the read bytes.\n\tif err = yaml.Unmarshal(data, &c); err != nil {\n\t\treturn nil, errors.Annotate(err, \"cannot unmarshal config file\")\n\t}\n\n\tc.Label = strings.ToLower(c.Label)\n\n\treturn c, nil\n}", "func LoadConfig(path string) (*Config, error) {\n\t// Read the HCL file and prepare for parsing\n\td, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"Error reading %s: %s\", path, err)\n\t}\n\n\t// Parse it\n\tobj, err := hcl.Parse(string(d))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"Error parsing %s: %s\", path, err)\n\t}\n\n\t// Build up the result\n\tvar result Config\n\tif err := hcl.DecodeObject(&result, obj); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &result, nil\n}", "func LoadConfig(filename string) error {\n\tcontent, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = yaml.Unmarshal(content, &config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttmpl, err = template.FromGlobs(config.Templates...)\n\treturn err\n}", "func LoadConfig(file string) *nebletpb.Config {\n\tvar content string\n\tb, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\tlogging.CLog().WithFields(logrus.Fields{\n\t\t\t\"err\": err,\n\t\t}).Fatal(\"Failed to read the config file: %s.\", file)\n\t}\n\tcontent = string(b)\n\n\tpb := new(nebletpb.Config)\n\tif err := proto.UnmarshalText(content, pb); err != nil {\n\t\tlogging.CLog().WithFields(logrus.Fields{\n\t\t\t\"err\": err,\n\t\t}).Fatal(\"Failed to parse the config file: %s.\", file)\n\t}\n\treturn pb\n}", "func LoadConfig(configPath string) {\n\tsource, err := ioutil.ReadFile(configPath)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = yaml.Unmarshal(source, &Config)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tloc, _ := time.LoadLocation(Config.TimeZone)\n\tConfig.TimeLoc = loc\n\n\tspew.Dump(Config)\n}", "func Load(path string) (*Config, error) {\n\tdata, err := ioutil.ReadFile(path)\n\tconfig := new(Config)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\n\terr = json.Unmarshal(data, config)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\n\treturn config, nil\n}", "func Load(p string) (cfg *Config, err error) {\n\tvar d []byte\n\td, err = ioutil.ReadFile(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcfg = new(Config)\n\tif err = yaml.Unmarshal(d, cfg); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif cfg.ConfigPath != p {\n\t\tcfg.ConfigPath = p\n\t}\n\tcfg.ConfigPath, err = filepath.Abs(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cfg, nil\n}", "func LoadConfig(configPath string) ([]byte, error) {\n\tconfig, err := ioutil.ReadFile(configPath)\n\treturn config, err\n}", "func LoadConfig(configPath string) (*Config, error) {\n\n\tvar c Config\n\n\tdata, err := ioutil.ReadFile(configPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = yaml.Unmarshal(data, &c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.LogLevel = ll[strings.ToUpper(c.LogLevelName)]\n\n\treturn &c, nil\n}", "func Load(path string) (*Configuration, error) {\n\tbytes, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading config file, %s\", err)\n\t}\n\tvar cfg = new(Configuration)\n\tif err := yaml.Unmarshal(bytes, cfg); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to decode into struct, %v\", err)\n\t}\n\treturn cfg, nil\n}", "func LoadConfig(configPath string) *models.Configuration {\r\n\r\n\tviper.SetEnvPrefix(\"EDUCATIVE\")\r\n\tviper.AddConfigPath(\".\")\r\n\tviper.SetConfigFile(configPath)\r\n\terr := viper.MergeInConfig()\r\n\tif err != nil {\r\n\t\tfmt.Println(\"Error in reading config\")\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\terr = viper.Unmarshal(&CFG, func(config *mapstructure.DecoderConfig) {\r\n\t\tconfig.TagName = \"yaml\"\r\n\t})\r\n\tif err != nil {\r\n\t\tfmt.Println(\"Error in un-marshaling config\")\r\n\t\tpanic(err)\r\n\t}\r\n\t// fillBanningJobTime()\r\n\tif CFG.APP.LogLevel == \"info\" {\r\n\t\tfmt.Printf(\"%#v \\n\", CFG)\r\n\t}\r\n\r\n\tpostgres, err := GetPostgres()\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\tutil.Initialize()\r\n\treturn &models.Configuration{\r\n\t\tPostgresConnection: postgres,\r\n\t}\r\n}", "func LoadConfig(configFile string) (*PortableInfo, error) {\n\tvar err error\n\tvar input = io.ReadCloser(os.Stdin)\n\tif input, err = os.Open(configFile); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Read the config file\n\tjsonBytes, err := ioutil.ReadAll(input)\n\tinput.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a new container\n\tpi := &PortableInfo{}\n\n\t// Parse the config\n\tif err := pi.parseJSON(jsonBytes); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn pi, nil\n}", "func LoadCfg(path string) Config {\r\n\tjsonBytes, err := ioutil.ReadFile(path)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\tres := Config{}\r\n\terr = json.Unmarshal(jsonBytes, &res)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\treturn res\r\n}", "func Load(filePath string) (*ThingConfig, error) {\n\n\tvar config ThingConfig\n\n\tdata, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Failed to load config file\")\n\t}\n\n\terr = yaml.Unmarshal(data, &config)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Failed to Unmarshal config file\")\n\t}\n\n\treturn &config, nil\n}", "func Load(path string) (*Config, error) {\n\tcfg := new(Config)\n\n\tswitch path {\n\tcase \"\":\n\t\tcfg.path = configFilePath()\n\tdefault:\n\t\tcfg.path = path\n\t}\n\n\tswitch exists, err := configFileExists(cfg.path); {\n\tcase err != nil:\n\t\treturn nil, errors.Wrap(err, \"failed to stat config file\")\n\tcase !exists:\n\t\tcfg.setDefaults()\n\t\treturn cfg, cfg.Write()\n\tdefault:\n\t\tfh, err := os.Open(cfg.path)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to open config file\")\n\t\t}\n\t\tdefer fh.Close()\n\n\t\tbuf, err := ioutil.ReadAll(fh)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to read file\")\n\t\t}\n\n\t\treturn cfg, yaml.Unmarshal(buf, &cfg)\n\t}\n}", "func LoadConfig(file string) (*Config, error) {\n\tvar conf Config\n\tif _, err := toml.DecodeFile(file, &conf); err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to load config: %v\", err)\n\t}\n\n\t// load signing key\n\tsignPath := utils.ResolvePath(conf.SignPubkeyPath, file)\n\tsignPubKey, err := ioutil.ReadFile(signPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Cannot read signing key: %v\", err)\n\t}\n\tif len(signPubKey) != sign.PublicKeySize {\n\t\treturn nil, fmt.Errorf(\"Signing public-key must be 32 bytes (got %d)\", len(signPubKey))\n\t}\n\n\tconf.SigningPubKey = signPubKey\n\n\treturn &conf, nil\n}", "func LoadConfig(path string) (*Config, error) {\n\tif path == \"\" {\n\t\tpath = configFileName\n\t}\n\n\tvar config = &Config{}\n\t_, err := toml.DecodeFile(path, &config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Println(\"ignore columns:\", config.Ignore)\n\n\treturn config, nil\n}", "func LoadConfig(configPath string) (*TemporalConfig, error) {\n\t// if configPath is empty, load from env\n\tif configPath == \"\" {\n\t\tconf, err := LoadConfigFromEnv()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// this will pass if we failed to pull config\n\t\t// from the environment, and will then default\n\t\t// to config file path based loading\n\t\tif !reflect.DeepEqual(&TemporalConfig{}, conf) {\n\t\t\treturn conf, nil\n\t\t}\n\t}\n\traw, err := ioutil.ReadFile(configPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar tCfg TemporalConfig\n\tif err = json.Unmarshal(raw, &tCfg); err != nil {\n\t\treturn nil, err\n\t}\n\n\ttCfg.setDefaults()\n\n\treturn &tCfg, nil\n}", "func Load(r io.Reader, config interface{}, logFunc func(args ...interface{})) error {\n\tif logFunc == nil {\n\t\tlogFunc = log.Println\n\t}\n\n\tconfigBytes, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\tlogFunc(\"ERROR reading from source\", err)\n\t\treturn err\n\t}\n\tlogFunc(\"CONFIG: \", string(configBytes))\n\n\ttpl := template.Must(template.New(\"config\").Parse(string(configBytes)))\n\n\t//pass env to config\n\tvar b bytes.Buffer\n\terr = tpl.Execute(&b, getEnv())\n\tif err != nil {\n\t\tlogFunc(\"ERROR in compiling the template. Check http://golang.org/pkg/text/template/ for the template format\", err)\n\t\treturn err\n\t}\n\n\tkt := reflect.TypeOf(\"\")\n\tvt := reflect.TypeOf(config)\n\tm := reflect.MakeMap(reflect.MapOf(kt, vt))\n\n\tconfigData := m.Interface()\n\n\terr = yaml.Unmarshal(b.Bytes(), configData)\n\tif err != nil {\n\t\tlogFunc(\"ERROR in parsing YAML\", err)\n\t\treturn err\n\t}\n\n\tc := m.MapIndex(reflect.ValueOf(GOENV))\n\n\tcptr := reflect.ValueOf(config)\n\n\tel := cptr.Elem()\n\n\tif !el.CanSet() {\n\t\terr = errors.New(\"ERROR: the config variable should be a pointer\")\n\t\tlogFunc(err)\n\t\treturn err\n\t}\n\n\tel.Set(c.Elem())\n\treturn nil\n}", "func Load() error {\n\tif configPathRaw == \"\" {\n\t\treturn errors.New(\"No configuration file path defined! See '-h'!\")\n\t}\n\n\tlog.Println(\"Loading configuration from file:\", configPathRaw)\n\n\t// Replace home directory if \"~\" was specified.\n\tif strings.Contains(configPathRaw, \"~\") {\n\t\tu, err := user.Current()\n\t\tif err != nil {\n\t\t\t// Well, I don't know how to test this.\n\t\t\treturn errors.New(\"Failed to get current user's data: \" + err.Error())\n\t\t}\n\n\t\tconfigPathRaw = strings.Replace(configPathRaw, \"~\", u.HomeDir, 1)\n\t}\n\n\t// Get absolute path to configuration file.\n\tconfigPath, err := filepath.Abs(configPathRaw)\n\tif err != nil {\n\t\t// Can't think of situation when it's testable.\n\t\treturn errors.New(\"Failed to get real configuration file path:\" + err.Error())\n\t}\n\n\t// Read it.\n\tconfigFileData, err := ioutil.ReadFile(configPath)\n\tif err != nil {\n\t\treturn errors.New(\"Failed to load configuration file data:\" + err.Error())\n\t}\n\n\t// Parse it.\n\terr1 := yaml.Unmarshal(configFileData, Cfg)\n\tif err1 != nil {\n\t\treturn errors.New(\"Failed to parse configuration file:\" + err1.Error())\n\t}\n\n\tlog.Printf(\"Configuration file parsed: %+v\\n\", Cfg)\n\treturn nil\n}", "func LoadConfig(path string) (*Config, error) {\n\tcfgBytes, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"reading config file: %s\", err)\n\t}\n\tcfg := new(Config)\n\terr = yaml.Unmarshal(cfgBytes, cfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"parsing config: %s\", err)\n\t}\n\terr = validator.Validate(cfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid config: %s\", err)\n\t}\n\treturn cfg, nil\n}", "func LoadConfig(file string) (AppConfig, error) {\n\tvar conf AppConfig\n\tif _, err := toml.DecodeFile(file, &conf); err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to load config: %v\", err)\n\t}\n\treturn conf, nil\n}", "func Load(path string) (*Config, error) {\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn load(b)\n}", "func (p *Pipeline) LoadConfig() error {\n\tdata, err := ioutil.ReadFile(p.ConfigPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp.Data = data\n\tvar conf Config\n\n\tif _, err := yaml.Unmarshal(data, p); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Load(r io.Reader) (*Config, error) {\n\tvar c Config\n\tif err := defaults.Set(&c); err != nil {\n\t\treturn nil, err\n\t}\n\tc.init()\n\tvar raw map[string]any\n\tif _, err := toml.NewDecoder(r).Decode(&raw); err != nil {\n\t\treturn nil, errors.Wrap(err, \"config: error decoding toml data\")\n\t}\n\tif err := c.parse(raw); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &c, nil\n}", "func (c *Container) LoadConfig() error {\n\tfilename := filepath.Join(containerPath, c.Digest, containerConfigFile)\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\tconfigFile, err := v1.ParseConfigFile(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.Config = configFile.Config.DeepCopy()\n\treturn nil\n}", "func LoadConfig(params map[string]string) *Config {\n\treturn &Config{params[\"githubToken\"], params[\"githubGistID\"], params[\"githubGistFileName\"]}\n}", "func LoadConfig() (ClientConfig, error) {\n conf := ClientConfig{}\n configFilePath, err := getConfigFilePath()\n if err != nil {\n return conf, err\n }\n\n data, err := os.ReadFile(configFilePath)\n if os.IsNotExist(err) {\n err = initConfig()\n if err != nil {\n return conf, err\n }\n data, err = os.ReadFile(configFilePath)\n }\n if err != nil {\n return conf, err\n }\n\n err = yaml.Unmarshal(data, &conf)\n if err != nil {\n return conf, err\n }\n\n return conf, nil\n}", "func Load() (cfg *Config, err error) {\n\tfile, err := Location()\n\tif err != nil {\n\t\treturn\n\t}\n\t_, err = os.Stat(file)\n\tif os.IsNotExist(err) {\n\t\tcfg = &Config{}\n\t\terr = nil\n\t\treturn\n\t}\n\tif err != nil {\n\t\terr = fmt.Errorf(\"can't check if config file '%s' exists: %v\", file, err)\n\t\treturn\n\t}\n\t// #nosec G304\n\tdata, err := os.ReadFile(file)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"can't read config file '%s': %v\", file, err)\n\t\treturn\n\t}\n\tcfg = &Config{}\n\tif len(data) == 0 {\n\t\treturn\n\t}\n\terr = json.Unmarshal(data, cfg)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"can't parse config file '%s': %v\", file, err)\n\t\treturn\n\t}\n\treturn\n}", "func Load(path string) (*Configuration, error) {\n\tbytes, err := ioutil.ReadFile(path)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading config file, %s\", err)\n\t}\n\tvar cfg = new(Configuration)\n\terr = json.Unmarshal(bytes, cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cfg, nil\n}", "func loadConfig(filename string) ConfigFile {\n\t// Deliberately don't catch errors, want script to crash on config file load error\n\tconfigFile, _ := ioutil.ReadFile(filename)\n\tvar config ConfigFile\n\tyaml.Unmarshal(configFile, &config)\n\n\t// Return the struct\n\treturn (config)\n}", "func LoadConfig(configFilePath string) (config *Table) {\n\tlog.Println(\"Load config = \", configFilePath)\n\tdata, err := ioutil.ReadFile(configFilePath)\n\tif err != nil {\n\t\tpanic(\"cannot load config\")\n\t}\n\n\terr = json.Unmarshal(data, &config)\n\tif err != nil {\n\t\tpanic(\"config invalid format\")\n\t}\n\n\treturn\n}", "func LoadConfig(name string) (*Config, error) {\n\tfile, err := os.Open(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbytes, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn LoadConfigFromBytes(bytes)\n}", "func LoadConfig(t *testing.T, configBytes []byte) (cfg ProvisionerConfig) {\n\terr := yaml.Unmarshal(configBytes, &cfg)\n\trequire.NoError(t, err, string(configBytes))\n\n\tswitch cfg.CloudProvider {\n\tcase constants.Azure:\n\t\trequire.NotNil(t, cfg.Azure)\n\t\tcfg.dockerDevice = cfg.Azure.DockerDevice\n\t\tcfg.cloudRegions = newCloudRegions(strings.Split(cfg.Azure.Location, \",\"))\n\tcase constants.AWS:\n\t\trequire.NotNil(t, cfg.AWS)\n\t\tcfg.dockerDevice = cfg.AWS.DockerDevice\n\tcase constants.GCE:\n\t\trequire.NotNil(t, cfg.GCE)\n\t\tcfg.cloudRegions = newCloudRegions(strings.Split(cfg.GCE.Region, \",\"))\n\tcase constants.Ops:\n\t\trequire.NotNil(t, cfg.Ops)\n\t\t// set AWS environment variables to be used by subsequent commands\n\t\tos.Setenv(\"AWS_ACCESS_KEY_ID\", cfg.Ops.EC2AccessKey)\n\t\tos.Setenv(\"AWS_SECRET_ACCESS_KEY\", cfg.Ops.EC2SecretKey)\n\t\t// normally the docker device is set to /dev/abc before gravity is installed\n\t\t// for throughput testing. However, when using the ops center for provisioning\n\t\t// the raw block device will have a partition on it, so we want to instead test\n\t\t// on the installation directory\n\t\tcfg.dockerDevice = \"/var/lib/gravity\"\n\tdefault:\n\t\tt.Fatalf(\"unknown cloud provider %s\", cfg.CloudProvider)\n\t}\n\treturn cfg\n}", "func (l *Loader) Load() (*Config, error) {\n\tif l.ConfigPath == \"\" {\n\t\treturn nil, errors.Reason(\"-qscheduler-config is required\").Err()\n\t}\n\n\tblob, err := ioutil.ReadFile(l.ConfigPath)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to open the config file\").Err()\n\t}\n\n\tcfg := &Config{}\n\tif err := proto.UnmarshalText(string(blob), cfg); err != nil {\n\t\treturn nil, errors.Annotate(err, \"not a valid Config proto message\").Err()\n\t}\n\n\tl.lastGood.Store(cfg)\n\treturn cfg, nil\n}", "func LoadConfig() Config {\n\tfiles, err := ioutil.ReadDir(\"/etc/lazarus/conf.d/\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar config Config\n\n\tfor _, file := range files {\n\t\tfilename := fmt.Sprintf(\"/etc/lazarus/conf.d/%s\", file.Name())\n\t\tyamlFile, err := ioutil.ReadFile(filename)\n\t\tif err != nil {\n\t\t\tlog.Print(\"Unable to Read Config file\", err)\n\t\t}\n\n\t\terr = yaml.Unmarshal(yamlFile, &config)\n\t\tif err != nil {\n\t\t\tlog.Print(\"Unable to Unmarshal Config\", err)\n\t\t}\n\n\t}\n\treturn config\n\n}", "func LoadConfig(configpath string) *viper.Viper {\n\tvar conf Config\n\tviperCfg := viper.New()\n\tviperCfg.SetConfigName(\"dev\")\n\tviperCfg.AddConfigPath(configpath)\n\tviperCfg.AutomaticEnv()\n\tviperCfg.SetConfigType(\"yml\")\n\t// configPath := \"${path}/config/config.yml\"\n\n\tif err := viperCfg.ReadInConfig(); err != nil {\n\t\tfmt.Printf(\"Failed to read the config file %s\", err)\n\t}\n\n\tif err := viperCfg.Unmarshal(&conf); err != nil {\n\t\tfmt.Printf(\"Failed to read the config file %s\", err)\n\t}\n\n\tviperCfg.WatchConfig()\n\n\treturn viperCfg\n}", "func loadConfig() Config {\n\tc := Config{}\n\n\t// if config file isn't passed in, don't try to look at it\n\tif len(os.Getenv(\"KIOSK_CONFIG_FILE\")) == 0 {\n\t\treturn c\n\t}\n\n\tfile, err := ioutil.ReadFile(os.Getenv(\"KIOSK_CONFIG_FILE\"))\n\tif err != nil {\n\t\tlog.Debugf(\"error reading in the config file: %s\", err)\n\t}\n\n\t_ = json.Unmarshal([]byte(file), &c)\n\n\t// if we still don't have an access secret let's generate a random one\n\treturn c\n}", "func LoadConfig(path string) (Config, error) {\n\tconfigBytes, err := os.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read lifecycle config from path %s: %w\", path, err)\n\t}\n\n\tvar lifecycleConfig Config\n\tif err := yaml.Unmarshal(configBytes, &lifecycleConfig); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to deserialize the lifecycle config: %w\", err)\n\t}\n\n\treturn lifecycleConfig, nil\n}", "func LoadConfig(configsPath string) {\n\n\tif _, err := toml.DecodeFile(configsPath + \"/app.toml\", &AppConfig); err != nil {\n\t\tpanic(fmt.Errorf(\"Failed to read the configuration file: %s\", err))\n\t}\n\tif _, err := toml.DecodeFile(configsPath + \"/storage.toml\", &StorageConfig); err != nil {\n\t\tpanic(fmt.Errorf(\"Failed to read the configuration file: %s\", err))\n\t}\n\n\tAppConfig.Validate()\n\tStorageConfig.Validate()\n}", "func LoadConfig() error {\n\tpath := filepath.FromSlash(configRoot + \"/config.json\")\n\tfile, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn util.WrapError(\"Error reading configuration file\", err)\n\t}\n\n\tif err := json.Unmarshal(file, &Config); err != nil {\n\t\treturn parseError(err)\n\t}\n\n\tvar data client\n\tif err := json.Unmarshal(file, &data); err != nil {\n\t\treturn parseError(err)\n\t}\n\n\tclientJSON, err := json.Marshal(data)\n\tif err != nil {\n\t\treturn parseError(err)\n\t}\n\tClientConfig = clientJSON\n\thash, err := util.HashBuffer(file)\n\tif err != nil {\n\t\treturn parseError(err)\n\t}\n\tHash = hash\n\tif err := mnemonic.SetSalt(Config.Posts.Salt); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func LoadConfig(config interface{}, files ...string) (err error) {\n\tfoundFiles := configFilesByEnv(files...)\n\tif len(foundFiles) == 0 {\n\t\treturn fmt.Errorf(\"no config file found for '%s'\", strings.Join(files, \" | \"))\n\t}\n\n\tfor _, file := range foundFiles {\n\t\tvar in []byte\n\t\tif in, err = ioutil.ReadFile(file); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\text := filepath.Ext(file)\n\n\t\tswitch {\n\t\tcase regexp.MustCompile(regexYAML).MatchString(ext):\n\t\t\terr = unmarshalYAML(in, config, file)\n\t\tcase regexp.MustCompile(regexTOML).MatchString(ext):\n\t\t\terr = unmarshalTOML(in, config, file)\n\t\tcase regexp.MustCompile(regexJSON).MatchString(ext):\n\t\t\terr = unmarshalJSON(in, config, file)\n\t\tdefault:\n\t\t\terr = fmt.Errorf(\"unknown data format, can't unmarshal file: '%s'\", file)\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err = parseTemplateFile(file, config); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t//configB, err := yaml.Marshal(config)\n\t//if err != nil {\n\t//\treturn err\n\t//}\n\t//if err = parseTemplate(configB, config); err != nil {\n\t//\treturn err\n\t//}\n\n\tdefer debugPrintf(\"%s\\n\", green(dump(config)))\n\treturn parseConfigTags(config, \"\")\n}", "func (cm *ConfigManager) Load(config interface{}) error {\n\tdata, err := ioutil.ReadFile(cm.file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// config is a link\n\terr = yaml.Unmarshal(data, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func LoadConfig(configPath string) error {\n\t// First obtain all the values from the environment variables if present.\n\tConfig.ListenHost = getEnv(envListenHost, Config.ListenHost)\n\tConfig.ListenPort = getEnvInt(envListenPort, Config.ListenPort)\n\tConfig.DestinationHost = getEnv(envDestinationHost, Config.DestinationHost)\n\tConfig.DestinationPort = getEnvInt(envDestinationPort, Config.DestinationPort)\n\tConfig.Description = getEnv(envDescription, Config.Description)\n\tConfig.PasswdFile = getEnv(envPasswdFile, Config.PasswdFile)\n\n\t// Load the config if it exists.\n\te, err := exists(configPath)\n\tif err != nil {\n\t\treturn err\n\t} else if !e {\n\t\tlog.Warningf(\"no watchman config found: '%s'\", configPath)\n\t} else {\n\t\t// Load and decode the file.\n\t\t_, err = toml.DecodeFile(configPath, &Config)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to load config file '%s': %v\", configPath, err)\n\t\t}\n\t}\n\n\t// Initialize the config.\n\treturn Config.Init()\n}", "func LoadConfig(confFile string) error {\n\tconfig, err := toml.LoadFile(confFile)\n\tif nil != err {\n\t\tlog.Errorf(\"open config file [%v] failed[%v]!\", confFile, err)\n\t\treturn err\n\t}\n\n\tif err = initRedis(config); nil != err {\n\t\tlog.Errorf(\"get Redis config failed[%v]!\", err)\n\t\treturn err\n\t}\n\t/*if err = initDB(config); nil != err {\n\t\tlog.Errorf(\"get db config failed:[%v]!\", err)\n\t\treturn err\n\t}*/\n\tif err = initMutilDB(config); nil != err {\n\t\tlog.Errorf(\"get db config failed:[%v]!\", err)\n\t\treturn err\n\t}\n\tif err = initToken(config); nil != err {\n\t\tlog.Errorf(\"get token config failed:[%v]!\", err)\n\t\treturn err\n\t}\n\tif err = initCommon(config); nil != err {\n\t\tlog.Errorf(\"get common config failed:[%v]!\", err)\n\t\treturn err\n\t}\n\t/*if err = initTestNet(config); nil != err {\n\t\tlog.Errorf(\"get testnet config failed:[%v]!\", err)\n\t\treturn err\n\t}*/\n\n\treturn nil\n}", "func LoadConfig(r io.Reader, configType string) (cfg *Config, id string, err error) {\n\tv := viper.New()\n\tif configType == \"\" {\n\t\tlog.Warning(\"no configType specified, defaulting to 'json'\")\n\t\tconfigType = \"json\"\n\t}\n\n\tv.SetConfigType(configType)\n\n\tif err := v.ReadConfig(r); err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tid = v.GetString(\"id\")\n\tif id == \"\" {\n\t\treturn nil, \"\", ErrNoConfigID\n\t}\n\n\ttmp := map[string]string{}\n\tif err := v.Unmarshal(&tmp); err != nil {\n\t\treturn nil, id, err\n\t}\n\n\tcfg = &Config{\n\t\tID: id,\n\t\tDiscoveryFlagsByImpl: map[string]map[string]string{},\n\t\tVtSQLFlags: map[string]string{},\n\t\tVtctldFlags: map[string]string{},\n\t}\n\n\tif err := cfg.unmarshalMap(tmp); err != nil {\n\t\treturn nil, id, err\n\t}\n\n\treturn cfg, id, nil\n}" ]
[ "0.7161106", "0.715963", "0.7044221", "0.69785136", "0.69676", "0.69121885", "0.6904957", "0.68580604", "0.6838161", "0.68353057", "0.68080896", "0.677335", "0.6762483", "0.6710661", "0.66872114", "0.6685924", "0.66724914", "0.66655004", "0.6646761", "0.6641647", "0.6617407", "0.6608323", "0.6597604", "0.6587378", "0.6581424", "0.6579315", "0.657927", "0.65714353", "0.6557504", "0.6556912", "0.65551746", "0.6534967", "0.6533373", "0.65087754", "0.65043914", "0.6503346", "0.6497505", "0.64916176", "0.6480214", "0.64788854", "0.6475956", "0.64713055", "0.64702296", "0.646849", "0.6465791", "0.6465398", "0.6463284", "0.6456639", "0.6447447", "0.6439385", "0.6415213", "0.64144194", "0.64081997", "0.6403338", "0.6401695", "0.6401008", "0.63994044", "0.6394695", "0.6386984", "0.63859427", "0.63838977", "0.6383591", "0.6380703", "0.6378956", "0.6374974", "0.63724244", "0.63706917", "0.6365147", "0.6357805", "0.6347826", "0.6345919", "0.6344967", "0.6344463", "0.63328886", "0.63259286", "0.63178164", "0.63084453", "0.6308354", "0.63068944", "0.6305515", "0.6304357", "0.63010657", "0.6297547", "0.6296586", "0.62882584", "0.62770385", "0.6274726", "0.6273812", "0.6271636", "0.6271156", "0.62704384", "0.6270013", "0.62698436", "0.62530035", "0.6247076", "0.6244343", "0.6231536", "0.62296706", "0.62248784", "0.62220514", "0.621418" ]
0.0
-1
DefaultConfig returns a configuration with only the default values set
func DefaultConfig() *Config { config := new(Config) config.URL = MktmpioURL return config }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func defaultConfig() *config {\n\treturn &config{}\n}", "func Default() *Config {\n\treturn &defaultConfig\n}", "func defaultConfig() interface{} {\n\treturn &config{\n\t\tPools: make(pools),\n\t\tConfDirPath: \"/etc/cmk\",\n\t}\n}", "func defaultConfig() *config {\n\treturn &config{\n\t\tOperations: operations{\n\t\t\tResize: resize{\n\t\t\t\tRaw: *resizeDefaults(),\n\t\t\t},\n\t\t\tFlip: flip{\n\t\t\t\tRaw: *flipDefaults(),\n\t\t\t},\n\t\t\tBlur: blur{\n\t\t\t\tRaw: *blurDefaults(),\n\t\t\t},\n\t\t\tRotate: rotate{\n\t\t\t\tRaw: *rotateDefaults(),\n\t\t\t},\n\t\t\tCrop: crop{\n\t\t\t\tRaw: *cropDefaults(),\n\t\t\t},\n\t\t\tLabel: label{\n\t\t\t\tRaw: *labelDefaults(),\n\t\t\t},\n\t\t},\n\t\tExport: export{\n\t\t\tRaw: *exportDefaults(),\n\t\t},\n\t}\n}", "func defaultConfig() interface{} {\n\treturn &conf{\n\t\tPools: make(map[string]poolConfig),\n\t\tLabelNode: false,\n\t\tTaintNode: false,\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tBaseConfig: defaultBaseConfig(),\n\t\tP2P: p2pConfig.DefaultConfig(),\n\t\tAPI: apiConfig.DefaultConfig(),\n\t\tCONSENSUS: consensusConfig.DefaultConfig(),\n\t\tHARE: hareConfig.DefaultConfig(),\n\t\tTIME: timeConfig.DefaultConfig(),\n\t}\n}", "func defaultConfig() Config {\n\treturn Config{\n\t\tConfFileOptions: defaultFileOptions(),\n\t}\n}", "func DefaultConfig() *Config { return &Config{BaseConfig{MinFees: defaultMinimumFees}} }", "func DefaultConfig() Config {\n\tnewConfig := Config{\n\t\t// Dependencies.\n\t\tFactoryCollection: factory.MustNewCollection(),\n\t\tLog: log.New(log.DefaultConfig()),\n\t\tStorageCollection: storage.MustNewCollection(),\n\t}\n\n\treturn newConfig\n}", "func configDefault(config ...Config) Config {\n\t// Return default config if nothing provided\n\tif len(config) < 1 {\n\t\treturn ConfigDefault\n\t}\n\n\t// Override default config\n\tcfg := config[0]\n\n\t// Set default values\n\tif cfg.Host == \"\" {\n\t\tcfg.Host = ConfigDefault.Host\n\t}\n\tif cfg.Port <= 0 {\n\t\tcfg.Port = ConfigDefault.Port\n\t}\n\tif cfg.Database == \"\" {\n\t\tcfg.Database = ConfigDefault.Database\n\t}\n\tif cfg.Table == \"\" {\n\t\tcfg.Table = ConfigDefault.Table\n\t}\n\tif int(cfg.GCInterval.Seconds()) <= 0 {\n\t\tcfg.GCInterval = ConfigDefault.GCInterval\n\t}\n\treturn cfg\n}", "func DefaultConfig() *Config {\n\tc := &Config{}\n\tif _, err := toml.Decode(defaultConfig, c); err != nil {\n\t\tpanic(err)\n\t}\n\tif err := c.Validate(); err != nil {\n\t\tpanic(err)\n\t}\n\treturn c\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tResource: nil,\n\n\t\t// Settings.\n\t\tName: \"\",\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tPUCT: 1.0,\n\t}\n}", "func Default() *Configuration {\n\treturn &Configuration{\n\t\tSplitMax: defaultSplitMax,\n\t\tPeekMax: defaultPeekMax,\n\t\tStringMax: defaultStringMax,\n\t\tDisableTransforms: []string{},\n\t\tDisableInterpolators: []string{},\n\t}\n}", "func DefaultConfig() Config {\n\tnewConfig := Config{\n\t\t// Dependencies.\n\t\tFactoryCollection: factory.MustNewCollection(),\n\t\tLog: log.New(log.DefaultConfig()),\n\t\tStorageCollection: storage.MustNewCollection(),\n\n\t\t// Settings.\n\t\tMaxSignals: 5,\n\t}\n\n\treturn newConfig\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tValueModifiers: nil,\n\n\t\t// Settings.\n\t\tIgnoreFields: nil,\n\t\tSelectFields: nil,\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tK8sClient: nil,\n\t\tLogger: nil,\n\t}\n}", "func DefaultConfig() Configuration {\n\tvar cfg Configuration\n\tSetDefaults(&cfg)\n\treturn cfg\n}", "func DefaultConfig() Config {\n\treturn MemoryConstrainedDefaults()\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 DefaultConfig() *Config {\n\treturn &Config{\n\t\tZapConfig: zap.NewProductionConfig(),\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tRedisURI: \"redis://127.0.0.1:6379\",\n\t\tGCP: &GCPConfig{\n\t\t\tProjectID: \"\",\n\t\t\tServiceAccountFile: \"\",\n\t\t},\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tAppName: pkg.Name(),\n\t\tLogPath: \"/tmp/log\",\n\t\tFlowRules: make([]*flow.Rule, 0),\n\t}\n}", "func Default() *AAAConfig {\n\treturn defaultStbConfig\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tSFCRenderer: defaultSFCRenderer,\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tK8sClient: nil,\n\t\tLogger: nil,\n\t\tVaultClient: nil,\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tHeartbeat: defaultHeartbeat,\n\t\tLocale: defaultLocale,\n\t\tDefaultLoggerLevel: zerolog.ErrorLevel,\n\t}\n}", "func DefaultConfig() Config {\n\tvar config Config\n\tconfig.DB.DSN = DefaultDSN\n\treturn config\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tLager: lager.NewLogLager(nil),\n\t\tPool: new(gob.Pool),\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tArtifactsDir: DefaultKataArtifactsDir,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tShowOurLogs: true,\n\t\tDeliverLogs: defaultDeliver,\n\t\tBackoffCap: defaultBackoffCap,\n\t\tBackoffGranularity: defaultBackoffGranularity,\n\t\tTickInterval: defaultTickInterval,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tDatabase: \"payments\",\n\t\tCollection: \"payments\",\n\t\tExpiryTimeInMinutes: \"90\",\n\t\tRefundBatchSize: 20,\n\t}\n}", "func (f *factory) DefaultConfig() interface{} {\n\treturn f.newDefaultCfg()\n}", "func configDefault(config ...Config) Config {\n\t// Return default config if nothing provided\n\tif len(config) < 1 {\n\t\treturn ConfigDefault\n\t}\n\n\t// Override default config\n\tcfg := config[0]\n\n\t// Set default values\n\n\tif cfg.Next == nil {\n\t\tcfg.Next = ConfigDefault.Next\n\t}\n\n\tif cfg.Lifetime.Nanoseconds() == 0 {\n\t\tcfg.Lifetime = ConfigDefault.Lifetime\n\t}\n\n\tif cfg.KeyHeader == \"\" {\n\t\tcfg.KeyHeader = ConfigDefault.KeyHeader\n\t}\n\tif cfg.KeyHeaderValidate == nil {\n\t\tcfg.KeyHeaderValidate = ConfigDefault.KeyHeaderValidate\n\t}\n\n\tif cfg.KeepResponseHeaders != nil && len(cfg.KeepResponseHeaders) == 0 {\n\t\tcfg.KeepResponseHeaders = ConfigDefault.KeepResponseHeaders\n\t}\n\n\tif cfg.Lock == nil {\n\t\tcfg.Lock = NewMemoryLock()\n\t}\n\n\tif cfg.Storage == nil {\n\t\tcfg.Storage = memory.New(memory.Config{\n\t\t\tGCInterval: cfg.Lifetime / 2, // Half the lifetime interval\n\t\t})\n\t}\n\n\treturn cfg\n}", "func ConfigDefault() Config {\n\tc := Config{\n\t\tCache: true,\n\t\tCacheRefresh: 3,\n\t\tCachePath: \"./.hpy\",\n\t\tMotd: true,\n\t\tMotdPath: \"/tmp/hpy.json\",\n\t\tLogging: true,\n\t\tLoggingPath: \"/var/log/hpy.log\",\n\t\tIgnoreLogging: false,\n\t\tDebug: false,\n\t}\n\treturn c\n}", "func NewDefault() *Config {\n\tvv := defaultConfig\n\treturn &vv\n}", "func NewDefault() *Config {\n\tvv := defaultConfig\n\treturn &vv\n}", "func defaultConfig() *config {\n\treturn &config{\n\t\tDrop: false,\n\t\tRGBA: rgba{\n\t\t\tR: 255,\n\t\t\tG: 255,\n\t\t\tB: 255,\n\t\t\tA: 1,\n\t\t},\n\t\tExport: export{\n\t\t\tFormat: \"jpeg\",\n\t\t\tQuality: 85,\n\t\t},\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tinjectString: defaultInject,\n\t\tconfigString: defaultConfig,\n\t\tappProfile: newAppProfile(),\n\t\tactivateES: false,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tBaseConfig: DefaultBaseConfig(),\n\t\tEth: DefaultEthConfig(),\n\t\tHuron: DefaultHuronConfig(),\n\t\tRaft: DefaultRaftConfig(),\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tBackOff: nil,\n\t\tFramework: nil,\n\t\tInformer: nil,\n\t\tLogger: nil,\n\t\tTPR: nil,\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tBuffered: true,\n\t\tDepth: 10,\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{make(map[string]string), DefaultBasicAuthRealm, 0, nil}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tLogger: nil,\n\n\t\t// Settings.\n\t\tFlag: nil,\n\t\tViper: nil,\n\n\t\tDescription: \"\",\n\t\tGitCommit: \"\",\n\t\tName: \"\",\n\t\tSource: \"\",\n\t}\n}", "func Default() *Config {\n\tconf := &Config{\n\t\tProtocol: \"tcp\",\n\t\tAddr: \"0.0.0.0:25565\",\n\t\tHosts: []HostConfig{\n\t\t\t{\n\t\t\t\tName: \"Server-1\",\n\t\t\t\tAddr: \"localhost:25580\",\n\t\t\t},\n\t\t},\n\t\tLogConfig: LogConfig{\n\t\t\tLogConnections: true,\n\t\t\tLogDisconnect: false,\n\t\t},\n\t\tHealthCheckTime: 5,\n\t\tUDPTimeout: 3000,\n\t\tSaveConfigOnClose: false,\n\t\tInterfaces: []string{},\n\t}\n\tconf.fillFlags()\n\treturn conf\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tPort: 5000,\n\t\tHapHome: \"/HOME/hapadm\",\n\t\tClusterID: \"default-name\",\n\t\tSudo: true,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tLogLevel: \"debug\",\n\t\tLogFormat: \"text\",\n\n\t\tDatabaseDriver: \"boltdb\",\n\t\tDatabasePath: \"db/eremetic.db\",\n\n\t\tName: \"Eremetic\",\n\t\tUser: \"root\",\n\t\tCheckpoint: true,\n\t\tFailoverTimeout: 2592000.0,\n\t\tQueueSize: 100,\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tFileSystem: nil,\n\t\tK8sClient: nil,\n\t\tLogger: nil,\n\n\t\t// Settings.\n\t\tFlag: nil,\n\t\tViper: nil,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tAddress: \"127.0.0.1\",\n\t\tPort: 5700,\n\t\tSyslogFacility: \"SYSLOG\",\n\t\tLogLevel: \"INFO\",\n\t\tConsulDatacenter: \"dc1\",\n\t\tConsulPort: 8500,\n\t\tParameters: make(map[string]string),\n\t\tDeclarations: essentials.NewDeclarationsConfig(),\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tContractQueryGasLimit: DefaultContractQueryGasLimit,\n\t\tContractDebugMode: DefaultContractDebugMode,\n\t\tWriteVMMemoryCacheSize: DefaultWriteVMMemoryCacheSize,\n\t\tReadVMMemoryCacheSize: DefaultReadVMMemoryCacheSize,\n\t\tNumReadVMs: DefaultNumReadVM,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tLogLevel: \"debug\",\n\t\tLogFormat: \"text\",\n\n\t\tDatabase: DatabaseConfig{\n\t\t\tHost: \"127.0.0.1\",\n\t\t\tPort: 3306,\n\t\t\tName: \"fusion\",\n\t\t\tUser: \"fusion\",\n\t\t\tPassword: \"password\",\n\t\t},\n\t}\n}", "func DefaultConfig() *config.Config {\n\treturn &config.Config{\n\t\tDebug: config.Debug{\n\t\t\tAddr: \"127.0.0.1:9174\",\n\t\t},\n\t\tService: config.Service{\n\t\t\tName: \"notifications\",\n\t\t},\n\t\tNotifications: config.Notifications{\n\t\t\tSMTP: config.SMTP{\n\t\t\t\tHost: \"127.0.0.1\",\n\t\t\t\tPort: \"1025\",\n\t\t\t\tSender: \"[email protected]\",\n\t\t\t},\n\t\t\tEvents: config.Events{\n\t\t\t\tEndpoint: \"127.0.0.1:9233\",\n\t\t\t\tCluster: \"ocis-cluster\",\n\t\t\t\tConsumerGroup: \"notifications\",\n\t\t\t},\n\t\t\tRevaGateway: \"127.0.0.1:9142\",\n\t\t},\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tLogger: nil,\n\n\t\t// Settings.\n\t\tBridgeName: \"\",\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tBaseConfig: BaseConfig{\n\t\t\tMinGasPrices: defaultMinGasPrices,\n\t\t\tQueryGasLimit: 0,\n\t\t\tInterBlockCache: true,\n\t\t\tPruning: pruningtypes.PruningOptionDefault,\n\t\t\tPruningKeepRecent: \"0\",\n\t\t\tPruningInterval: \"0\",\n\t\t\tMinRetainBlocks: 0,\n\t\t\tIndexEvents: make([]string, 0),\n\t\t\tIAVLCacheSize: 781250,\n\t\t\tIAVLDisableFastNode: false,\n\t\t\tAppDBBackend: \"\",\n\t\t},\n\t\tTelemetry: telemetry.Config{\n\t\t\tEnabled: false,\n\t\t\tGlobalLabels: [][]string{},\n\t\t},\n\t\tAPI: APIConfig{\n\t\t\tEnable: false,\n\t\t\tSwagger: false,\n\t\t\tAddress: DefaultAPIAddress,\n\t\t\tMaxOpenConnections: 1000,\n\t\t\tRPCReadTimeout: 10,\n\t\t\tRPCMaxBodyBytes: 1000000,\n\t\t},\n\t\tGRPC: GRPCConfig{\n\t\t\tEnable: true,\n\t\t\tAddress: DefaultGRPCAddress,\n\t\t\tMaxRecvMsgSize: DefaultGRPCMaxRecvMsgSize,\n\t\t\tMaxSendMsgSize: DefaultGRPCMaxSendMsgSize,\n\t\t},\n\t\tGRPCWeb: GRPCWebConfig{\n\t\t\tEnable: true,\n\t\t},\n\t\tStateSync: StateSyncConfig{\n\t\t\tSnapshotInterval: 0,\n\t\t\tSnapshotKeepRecent: 2,\n\t\t},\n\t\tStreaming: StreamingConfig{\n\t\t\tABCI: ABCIListenerConfig{\n\t\t\t\tKeys: []string{},\n\t\t\t\tStopNodeOnErr: true,\n\t\t\t},\n\t\t},\n\t\tMempool: MempoolConfig{\n\t\t\tMaxTxs: 5_000,\n\t\t},\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tCache: CacheConfig{\n\t\t\tType: FILE,\n\t\t\tExpiration: 10,\n\t\t},\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tConfigurers: nil,\n\t\tFileSystem: afero.NewMemMapFs(),\n\t\tLogger: nil,\n\n\t\t// Settings.\n\t\tHelmBinaryPath: \"\",\n\t\tOrganisation: \"\",\n\t\tPassword: \"\",\n\t\tRegistry: \"\",\n\t\tUsername: \"\",\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tAddr: DefaultAddr,\n\t\tDirPath: DefaultDirPath,\n\t\tBlockSize: DefaultBlockSize,\n\t\tRwMethod: storage.FileIO,\n\t\tIdxMode: KeyValueMemMode,\n\t\tMaxKeySize: DefaultMaxKeySize,\n\t\tMaxValueSize: DefaultMaxValueSize,\n\t\tSync: false,\n\t\tReclaimThreshold: DefaultReclaimThreshold,\n\t\tSingleReclaimThreshold: DefaultSingleReclaimThreshold,\n\t}\n}", "func configDefault(config ...Config) Config {\n\t// Return default config if nothing provided\n\tif len(config) < 1 {\n\t\treturn ConfigDefault\n\t}\n\n\t// Override default config\n\tcfg := config[0]\n\n\tif cfg.EnableStackTrace && cfg.StackTraceHandler == nil {\n\t\tcfg.StackTraceHandler = defaultStackTraceHandler\n\t}\n\n\treturn cfg\n}", "func DefaultConfig() Config {\n\treturn Config{TrimSpaces: false, FieldDelim: ','}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tApiAddress: \"http://api.bosh-lite.com\",\n\t\tUsername: \"admin\",\n\t\tPassword: \"admin\",\n\t\tToken: \"\",\n\t\tSkipSslValidation: false,\n\t\tHttpClient: http.DefaultClient,\n\t\tUserAgent: \"SM-CF-client/1.0\",\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tN: 10,\n\t\tRoundDuration: 10 * time.Second,\n\t\tWakeupDelta: 10 * time.Second,\n\t\tExpectedLeaders: 5,\n\t\tLimitIterations: 5,\n\t\tLimitConcurrent: 5,\n\t\tHdist: 20,\n\t}\n}", "func defaultConfig() *ApplicationConfig {\n\tconf := &ApplicationConfig{\n\t\tLogLevel: \"info\",\n\t\tHideArchived: true,\n\t\tDefaultMetadata: []string{\"Author\", \"Published At\", \"Language\", \"Ipfs\", \"Class\", \"Title\"},\n\t\tAutoComplete: true,\n\t\tAutoCompleteMaxResults: 20,\n\t\tEnableFullTextSearch: true,\n\t\tColors: defaultColors(),\n\t\tShortcuts: defaultShortcuts(),\n\t}\n\treturn conf\n}", "func defaultConfig() *config {\n\treturn &config{\n\t\tPermission: 0777,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tMaxRetries: defaultMaxRetries,\n\t\tInitialBackoff: defaultInitialBackoff,\n\t\tMaxBackoff: defaultMaxBackoff,\n\t\tBackoffFactor: defaultBackoffFactor,\n\t\tMaxMessages: defaultMaxMessages,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tNats: \"nats://192.168.168.195:4222\",\n\t\tKafka: \"\",\n\t\tQscNames: DefaultQscConfig(),\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tLogLevel: \"INFO\",\n\t\tBindAddr: \"127.0.0.1\",\n\t\tPorts: &Ports{\n\t\t\tHTTP: 4646,\n\t\t\tRPC: 4647,\n\t\t\tSerf: 4648,\n\t\t},\n\t\tAddresses: &Addresses{},\n\t\tServer: &ServerConfig{\n\t\t\tEnabled: false,\n\t\t},\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tRateLimit: map[notification.DestType]*RateConfig{\n\t\t\tnotification.DestTypeSMS: {\n\t\t\t\tPerSecond: 1,\n\t\t\t\tBatch: 5 * time.Second,\n\t\t\t},\n\t\t\tnotification.DestTypeVoice: {\n\t\t\t\tPerSecond: 1,\n\t\t\t\tBatch: 5 * time.Second,\n\t\t\t},\n\t\t},\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tIgnoreNamespaces: []string{\"kube-system\", \"kube-admission\"},\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tIgnoreNamespaces: []string{\"kube-system\", \"kube-admission\"},\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tIgnoreNamespaces: []string{\"kube-system\", \"kube-public\"},\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tPort: 3010,\n\t\tEnv: \"dev\",\n\t\tDatabase: DefaultPostgresConfig(),\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\t// Dependencies.\n\t\tHTTPClient: nil,\n\t\tLogger: nil,\n\n\t\t// Settings.\n\t\tFlag: nil,\n\t\tViper: nil,\n\t}\n}", "func NewDefaultConfig() Config {\n\treturn Config{\n\t\tStepSize: 0.001,\n\t\tBeta1: 0.9,\n\t\tBeta2: 0.999,\n\t\tEpsilon: 1.0e-8,\n\t}\n}", "func NewDefaultConfig() Config {\n\treturn Config{\n\t\tName: \"avo\",\n\t\tPkg: pkg(),\n\t}\n}", "func (c *ConfHolder) Default() []byte {\n\treturn nil\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tBlockSize: 64,\n\t\tNumReplicas: 2,\n\t\tNumTapestry: 2,\n\t\tZkAddr: \"localhost:2181\",\n\t}\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 DefaultConfig() *AppConfig {\r\n\treturn &AppConfig{\r\n\t\tEngine: EngineSDL,\r\n\t\tGraphics: gfx.DefaultConfig(),\r\n\t}\r\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tObservability: DefaultObservability(),\n\t\tWorkerHasher: DefaultHasher,\n\t\tWorkerCount: 1,\n\t\tMaxItemRetries: 10,\n\t\tWorkerQueueSize: 2000,\n\t\tLeaderElectionEnabled: true,\n\t\tDelayResolution: time.Millisecond * 250,\n\t\tDelayQueueSize: 1000,\n\t\tMaxReconcileTime: time.Second * 10,\n\t}\n}", "func DefaultConfig() (*Config, format.PropKeyResolver) {\n\tconfig := &Config{}\n\tpkr := format.NewPropKeyResolver(config)\n\t_ = pkr.SetDefaultProps(config)\n\treturn config, pkr\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tChdir: \".\",\n\t\tCollectorTimeout: collectorTimeout,\n\t\tWaitTime: 10,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tAddress: \"127.0.0.1:8080\",\n\t\tScheme: \"http\",\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: time.Duration(5 * time.Second),\n\t\t},\n\t}\n}", "func DefaultConfiguration() Configuration {\n\treturn Configuration{\n\t\t\tDescribeCaller: true,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tSMTPBindAddr: \"0.0.0.0:1025\",\n\t\tHTTPBindAddr: \"0.0.0.0:8025\",\n\t\tHostname: \"mailhog.example\",\n\t\tMongoURI: \"127.0.0.1:27017\",\n\t\tMongoDatabase: \"mailhog\",\n\t\tPostgresURI: \"postgres://127.0.0.1:5432/mailhog\",\n\t\tMongoColl: \"messages\",\n\t\tStorageType: \"memory\",\n\t\tMessageChan: make(chan *data.Message),\n\t\tOutgoingSMTP: make(map[string]*OutgoingSMTP),\n\t}\n}", "func configDefault(config ...Config) Config {\n\t// Return default config if nothing provided\n\tif len(config) < 1 {\n\t\treturn ConfigDefault\n\t}\n\n\t// Override default config\n\tcfg := config[0]\n\n\t// Set default values\n\tif int(cfg.Duration.Seconds()) > 0 {\n\t\tlog.Warn(\"[LIMITER] Duration is deprecated, please use Expiration\")\n\t\tcfg.Expiration = cfg.Duration\n\t}\n\tif cfg.Key != nil {\n\t\tlog.Warn(\"[LIMITER] Key is deprecated, please us KeyGenerator\")\n\t\tcfg.KeyGenerator = cfg.Key\n\t}\n\tif cfg.Store != nil {\n\t\tlog.Warn(\"[LIMITER] Store is deprecated, please use Storage\")\n\t\tcfg.Storage = cfg.Store\n\t}\n\tif cfg.Next == nil {\n\t\tcfg.Next = ConfigDefault.Next\n\t}\n\tif cfg.Max <= 0 {\n\t\tcfg.Max = ConfigDefault.Max\n\t}\n\tif int(cfg.Expiration.Seconds()) <= 0 {\n\t\tcfg.Expiration = ConfigDefault.Expiration\n\t}\n\tif cfg.KeyGenerator == nil {\n\t\tcfg.KeyGenerator = ConfigDefault.KeyGenerator\n\t}\n\tif cfg.LimitReached == nil {\n\t\tcfg.LimitReached = ConfigDefault.LimitReached\n\t}\n\tif cfg.LimiterMiddleware == nil {\n\t\tcfg.LimiterMiddleware = ConfigDefault.LimiterMiddleware\n\t}\n\treturn cfg\n}", "func DefaultConfig() *Config {\n\tcfg := &Config{\n\t\tuserHost: \"sms.yunpian.com\",\n\t\tsignHost: \"sms.yunpian.com\",\n\t\ttplHost: \"sms.yunpian.com\",\n\t\tsmsHost: \"sms.yunpian.com\",\n\t\tvoiceHost: \"voice.yunpian.com\",\n\t\tflowHost: \"flow.yunpian.com\",\n\t}\n\treturn cfg.WithUseSSL(true).WithHTTPClient(defaultHTTPClient())\n}", "func DefaultConfig() *Config {\n\tconfig := &Config{\n\t\tOwnerProcName: \"\",\n\t\tOwnerReleaseInterval: 1 * time.Second,\n\t\tOwnerReleaseTimeout: 5 * time.Minute,\n\t\tSourcePattern: \"/tmp/rotate/source\",\n\t\tTempStorage: \"/tmp/rotate/tmp\",\n\t\tArchiveStorage: \"/tmp/rotate/archive\",\n\t\tFinalizeCommands: []string{},\n\t}\n\treturn config\n}", "func NewDefaultConfig() *Config {\n\tconf := &Config{\n\t\tUnicastConfig: NewDefaultUnicastConfig(),\n\t\tExtensionConfig: NewDefaultExtensionConfig(),\n\t}\n\treturn conf\n}", "func (c *KubeadmConfig) Default() {\n\tDefaultKubeadmConfigSpec(&c.Spec)\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tVersionToPublish: params.VersionWithMeta(),\n\n\t\tEmitIntervals: EmitIntervals{\n\t\t\tMin: 110 * time.Millisecond,\n\t\t\tMax: 10 * time.Minute,\n\t\t\tConfirming: 120 * time.Millisecond,\n\t\t\tDoublesignProtection: 27 * time.Minute, // should be greater than MaxEmitInterval\n\t\t\tParallelInstanceProtection: 1 * time.Minute,\n\t\t},\n\n\t\tMaxTxsPerAddress: TxTurnNonces,\n\n\t\tMaxParents: 0,\n\n\t\tLimitedTpsThreshold: opera.DefaultEventGas * 120,\n\t\tNoTxsThreshold: opera.DefaultEventGas * 30,\n\t\tEmergencyThreshold: opera.DefaultEventGas * 5,\n\n\t\tTxsCacheInvalidation: 200 * time.Millisecond,\n\t}\n}", "func createDefaultConfig() component.Config {\n\treturn &Config{\n\t\tScraperControllerSettings: scraperhelper.ScraperControllerSettings{\n\t\t\tCollectionInterval: defaultCollectionInterval,\n\t\t\tTimeout: defaultTimeout,\n\t\t},\n\t\tEndpoint: defaultEndpoint,\n\t\tVersion: defaultVersion,\n\t\tCommunity: defaultCommunity,\n\t\tSecurityLevel: defaultSecurityLevel,\n\t\tAuthType: defaultAuthType,\n\t\tPrivacyType: defaultPrivacyType,\n\t}\n}", "func DefaultConfig() *Config {\n\treturn &Config{\n\t\tPort: defaultPort,\n\t\tAutoConnect: false,\n\t\tAllowReconnect: false,\n\t\tReconnectSeconds: 5,\n\t}\n}", "func DefaultConfig() Config {\n\tencoding := cosmoscmd.MakeEncodingConfig(app.ModuleBasics)\n\n\treturn Config{\n\t\tCodec: encoding.Marshaler,\n\t\tTxConfig: encoding.TxConfig,\n\t\tLegacyAmino: encoding.Amino,\n\t\tInterfaceRegistry: encoding.InterfaceRegistry,\n\t\tAccountRetriever: dclauthtypes.AccountRetriever{},\n\t\tAppConstructor: func(val Validator) servertypes.Application {\n\t\t\treturn app.New(\n\t\t\t\tval.Ctx.Logger, tmdb.NewMemDB(), nil, true, map[int64]bool{}, val.Ctx.Config.RootDir, 0,\n\t\t\t\tencoding,\n\t\t\t\tsimapp.EmptyAppOptions{},\n\t\t\t\tbaseapp.SetPruning(storetypes.NewPruningOptionsFromString(val.AppConfig.Pruning)),\n\t\t\t\tbaseapp.SetMinGasPrices(val.AppConfig.MinGasPrices),\n\t\t\t)\n\t\t},\n\t\tGenesisState: app.ModuleBasics.DefaultGenesis(encoding.Marshaler),\n\t\tTimeoutCommit: 2 * time.Second,\n\t\tChainID: \"chain-\" + tmrand.NewRand().Str(6),\n\t\tNumValidators: 1,\n\t\tBondDenom: sdk.DefaultBondDenom,\n\t\tMinGasPrices: fmt.Sprintf(\"0.000006%s\", sdk.DefaultBondDenom),\n\t\tAccountTokens: sdk.TokensFromConsensusPower(1000, sdk.DefaultPowerReduction),\n\t\tStakingTokens: sdk.TokensFromConsensusPower(500, sdk.DefaultPowerReduction),\n\t\tBondedTokens: sdk.TokensFromConsensusPower(100, sdk.DefaultPowerReduction),\n\t\tPruningStrategy: storetypes.PruningOptionNothing,\n\t\tCleanupDir: true,\n\t\tSigningAlgo: string(hd.Secp256k1Type),\n\t\tKeyringOptions: []keyring.Option{},\n\t}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tDir: DefaultConfDir,\n\t\tTimeout: xtime.Duration(\"1s\"),\n\t\tEnable: false,\n\t\tMysql: ConfDataSourceMysql{\n\t\t\tEnable: false,\n\t\t\tDsn: \"127.0.0.1:6379\",\n\t\t},\n\t\tEtcd: ConfDataSourceEtcd{\n\t\t\tEnable: false,\n\t\t\tSecure: false,\n\t\t\tEndPoints: []string{\"127.0.0.1:2379\"},\n\t\t},\n\t}\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 createDefaultConfig() component.Config {\n\treturn &Config{}\n}", "func createDefaultConfig() component.Config {\n\treturn &Config{}\n}", "func DefaultConfig() Config {\n\treturn Config{\n\t\tBlockchainInfo: types.DefaultBlockchainInfo(),\n\n\t\tAPIPassword: \"\",\n\n\t\tAPIaddr: \"localhost:23110\",\n\t\tRPCaddr: \":23112\",\n\t\tAllowAPIBind: false,\n\n\t\tNoBootstrap: false,\n\t\tRequiredUserAgent: RivineUserAgent,\n\t\tAuthenticateAPI: false,\n\n\t\tProfile: false,\n\t\tProfileDir: \"profiles\",\n\t\tRootPersistentDir: \"\",\n\t\tVerboseLogging: false,\n\n\t\tBootstrapPeers: nil,\n\n\t\tDebugConsensusDB: \"\",\n\t}\n}", "func NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tDefaultNamespace: \"default\",\n\t\tFileName: \"stdin\",\n\t\tTargetKubernetesVersion: \"master\",\n\t}\n}", "func NewDefaultConfig() *Config {\n\thostname, _ := os.Hostname()\n\tc := &Config{\n\t\tHostname: hostname,\n\t\tEncoder: NewAutomaticEventEncoder(),\n\t\tClient: &http.Client{},\n\t}\n\treturn c\n}" ]
[ "0.8259287", "0.8180411", "0.80875975", "0.8046045", "0.80177665", "0.7989454", "0.79624265", "0.7947094", "0.7923509", "0.79218996", "0.79001623", "0.7893205", "0.78920007", "0.7891704", "0.7888512", "0.7865028", "0.7835923", "0.7829766", "0.7825769", "0.78229904", "0.782248", "0.7807851", "0.78075767", "0.7798874", "0.7791665", "0.7775328", "0.777284", "0.7754906", "0.7747329", "0.7743773", "0.77406174", "0.773123", "0.77255636", "0.7724311", "0.77234364", "0.77233744", "0.77233744", "0.7722182", "0.7709134", "0.7666356", "0.7658851", "0.76543885", "0.7626746", "0.76154786", "0.7613593", "0.7610199", "0.760452", "0.7600393", "0.759219", "0.7577431", "0.7568987", "0.7561394", "0.75603616", "0.75493425", "0.75482476", "0.75480944", "0.7547309", "0.7534986", "0.752042", "0.7498374", "0.7494728", "0.7493648", "0.7493002", "0.74827975", "0.7478428", "0.74735904", "0.7465556", "0.74651676", "0.74651676", "0.74647945", "0.74587965", "0.74544835", "0.7453481", "0.74392265", "0.743815", "0.7427585", "0.7426448", "0.7417217", "0.74032557", "0.73793334", "0.7378858", "0.73670477", "0.73518544", "0.7346889", "0.73276776", "0.7322543", "0.7322389", "0.7320063", "0.73163813", "0.7300952", "0.72848034", "0.7282455", "0.7276353", "0.72671056", "0.7259707", "0.7253606", "0.7253606", "0.72480667", "0.72442365", "0.7230939" ]
0.7605427
46
EnvConfig returns a configuration with only values provided by environment variables
func EnvConfig() *Config { config := new(Config) config.Token = os.Getenv("MKTMPIO_TOKEN") config.URL = os.Getenv("MKTMPIO_URL") return config }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func envConfig(c *cli.Context) error {\n\tvar err error\n\n\terr = setEnvOptStr(\"DOCKER_HOST\", c.GlobalString(\"host\"))\n\terr = setEnvOptBool(\"DOCKER_TLS_VERIFY\", c.GlobalBool(\"tlsverify\"))\n\terr = setEnvOptStr(\"DOCKER_API_VERSION\", DockerAPIMinVersion)\n\n\treturn err\n}", "func (g *Generator) ConfigEnv() []string {\n\tcopy := []string{}\n\tfor _, v := range g.image.Config.Env {\n\t\tcopy = append(copy, v)\n\t}\n\treturn copy\n}", "func ConfigFromEnv() Config {\n\tdefaultEnv := func(key, def string) string {\n\t\tif val := os.Getenv(key); val != \"\" {\n\t\t\treturn val\n\t\t}\n\t\treturn def\n\t}\n\n\treturn Config{\n\t\tDailySnapshots: true,\n\t\tDatabasePath: defaultEnv(\"HIPPIAS_DB\", \"\"),\n\t\tListenPort: defaultEnv(\"HIPPIAS_PORT\", \"10100\"),\n\t\tOasisSocket: defaultEnv(\"HIPPIAS_SOCKET\", \"./internal.sock\"),\n\t\tSnapshotFrequency: 0,\n\t}\n}", "func Env() Config {\n\tif c.loaded {\n\t\treturn c\n\t}\n\n\tdebug := os.Getenv(\"DEBUG\") == \"1\"\n\tif debug {\n\t\tlog.Warning(\"DEBUG DEBUG DEBUG mode !\")\n\t}\n\n\tc = Config{\n\t\tConsumerKey: readEnvVar(\"CONSUMER_KEY\", true, \"\"),\n\t\tConsumerSecret: readEnvVar(\"CONSUMER_SECRET\", true, \"\"),\n\t\tAccessToken: readEnvVar(\"ACCESS_TOKEN\", false, \"\"),\n\t\tAccessTokenSecret: readEnvVar(\"ACCESS_TOKEN_SECRET\", false, \"\"),\n\t\tConn: readEnvVar(\"CONN\", false, \"host=/var/run/postgresql sslmode=disable user=smartwitter dbname=smartwitter password=smartwitter\"),\n\t\tAppUrl: readEnvVar(\"APP_URL\", false, \"http://localhost:3000\"),\n\t\tListenAddr: readEnvVar(\"ADDR\", false, \":9999\"),\n\t\tPublicDir: readEnvVar(\"PUBLIC\", false, \"public/\"),\n\t\tDebug: debug,\n\t\tloaded: true,\n\t}\n\n\treturn c\n}", "func CredentialsConfigEnv(own string) *CredentialsConfig {\n\tconfig := CredentialsConfig{\n\t\tAccessKey: os.Getenv(fmt.Sprint(\"aws_\", own, \"_access_key\")),\n\t\tSecretKey: os.Getenv(fmt.Sprint(\"aws_\", own, \"_secret_key\")),\n\t\tRegion: os.Getenv(fmt.Sprint(\"aws_\", own, \"_region\")),\n\t\tRoleARN: os.Getenv(fmt.Sprint(\"aws_\", own, \"_role_arn\")),\n\t\tFilename: os.Getenv(fmt.Sprint(\"aws_\", own, \"_filename\")),\n\t\tProfile: os.Getenv(fmt.Sprint(\"aws_\", own, \"_profile\")),\n\t\tToken: os.Getenv(fmt.Sprint(\"aws_\", own, \"_token\")),\n\t}\n\treturn &config\n}", "func (p *Parser) GenerateEnvConfig() []byte {\n\tvar result bytes.Buffer\n\tfor _, rule := range p.rules {\n\t\tif rule.EnvVar == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tresult.Write(rule.GenerateEnvUsage(p.cfg.WordWrap))\n\t}\n\treturn result.Bytes()\n}", "func EnvVarsConfig() Config {\n\treturn Config{\n\t\tPort: 3010,\n\t\tEnv: \"stage\",\n\t\tDatabase: EnvPostgresConfig(),\n\t}\n}", "func FromEnv() (*Configuration, error) {\n\treturn &Configuration{\n\t\tEndpoint: Endpoint(os.Getenv(\"OVH_ENDPOINT\")),\n\t\tApplicationKey: os.Getenv(\"OVH_APPLICATION_KEY\"),\n\t\tApplicationSecret: os.Getenv(\"OVH_APPLICATION_SECRET\"),\n\t\tConsumerKey: os.Getenv(\"OVH_CONSUMER_KEY\"),\n\t}, nil\n}", "func Env() (*Config, error) {\n\treturn readConfig(\"\", \"\")\n}", "func ConfigFromEnv() {\n\tDisableEmail()\n\tDisablePushover()\n\tm := mailConfig{os.Getenv(\"MAIL_SERVER\"),\n\t\tos.Getenv(\"MAIL_USER\"),\n\t\tos.Getenv(\"MAIL_PASS\"),\n\t\tos.Getenv(\"MAIL_ADDRESS\"),\n\t\tos.Getenv(\"MAIL_PORT\"),\n\t\tstrings.Split(os.Getenv(\"MAIL_TO\"), \",\"),\n\t}\n\tif validMailConfig(&m) {\n\t\tEnableEmail()\n\t}\n\n\tp := pushover.Identity{os.Getenv(\"PO_APIKEY\"),\n\t\tos.Getenv(\"PO_USER\"),\n\t}\n\tif validPushoverConfig(&p) {\n\t\tEnablePushover()\n\t}\n}", "func envWithoutExecutorConfig() (env []string) {\n\tfor _, variable := range os.Environ() {\n\t\tif !strings.HasPrefix(variable, strings.ToUpper(EnvironmentPrefix)) {\n\t\t\tenv = append(env, variable)\n\t\t} else {\n\n\t\t}\n\t}\n\treturn env\n}", "func (cfg *Config) FromEnv() error {\n\n\t//Init\n\tif cfg.VirtualCenter == nil {\n\t\tcfg.VirtualCenter = make(map[string]*VirtualCenterConfig)\n\t}\n\n\t//Globals\n\tif v := os.Getenv(\"VSPHERE_VCENTER\"); v != \"\" {\n\t\tcfg.Global.VCenterIP = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_VCENTER_PORT\"); v != \"\" {\n\t\tcfg.Global.VCenterPort = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_USER\"); v != \"\" {\n\t\tcfg.Global.User = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_PASSWORD\"); v != \"\" {\n\t\tcfg.Global.Password = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_DATACENTER\"); v != \"\" {\n\t\tcfg.Global.Datacenters = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_SECRET_NAME\"); v != \"\" {\n\t\tcfg.Global.SecretName = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_SECRET_NAMESPACE\"); v != \"\" {\n\t\tcfg.Global.SecretNamespace = v\n\t}\n\n\tif v := os.Getenv(\"VSPHERE_ROUNDTRIP_COUNT\"); v != \"\" {\n\t\ttmp, err := strconv.ParseUint(v, 10, 32)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to parse VSPHERE_ROUNDTRIP_COUNT: %s\", err)\n\t\t} else {\n\t\t\tcfg.Global.RoundTripperCount = uint(tmp)\n\t\t}\n\t}\n\n\tif v := os.Getenv(\"VSPHERE_INSECURE\"); v != \"\" {\n\t\tInsecureFlag, err := strconv.ParseBool(v)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to parse VSPHERE_INSECURE: %s\", err)\n\t\t} else {\n\t\t\tcfg.Global.InsecureFlag = InsecureFlag\n\t\t}\n\t}\n\n\tif v := os.Getenv(\"VSPHERE_API_DISABLE\"); v != \"\" {\n\t\tAPIDisable, err := strconv.ParseBool(v)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to parse VSPHERE_API_DISABLE: %s\", err)\n\t\t} else {\n\t\t\tcfg.Global.APIDisable = APIDisable\n\t\t}\n\t}\n\n\tif v := os.Getenv(\"VSPHERE_API_BINDING\"); v != \"\" {\n\t\tcfg.Global.APIBinding = v\n\t}\n\n\tif v := os.Getenv(\"VSPHERE_SECRETS_DIRECTORY\"); v != \"\" {\n\t\tcfg.Global.SecretsDirectory = v\n\t}\n\tif cfg.Global.SecretsDirectory == \"\" {\n\t\tcfg.Global.SecretsDirectory = DefaultSecretDirectory\n\t}\n\tif _, err := os.Stat(cfg.Global.SecretsDirectory); os.IsNotExist(err) {\n\t\tcfg.Global.SecretsDirectory = \"\" //Dir does not exist, set to empty string\n\t}\n\n\tif v := os.Getenv(\"VSPHERE_CAFILE\"); v != \"\" {\n\t\tcfg.Global.CAFile = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_THUMBPRINT\"); v != \"\" {\n\t\tcfg.Global.Thumbprint = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_LABEL_REGION\"); v != \"\" {\n\t\tcfg.Labels.Region = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_LABEL_ZONE\"); v != \"\" {\n\t\tcfg.Labels.Zone = v\n\t}\n\n\t//Build VirtualCenter from ENVs\n\tfor _, e := range os.Environ() {\n\t\tpair := strings.Split(e, \"=\")\n\n\t\tif len(pair) != 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tkey := pair[0]\n\t\tvalue := pair[1]\n\n\t\tif strings.HasPrefix(key, \"VSPHERE_VCENTER_\") && len(value) > 0 {\n\t\t\tid := strings.TrimPrefix(key, \"VSPHERE_VCENTER_\")\n\t\t\tvcenter := value\n\n\t\t\t_, username, errUsername := getEnvKeyValue(\"VCENTER_\"+id+\"_USERNAME\", false)\n\t\t\tif errUsername != nil {\n\t\t\t\tusername = cfg.Global.User\n\t\t\t}\n\t\t\t_, password, errPassword := getEnvKeyValue(\"VCENTER_\"+id+\"_PASSWORD\", false)\n\t\t\tif errPassword != nil {\n\t\t\t\tpassword = cfg.Global.Password\n\t\t\t}\n\t\t\t_, server, errServer := getEnvKeyValue(\"VCENTER_\"+id+\"_SERVER\", false)\n\t\t\tif errServer != nil {\n\t\t\t\tserver = \"\"\n\t\t\t}\n\t\t\t_, port, errPort := getEnvKeyValue(\"VCENTER_\"+id+\"_PORT\", false)\n\t\t\tif errPort != nil {\n\t\t\t\tport = cfg.Global.VCenterPort\n\t\t\t}\n\t\t\tinsecureFlag := false\n\t\t\t_, insecureTmp, errInsecure := getEnvKeyValue(\"VCENTER_\"+id+\"_INSECURE\", false)\n\t\t\tif errInsecure != nil {\n\t\t\t\tinsecureFlagTmp, errTmp := strconv.ParseBool(insecureTmp)\n\t\t\t\tif errTmp == nil {\n\t\t\t\t\tinsecureFlag = insecureFlagTmp\n\t\t\t\t}\n\t\t\t}\n\t\t\t_, datacenters, errDatacenters := getEnvKeyValue(\"VCENTER_\"+id+\"_DATACENTERS\", false)\n\t\t\tif errDatacenters != nil {\n\t\t\t\tdatacenters = cfg.Global.Datacenters\n\t\t\t}\n\t\t\troundtrip := DefaultRoundTripperCount\n\t\t\t_, roundtripTmp, errRoundtrip := getEnvKeyValue(\"VCENTER_\"+id+\"_ROUNDTRIP\", false)\n\t\t\tif errRoundtrip != nil {\n\t\t\t\troundtripFlagTmp, errTmp := strconv.ParseUint(roundtripTmp, 10, 32)\n\t\t\t\tif errTmp == nil {\n\t\t\t\t\troundtrip = uint(roundtripFlagTmp)\n\t\t\t\t}\n\t\t\t}\n\t\t\t_, caFile, errCaFile := getEnvKeyValue(\"VCENTER_\"+id+\"_CAFILE\", false)\n\t\t\tif errCaFile != nil {\n\t\t\t\tcaFile = cfg.Global.CAFile\n\t\t\t}\n\t\t\t_, thumbprint, errThumbprint := getEnvKeyValue(\"VCENTER_\"+id+\"_THUMBPRINT\", false)\n\t\t\tif errThumbprint != nil {\n\t\t\t\tthumbprint = cfg.Global.Thumbprint\n\t\t\t}\n\n\t\t\t_, secretName, secretNameErr := getEnvKeyValue(\"VCENTER_\"+id+\"_SECRET_NAME\", false)\n\t\t\t_, secretNamespace, secretNamespaceErr := getEnvKeyValue(\"VCENTER_\"+id+\"_SECRET_NAMESPACE\", false)\n\n\t\t\tif secretNameErr != nil || secretNamespaceErr != nil {\n\t\t\t\tsecretName = \"\"\n\t\t\t\tsecretNamespace = \"\"\n\t\t\t}\n\t\t\tsecretRef := DefaultCredentialManager\n\t\t\tif secretName != \"\" && secretNamespace != \"\" {\n\t\t\t\tsecretRef = vcenter\n\t\t\t}\n\n\t\t\tiPFamilyPriority := []string{DefaultIPFamily}\n\t\t\t_, ipFamily, errIPFamily := getEnvKeyValue(\"VCENTER_\"+id+\"_IP_FAMILY\", false)\n\t\t\tif errIPFamily != nil {\n\t\t\t\tiPFamilyPriority = []string{ipFamily}\n\t\t\t}\n\n\t\t\t// If server is explicitly set, that means the vcenter value above is the TenantRef\n\t\t\tvcenterIP := vcenter\n\t\t\ttenantRef := vcenter\n\t\t\tif server != \"\" {\n\t\t\t\tvcenterIP = server\n\t\t\t\ttenantRef = vcenter\n\t\t\t}\n\n\t\t\tvar vcc *VirtualCenterConfig\n\t\t\tif cfg.VirtualCenter[tenantRef] != nil {\n\t\t\t\tvcc = cfg.VirtualCenter[tenantRef]\n\t\t\t} else {\n\t\t\t\tvcc = &VirtualCenterConfig{}\n\t\t\t\tcfg.VirtualCenter[tenantRef] = vcc\n\t\t\t}\n\n\t\t\tvcc.User = username\n\t\t\tvcc.Password = password\n\t\t\tvcc.TenantRef = tenantRef\n\t\t\tvcc.VCenterIP = vcenterIP\n\t\t\tvcc.VCenterPort = port\n\t\t\tvcc.InsecureFlag = insecureFlag\n\t\t\tvcc.Datacenters = datacenters\n\t\t\tvcc.RoundTripperCount = roundtrip\n\t\t\tvcc.CAFile = caFile\n\t\t\tvcc.Thumbprint = thumbprint\n\t\t\tvcc.SecretRef = secretRef\n\t\t\tvcc.SecretName = secretName\n\t\t\tvcc.SecretNamespace = secretNamespace\n\t\t\tvcc.IPFamilyPriority = iPFamilyPriority\n\t\t}\n\t}\n\n\treturn nil\n}", "func ConfigurationWithEnv() {\n\n\t//Service Configuration\n\tConf.Service.Environment = os.Getenv(\"ENVIRONMENT\")\n\tConf.Service.Build = os.Getenv(\"BUILD_IMAGE\")\n\tConf.Service.RepoURL = os.Getenv(\"REPO_URL_OF_SCRIPT\")\n\tConf.Service.RepoPrivateKey = os.Getenv(\"PRIVATE_KEY_OF_REPO\")\n\n\tConf.NatsServer.Subject = os.Getenv(\"SCRIPT_NAME\")\n\n\t//nats server\n\tConf.NatsServer.URL = os.Getenv(\"NATS_URL\")\n\tConf.NatsServer.Token = os.Getenv(\"NATS_TOKEN\")\n\tConf.NatsServer.Username = os.Getenv(\"NATS_USERNAME\")\n\tConf.NatsServer.Password = os.Getenv(\"NATS_PASSWORD\")\n\tlog.Println(Conf)\n\n}", "func (c *Config) GetByENV() {\n\t// port\n\tif val, ok := os.LookupEnv(\"PORT\"); ok {\n\t\tif Num, err := strconv.Atoi(val); err == nil {\n\t\t\tc.Port = Num\n\t\t}\n\t}\n\t// mssql\n\tc.Mssql.Port = 1433 // default\n\n\tif val, ok := os.LookupEnv(\"MSSQL_HOST\"); ok {\n\t\tc.Mssql.Host = val\n\t}\n\tif val, ok := os.LookupEnv(\"MSSQL_DB\"); ok {\n\t\tc.Mssql.Database = val\n\t}\n\tif val, ok := os.LookupEnv(\"MSSQL_USERNAME\"); ok {\n\t\tc.Mssql.Username = val\n\t}\n\tif val, ok := os.LookupEnv(\"MSSQL_PASSWORD\"); ok {\n\t\tc.Mssql.Password = val\n\t}\n\n\t// mongo\n\tif val, ok := os.LookupEnv(\"MONGO_HOST\"); ok {\n\t\tc.Mongodb.Host = val\n\t}\n\tif val, ok := os.LookupEnv(\"MONGO_DB\"); ok {\n\t\tc.Mongodb.Database = val\n\t}\n\tif val, ok := os.LookupEnv(\"MONGO_USERNAME\"); ok {\n\t\tc.Mongodb.Username = val\n\t}\n\tif val, ok := os.LookupEnv(\"MONGO_PASSWORD\"); ok {\n\t\tc.Mongodb.Password = val\n\t}\n}", "func EnvConfig() Config {\n\tport := getenvOrElse(\"PORT\", \"3000\")\n\taddr := getenvOrElse(\"ADDR\", \"127.0.0.1\")\n\n\treturn Config{\n\t\tPort: port,\n\t\tAddr: addr,\n\t}\n}", "func ConfigEnv() Config {\n\treturn Config{\n\t\tUser: os.Getenv(\"POSTGRES_USER\"),\n\t\tPass: os.Getenv(\"POSTGRES_PASS\"),\n\t\tHost: os.Getenv(\"POSTGRES_HOST\"),\n\t\tDatabaseName: os.Getenv(\"POSTGRES_DATABASE\"),\n\t\tPort: os.Getenv(\"POSTGRES_PORT\"),\n\t\t// The default SSL mode is \"disable\", ex: \"verify-full\"\n\t\tSSLMode: os.Getenv(\"POSTGRES_SSL_MODE\"),\n\t\t// The default maxLifetime = 0, Connections are reused forever, ex: \"60\"\n\t\tMaxLifetime: os.Getenv(\"POSTGRES_MAX_LIFETIME\"),\n\t\t// The default maxIdleConns = 2, ex: 10\n\t\tMaxIdleConns: os.Getenv(\"POSTGRES_MAX_IDLE_CONNS\"),\n\t\t// The default is 0 (unlimited), ex: 1000\n\t\tMaxOpenConns: os.Getenv(\"POSTGRES_MAX_OPEN_CONNS\"),\n\t}\n}", "func ConfigFromEnv() Config {\n\treturn Config{\n\t\tServerPort: getEnvOrElse(\"SERVER_PORT\", \"8080\"),\n\t\tDBPort: getEnvOrElse(\"DB_PORT\", \"28015\"),\n\t\tDBHost: getEnvOrElse(\"DB_HOST\", \"localhost\"),\n\t\tDBName: getEnvOrElse(\"DB_NAME\", \"been_there\"),\n\t\tVisitsTable: getEnvOrElse(\"VISITS_TABLE\", \"visits\"),\n\t\tCitiesTable: getEnvOrElse(\"CITIES_TABLE\", \"cities\"),\n\t}\n}", "func ConfigFromEnv(set *flag.FlagSet) error {\n\tvar errs []string\n\tset.VisitAll(func(f *flag.Flag) {\n\t\tval := os.Getenv(f.Name)\n\t\tif val == \"\" {\n\t\t\terrs = append(errs, fmt.Sprintf(\"env variable %s missing\", f.Name))\n\t\t\treturn\n\t\t}\n\t\tif err := f.Value.Set(val); err != nil {\n\t\t\terrs = append(errs, fmt.Sprintf(\"failed to set flag %q with value %q - %s\\n\", f.Name, val, err))\n\n\t\t}\n\t})\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(strings.Join(errs, \", \"))\n\t}\n\treturn nil\n}", "func Environ() (Config, error) {\n\tcfg := Config{}\n\terr := envconfig.Process(\"\", &cfg)\n\tdefaultAddress(&cfg)\n\tdefaultProxy(&cfg)\n\tdefaultRunner(&cfg)\n\tdefaultSession(&cfg)\n\tdefaultCallback(&cfg)\n\tconfigureGithub(&cfg)\n\tif err := kubernetesServiceConflict(&cfg); err != nil {\n\t\treturn cfg, err\n\t}\n\treturn cfg, err\n}", "func (em *envMap) Config() (map[string]interface{}, error) {\n\tif em.emap == nil {\n\t\tem.emap = em.getenvironment(os.Environ(), func(item string) (key, val string) {\n\t\t\tsplits := strings.Split(item, \"=\")\n\n\t\t\t// allow dot representation, eg \"sever__port\" => \"server.port\"\n\t\t\tkey = strings.Replace(splits[0], em.dotAlias, \".\", -1)\n\t\t\tval = strings.Join(splits[1:], \"=\")\n\t\t\treturn\n\t\t})\n\t}\n\treturn em.emap, nil\n}", "func ConfigFromEnv() (Config, bool) {\n\t//unless affirmatively set assume that they have the improved firmware with the bug around variables\n\timproved := strings.ToLower(strings.TrimSpace(os.Getenv(ImprovedFirmwareEnv))) != \"false\"\n\n\tfilter := BadResponseVariables\n\tif improved {\n\t\tfilter = NoFilter\n\t}\n\n\tconfig := Config{\n\t\tLocation: os.Getenv(LocationEnv),\n\t\tUser: os.Getenv(UserEnv),\n\t\tpassword: os.Getenv(PasswordEnv),\n\n\t\tImprovedFirmware: improved,\n\n\t\tFilter: filter,\n\n\t\tModelIDForMeter: strings.TrimSpace(os.Getenv(MeterModelIDEnv)),\n\n\t\tDebugRequest: strings.TrimSpace(os.Getenv(DebugRequestEnv)) == \"true\",\n\t\tDebugResponse: strings.TrimSpace(os.Getenv(DebugResponseEnv)) == \"true\",\n\t}\n\n\treturn config, ConfigOK(config)\n}", "func getConfig(envVars []string) (value string) {\n\tvalue = \"\"\n\tfor _, v := range envVars {\n\t\tvalue = os.Getenv(v)\n\t\tif value != \"\" {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn\n}", "func GetConfigFromEnv() *Config {\n\tconfig := &Config{HTTPPort, LNDHost, LNDPort, MACPath, TLSCertPath}\n\n\tif _, present := os.LookupEnv(\"HTTP_PORT\"); present {\n\t\tconfig.HTTPPort = os.Getenv(\"HTTP_PORT\")\n\t}\n\n\tif _, present := os.LookupEnv(\"LND_PORT\"); present {\n\t\tconfig.LNDPort = os.Getenv(\"LND_PORT\")\n\t}\n\n\tif _, present := os.LookupEnv(\"LND_HOST\"); present {\n\t\tconfig.LNDHost = os.Getenv(\"LND_HOST\")\n\t}\n\n\tif _, present := os.LookupEnv(\"TLS_PATH\"); present {\n\t\tconfig.TLSCertPath = os.Getenv(\"TLS_PATH\")\n\t}\n\n\tif _, present := os.LookupEnv(\"MAC_PATH\"); present {\n\t\tconfig.MACPath = os.Getenv(\"MAC_PATH\")\n\t}\n\n\treturn config\n\n}", "func ConfigFromEnv(l models.Logger) *Config {\n\tif l == nil {\n\t\tl = models.StdLogger\n\t}\n\n\tconfig := &Config{Log: l}\n\n\tredisURL := os.Getenv(\"REDIS_URL\")\n\tif redisURL == \"\" {\n\t\tredisURL = \"127.0.0.1:6379\"\n\t}\n\tconfig.ServerURL = redisURL\n\treturn config\n}", "func (s) TestBothConfigEnvVarsSet(t *testing.T) {\n\tinvalidConfig := &config{\n\t\tProjectID: \"fake\",\n\t\tCloudLogging: &cloudLogging{\n\t\t\tClientRPCEvents: []clientRPCEvents{\n\t\t\t\t{\n\t\t\t\t\tMethods: []string{\":-)\"},\n\t\t\t\t\tMaxMetadataBytes: 30,\n\t\t\t\t\tMaxMessageBytes: 30,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tinvalidConfigJSON, err := json.Marshal(invalidConfig)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to convert config to JSON: %v\", err)\n\t}\n\tcleanup, err := createTmpConfigInFileSystem(string(invalidConfigJSON))\n\tdefer cleanup()\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create config in file system: %v\", err)\n\t}\n\t// This configuration should be ignored, as precedence 2.\n\tvalidConfig := &config{\n\t\tProjectID: \"fake\",\n\t\tCloudLogging: &cloudLogging{\n\t\t\tClientRPCEvents: []clientRPCEvents{\n\t\t\t\t{\n\t\t\t\t\tMethods: []string{\"*\"},\n\t\t\t\t\tMaxMetadataBytes: 30,\n\t\t\t\t\tMaxMessageBytes: 30,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tvalidConfigJSON, err := json.Marshal(validConfig)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to convert config to JSON: %v\", err)\n\t}\n\toldObservabilityConfig := envconfig.ObservabilityConfig\n\tenvconfig.ObservabilityConfig = string(validConfigJSON)\n\tdefer func() {\n\t\tenvconfig.ObservabilityConfig = oldObservabilityConfig\n\t}()\n\tif err := Start(context.Background()); err == nil {\n\t\tt.Fatalf(\"Invalid patterns not triggering error\")\n\t}\n}", "func GetFromEnv() *Config {\n\tv := viper.New()\n\tv.SetDefault(DomainSuffix, \".docker.\")\n\tv.SetDefault(ServerHost, \"0.0.0.0\")\n\tv.SetDefault(ServerPort, 5300)\n\tv.SetDefault(ServerProtocol, \"udp\")\n\n\tv.AutomaticEnv()\n\n\treturn &Config{\n\t\tDomainSuffix: v.GetString(DomainSuffix),\n\t\tServerHost: v.GetString(ServerHost),\n\t\tServerPort: v.GetInt(ServerPort),\n\t\tServerProtocol: v.GetString(ServerProtocol),\n\t}\n}", "func (c *Configuration) FromEnv() {\n\tif api := getOSPrefixEnv(\"API\"); api != nil {\n\t\tc.APIListener = *api\n\t}\n\n\tif httpListener := getOSPrefixEnv(\"HTTP\"); httpListener != nil {\n\t\tc.HTTPListener = *httpListener\n\t}\n\n\tif httpsListener := getOSPrefixEnv(\"HTTPS\"); httpsListener != nil {\n\t\tc.HTTPSListener = *httpsListener\n\t}\n\n\tif dbEndpoint := getOSPrefixEnv(\"DB_ENDPOINT\"); dbEndpoint != nil {\n\t\tc.DynamoDB.Endpoint = *dbEndpoint\n\t}\n\n\tif dbRegion := getOSPrefixEnv(\"DB_REGION\"); dbRegion != nil {\n\t\tc.DynamoDB.Region = *dbRegion\n\t}\n\n\tif dbKey := getOSPrefixEnv(\"DB_KEY\"); dbKey != nil {\n\t\tif dbSecret := getOSPrefixEnv(\"DB_SECRET\"); dbSecret != nil {\n\t\t\tc.DynamoDB.Key = *dbKey\n\t\t\tc.DynamoDB.Secret = *dbSecret\n\t\t}\n\t}\n\n\tif dbBootstrap := getOSPrefixEnv(\"BOOTSTRAP\"); dbBootstrap != nil {\n\t\tc.Bootstrap = len(*dbBootstrap) > 0 && *dbBootstrap != \"0\"\n\t}\n\n\tif logLevel := getOSPrefixEnv(\"LOG_LEVEL\"); logLevel != nil {\n\t\tc.LogLevel = *logLevel\n\t}\n\n\tif logFormatter := getOSPrefixEnv(\"LOG_FORMATTER\"); logFormatter != nil {\n\t\tc.LogFormatter = *logFormatter\n\t}\n}", "func setupEnvConfigViper(environmentFlag string) *viper.Viper {\n\tconfig := viper.New()\n\tconfig.SetConfigName(environmentFlag)\n\tconfig.AddConfigPath(\"./.argo/environments\")\n\tif err := config.ReadInConfig(); err != nil {\n\t\tcolor.Red(\"%s\",err)\n\t\tcolor.Red(\"Error locating or parsing %s env's helm value file (should be ./argo/environments/%s.yaml!\", environmentFlag)\n\t\tos.Exit(1)\n\t}\n\treturn config\n}", "func configFromEnvOrSim(multiDc bool) (*vcfg.Config, func()) {\n\tcfg, fin := configFromSim(multiDc)\n\tif err := cfg.FromEnv(); err != nil {\n\t\treturn nil, nil\n\t}\n\treturn cfg, fin\n}", "func TestGetConfigEnvVars(t *testing.T) {\n\tdefer clearEnvs()\n\tos.Setenv(\"ENV_SET\", \"TRUE\")\n\tos.Setenv(\"MAX_DECK_SIZE\", \"5\")\n\tos.Setenv(\"MAX_SHUFFLES\", \"100\")\n\tos.Setenv(\"PRINT_EVERY\", \"1000\")\n\tos.Setenv(\"START_DECK_SIZE\", \"5\")\n\tos.Setenv(\"VERBOSE\", \"false\")\n\n\tconf := getConfig()\n\tassert.Equal(t, conf.maxDeckSize, 5)\n\tassert.Equal(t, conf.maxShuffles, 100)\n\tassert.Equal(t, conf.printEvery, 1000)\n\tassert.Equal(t, conf.startDeckSize, 5)\n\tassert.Equal(t, conf.verbose, false)\n}", "func Environ() (Config, error) {\n\tcfg := Config{}\n\terr := envconfig.Process(\"\", &cfg)\n\tdefualtAddr(&cfg)\n\treturn cfg, err\n}", "func GetConfigs() *Configs {\n\tconfig := Configs{}\n\n\tv := viper.New()\n\n\tif _, err := os.Stat(\".env\"); os.IsNotExist(err) {\n\t\tv.AutomaticEnv()\n\t} else {\n\t\tv.SetConfigType(\"dotenv\")\n\t\tv.SetConfigFile(\".env\")\n\t\terr := v.ReadInConfig()\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"fail to read dotenv file:%s\", err.Error())\n\t\t}\n\t}\n\n\tv.SetDefault(EnvDeploy, EnvDeployDebug)\n\tv.SetDefault(EnvSecretKey, \"e190ufqe2\")\n\tv.SetDefault(EnvKubernetesNamespace, \"jupy\")\n\tv.SetDefault(EnvKubernetesCreateNamespaceIfNotPresent, false)\n\tv.SetDefault(EnvDatabaseSalt, \"ab448a918\")\n\n\tv.SetDefault(EnvQuotaInstance, -1)\n\tv.SetDefault(EnvQuotaCpu, -1)\n\tv.SetDefault(EnvQuotaMemory, -1)\n\tv.SetDefault(EnvQuotaNvidiaGpu, -1)\n\tv.SetDefault(EnvQuotaStorage, -1)\n\n\tv.SetDefault(EnvDomainUpper, \"\")\n\tv.SetDefault(EnvDomainPrefix, \"\")\n\n\t//\n\tconfig.Deploy = v.GetString(EnvDeploy)\n\tconfig.SecretKey = v.GetString(EnvSecretKey)\n\tconfig.Kubernetes.Namespace = v.GetString(EnvKubernetesNamespace)\n\tconfig.Kubernetes.CreateNamespaceIfNotPresent = v.GetBool(EnvKubernetesCreateNamespaceIfNotPresent)\n\n\tconfig.Database.URI = v.GetString(EnvDatabaseURI)\n\tconfig.Database.Salt = v.GetString(EnvDatabaseSalt)\n\n\tconfig.Quota.Instance = v.GetInt(EnvQuotaInstance)\n\tconfig.Quota.Cpu = v.GetInt(EnvQuotaCpu)\n\tconfig.Quota.Memory = v.GetInt(EnvQuotaMemory)\n\tconfig.Quota.NvidiaGpu = v.GetInt(EnvQuotaNvidiaGpu)\n\tconfig.Quota.Storage = v.GetInt(EnvQuotaStorage)\n\n\tconfig.Domain.Upper = v.GetString(EnvDomainUpper)\n\tconfig.Domain.Prefix = v.GetString(EnvDomainPrefix)\n\n\treturn &config\n}", "func loadEnvironmentConfig(env string) types.Options {\n\tconfigFile := \"config/\" + ServiceName + \"/\" + env + \".json\"\n\tif _, err := os.Stat(configFile); os.IsNotExist(err) {\n\t\tpanic(err)\n\t}\n\treturn parseConfigFile(configFile)\n}", "func loadConfigFromEnvironment(appConfig *configuration) {\n\tserver, ok := os.LookupEnv(\"CINEMA_MOVIES\")\n\tif ok {\n\t\tappConfig.Server = server\t\n\t\tlog.Printf(\"[INFO]: Server information loaded from env.\")\n\t}\n\t\n\tmongodbHost, ok := os.LookupEnv(\"MONGODB_HOST\")\n\tif ok {\n\t\tappConfig.MongoDBHost = mongodbHost\t\n\t\tlog.Printf(\"[INFO]: MongoDB host information loaded from env.\")\n\t}\n\t\n\tmongodbUser, ok := os.LookupEnv(\"MONGODB_USER\")\n\tif ok {\n\t\tappConfig.DBUser = mongodbUser\n\t\tlog.Printf(\"[INFO]: MongoDB user information loaded from env.\")\n\t}\n\t\n\tmongodbPwd, ok := os.LookupEnv(\"MONGODB_PWD\")\n\tif ok {\n\t\tappConfig.DBPwd = mongodbPwd\n\t\tlog.Printf(\"[INFO]: MongoDB password information loaded from env.\")\n\t}\n\t\n\tdatabase, ok := os.LookupEnv(\"MONGODB_DATABASE\")\n\tif ok {\n\t\tappConfig.Database = database\n\t\tlog.Printf(\"[INFO]: MongoDB database information loaded from env.\")\n\t}\n}", "func GetConfig(mode string) Configuration {\n var ret Configuration\n \n // Anthing other than \"prod\" results in test env\n if (mode == \"prod\") {\n // Set defaults for prod\n ret.Username = os.Getenv(\"nameuser\")\n ret.Token = os.Getenv(\"nametoken\")\n ret.BaseURL = \"https://api.name.com/v4\"\n ret.Debug = false\n } else {\n // Set defaults for test\n ret.Username = os.Getenv(\"nametestuser\")\n ret.Token = os.Getenv(\"nametesttoken\")\n ret.BaseURL = \"https://api.dev.name.com/v4\"\n ret.Debug = true\n }\n \n return ret\n}", "func NewEnvConfig(filepathList ...string) *EnvConfig {\n\tif len(filepathList) > 0 {\n\t\tif err := godotenv.Load(filepathList...); err != nil {\n\t\t\tpanic(fmt.Sprintf(\"failed to load .env files. %v\", filepathList))\n\t\t}\n\t}\n\treturn &EnvConfig{}\n}", "func Config() (*Configuration, error) {\n\n\t// viper config/env key replacer configuration\n\tviper.AutomaticEnv()\n\tviper.SetEnvKeyReplacer(strings.NewReplacer(\".\", \"_\"))\n\n\t// Bind viper keys to env vars\n\tfor _, v := range envVars {\n\t\tif err := viper.BindEnv(v); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// unmarshall the configuration structure\n\tvar config Configuration\n\tif err := viper.Unmarshal(&config); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// set env config. file name, type and path\n\tviper.SetConfigName(\".env\")\n\tviper.SetConfigType(\"env\")\n\tviper.AddConfigPath(\".\")\n\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := viper.Unmarshal(&config); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// set every one of env variables into os\n\tfor _, v := range envVars {\n\t\tos.Setenv(v, viper.GetString(v))\n\t}\n\n\treturn &config, nil\n}", "func (c *Config) Env() map[string]interface{} {\r\n\tc.mu.Lock()\r\n\tdefer c.mu.Unlock()\r\n\r\n\treturn cloneMap(c.env)\r\n}", "func (r *Reader) getProvidersFromEnv(filePath string) (\n\tproviders []provider.Provider, warnings []string, err error) {\n\ts := os.Getenv(\"CONFIG\")\n\tif s == \"\" {\n\t\treturn nil, nil, nil\n\t}\n\tr.logger.Info(\"reading JSON config from environment variable CONFIG\")\n\tr.logger.Debug(\"config read: \" + s)\n\n\tb := []byte(s)\n\n\tproviders, warnings, err = extractAllSettings(b)\n\tif err != nil {\n\t\treturn providers, warnings, fmt.Errorf(\"configuration given: %w\", err)\n\t}\n\n\tbuffer := bytes.NewBuffer(nil)\n\terr = json.Indent(buffer, b, \"\", \" \")\n\tif err != nil {\n\t\treturn providers, warnings, fmt.Errorf(\"%w: %w\", errWriteConfigToFile, err)\n\t}\n\tconst mode = fs.FileMode(0600)\n\terr = r.writeFile(filePath, buffer.Bytes(), mode)\n\tif err != nil {\n\t\treturn providers, warnings, fmt.Errorf(\"%w: %w\", errWriteConfigToFile, err)\n\t}\n\n\treturn providers, warnings, nil\n}", "func MustEnv() *Config {\n\tconf, err := Env()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn conf\n}", "func TestConfigOrSkip(t testing.TB) Config {\n\tconfig, ok := ConfigFromEnv()\n\tif !ok {\n\t\tt.Skipf(\"Skipping because one or more of [%v, %v, %v] is not set\", LocationEnv, UserEnv, PasswordEnv)\n\t}\n\n\treturn config\n}", "func setupEnv() config.Config {\n\trequiredEnvVars := []string {\n\t\tconfig.EnvURL,\n\t\tconfig.EnvPort,\n\t}\n\n\tfor _, key := range requiredEnvVars {\n\t\t_, exists := os.LookupEnv(key)\n\t\tif !exists {\n\t\t\tfmt.Printf(\"Environment mismatch. Missing required: %s\\n\", key)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\tclientURL := os.Getenv(config.EnvURL)\n\tport := os.Getenv(config.EnvPort)\n\n\treturn config.Config{MemDBSchema: config.DBSchema, SSEServerUrl: clientURL, PORT: port}\n}", "func loadEnv() Configuration {\n\thistorySize := 10\n\thistorySizeStr := os.Getenv(\"HISTORY_SIZE\")\n\tif historySizeStr != \"\" {\n\t\thistorySize , _ = strconv.Atoi(historySizeStr)\n\t}\n\tthreads := 10\n\tthreadsStr := os.Getenv(\"THREADS\")\n\tif threadsStr != \"\" {\n\t\tthreads, _ = strconv.Atoi(threadsStr)\n\t}\n\tserverUrl := os.Getenv(\"SERVER_URL\")\n\tif serverUrl == \"\" {\n\t\tserverUrl = \":9000\"\n\t}\n\tclientUrl := os.Getenv(\"CLIENT_URL\")\n\tif clientUrl == \"\" {\n\t\tclientUrl = \":9001\"\n\t}\n\treturn Configuration{\n\t\tHistorySize: historySize,\n\t\tClientUrl: clientUrl,\n\t\tServerUrl: serverUrl,\n\t\tThreads: threads}\n}", "func environment(prefix string) map[string]string {\n\tenv := make(map[string]string)\n\tfor _, setting := range os.Environ() {\n\t\tpair := strings.SplitN(setting, \"=\", 2)\n\t\tif strings.HasPrefix(pair[0], prefix) {\n\t\t\tenv[pair[0]] = pair[1]\n\t\t}\n\t}\n\treturn env\n}", "func environment(prefix string) map[string]string {\n\tenv := make(map[string]string)\n\tfor _, setting := range os.Environ() {\n\t\tpair := strings.SplitN(setting, \"=\", 2)\n\t\tif strings.HasPrefix(pair[0], prefix) {\n\t\t\tenv[pair[0]] = pair[1]\n\t\t}\n\t}\n\treturn env\n}", "func Env() string {\n\treturn AppConfig.Env\n}", "func envList(key, def string) []string {\n\tv := os.Getenv(key)\n\tif v == \"\" {\n\t\tv = def\n\t}\n\treturn strings.Fields(v)\n}", "func ReadConfigFromEnv() *Config {\n\tvar c = Config{\n\t\tPort: SafeStringToInt(os.Getenv(\"PORT\"), 8080),\n\t\tHost: os.Getenv(\"HOST\"),\n\t\tMongoDbDatabase: os.Getenv(\"MONGO_DB_DATABASE\"),\n\t\tMongoDbURI: os.Getenv(\"MONGO_DB_URI\"),\n\t}\n\treturn &c\n}", "func GetCommonEnvironmentConfigurations() map[string]string {\n\n\tenvs := make(map[string]string)\n\tenvs[\"PATH\"], envs[\"USERNAME\"] = os.Getenv(\"PATH\"), os.Getenv(\"USERNAME\")\n\treturn envs\n}", "func env(key string, defaultValue string) string {\n\tvalue := os.Getenv(key)\n\n\tif len(value) > 0 {\n\t\treturn value\n\t}\n\treturn defaultValue\n\n}", "func initConfig() {\n\tviper.AutomaticEnv() // read in environment variables that match\n}", "func buildEnvironment(env []string) (map[string]string, error) {\n result := make(map[string]string, len(env))\n for _, s := range env {\n // if value is empty, s is like \"K=\", not \"K\".\n if !strings.Contains(s, \"=\") {\n return result, errors.Errorf(\"unexpected environment %q\", s)\n }\n kv := strings.SplitN(s, \"=\", 2)\n result[kv[0]] = kv[1]\n }\n return result, nil\n}", "func envOverride(config *DefaultConfig) (*DefaultConfig, error) {\n\t// override UpdateTime\n\tupdateTime := os.Getenv(\"XIGNITE_FEEDER_UPDATE_TIME\")\n\tif updateTime != \"\" {\n\t\tt, err := time.Parse(ctLayout, updateTime)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tconfig.UpdateTime = t\n\t}\n\n\t// override APIToken\n\tapiToken := os.Getenv(\"XIGNITE_FEEDER_API_TOKEN\")\n\tif apiToken != \"\" {\n\t\tconfig.APIToken = apiToken\n\t}\n\n\t// override NotQuoteSymbolList\n\tnotQuoteStockList := os.Getenv(\"XIGNITE_FEEDER_NOT_QUOTE_STOCK_LIST\")\n\tif notQuoteStockList != \"\" {\n\t\tconfig.NotQuoteStockList = strings.Split(notQuoteStockList, \",\")\n\t}\n\n\treturn config, nil\n}", "func loadFromEnvvar() (*Config, error) {\n\t// App\n\tappServerPort, _ := strconv.Atoi(GetEnvOrDef(\"POSLAN_SERVER_PORT\", \"8080\"))\n\tappLogLevel := GetEnvOrDef(\"POSLAN_LOG_LEVEL\", \"debug\")\n\tproviders := loadProvidersFromEnvars()\n\n\tapp := AppConfig{\n\t\tServerPort: appServerPort,\n\t\tLogLevel: logLevel(appLogLevel),\n\t}\n\n\tmailers := MailerConfig{\n\t\tProviders: providers,\n\t}\n\n\tcfg := &Config{\n\t\tApp: app,\n\t\tMailer: mailers,\n\t}\n\n\treturn cfg, nil\n}", "func NewConfigFromEnv() Config {\n\treturn Config{\n\t\tPort: os.Getenv(EnvPort),\n\t\tDSN: os.Getenv(EnvDSN),\n\t}\n}", "func getEnvConfigSettings(envName *string, appName *string, sess *session.Session) []*elasticbeanstalk.ConfigurationSettingsDescription {\n\tsvc := elasticbeanstalk.New(sess, aws.NewConfig())\n\tinput := &elasticbeanstalk.DescribeConfigurationSettingsInput{\n\t\tApplicationName: appName,\n\t\tEnvironmentName: envName,\n\t}\n\tres, err := svc.DescribeConfigurationSettings(input)\n\tutils.CheckErr(err)\n\treturn res.ConfigurationSettings\n}", "func Config() map[string]string {\n\n\tsetEnv()\n\n\tcfg := make(map[string]string)\n\n\tcfg[\"MYSQL_DB_ENDPOINT\"] = os.Getenv(\"MYSQL_DB_ENDPOINT\")\n\tcfg[\"MYSQL_DB_PORT\"] = os.Getenv(\"MYSQL_DB_PORT\")\n\tcfg[\"MYSQL_DB_SCHEMA\"] = os.Getenv(\"MYSQL_DB_SCHEMA\")\n\tcfg[\"MYSQL_DB_USER\"] = os.Getenv(\"MYSQL_DB_USER\")\n\tcfg[\"MYSQL_DB_PASSWORD\"] = os.Getenv(\"MYSQL_DB_PASSWORD\")\n\n\treturn cfg\n}", "func FromEnv() (*Configuration, error) {\n\tc := &Configuration{}\n\treturn c.FromEnv()\n}", "func ApplyEnvironment(prefix string, cfg interface{}) error {\n\tc := cfg.(*Config)\n\tfor _, val := range []struct {\n\t\ts *string\n\t\tenv string\n\t}{\n\t\t// v2/v3 specific\n\t\t{&c.UserName, prefix + \"OS_USERNAME\"},\n\t\t{&c.APIKey, prefix + \"OS_PASSWORD\"},\n\t\t{&c.Region, prefix + \"OS_REGION_NAME\"},\n\t\t{&c.AuthURL, prefix + \"OS_AUTH_URL\"},\n\n\t\t// v3 specific\n\t\t{&c.Domain, prefix + \"OS_USER_DOMAIN_NAME\"},\n\t\t{&c.Tenant, prefix + \"OS_PROJECT_NAME\"},\n\t\t{&c.TenantDomain, prefix + \"OS_PROJECT_DOMAIN_NAME\"},\n\n\t\t// v2 specific\n\t\t{&c.TenantID, prefix + \"OS_TENANT_ID\"},\n\t\t{&c.Tenant, prefix + \"OS_TENANT_NAME\"},\n\n\t\t// v1 specific\n\t\t{&c.AuthURL, prefix + \"ST_AUTH\"},\n\t\t{&c.UserName, prefix + \"ST_USER\"},\n\t\t{&c.APIKey, prefix + \"ST_KEY\"},\n\n\t\t// Application Credential auth\n\t\t{&c.ApplicationCredentialID, prefix + \"OS_APPLICATION_CREDENTIAL_ID\"},\n\t\t{&c.ApplicationCredentialName, prefix + \"OS_APPLICATION_CREDENTIAL_NAME\"},\n\t\t{&c.ApplicationCredentialSecret, prefix + \"OS_APPLICATION_CREDENTIAL_SECRET\"},\n\n\t\t// Manual authentication\n\t\t{&c.StorageURL, prefix + \"OS_STORAGE_URL\"},\n\t\t{&c.AuthToken, prefix + \"OS_AUTH_TOKEN\"},\n\n\t\t{&c.DefaultContainerPolicy, prefix + \"SWIFT_DEFAULT_CONTAINER_POLICY\"},\n\t} {\n\t\tif *val.s == \"\" {\n\t\t\t*val.s = os.Getenv(val.env)\n\t\t}\n\t}\n\treturn nil\n}", "func (e envoyBootstrapArgs) env(env []string) []string {\n\tif v := e.consulConfig.Auth; v != \"\" {\n\t\tenv = append(env, fmt.Sprintf(\"%s=%s\", \"CONSUL_HTTP_AUTH\", v))\n\t}\n\tif v := e.consulConfig.SSL; v != \"\" {\n\t\tenv = append(env, fmt.Sprintf(\"%s=%s\", \"CONSUL_HTTP_SSL\", v))\n\t}\n\tif v := e.consulConfig.VerifySSL; v != \"\" {\n\t\tenv = append(env, fmt.Sprintf(\"%s=%s\", \"CONSUL_HTTP_SSL_VERIFY\", v))\n\t}\n\tif v := e.namespace; v != \"\" {\n\t\tenv = append(env, fmt.Sprintf(\"%s=%s\", \"CONSUL_NAMESPACE\", v))\n\t}\n\treturn env\n}", "func ConfigFromEnv() (*Config, error) {\n\tvar cfg Config\n\tif err := babyenv.Parse(&cfg); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &cfg, nil\n}", "func ParseEnvironmentConfig() Configuration {\n\tmySession := session.Must(session.NewSession())\n\tsvc := ssm.New(mySession)\n\tparameter, err := svc.GetParameter(&ssm.GetParameterInput{\n\t\tName: aws.String(os.Getenv(\"API_TOKEN_PARAMETER\")),\n\t\tWithDecryption: aws.Bool(true),\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tconfiguration := Configuration{\n\t\tToken: *parameter.Parameter.Value,\n\t\tStartDate: time.Now(),\n\t\tEndDate: time.Now(),\n\t}\n\treturn configuration\n}", "func Get() (*Config, error) {\n\tcfg := &Config{}\n\tgoenv.StringVar(&cfg.TEST, TESTEnvName, \"value for test\")\n\tgoenv.IntVar(&cfg.TEST2, TEST2EnvName, 123)\n\tgoenv.DurationVar(&cfg.TEST3, TEST3EnvName, 5*time.Second)\n\n\t//goenv.Parse()\n\t//if cfg.Mongo.URL == \"\" {\n\t//\treturn nil, fmt.Errorf(\"could not set %s\", DBConnStrEnvName)\n\t//}\n\treturn cfg, nil\n}", "func Cfg(v *viper.Viper) *zap.Config {\n\tswitch environment := v.GetString(\"environment\"); environment {\n\tcase \"dev\":\n\t\treturn devZapConfig()\n\tdefault:\n\t\treturn productionZapConfig()\n\t}\n}", "func LoadConfigFromEnv() Config {\n\tvar gcp Config\n\tconfig.LoadEnvConfig(&gcp)\n\treturn gcp\n}", "func env() *awscdk.Environment {\n\treturn &awscdk.Environment{\n\t Account: aws.String(os.Getenv(\"CDK_DEFAULT_ACCOUNT\")),\n\t Region: aws.String(os.Getenv(\"CDK_DEFAULT_REGION\")),\n\t}\n}", "func FromEnv(prefix string) (Config, error) {\n\treturn &envConfig{\n\t\tprefix: prefix,\n\t\tlookup: os.LookupEnv,\n\t\tconvert: DotToSnake,\n\t}, nil\n}", "func (config *Configuration) GetEnvConfString(key string) string {\n\treturn config.v.GetString(fmt.Sprintf(\"%s.%s\", config.env, key))\n}", "func DefaultServiceConfigFromEnv() Server {\n\tconfigOnce.Do(func() {\n\t\tconfig = Server{\n\t\t\tDatabase: Database{\n\t\t\t\tHost: util.GetEnv(\"PGHOST\", \"postgres\"),\n\t\t\t\tPort: util.GetEnvAsInt(\"PGPORT\", 5432),\n\t\t\t\tDatabase: util.GetEnv(\"PGDATABASE\", \"development\"),\n\t\t\t\tUsername: util.GetEnv(\"PGUSER\", \"dbuser\"),\n\t\t\t\tPassword: util.GetEnv(\"PGPASSWORD\", \"\"),\n\t\t\t\tAdditionalParams: map[string]string{\n\t\t\t\t\t\"sslmode\": util.GetEnv(\"PGSSLMODE\", \"disable\"),\n\t\t\t\t},\n\t\t\t\tMaxOpenConns: util.GetEnvAsInt(\"DB_MAX_OPEN_CONNS\", runtime.NumCPU()*2),\n\t\t\t\tMaxIdleConns: util.GetEnvAsInt(\"DB_MAX_IDLE_CONNS\", 1),\n\t\t\t\tConnMaxLifetime: time.Second * time.Duration(util.GetEnvAsInt(\"DB_CONN_MAX_LIFETIME_SEC\", 60)),\n\t\t\t},\n\t\t\tEcho: EchoServer{\n\t\t\t\tDebug: util.GetEnvAsBool(\"SERVER_ECHO_DEBUG\", false),\n\t\t\t\tListenAddress: util.GetEnv(\"SERVER_ECHO_LISTEN_ADDRESS\", \":8080\"),\n\t\t\t\tHideInternalServerErrorDetails: util.GetEnvAsBool(\"SERVER_ECHO_HIDE_INTERNAL_SERVER_ERROR_DETAILS\", true),\n\t\t\t\tBaseURL: util.GetEnv(\"SERVER_ECHO_BASE_URL\", \"http://localhost:8080\"),\n\t\t\t\tEnableCORSMiddleware: util.GetEnvAsBool(\"SERVER_ECHO_ENABLE_CORS_MIDDLEWARE\", true),\n\t\t\t\tEnableLoggerMiddleware: util.GetEnvAsBool(\"SERVER_ECHO_ENABLE_LOGGER_MIDDLEWARE\", true),\n\t\t\t\tEnableRecoverMiddleware: util.GetEnvAsBool(\"SERVER_ECHO_ENABLE_RECOVER_MIDDLEWARE\", true),\n\t\t\t\tEnableRequestIDMiddleware: util.GetEnvAsBool(\"SERVER_ECHO_ENABLE_REQUEST_ID_MIDDLEWARE\", true),\n\t\t\t\tEnableTrailingSlashMiddleware: util.GetEnvAsBool(\"SERVER_ECHO_ENABLE_TRAILING_SLASH_MIDDLEWARE\", true),\n\t\t\t},\n\t\t\tPaths: PathsServer{\n\t\t\t\t// Please ALWAYS work with ABSOLUTE (ABS) paths from ENV_VARS (however you may resolve a project-relative to absolute for the default value)\n\t\t\t\tAPIBaseDirAbs: util.GetEnv(\"SERVER_PATHS_API_BASE_DIR_ABS\", filepath.Join(util.GetProjectRootDir(), \"/api\")), // /app/api (swagger.yml)\n\t\t\t\tMntBaseDirAbs: util.GetEnv(\"SERVER_PATHS_MNT_BASE_DIR_ABS\", filepath.Join(util.GetProjectRootDir(), \"/assets/mnt\")), // /app/assets/mnt (user-generated content)\n\t\t\t},\n\t\t\tAuth: AuthServer{\n\t\t\t\tAccessTokenValidity: time.Second * time.Duration(util.GetEnvAsInt(\"SERVER_AUTH_ACCESS_TOKEN_VALIDITY\", 86400)),\n\t\t\t\tPasswordResetTokenValidity: time.Second * time.Duration(util.GetEnvAsInt(\"SERVER_AUTH_PASSWORD_RESET_TOKEN_VALIDITY\", 900)),\n\t\t\t\tDefaultUserScopes: util.GetEnvAsStringArr(\"SERVER_AUTH_DEFAULT_USER_SCOPES\", []string{\"app\"}),\n\t\t\t\tLastAuthenticatedAtThreshold: time.Second * time.Duration(util.GetEnvAsInt(\"SERVER_AUTH_LAST_AUTHENTICATED_AT_THRESHOLD\", 900)),\n\t\t\t},\n\t\t\tManagement: ManagementServer{\n\t\t\t\tSecret: util.GetMgmtSecret(\"SERVER_MANAGEMENT_SECRET\"),\n\t\t\t},\n\t\t\tMailer: Mailer{\n\t\t\t\tDefaultSender: util.GetEnv(\"SERVER_MAILER_DEFAULT_SENDER\", \"[email protected]\"),\n\t\t\t\tSend: util.GetEnvAsBool(\"SERVER_MAILER_SEND\", true),\n\t\t\t\tWebTemplatesEmailBaseDirAbs: util.GetEnv(\"SERVER_MAILER_WEB_TEMPLATES_EMAIL_BASE_DIR_ABS\", filepath.Join(util.GetProjectRootDir(), \"/web/templates/email\")), // /app/web/templates/email\n\t\t\t\tTransporter: util.GetEnvEnum(\"SERVER_MAILER_TRANSPORTER\", MailerTransporterMock.String(), []string{MailerTransporterSMTP.String(), MailerTransporterMock.String()}),\n\t\t\t},\n\t\t\tSMTP: transport.SMTPMailTransportConfig{\n\t\t\t\tHost: util.GetEnv(\"SERVER_SMTP_HOST\", \"mailhog\"),\n\t\t\t\tPort: util.GetEnvAsInt(\"SERVER_SMTP_PORT\", 1025),\n\t\t\t\tUsername: util.GetEnv(\"SERVER_SMTP_USERNAME\", \"\"),\n\t\t\t\tPassword: util.GetEnv(\"SERVER_SMTP_PASSWORD\", \"\"),\n\t\t\t\tAuthType: transport.SMTPAuthTypeFromString(util.GetEnv(\"SERVER_SMTP_AUTH_TYPE\", transport.SMTPAuthTypeNone.String())),\n\t\t\t\tUseTLS: util.GetEnvAsBool(\"SERVER_SMTP_USE_TLS\", false),\n\t\t\t\tTLSConfig: nil,\n\t\t\t},\n\t\t\tFrontend: FrontendServer{\n\t\t\t\tBaseURL: util.GetEnv(\"SERVER_FRONTEND_BASE_URL\", \"http://localhost:3000\"),\n\t\t\t\tPasswordResetEndpoint: util.GetEnv(\"SERVER_FRONTEND_PASSWORD_RESET_ENDPOINT\", \"/set-new-password\"),\n\t\t\t},\n\t\t\tLogger: LoggerServer{\n\t\t\t\tLevel: util.LogLevelFromString(util.GetEnv(\"SERVER_LOGGER_LEVEL\", zerolog.DebugLevel.String())),\n\t\t\t\tRequestLevel: util.LogLevelFromString(util.GetEnv(\"SERVER_LOGGER_REQUEST_LEVEL\", zerolog.DebugLevel.String())),\n\t\t\t\tLogRequestBody: util.GetEnvAsBool(\"SERVER_LOGGER_LOG_REQUEST_BODY\", false),\n\t\t\t\tLogRequestHeader: util.GetEnvAsBool(\"SERVER_LOGGER_LOG_REQUEST_HEADER\", false),\n\t\t\t\tLogRequestQuery: util.GetEnvAsBool(\"SERVER_LOGGER_LOG_REQUEST_QUERY\", false),\n\t\t\t\tLogResponseBody: util.GetEnvAsBool(\"SERVER_LOGGER_LOG_RESPONSE_BODY\", false),\n\t\t\t\tLogResponseHeader: util.GetEnvAsBool(\"SERVER_LOGGER_LOG_RESPONSE_HEADER\", false),\n\t\t\t\tPrettyPrintConsole: util.GetEnvAsBool(\"SERVER_LOGGER_PRETTY_PRINT_CONSOLE\", false),\n\t\t\t},\n\t\t\tPush: PushService{\n\t\t\t\tUseFCMProvider: util.GetEnvAsBool(\"SERVER_PUSH_USE_FCM\", false),\n\t\t\t\tUseMockProvider: util.GetEnvAsBool(\"SERVER_PUSH_USE_MOCK\", true),\n\t\t\t},\n\t\t\tFCMConfig: provider.FCMConfig{\n\t\t\t\tGoogleApplicationCredentials: util.GetEnv(\"GOOGLE_APPLICATION_CREDENTIALS\", \"\"),\n\t\t\t\tProjectID: util.GetEnv(\"SERVER_FCM_PROJECT_ID\", \"no-fcm-project-id-set\"),\n\t\t\t\tValidateOnly: util.GetEnvAsBool(\"SERVER_FCM_VALIDATE_ONLY\", true),\n\t\t\t},\n\t\t}\n\n\t})\n\n\treturn config\n}", "func (clbCfg *CLBConfig) LoadFromEnv() error {\n\tvar err error\n\tclbCfg.ImplementMode = os.Getenv(ConfigBcsClbImplement)\n\tif clbCfg.ImplementMode != ConfigBcsClbImplementAPI &&\n\t\tclbCfg.ImplementMode != ConfigBcsClbImplementSDK {\n\t\tblog.Errorf(\"implement type [%s] from env %s is invalid\", clbCfg.BackendMode, ConfigBcsClbImplement)\n\t\treturn fmt.Errorf(\"backend type [%s] from env %s is invalid\", clbCfg.BackendMode, ConfigBcsClbImplement)\n\t}\n\tclbCfg.BackendMode = os.Getenv(ConfigBcsClbBackendMode)\n\tif clbCfg.BackendMode != ConfigBcsClbBackendModeENI &&\n\t\tclbCfg.BackendMode != ConfigBcsClbBackendModeCVM {\n\t\tblog.Errorf(\"backend type [%s] from env %s is invalid\", clbCfg.BackendMode, ConfigBcsClbBackendMode)\n\t\treturn fmt.Errorf(\"backend type [%s] from env %s is invalid\", clbCfg.BackendMode, ConfigBcsClbBackendMode)\n\t}\n\tclbCfg.Region = os.Getenv(ConfigBcsClbRegion)\n\tif !CheckRegion(clbCfg.Region) {\n\t\tblog.Errorf(\"region [%s] is invalid\", clbCfg.Region)\n\t\treturn fmt.Errorf(\"region [%s] is invalid\", clbCfg.Region)\n\t}\n\tclbCfg.SecretID = os.Getenv(ConfigBcsClbSecretID)\n\tif len(clbCfg.SecretID) == 0 {\n\t\tblog.Errorf(\"secret id cannot be empty\")\n\t\treturn fmt.Errorf(\"secret id cannot be empty\")\n\t}\n\tclbCfg.SecretKey = os.Getenv(ConfigBcsClbSecretKey)\n\tif len(clbCfg.SecretKey) == 0 {\n\t\tblog.Errorf(\"secret key cannot be empty\")\n\t\treturn fmt.Errorf(\"secret key cannot be empty\")\n\t}\n\n\tprojectID := os.Getenv(ConfigBcsClbProjectID)\n\tif len(projectID) == 0 {\n\t\tblog.Errorf(\"project id cannot be empty\")\n\t\treturn fmt.Errorf(\"project id cannot be empty\")\n\t}\n\tclbCfg.ProjectID, err = strconv.Atoi(projectID)\n\tif err != nil {\n\t\tblog.Errorf(\"convert project id %s to int failed, err %s\", projectID, err.Error())\n\t\treturn fmt.Errorf(\"convert project id %s to int failed, err %s\", projectID, err.Error())\n\t}\n\tclbCfg.VpcID = os.Getenv(ConfigBcsClbVpcID)\n\tif len(clbCfg.VpcID) == 0 {\n\t\tblog.Errorf(\"vpc id cannot be empty\")\n\t\treturn fmt.Errorf(\"vpc id cannot be empty\")\n\t}\n\n\t//load expire time\n\texpireTime := os.Getenv(ConfigBcsClbExpireTime)\n\tif len(expireTime) != 0 {\n\t\teTime, err := strconv.Atoi(expireTime)\n\t\tif err != nil {\n\t\t\tblog.Errorf(\"expire time %s invalid, set default value 0\", expireTime)\n\t\t\tclbCfg.ExpireTime = 0\n\t\t} else {\n\t\t\t//expire time: range 30~3600\n\t\t\tif eTime < 30 {\n\t\t\t\tclbCfg.ExpireTime = 30\n\t\t\t} else if eTime > 3600 {\n\t\t\t\tclbCfg.ExpireTime = 3600\n\t\t\t} else {\n\t\t\t\tclbCfg.ExpireTime = eTime\n\t\t\t}\n\t\t}\n\t} else {\n\t\t//default 0: means do not set expire time\n\t\tclbCfg.ExpireTime = 0\n\t}\n\n\tclbCfg.SubnetID = os.Getenv(ConfigBcsClbSubnet)\n\tmaxTimeout := os.Getenv(ConfigBcsClbMaxTimeout)\n\tif len(maxTimeout) != 0 {\n\t\ttimeout, err := strconv.Atoi(maxTimeout)\n\t\tif err != nil {\n\t\t\tblog.Errorf(\"convert max timeout %s to int error, err %s, set default value 180\", maxTimeout, err.Error())\n\t\t\tclbCfg.MaxTimeout = DefaultClbMaxTimeout\n\t\t} else {\n\t\t\tclbCfg.MaxTimeout = timeout\n\t\t}\n\t} else {\n\t\tclbCfg.MaxTimeout = DefaultClbMaxTimeout\n\t}\n\twaitPeriodExceedLimit := os.Getenv(ConfigBcsClbWaitPeriodExceedLimit)\n\tif len(waitPeriodExceedLimit) != 0 {\n\t\tperiod, err := strconv.Atoi(waitPeriodExceedLimit)\n\t\tif err != nil {\n\t\t\tblog.Errorf(\"convert wait period exceed limit %s to int error, err %s, set default value 10\",\n\t\t\t\twaitPeriodExceedLimit, err.Error())\n\t\t\tclbCfg.WaitPeriodExceedLimit = DefaultClbWaitPeriodExceedLimit\n\t\t} else {\n\t\t\tclbCfg.WaitPeriodExceedLimit = period\n\t\t}\n\t} else {\n\t\tclbCfg.WaitPeriodExceedLimit = DefaultClbWaitPeriodExceedLimit\n\t}\n\twaitPeriodLBDealing := os.Getenv(ConfigBcsClbWaitPeriodDealing)\n\tif len(waitPeriodLBDealing) != 0 {\n\t\tperiod, err := strconv.Atoi(waitPeriodLBDealing)\n\t\tif err != nil {\n\t\t\tblog.Errorf(\"convert wait period lb dealing limit %s to int error, err %s, set default value 3\",\n\t\t\t\twaitPeriodLBDealing, err.Error())\n\t\t\tclbCfg.WaitPeriodLBDealing = DefaultClbWaitPeriodDealing\n\t\t} else {\n\t\t\tclbCfg.WaitPeriodLBDealing = period\n\t\t}\n\t} else {\n\t\tclbCfg.WaitPeriodLBDealing = DefaultClbWaitPeriodDealing\n\t}\n\n\tblog.Infof(\"load clb config successfully\\n\")\n\treturn nil\n}", "func env(key string, fallback string) string {\n\tif v := os.Getenv(key); v != \"\" {\n\t\treturn v\n\t}\n\treturn fallback\n}", "func NewConfigFromEnv(log *log.Logger) *ApiConfig {\n\tvar err error\n\tvar intValue int\n\tvar found bool\n\tconfig := &ApiConfig{\n\t\tPublicApiURl: \"http://localhost:9107\",\n\t\tFrontUrl: \"http://localhost:3001\",\n\t\tMaxFailedLogin: 5,\n\t\tDelayBeforeNextLoginAttempt: 10, // 10 Minutes\n\t\tMaxConcurrentLogin: 100,\n\t\tBlockParallelLogin: true,\n\t\tLongTermsDuration: 30 * dayAsSecs,\n\t\tUserTokenDurationSecs: 60 * 60,\n\t\tServerTokenDurationSecs: dayAsSecs,\n\t\tSalt: \"ADihSEI7tOQQP9xfXMO9HfRpXKu1NpIJ\",\n\t\tServerSecrets: make(map[string]string),\n\t\tTokenSecrets: make(map[string]string),\n\t\tSecret: \"abcdefghijklmnopqrstuvwxyz\",\n\t}\n\tconfig.ServerSecrets[\"default\"] = config.Secret\n\tconfig.TokenSecrets[\"default\"] = config.Secret\n\n\tbaseUrl, found := os.LookupEnv(\"AUTH_BASE_URL\")\n\tif found {\n\t\tconfig.PublicApiURl = baseUrl\n\t}\n\tfrontUrl, found := os.LookupEnv(\"FRONT_BASE_URL\")\n\tif found {\n\t\tconfig.FrontUrl = frontUrl\n\t}\n\n\tintValue, found, err = getIntFromEnvVar(\"USER_MAX_FAILED_LOGIN\", 1, math.MaxInt16)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t} else if found {\n\t\tconfig.MaxFailedLogin = intValue\n\t}\n\n\tintValue, found, err = getIntFromEnvVar(\"USER_DELAY_NEXT_LOGIN\", 1, math.MaxInt16)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t} else if found {\n\t\tconfig.DelayBeforeNextLoginAttempt = int64(intValue)\n\t}\n\n\tintValue, found, err = getIntFromEnvVar(\"USER_MAX_CONCURRENT_LOGIN\", 1, math.MaxInt16)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t} else if found {\n\t\tconfig.MaxConcurrentLogin = intValue\n\t}\n\n\tblockConcurrentUserLogin, found := os.LookupEnv(\"USER_BLOCK_CONCURRENT_LOGIN\")\n\tif found && blockConcurrentUserLogin == \"false\" {\n\t\tconfig.BlockParallelLogin = false\n\t}\n\n\t// server secret may be passed via a separate env variable to accommodate easy secrets injection via Kubernetes\n\t// The server secret is the password any Tidepool service is supposed to know and pass to shoreline for authentication and for getting token\n\t// With Mdblp, we consider we can have different server secrets\n\t// These secrets are hosted in a map[string][string] instead of single string\n\t// which 1st string represents Server/Service name and 2nd represents the actual secret\n\t// here we consider this SERVER_SECRET that can be injected via Kubernetes is the one for the default server/service (any Tidepool service)\n\tserverSecret, found := os.LookupEnv(\"SERVER_SECRET\")\n\tif found {\n\t\tconfig.ServerSecrets[\"default\"] = serverSecret\n\t}\n\tserverSecret, found = os.LookupEnv(\"AUTHENT_API_SECRET\")\n\tif found {\n\t\tconfig.ServerSecrets[\"authent_api\"] = serverSecret\n\t}\n\tserverSecret, found = os.LookupEnv(\"AUTH0_API_SECRET\")\n\tif found {\n\t\tconfig.ServerSecrets[\"auth0\"] = serverSecret\n\t}\n\n\tuserSecret, found := os.LookupEnv(\"API_SECRET\")\n\tif found {\n\t\tconfig.Secret = userSecret\n\t\tconfig.TokenSecrets[\"default\"] = userSecret\n\t}\n\n\tverificationSecret, found := os.LookupEnv(\"VERIFICATION_SECRET\")\n\tif found {\n\t\tconfig.VerificationSecret = verificationSecret\n\t}\n\n\tlongTermKey, found := os.LookupEnv(\"LONG_TERM_KEY\")\n\tif found {\n\t\tconfig.LongTermKey = longTermKey\n\t}\n\n\tintValue, found, err = getIntFromEnvVar(\"LONG_TERM_TOKEN_DURATION_DAYS\", 1, 60)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t} else if found {\n\t\tconfig.LongTermsDuration = int64(intValue) * dayAsSecs\n\t}\n\n\tintValue, found, err = getIntFromEnvVar(\"USER_TOKEN_DURATION_SECS\", 60, math.MaxInt32)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t} else if found {\n\t\tconfig.UserTokenDurationSecs = int64(intValue)\n\t}\n\tlog.Infof(\"User token duration: %v\", time.Duration(config.UserTokenDurationSecs)*time.Second)\n\n\tintValue, found, err = getIntFromEnvVar(\"SERVER_TOKEN_DURATION_SECS\", 60, math.MaxInt32)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t} else if found {\n\t\tconfig.ServerTokenDurationSecs = int64(intValue)\n\t}\n\tlog.Infof(\"Server token duration: %v\", time.Duration(config.ServerTokenDurationSecs)*time.Second)\n\n\tsalt, found := os.LookupEnv(\"SALT\")\n\tif found && len(salt) > 0 {\n\t\tconfig.Salt = salt\n\t}\n\n\treturn config\n}", "func ReadConfig() (*Config, error) {\n\tconfig := &Config{}\n\tconfig.MinIOProvider = &MinIOProvider{}\n\n\tfor _, cv := range configVars {\n\t\tvar value any\n\t\tvar parseErr error\n\t\tstrValue, err := readConfigVar(cv)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Parse the environment variable depending of its type\n\t\tswitch cv.varType {\n\t\tcase stringType:\n\t\t\tvalue = strings.TrimSpace(strValue)\n\t\tcase stringSliceType:\n\t\t\tvalue = parseStringSlice(strValue)\n\t\tcase intType:\n\t\t\tvalue, parseErr = strconv.Atoi(strValue)\n\t\tcase boolType:\n\t\t\tvalue, parseErr = strconv.ParseBool(strValue)\n\t\tcase secondsType:\n\t\t\tvalue, parseErr = parseSeconds(strValue)\n\t\tcase serverlessBackendType:\n\t\t\tvalue, parseErr = parseServerlessBackend(strValue)\n\t\tcase urlType:\n\t\t\t// Only check if can be parsed\n\t\t\t_, parseErr = url.Parse(strValue)\n\t\t\tvalue = strValue\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\n\t\t// If there are some parseErr return error\n\t\tif parseErr != nil {\n\t\t\treturn nil, fmt.Errorf(\"the %s value is not valid. Expected type: %s. Error: %v\", cv.envVarName, cv.varType, parseErr)\n\t\t}\n\n\t\t// Set the value in the Config struct\n\t\tsetValue(value, cv.name, config)\n\n\t}\n\n\treturn config, nil\n}", "func initConfig() *domain.ApplicationConfig {\n\tconfigPath := util.GetEnv(envConfigPath, defaultConfigPath)\n\tprefix := util.GetEnv(envConfigPrefix, defaultConfigPrefix)\n\tcfg, err := util.ReadConfig(configPath, prefix)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn cfg\n}", "func env() *awscdk.Environment {\n\treturn nil\n\n\t//---------------------------------------------------------------------------\n\t// return &awscdk.Environment{\n\t// Account: jsii.String(os.Getenv(\"CDK_DEFAULT_ACCOUNT\")),\n\t// Region: jsii.String(os.Getenv(\"CDK_DEFAULT_REGION\")),\n\t// }\n}", "func (cfg *Conf) overrideEnvConf() {\n\tif os.Getenv(\"SMGMG_BK_API_KEY\") != \"\" {\n\t\tcfg.ApiKey = os.Getenv(\"SMGMG_BK_API_KEY\")\n\t}\n\n\tif os.Getenv(\"SMGMG_BK_API_SECRET\") != \"\" {\n\t\tcfg.ApiSecret = os.Getenv(\"SMGMG_BK_API_SECRET\")\n\t}\n\n\tif os.Getenv(\"SMGMG_BK_USER_TOKEN\") != \"\" {\n\t\tcfg.UserToken = os.Getenv(\"SMGMG_BK_USER_TOKEN\")\n\t}\n\n\tif os.Getenv(\"SMGMG_BK_USER_SECRET\") != \"\" {\n\t\tcfg.UserSecret = os.Getenv(\"SMGMG_BK_USER_SECRET\")\n\t}\n\n\tif os.Getenv(\"SMGMG_BK_DESTINATION\") != \"\" {\n\t\tcfg.Destination = os.Getenv(\"SMGMG_BK_DESTINATION\")\n\t}\n\n\tif os.Getenv(\"SMGMG_BK_FILE_NAMES\") != \"\" {\n\t\tcfg.Filenames = os.Getenv(\"SMGMG_BK_FILE_NAMES\")\n\t}\n}", "func dbConfig() (map[string]string, error) {\n\tconf := make(map[string]string)\n\thost, ok := os.LookupEnv(dbhost)\n\tif !ok {\n\t\treturn nil, errors.New(\"DBHOST environment variable required\")\n\t}\n\tport, ok := os.LookupEnv(dbport)\n\tif !ok {\n\t\treturn nil, errors.New(\"DBPORT environment variable required\")\n\t}\n\tuser, ok := os.LookupEnv(dbuser)\n\tif !ok {\n\t\treturn nil, errors.New(\"DBUSER environment variable required\")\n\t}\n\tpassword, ok := os.LookupEnv(dbpass)\n\tif !ok {\n\t\treturn nil, errors.New(\"DBPASS environment variable required\")\n\t}\n\tname, ok := os.LookupEnv(dbname)\n\tif !ok {\n\t\treturn nil, errors.New(\"DBNAME environment variable required\")\n\t}\n\tconf[dbhost] = host\n\tconf[dbport] = port\n\tconf[dbuser] = user\n\tconf[dbpass] = password\n\tconf[dbname] = name\n\treturn conf, nil\n}", "func (c *Configuration) FromEnv() (*Configuration, error) {\n\tif e := os.Getenv(envEnabled); e != \"\" {\n\t\tif value, err := strconv.ParseBool(e); err == nil {\n\t\t\tc.Enabled = value\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"cannot parse env var %s=%s, %w\", envEnabled, e, err)\n\t\t}\n\t}\n\n\tif e := os.Getenv(envAgentEndpoint); e != \"\" {\n\t\tc.AgentEndpoint = e\n\t}\n\n\treturn c, nil\n}", "func tmplENV(keys ...string) (value string) {\n\tswitch len(keys) {\n\tcase 1:\n\t\tvalue = os.Getenv(keys[0])\n\tcase 2:\n\t\tvalue = os.Getenv(keys[0])\n\t\tif value == \"\" {\n\t\t\tvalue = keys[1]\n\t\t}\n\t}\n\treturn\n}", "func loadConfig() configuration {\n\terr := godotenv.Load(\"config.env\")\n\tif err != nil {\n\t\tlog.Fatal(\"Error loading .env file\")\n\t}\n\n\tconfig := configuration{}\n\n\tconfig.cityName = os.Getenv(\"CITY_NAME\")\n\tconfig.cityLat, err = strconv.ParseFloat(os.Getenv(\"CITY_LAT\"), 64)\n\tif err != nil {\n\t\tlog.Fatal(\"CITY_LAT configuration is missing\")\n\t}\n\n\tconfig.cityLong, err = strconv.ParseFloat(os.Getenv(\"CITY_LONG\"), 64)\n\tif err != nil {\n\t\tlog.Fatal(\"CITY_LONG configuration is missing\")\n\t}\n\n\tconfig.cityTimezone, err = strconv.Atoi(os.Getenv(\"CITY_TIMEZONE\"))\n\tif err != nil {\n\t\tlog.Fatal(\"CITY_TIMEZONE configuration is missing\")\n\t}\n\n\tconfig.azanFile = os.Getenv(\"AZAN_FILENAME\")\n\tif config.azanFile == \"\" {\n\t\tlog.Fatal(\"AZAN_FILENAME configuration is missing\")\n\t}\n\n\tconfig.method = os.Getenv(\"METHOD\")\n\tif config.azanFile == \"\" {\n\t\tlog.Fatal(\"METHOD configuration is missing\")\n\t}\n\n\treturn config\n}", "func mustGetEnv(name string) string {\n\tenv, ok := os.LookupEnv(name)\n\tif !ok {\n\t\tlog.WithField(\"env\", name).Fatalf(\"missing required environment variable for configuration\")\n\t}\n\tlog.WithField(name, env).Info(\"using env variable\")\n\treturn env\n}", "func EnvPostgresConfig() PostgresConfig {\n\tport, _ := strconv.Atoi(os.Getenv(\"POSTGRES_PORT\"))\n\treturn PostgresConfig{\n\t\tHost: os.Getenv(\"POSTGRES_HOST\"),\n\t\tPort: port,\n\t\tUser: os.Getenv(\"POSTGRES_USER\"),\n\t\tPassword: os.Getenv(\"POSTGRES_PASSWORD\"),\n\t\tName: os.Getenv(\"POSTGRES_DB\"),\n\t}\n}", "func configureDriver(configurable driver.Configurable) {\n\tdriverCfg := map[string]string{}\n\tfor env := range configurable.Config() {\n\t\tif val, ok := os.LookupEnv(env); ok {\n\t\t\tdriverCfg[env] = val\n\t\t}\n\t}\n\tconfigurable.SetConfig(driverCfg)\n}", "func (a *App) GetEnvironmentConfig() map[string]interface{} {\n\treturn a.EnvironmentConfig()\n}", "func (a *App) GetEnvironmentConfig() map[string]interface{} {\n\treturn a.EnvironmentConfig()\n}", "func InitConfig() Config {\n\tif !(testingMode == \"true\") && gopath != \"\" {\n\t\tfullpath := gopath + \"/src/github.com/lancetw/lubike/.env\"\n\t\terr := godotenvLoad(fullpath)\n\t\tif err != nil {\n\t\t\tlogFatalf(\"Error loading .env file %v\", fullpath)\n\t\t}\n\t}\n\n\tvar config Config\n\tconfig.UbikeEndpoint = os.Getenv(\"UBIKE_ENDPOINT\")\n\tconfig.UbikeEndpointTimeout, _ = strconv.Atoi(os.Getenv(\"UBIKE_ENDPOINT_TIMEOUT\"))\n\tconfig.MapquestAPIKey = os.Getenv(\"MAPQUEST_API_KEY\")\n\tconfig.MapquestRouteMatrixEndpoint = os.Getenv(\"MAPQUEST_ROUTE_MATRIX_ENDPOINT\")\n\tconfig.MapquestRouteMatrixEndpointTimeout, _ = strconv.Atoi(os.Getenv(\"MAPQUEST_ROUTE_MATRIX_ENDPOINT_TIMEOUT\"))\n\tconfig.GoogleMapMatrixAPIKey = os.Getenv(\"GOOGLEMAP_MATRIX_API_KEY\")\n\tconfig.GoogleMapMatrixEndpoint = os.Getenv(\"GOOGLEMAP_MATRIX_ENDPOINT\")\n\tconfig.GoogleMapMatrixEndpointTimeout, _ = strconv.Atoi(os.Getenv(\"GOOGLEMAP_MATRIX_API_ENDPOINT_TIMEOUT\"))\n\n\treturn config\n}", "func listEnv(c *build.Context) []string {\n\tif c == nil {\n\t\treturn os.Environ()\n\t}\n\n\tenviron := append(os.Environ(),\n\t\t\"GOOS=\"+c.GOOS,\n\t\t\"GOARCH=\"+c.GOARCH)\n\tif c.CgoEnabled {\n\t\tenviron = append(environ, \"CGO_ENABLED=1\")\n\t} else {\n\t\tenviron = append(environ, \"CGO_ENABLED=0\")\n\t}\n\treturn environ\n}", "func configRetriever(c *cli.Context) error {\n\tcfg := config.FromEnv()\n\n\tc.Context = context.WithValue(c.Context, config.Key(), cfg)\n\n\treturn nil\n}", "func loadConfig() (config Config) {\n var set bool\n if config.DockerSock, set = os.LookupEnv(\"DOCKER_SOCK\"); !set {\n config.DockerSock = \"/var/run/docker.sock\"\n }\n if config.VaultAddr, set = os.LookupEnv(\"VAULT_ADDR\"); !set {\n config.VaultAddr = \"http://127.0.0.1:8200\"\n }\n config.VaultSalt, _ = os.LookupEnv(\"VAULT_SALT\")\n return\n}", "func ProcConfigFromEnv() (ProcConfig, error) {\n\tv, ok := os.LookupEnv(EnvProcConfig)\n\tif !ok {\n\t\treturn ProcConfig{}, ErrProcConfigEnvNotDefined\n\t}\n\tvar conf ProcConfig\n\tif err := json.Unmarshal([]byte(v), &conf); err != nil {\n\t\treturn ProcConfig{}, fmt.Errorf(\"invalid %s env value: %w\", EnvProcConfig, err)\n\t}\n\treturn conf, nil\n}", "func environ(envVars []*apiclient.EnvEntry) []string {\n\tvar environ []string\n\tfor _, item := range envVars {\n\t\tif item != nil && item.Name != \"\" && item.Value != \"\" {\n\t\t\tenviron = append(environ, fmt.Sprintf(\"%s=%s\", item.Name, item.Value))\n\t\t}\n\t}\n\treturn environ\n}", "func ReadEnv(configString []byte) []string {\n\treturn regexp.MustCompile(`\\$\\{[a-zA-Z0-9_\\-]+\\}`).FindAllString(string(configString), -1)\n}", "func (c *Config) GetFromEnvironmentVariable() error {\n\taccessKeyID := strings.TrimSpace(os.Getenv(\"AccessKeyID\"))\n\tif accessKeyID == \"\" {\n\t\treturn fmt.Errorf(\"AccessKeyID invalid\")\n\t}\n\n\tsecretAccessKey := strings.TrimSpace(os.Getenv(\"SecretAccessKey\"))\n\tif secretAccessKey == \"\" {\n\t\treturn fmt.Errorf(\"SecretAccessKey invalid\")\n\t}\n\n\tregion := strings.TrimSpace(os.Getenv(\"Region\"))\n\tif region == \"\" {\n\t\treturn fmt.Errorf(\"Region invalid\")\n\t}\n\n\tmaxRetry, err := strconv.Atoi(strings.TrimSpace(os.Getenv(\"MaxRetry\")))\n\tif err != nil {\n\t\tmaxRetry = constants.RetryCount\n\t}\n\n\tbucket := strings.TrimSpace(os.Getenv(\"Bucket\"))\n\tif bucket == \"\" {\n\t\treturn fmt.Errorf(\"Bucket invalid\")\n\t}\n\n\tqueueURL := strings.TrimSpace(os.Getenv(\"QueueUrl\"))\n\tif queueURL == \"\" {\n\t\treturn fmt.Errorf(\"QueueUrl invalid\")\n\t}\n\n\tc.AccessKeyID = accessKeyID\n\tc.SecretAccessKey = secretAccessKey\n\tc.Region = region\n\tc.MaxRetry = maxRetry\n\tc.Bucket = bucket\n\tc.QueueURL = queueURL\n\n\treturn nil\n}", "func get_env_vars()map[string]string{\n\tenv_vars := make(map[string]string)\n\tfor _, e := range os.Environ() {\n\t\tpair := strings.Split(e, \"=\")\n\t\t//fmt.Println(pair[0], \"---\", pair[1])\n\t\tenv_vars[pair[0]]=pair[1]\n\t}\n\treturn env_vars\n}", "func (c *Config) Getenv(key string) string {\n\treturn os.ExpandEnv(c.GetString(key))\n}", "func NewConfigFromEnv() (Config, error) {\n\tcfg := Config{\n\t\tVnetResourceGroupName: os.Getenv(VnetResourceGroupEnvName),\n\t\tVnetName: os.Getenv(VnetEnvName),\n\t\tNatSubnetName: os.Getenv(NatSubnetEnvName),\n\t\tNatSubnetPrefix: os.Getenv(NatSubnetPrefixEnvName),\n\t\tLoadBalancerResourceGroup: os.Getenv(LoadBalancerResourceGroupEnvName),\n\t\tLoadBalancerName: os.Getenv(LoadBalancerEnvName),\n\t\tServiceAnnotation: os.Getenv(ServiceAnnotationEnvName),\n\t\tAzureAuthLocation: os.Getenv(AzureAuthLocationEnvName),\n\t}\n\n\tif i, err := strconv.Atoi(os.Getenv(SyncPeriodEnvName)); err == nil{\n\t\tcfg.SyncPeriod = time.Duration(i) * time.Second\n\t} else {\n\t\tcfg.SyncPeriod = time.Duration(DefaultSyncPeriod) * time.Second\n\t}\n\n\tif i, err := strconv.Atoi(os.Getenv(MinRetryDelayEnvName)); err == nil{\n\t\tcfg.MinRetryDelay = time.Duration(i) * time.Second \n\t} else {\n\t\tcfg.MinRetryDelay = time.Duration(DefaultMinRetryDelay) * time.Second\n\t}\n\n\tif i, err := strconv.Atoi(os.Getenv(MaxRetryDelayEnvName)); err == nil{\n\t\tcfg.MaxRetryDelay = time.Duration(i)\n\t} else {\n\t\tcfg.MaxRetryDelay = time.Duration(DefaultMaxRetryDelay) * time.Second\n\t}\n\n\tif cfg.ServiceAnnotation == \"\" {\n\t\tcfg.ServiceAnnotation = DefaultServiceAnnotation\n\t}\n\n\tif err := cfg.parse(); err != nil {\n\t\treturn cfg, err\n\t} \n\n\treturn cfg, nil\n}", "func configOptionsByEnvironmentVariables(options *Options) error {\n\tif s, ok := os.LookupEnv(\"AWS_MAX_RETRIES\"); ok {\n\t\tglog.Warningf(\"Environment variable configuration is deprecated, switch to the --aws-max-retries flag.\")\n\t\tv, err := strconv.ParseInt(s, 0, 32)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"AWS_MAX_RETRIES environment variable must be an integer. Value was: %s\", s)\n\t\t}\n\t\toptions.AWSAPIMaxRetries = int(v)\n\t}\n\tif s, ok := os.LookupEnv(\"CLUSTER_NAME\"); ok {\n\t\tglog.Warningf(\"Environment variable configuration is deprecated, switch to the --cluster-name flag.\")\n\t\toptions.config.ClusterName = s\n\t}\n\tif s, ok := os.LookupEnv(\"ALB_PREFIX\"); ok {\n\t\tglog.Warningf(\"Environment variable configuration is deprecated, switch to the --alb-name-prefix flag.\")\n\t\toptions.config.ALBNamePrefix = s\n\t}\n\tif s, ok := os.LookupEnv(\"ALB_CONTROLLER_RESTRICT_SCHEME\"); ok {\n\t\tglog.Warningf(\"Environment variable configuration is deprecated, switch to the --restrict-scheme flag.\")\n\t\tv, err := strconv.ParseBool(s)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"ALB_CONTROLLER_RESTRICT_SCHEME environment variable must be either true or false. Value was: %s\", s)\n\t\t}\n\t\toptions.config.RestrictScheme = v\n\t}\n\tif s, ok := os.LookupEnv(\"ALB_CONTROLLER_RESTRICT_SCHEME_CONFIG_NAMESPACE\"); ok {\n\t\tglog.Warningf(\"Environment variable configuration is deprecated, switch to the --restrict-scheme-namespace flag.\")\n\t\toptions.config.RestrictSchemeNamespace = s\n\t}\n\treturn nil\n}", "func Env() *viper.Viper {\n\tv := viper.New()\n\tv.AutomaticEnv()\n\tv.SetEnvPrefix(\"syl\")\n\tv.BindEnv(\"oauth_clientID\")\n\tv.BindEnv(\"oauth_client_secret\")\n\tv.BindEnv(\"redis_url\")\n\terr := v.BindEnv(\"api_port\")\n\tif err != nil {\n\t\tfmt.Println(\"ERROR setting env var\", err.Error())\n\t}\n\tv.BindEnv(\"oauth_redirect_url\")\n\treturn v\n}", "func GetENV(experimentDetails *experimentTypes.ExperimentDetails) {\n\texperimentDetails.ExperimentName = Getenv(\"EXPERIMENT_NAME\", \"\")\n\texperimentDetails.AppNS = Getenv(\"APP_NS\", \"\")\n\texperimentDetails.TargetContainer = Getenv(\"APP_CONTAINER\", \"\")\n\texperimentDetails.TargetPods = Getenv(\"APP_POD\", \"\")\n\texperimentDetails.AppLabel = Getenv(\"APP_LABEL\", \"\")\n\texperimentDetails.ChaosDuration, _ = strconv.Atoi(Getenv(\"TOTAL_CHAOS_DURATION\", \"30\"))\n\texperimentDetails.ChaosNamespace = Getenv(\"CHAOS_NAMESPACE\", \"litmus\")\n\texperimentDetails.EngineName = Getenv(\"CHAOS_ENGINE\", \"\")\n\texperimentDetails.ChaosUID = clientTypes.UID(Getenv(\"CHAOS_UID\", \"\"))\n\texperimentDetails.ChaosPodName = Getenv(\"POD_NAME\", \"\")\n\texperimentDetails.ContainerRuntime = Getenv(\"CONTAINER_RUNTIME\", \"\")\n\texperimentDetails.NetworkInterface = Getenv(\"NETWORK_INTERFACE\", \"eth0\")\n\texperimentDetails.TargetIPs = Getenv(\"TARGET_IPs\", \"\")\n}", "func initConfig(secret map[string]string) *Config {\n\tc := Config{\n\t\tmember: viper.New(),\n\t\tsecretValues: secret,\n\t}\n\tc.member.SetEnvPrefix(MemberEnvPrefix)\n\tc.member.AutomaticEnv()\n\tc.member.SetEnvKeyReplacer(strings.NewReplacer(\".\", \"_\"))\n\tc.setConfigDefaults()\n\treturn &c\n}" ]
[ "0.69667965", "0.68781495", "0.6656939", "0.6593634", "0.6542232", "0.6524963", "0.6486533", "0.64751476", "0.64419335", "0.63989925", "0.63914573", "0.63172793", "0.6315013", "0.6282576", "0.6251936", "0.62236834", "0.61967146", "0.6178627", "0.61679006", "0.6166197", "0.61454177", "0.61341476", "0.6075719", "0.6055461", "0.60544056", "0.60320073", "0.60054517", "0.59753823", "0.59504426", "0.59490675", "0.59460014", "0.59213954", "0.59207237", "0.59157914", "0.58691704", "0.58601844", "0.5851211", "0.5838005", "0.5832083", "0.5829004", "0.58282566", "0.582237", "0.58117163", "0.58075595", "0.58075595", "0.5802406", "0.5783328", "0.5781996", "0.5778848", "0.5777661", "0.577609", "0.57750857", "0.5755636", "0.574993", "0.5747442", "0.5744126", "0.57350963", "0.57286555", "0.5727477", "0.572724", "0.57151127", "0.5701219", "0.5682531", "0.5679134", "0.566988", "0.5663032", "0.5654756", "0.5650311", "0.5649323", "0.56487274", "0.56332076", "0.563065", "0.5630089", "0.5628667", "0.5616201", "0.560829", "0.5600804", "0.5593354", "0.55797553", "0.55791736", "0.5574517", "0.5568733", "0.5551747", "0.555102", "0.555102", "0.554849", "0.55481356", "0.5544572", "0.5544073", "0.55306506", "0.55219036", "0.5521836", "0.55208933", "0.551659", "0.551497", "0.55131674", "0.55108523", "0.55071545", "0.54973954", "0.5493939" ]
0.6331278
11
FileConfig returns a configuration with any values provided by the given YAML config file
func FileConfig(cfgPath string) *Config { config := new(Config) cfgFile, err := ioutil.ReadFile(cfgPath) if err != nil { config.err = err } else { config.err = yaml.Unmarshal(cfgFile, config) } return config }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func LoadFileConfig(file string) (*Configuration, error) {\n\tlog.Printf(\"[DEBUG] Load configuration file: %s\", file)\n\tconfiguration := New()\n\tif _, err := toml.DecodeFile(file, configuration); err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"[DEBUG] Configuration : %#v\", configuration)\n\tif configuration.Freebox != nil {\n\t\tlog.Printf(\"[DEBUG] Configuration : %#v\", configuration.Freebox)\n\t}\n\tif configuration.InfluxDB != nil {\n\t\tlog.Printf(\"[DEBUG] Configuration : %#v\", configuration.InfluxDB)\n\t}\n\treturn configuration, nil\n}", "func loadFileConfig(configurationFilePath string) (*fileConfig, error) {\n\tc := &fileConfig{}\n\n\tdata, err := ioutil.ReadFile(configurationFilePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := yaml.Unmarshal(data, &c); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}", "func FromFile(path string) (Config, error) {\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, errors.New(\"config: \" + err.Error())\n\t}\n\n\ttype authYAML struct {\n\t\tUsername string `yaml:\"username\"`\n\t\tPassword string `yaml:\"password\"`\n\t\tTenantName string `yaml:\"tenant_name\"`\n\t\tTenantID string `yaml:\"tenant_id\"`\n\t\tAuthURL string `yaml:\"auth_url\"`\n\t}\n\ty := map[string]map[string]map[string]*authYAML{}\n\tif err := yaml.Unmarshal(b, y); err != nil {\n\t\treturn nil, &ParseError{path, err}\n\t}\n\tif len(y[\"clouds\"]) == 0 {\n\t\treturn nil, &ParseError{path, errors.New(\"config is empty\")}\n\t}\n\n\tclouds := map[string]gophercloud.AuthOptions{}\n\tfor k, v := range y[\"clouds\"] {\n\t\tif a, ok := v[\"auth\"]; ok {\n\t\t\tclouds[k] = gophercloud.AuthOptions{\n\t\t\t\tIdentityEndpoint: a.AuthURL,\n\t\t\t\tPassword: a.Password,\n\t\t\t\tTenantID: a.TenantID,\n\t\t\t\tTenantName: a.TenantName,\n\t\t\t\tUsername: a.Username,\n\t\t\t}\n\t\t}\n\t}\n\treturn &configImpl{clouds: clouds}, nil\n}", "func NewConfigFromFile(file *os.File) (Config, error) {\n\tif file == nil {\n\t\treturn Config{}, errors.New(\"file is required\")\n\t}\n\n\tc := Config{file: file}\n\tif err := yaml.NewDecoder(file).Decode(&c); err != nil {\n\t\treturn Config{}, err\n\t}\n\n\treturn c, nil\n}", "func New(options file.Options) config.Configuration {\n\treturn file.NewFileConfiguration(\n\t\tfile.FullOptions{\n\t\t\tOptions: options.WithDefaults(),\n\t\t\tByteToMapReader: yamlFileValuesFiller,\n\t\t\tReflectionMapper: yamlFileValuesMapper,\n\t\t},\n\t)\n}", "func getConfigurationFromFile(file string) (*kurmaConfig, error) {\n\tvar unmarshalFunc func([]byte, interface{}) error\n\tswitch filepath.Ext(file) {\n\tcase \".json\":\n\t\tunmarshalFunc = json.Unmarshal\n\tcase \".yml\", \".yaml\":\n\t\tunmarshalFunc = yaml.Unmarshal\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unrecognized configation file format, please use JSON or YAML\")\n\t}\n\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, fmt.Errorf(\"failed to load configuration: %v\", err)\n\t}\n\tdefer f.Close()\n\n\tb, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read configuration file: %v\", err)\n\t}\n\n\tvar config *kurmaConfig\n\tif err := unmarshalFunc(b, &config); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse configuration file: %v\", err)\n\t}\n\treturn config, nil\n}", "func loadConfig(filename string) ConfigFile {\n\t// Deliberately don't catch errors, want script to crash on config file load error\n\tconfigFile, _ := ioutil.ReadFile(filename)\n\tvar config ConfigFile\n\tyaml.Unmarshal(configFile, &config)\n\n\t// Return the struct\n\treturn (config)\n}", "func NewConfig(file string) Config {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar cfg Config\n\tdecoder := yaml.NewDecoder(f)\n\terr = decoder.Decode(&cfg)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn cfg\n}", "func loadConfig(filename string) (configuration, error) {\n\tconf := configuration{Exclusions: []string{}}\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn conf, err\n\t\t}\n\t} else {\n\t\tif err := yaml.Unmarshal(data, &conf); err != nil {\n\t\t\treturn configuration{}, err\n\t\t}\n\t}\n\treturn conf, nil\n}", "func ParseConfigFile(fileName string) (*common.Config, error) {\n\n\t_, configFileName, _, ok := runtime.Caller(0)\n\tif !ok {\n\t\tpanic(\"No caller information\")\n\t}\n\n\tyamlFile, err := ioutil.ReadFile(path.Dir(path.Dir(configFileName)) + configDir + fileName)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while reading file given from input: %s\", err)\n\t}\n\n\tconfig := common.NewConfig()\n\n\terr = yaml.Unmarshal(yamlFile, config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while parsing config yaml file: %s\", err)\n\t}\n\n\treturn config, nil\n}", "func NewConfigFromFile(filename string, values map[string]string) (*Config, error) {\n\tfile, err := FileSystem.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewConfig(file, filename, values)\n}", "func ReadConfigFromFile(file string) *Config {\n\tc := &Config{}\n\n\tconfFile, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to read yaml configuration from file %s, #%v \", file, err)\n\t\treturn nil\n\t}\n\n\terr = yaml.Unmarshal(confFile, c)\n\tif err != nil {\n\t\tlog.Fatalf(\"Invalid configuration: %v\", err)\n\t\treturn nil\n\t}\n\n\t// m, _ := yaml.Marshal(c)\n\t// log.Printf(\"Parsed configuration file\\n%s\\n\", string(m))\n\n\tc.Vars.init()\n\treturn c\n}", "func ParseConfigFile(filePath string) (*Config, error) {\n\tv := viper.New()\n\tcfg := &Config{v}\n\tcfg.SetDefault(\"init\", \"\") // e.g. \"init.sh\"\n\tcfg.SetDefault(\"run\", \"\") // e.g. \"run.sh\"\n\tcfg.SetDefault(\"clean\", \"\") // e.g. \"clean.sh\"\n\tcfg.SetDefault(\"validate\", \"\") // e.g. \"validate.sh\"\n\tcfg.SetDefault(\"kill\", \"\") // e.g. \"kill.sh\", unexpected death\n\tcfg.SetDefault(\"shutdown\", \"\") // e.g. \"shutdown.sh\", graceful shutdown\n\tcfg.SetDefault(\"explorePolicy\", \"dumb\")\n\tcfg.SetDefault(\"explorePolicyParam\", map[string]interface{}{})\n\tcfg.SetDefault(\"storageType\", \"naive\")\n\tcfg.SetDefault(\"notCleanIfValidationFail\", false)\n\t// Viper Issue: Default value for nested key #71 (https://github.com/spf13/viper/issues/71)\n\tcfg.SetDefault(\"inspectorHandler\",\n\t\tmap[string]interface{}{\n\t\t\t\"pb\": map[string]interface{}{\n\t\t\t\t// TODO: port\n\t\t\t},\n\t\t\t\"rest\": map[string]interface{}{\n\t\t\t\t// TODO: port\n\t\t\t},\n\t\t})\n\t// viper supports JSON, YAML, and TOML\n\tcfg.SetConfigFile(filePath)\n\terr := cfg.ReadInConfig()\n\tif err == nil {\n\t\tif cfg.GetString(\"run\") == \"\" {\n\t\t\terr = errors.New(\"required field \\\"run\\\" is missing\")\n\t\t}\n\t}\n\treturn cfg, err\n}", "func configFromFile(env string) (Config, error) {\n\tenv = strings.ToLower(env)\n\t// attempt to read config from {{environment}}.yml (defaults to development.yml)\n\tvar fname string\n\tvar conf Config\n\tif _, err := os.Stat(fmt.Sprintf(\"config/%s.yml\", env)); err == nil {\n\t\tfname = fmt.Sprintf(\"config/%s.yml\", env)\n\t} else {\n\t\tfname = fmt.Sprintf(\"config/development.yml\")\n\t}\n\n\tymlFile, err := ioutil.ReadFile(fname)\n\tif err != nil {\n\t\treturn conf, err\n\t}\n\n\terr = yaml.Unmarshal(ymlFile, &conf)\n\tif err != nil {\n\t\treturn conf, err\n\t}\n\n\treturn conf, nil\n\n}", "func ConfigFromFile(path string) (*Config, error) {\n\tf, err := os.Open(path)\n\tdefer f.Close()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open config file: %v\", err)\n\t}\n\treturn NewConfig(f)\n}", "func New(configFile string) *Config {\n\tc, err := ioutil.ReadFile(configFile)\n\tif err != nil {\n\t\tlog.Panicf(\"Read config file %s failed: %s\", configFile, err.Error())\n\t}\n\tcfg := &Config{}\n\tif err := yaml.Unmarshal(c, cfg); err != nil {\n\t\tlog.Panicf(\"yaml.Unmarshal config file %s failed: %s\", configFile, err.Error())\n\t}\n\treturn cfg\n}", "func loadConfigFromFile(filePath string) (*Config, error) {\n\tconf := configDefault\n\n\tfileData, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = yaml.Unmarshal(fileData, &conf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn conf, nil\n}", "func NewConfigFromFile(path string) (*ParserConfig, error) {\n\tvar config ParserConfig\n\tvar err error\n\tvar data []byte\n\n\tif data, err = ioutil.ReadFile(path); err != nil {\n\t\treturn nil, fmt.Errorf(\"unabel to read config file: %s\", err.Error())\n\t} else if err = yaml.Unmarshal(data, &config); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to parse config: %s\", err.Error())\n\t}\n\n\tconfig.RootDir = filepath.Dir(path)\n\tconfig.OutDir = filepath.Join(config.RootDir, config.OutDir)\n\n\tfor _, t := range config.Templates {\n\t\tif !filepath.IsAbs(t.SourceFile) {\n\t\t\tt.SourceFile = filepath.Join(config.RootDir, t.SourceFile)\n\t\t}\n\t}\n\n\treturn &config, nil\n}", "func LoadConfigFile(configFile string) (*Config, error) {\n\tfileContent, err := ioutil.ReadFile(configFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to load config file '%s', error: %s\", configFile, err.Error())\n\t}\n\n\tc := &Config{}\n\tif err = yaml.Unmarshal(fileContent, c); err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to parse config file '%s' as yaml, error: %s\", configFile, err.Error())\n\t}\n\n\tfor _, proj := range c.Projects {\n\t\tproj.YamlFile = os.ExpandEnv(proj.YamlFile)\n\t}\n\n\tif err = c.validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}", "func (c *Config) configFromFile(path string) error {\n\t_, err := toml.DecodeFile(path, c)\n\treturn errors.Trace(err)\n}", "func (c *Config) configFromFile(path string) error {\n\t_, err := toml.DecodeFile(path, c)\n\treturn errors.Trace(err)\n}", "func (c *Config) configFromFile(path string) error {\n\t_, err := toml.DecodeFile(path, c)\n\treturn errors.Trace(err)\n}", "func (config *Config) FromFile(configfile string) {\n\tvar newconfig Config\n\n\tdata, err := ioutil.ReadFile(configfile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := yaml.Unmarshal(data, &newconfig); err != nil {\n\t\tpanic(err)\n\t}\n\n\tlog.Debugf(\"%s has config: %+v\", configfile, newconfig)\n\tconfig.Merge(newconfig)\n\tlog.Debugf(\"merged config is: %+v\", config)\n}", "func ConfigFileReader(filePath string) (map[string][]map[string]string, error) {\n\t// file path is the configuration file which is written in yaml\n\tvar config map[string][]map[string]string\n\t// opening config file\n\tfile, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn config, fmt.Errorf(\"unable to parse config file %v file \", err)\n\t}\n\n\tdefer file.Close()\n\n\tif yaml.NewDecoder(file).Decode(&config); err != nil {\n\t\treturn config, fmt.Errorf(\"unable to decode file %v file \", err)\n\t}\n\treturn config, nil\n}", "func LoadFromFile(configFile string) (*Config, error) {\n\tcfg := defaultConfig()\n\tif _, err := toml.DecodeFile(configFile, &cfg); err != nil {\n\t\treturn &cfg, err\n\t}\n\tcfg.File = configFile\n\treturn &cfg, nil\n}", "func ConfigFile(path string) Option {\n\treturn func(ec *Envcfg) {\n\t\tec.configFile = path\n\t}\n}", "func NewConfig(file *os.File) *Config {\n\tif file != nil {\n\t\tscner := bufio.NewScanner(file)\n\t\tvar bs []byte\n\t\tfor scner.Scan() {\n\t\t\tbs = append(bs, scner.Bytes()...)\n\t\t}\n\n\t\tvar conf Config\n\t\terr := json.Unmarshal(bs, &conf)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn &conf\n\t}\n\treturn nil\n}", "func ParseCfgFile(cfgFile string) (*Config, error) {\n\tlogrus.Info(\"**** FILE PROVIDED**** \", cfgFile)\n\tif cfgFile == \"\" {\n\t\treturn nil, fmt.Errorf(\"no config file provided\")\n\t}\n\n\tfilename, err := getAbsFilename(cfgFile)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tyamlFile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcfg := &Config{}\n\terr = yaml.Unmarshal(yamlFile, cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\temptyurl := URL{}\n\tif cfg.KairosdbURL == emptyurl {\n\t\treturn nil, fmt.Errorf(\"kairosdb-url is mandatory\")\n\t}\n\n\tif cfg.Server.Port == \"\" {\n\t\tcfg.Server.Port = defaultServerPort\n\t}\n\n\tif cfg.MetricnamePrefix != \"\" {\n\t\tregex, err := NewRegexp(\".*\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\trelabelConfig := &RelabelConfig{\n\t\t\tSourceLabels: model.LabelNames{model.MetricNameLabel},\n\t\t\tRegex: regex,\n\t\t\tAction: RelabelAddPrefix,\n\t\t\tPrefix: cfg.MetricnamePrefix,\n\t\t}\n\n\t\tcfg.MetricRelabelConfigs = append(cfg.MetricRelabelConfigs, relabelConfig)\n\t}\n\n\terr = validateMetricRelabelConfigs(cfg.MetricRelabelConfigs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif cfg.Timeout == 0*time.Second {\n\t\tlogrus.Infof(\"timeout not provided. Setting it to default value of %s\", defaultTimeout)\n\t\tcfg.Timeout = defaultTimeout\n\t}\n\tif cfg.Timeout > maxTimeout {\n\t\treturn nil, fmt.Errorf(\"timeout %d is too high. It should be between %v and %v\", cfg.Timeout, minTimeout, maxTimeout)\n\t}\n\n\tif cfg.Timeout < minTimeout {\n\t\treturn nil, fmt.Errorf(\"timeout %d is too low. It should be between %v and %v\", cfg.Timeout, minTimeout, maxTimeout)\n\t}\n\n\treturn cfg, nil\n}", "func FromFile(file string) *Config {\n\tbytes, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed read config, check ./config.json or use flag -conf=/path, err: \", err)\n\t}\n\tvar conf Config\n\tpErr := json.Unmarshal(bytes, &conf)\n\tif pErr != nil {\n\t\tlog.Fatal(\"Failed parse config: \", pErr)\n\t}\n\treturn &conf\n\n}", "func ConfigLoadFile(filename string) (*Config, error) {\n\t_, err := os.Stat(filename)\n\tif err == nil {\n\t\tfile, err := os.Open(filename)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer file.Close()\n\t\tc, err := ConfigLoadReader(file)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tc.Filename = filename\n\t\treturn c, nil\n\t}\n\treturn nil, err\n}", "func loadFromFile(filePath string) (*Config, error) {\n\tvar cfg *Config\n\tfileBytes, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\t// logger.Log(\"level\", LogLevel.Error, \"message\", \"File open error\", \"file\", filePath)\n\t\treturn nil, err\n\t}\n\terr = yaml.Unmarshal(fileBytes, &cfg)\n\tif err != nil {\n\t\treturn nil, err\n\n\t}\n\t// logger.Log(\"level\", LogLevel.Debug, \"message\", \"Config\", \"file\", cfg)\n\treturn cfg, nil\n}", "func FromYamlFile(filename string, expandEnv bool) (*Config, error) {\n\tbytes, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn FromYaml(bytes, expandEnv)\n}", "func recupStructWithConfigFile(file string, debugFile string, debugLog bool) (config Config) {\n\n\t// check if file exists\n\te, err := os.Stat(file)\n\tif err != nil {\n\t\tfmt.Println(\"config file not found\")\n\t\tutils.StopApp()\n\t}\n\tDebugPrint(debugFile, debugLog, \"DEBUG: \", \"File opened : \"+e.Name())\n\n\t// open the file\n\tf, _ := os.Open(file)\n\tdefer f.Close()\n\n\t// read the file contents\n\tbyteValue, _ := ioutil.ReadAll(f)\n\n\t// unmarshal the file's content and save to config variable\n\tjson.Unmarshal(byteValue, &config)\n\n\treturn\n}", "func (*Config) Parse(filename string) (y config.Configer, err error) {\n\tcnf, err := ReadYmlReader(filename)\n\tif err != nil {\n\t\treturn\n\t}\n\ty = &ConfigContainer{\n\t\tdata: cnf,\n\t}\n\treturn\n}", "func (c *Config) ParseConfig(filename string) *Config {\n\tyamlFile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tlog.Printf(\"yamlFile.Get err #%v \", err)\n\t}\n\terr = yaml.Unmarshal(yamlFile, c)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unmarshal: %v\", err)\n\t}\n\treturn c\n}", "func ConfigureFile(filename string) *config.Config {\n\treturn config.CreateConfigFromFile(filename)\n}", "func (p Plans) ConfigFile() Path {\n\treturn p.Expand().Join(\"config.json\")\n}", "func ParseConfig(file string) (Containers, error) {\n\tdata, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig := Containers{}\n\n\terr = yaml.Unmarshal([]byte(data), &config)\n\tif err != nil {\n\t\tfmt.Printf(\"error: %v\", err)\n\t}\n\n\treturn config, err\n}", "func readConfigfile(configFile string) ConfigSettings {\n\tDebugf(\"Trying to read config file: \" + configFile)\n\tdata, err := ioutil.ReadFile(configFile)\n\tif err != nil {\n\t\tFatalf(\"readConfigfile(): There was an error parsing the config file \" + configFile + \": \" + err.Error())\n\t}\n\n\tvar config ConfigSettings\n\terr = yaml.Unmarshal([]byte(data), &config)\n\tif err != nil {\n\t\tFatalf(\"YAML unmarshal error: \" + err.Error())\n\t}\n\n\t// check if cachedir exists\n\tconfig.CacheDir = checkDirAndCreate(config.CacheDir, \"cachedir\")\n\n\tif len(config.ForgeUrl) == 0 {\n\t\tconfig.ForgeUrl = \"https://forgeapi.puppetlabs.com\"\n\t}\n\n\t// set default timeout to 5 seconds if no timeout setting found\n\tif config.Timeout == 0 {\n\t\tconfig.Timeout = 5\n\t}\n\n\t// set default max Go routines for Forge and Git module resolution if none is given\n\tif maxworker == 0 {\n\t\tconfig.Maxworker = 5\n\t} else {\n\t\tconfig.Maxworker = maxworker\n\t}\n\n\treturn config\n}", "func Config(fileName string) func(opa *OPA) error {\n\treturn func(opa *OPA) error {\n\t\tbs, err := ioutil.ReadFile(fileName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\topa.configBytes = bs\n\t\treturn nil\n\t}\n}", "func ReadFrom(pathToYamlFile string) (*FileConfiguration, error) {\n\tyamlConfiguration := new(yamlConfigurationFormat)\n\n\tvar err error\n\tvar yamlContent []byte\n\tyamlContent, err = ioutil.ReadFile(pathToYamlFile)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = yaml.Unmarshal(yamlContent, &yamlConfiguration)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := &FileConfiguration{parsedYaml: yamlConfiguration}\n\n\treturn result, nil\n}", "func LoadConfigFile(filename string) (cfg Config, err error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn cfg, err\n\t}\n\tdefer f.Close()\n\n\treturn cfg, toml.NewDecoder(f).Decode(&cfg)\n}", "func ParseConfig(file string) *Config {\n\tdata, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\tlog.Error(\"%v\", err)\n\t\tos.Exit(1)\n\t}\n\n\tconfig := new(Config)\n\n\terr = yaml.Unmarshal(data, config)\n\n\tif err != nil {\n\t\tlog.Error(\"get config error, %v\", err)\n\t\tos.Exit(1)\n\t}\n\n\treturn config\n}", "func ReadFromFile() (*Config, error) {\n\t// usr, err := user.Current()\n\t// if err != nil {\n\t// \tlog.Fatal(err)\n\t// }\n\n\t// configPath := path.Join(usr.HomeDir, `.matic-jagar/config/`)\n\t// log.Printf(\"Config Path : %s\", configPath)\n\n\tv := viper.New()\n\tv.AddConfigPath(\".\")\n\t// v.AddConfigPath(configPath)\n\tv.SetConfigName(\"config\")\n\tif err := v.ReadInConfig(); err != nil {\n\t\tlog.Fatalf(\"error while reading config.toml: %v\", err)\n\t}\n\n\tvar cfg Config\n\tif err := v.Unmarshal(&cfg); err != nil {\n\t\tlog.Fatalf(\"error unmarshaling config.toml to application config: %v\", err)\n\t}\n\n\tif err := cfg.Validate(); err != nil {\n\t\tlog.Fatalf(\"error occurred in config validation: %v\", err)\n\t}\n\n\treturn &cfg, nil\n}", "func NewFromFile(filepath string, cfg *Config) error {\n\tvar cfgraw []byte\n\tvar err error\n\n\tcfgraw, err = ioutil.ReadFile(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = yaml.Unmarshal(cfgraw, &cfg); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func NewConfig(fileName string) (*fileConfig, error) {\n\tconfig := make(map[string]json.RawMessage)\n\n\terr := util.ReadFile(&config, fileName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlogger.Debug(\"config => \", config)\n\treturn &fileConfig{\n\t\tconfig: config,\n\t}, nil\n}", "func ParseConfig(fnm string) Config {\n\tvar config Config\n\tconfigData, err := ioutil.ReadFile(fnm)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR:\", err)\n\t}\n\terr = yaml.Unmarshal(configData, &config)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR:\", err)\n\t}\n\treturn config\n}", "func NewConfigFromFile(filePath string) (*Config, error) {\n\tbytes, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar c *Config\n\terr = json.Unmarshal(bytes, &c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c, nil\n}", "func LoadConfigFromFile(yamlFile string) (Config, error) {\n\tbuf, err := ioutil.ReadFile(yamlFile)\n\n\tif err != nil {\n\t\treturn Config{}, err\n\t}\n\n\treturn LoadConfigFromData(string(buf))\n}", "func New() (Config, error) {\n\tpaths, err := getDefaultPaths()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, p := range paths {\n\t\tconf, err := FromFile(p)\n\t\tif err == nil {\n\t\t\treturn conf, nil\n\t\t}\n\t\t// Return an error if cloud.yaml is not well-formed; otherwise,\n\t\t// just continue to the next file.\n\t\tif parseErr, ok := err.(*ParseError); ok {\n\t\t\treturn nil, parseErr\n\t\t}\n\t}\n\treturn nil, errors.New(\"config: no usable clouds.yaml file found\")\n}", "func ConfigFile(configFile string) ReloaderOption {\n\treturn func(c *ConfigReloader) {\n\t\tc.configFile = configFile\n\t}\n}", "func NewConfig(file string) (*Config, error) {\n\tvar c Config\n\tif file != \"\" {\n\t\tcf, err := os.Open(file)\n\t\tjson.NewDecoder(cf).Decode(&c)\n\t\treturn &c, err\n\t}\n\treturn &c, nil\n}", "func NewProjectConfigFromFile(filename string) (*ProjectConfig, error) {\n\tlogger := util.Logger()\n\tfilepath, _ := filepath.Abs(filename) // nolint: gosec\n\tconfig := &ProjectConfig{\n\t\tFile: filename,\n\t\tPath: filepath,\n\t}\n\n\tyamlFile, err := ioutil.ReadFile(config.File)\n\tif err != nil {\n\t\tlogger.Verbose(\"No project configuration file could be read at: %s\", config.File)\n\t\treturn config, err\n\t}\n\n\tif err := yaml.Unmarshal(yamlFile, config); err != nil {\n\t\tlogger.Channel.Error.Fatalf(\"Failure parsing YAML config: %v\", err)\n\t}\n\n\tif err := config.ValidateConfigVersion(); err != nil {\n\t\tlogger.Channel.Error.Fatalf(\"Failure in %s: %s\", filename, err)\n\t}\n\n\tif len(config.Bin) == 0 {\n\t\tconfig.Bin = \"./bin\"\n\t}\n\n\tfor id, script := range config.Scripts {\n\t\tif script != nil {\n\t\t\tif script.Description == \"\" {\n\t\t\t\tconfig.Scripts[id].Description = fmt.Sprintf(\"Configured operation for '%s'\", id)\n\t\t\t}\n\t\t\tconfig.Scripts[id].ID = id\n\t\t}\n\t}\n\n\treturn config, nil\n}", "func Config(args []string) (config.Config, error) {\n\tif err := fs.Parse(args); err != nil {\n\t\treturn config.Config{}, err\n\t}\n\n\tprepareComplexDefaults()\n\treturn defaults, nil\n}", "func parseDatabaseConfig(filename string) Configs {\n\tvar parsed Configs\n\tbody, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\twithoutERB := parseERB(body)\n\terr = yaml.Unmarshal(withoutERB, &parsed)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\treturn parsed\n}", "func (c *Config) ConfigFile() string {\n\tif c.options.ConfigFile == \"\" || !fs.FileExists(c.options.ConfigFile) {\n\t\treturn filepath.Join(c.ConfigPath(), \"options.yml\")\n\t}\n\n\treturn c.options.ConfigFile\n}", "func Read(filename string) (*Config, error) {\n\tconfig := &Config{\n\t\tPollerConfig: PollerConfig{\n\t\t\tPollInterval: \"2s\",\n\t\t\tTimeout: \"3s\",\n\t\t},\n\t\tTriggersConfig: TriggersConfig{\n\t\t\tXrandr: &XrandrConfig{\n\t\t\t\tXrandrBinary: \"/usr/bin/xrandr\",\n\t\t\t\tIgnoreSegFault: true,\n\t\t\t\tXAuthoritiy: \"/home/$USER/.Xauthority\",\n\t\t\t},\n\t\t},\n\t}\n\n\tcontent, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = yaml.Unmarshal(content, &config); err != nil {\n\t\treturn nil, err\n\t}\n\treturn config, nil\n}", "func ParseConfigFile() Configuration {\n\tfile, _ := os.Open(\"config.json\")\n\tdefer file.Close()\n\tdecoder := json.NewDecoder(file)\n\tconfiguration := Configuration{}\n\terr := decoder.Decode(&configuration)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif configuration.StartDate.IsZero() {\n\t\tconfiguration.StartDate = time.Now().Local()\n\t}\n\tif configuration.EndDate.IsZero() {\n\t\tconfiguration.EndDate = time.Now().Local()\n\t}\n\treturn configuration\n}", "func FromFile(filepath string) (*Config, error) {\n\tcontents, err := ioutil.ReadFile(filepath)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn unmarshall(contents)\n}", "func (p Config) Load(file string) Config {\n\tdata, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar config Config\n\tif err := config.ParseYAML(data); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn config\n}", "func NewConfigFromFile(filePath string) (Config, error) {\n\tbytes, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconf := new(configImpl)\n\terr = jsoniter.ConfigFastest.Unmarshal(bytes, conf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn conf, nil\n}", "func ParseFile(configFilePath string) (*Config, error) {\n\t// Read the config file\n\tconfigData, err := ioutil.ReadFile(configFilePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Parse the config JSON\n\tconfig := Config{}\n\terr = json.Unmarshal(configData, &config)\n\tif err != nil {\n\t\treturn nil, errors.New(\"invalid config file\")\n\t}\n\n\t// Validate the ports\n\tif config.TelnetPort <= 0 {\n\t\treturn nil, errors.New(\"invalid telnet port\")\n\t}\n\n\tif config.WebPort <= 0 {\n\t\treturn nil, errors.New(\"invalid web port\")\n\t}\n\n\t// Validate the web client path\n\tinfo, err := os.Stat(config.WebClientPath)\n\tif (err != nil && os.IsNotExist(err)) || !info.IsDir() {\n\t\treturn nil, errors.New(\"invalid web client path\")\n\t}\n\n\treturn &config, nil\n}", "func loadConfig(file string) (*Config, error) {\n\n\t// Try to get config file, fallback to alternatives\n\tfile, err := getConfigFile(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparsedConfig, err := ini.LooseLoad(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Map sections\n\tserver := ServerConfig{}\n\tparsedConfig.Section(\"server\").MapTo(&server)\n\n\t// Get all sources\n\tsources, err := getSources(parsedConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Get UI configurations\n\tui, err := getUiConfig(parsedConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig := &Config{\n\t\tServer: server,\n\t\tUi: ui,\n\t\tSources: sources,\n\t\tFile: file,\n\t}\n\n\treturn config, nil\n}", "func LoadConfigFile(configFilePath string) *Config {\n\tconfigData := CreateNewConfig()\n\n\tconfigFileData, err := ioutil.ReadFile(configFilePath)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = yaml.Unmarshal([]byte(configFileData), configData)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn configData\n}", "func Configs() DataBase {\n\tvar db DataBase\n\n\tif _, err := toml.DecodeFile(path, &db); err != nil {\n\t\tlog.Fatalf(\"Configs not received: %v\\n%v\", err, db)\n\t}\n\treturn db\n}", "func ReadConfigFile() (*Config, error) {\n\tconfigPath, err := getConfigPath()\n\tif err != nil {\n\t\tlog.Println(\"Error when retrieving config path\\n %v\", err)\n\t\treturn nil, err\n\t}\n\n\t_, err = os.Stat(configPath)\n\tif err != nil {\n\t\tlog.Printf(\"Error when checking if file exists\\n%v\", err)\n\t\treturn nil, err\n\t}\n\n\tviper.SetConfigFile(configPath)\n\terr = viper.ReadInConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Config{\n\t\tOutputFormat: viper.GetString(\"output_format\"),\n\t\tSlackToken: viper.GetString(\"slack_token\"),\n\t\tTodoistToken: viper.GetString(\"todoist_token\"),\n\t}, nil\n}", "func loadConfigFromFile(c Configuration, configPath string) (Configuration, error) {\n\tfile, err := os.Open(configPath)\n\tif err != nil {\n\t\tfmt.Printf(\"error opening config file: %v\", err)\n\t\treturn c, err\n\t}\n\n\tdefer file.Close()\n\terr = json.NewDecoder(file).Decode(&c)\n\tif err != nil {\n\t\tlog.Printf(\"Error decoding config file: %v\", err)\n\t\treturn c, err\n\t}\n\n\treturn c, err\n}", "func ParseFile(p string) (*Config, error) {\n\tf, err := os.Open(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\treturn Parse(f)\n}", "func parseYamlFile(filename string, conf *Config) error {\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn yaml.Unmarshal(data, conf)\n}", "func loadConfig(file string) error {\n\tf, err := os.Open(file) // Open file\n\n\t// Error checking, returns error\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close() // Defer file closing to end of function\n\n\tdecoder := json.NewDecoder(f) // Create json decoder\n\terr = decoder.Decode(&cfg) // Decode the json into the config struct\n\n\t// Error checking\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func getFileConfiguration(t *testing.T, content string) *configuration.Registry {\n\ttmpFile, err := ioutil.TempFile(os.TempDir(), \"configFile-\")\n\trequire.NoError(t, err)\n\tdefer os.Remove(tmpFile.Name())\n\t_, err = tmpFile.Write([]byte(content))\n\trequire.NoError(t, err)\n\trequire.NoError(t, tmpFile.Close())\n\tconfig, err := configuration.New(tmpFile.Name())\n\trequire.NoError(t, err)\n\treturn config\n}", "func loadConfigs(filename string) {\n\tc := Config{}\n\tviper.SetConfigType(\"yaml\")\n\tviper.AddConfigPath(\".\")\n\tviper.SetEnvPrefix(envPrefix)\n\tviper.SetEnvKeyReplacer(strings.NewReplacer(\".\", \"_\", \"-\", \"_\"))\n\tviper.AutomaticEnv()\n\n\tif filename != \"\" {\n\t\tviper.SetConfigFile(filename)\n\t\tif err := viper.MergeInConfig(); err != nil {\n\t\t\tlog.Fatal().Msgf(\"loading configs file [%s] failed: %s\", filename, err)\n\t\t} else {\n\t\t\tlog.Info().Msgf(\"configs file [%s] loaded successfully\", filename)\n\t\t}\n\t} else {\n\t\tlog.Fatal().Msg(\"Config file is not determined\")\n\t}\n\n\terr := viper.Unmarshal(&c, func(config *mapstructure.DecoderConfig) {\n\t\tconfig.TagName = \"yaml\"\n\t})\n\tif err != nil {\n\t\tlog.Fatal().Msg(\"failed on configs unmarshal: \" + err.Error())\n\t}\n\n\tC = c\n}", "func MakeConfigFromFile(path string) (*Config, error) {\n\traw, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcfg := &Config{Global: Global{UserAgentCacheSize: defaultUserAgentCacheSize, ExportWorkers: defaultExportWorkers}}\n\terr = yaml.Unmarshal(raw, cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, rep := range cfg.Global.UserAgentReplacementSettingsRaw {\n\t\tif rep.MatchRe != \"\" {\n\t\t\tcfg.Global.UserAgentReplacementSettings = append(cfg.Global.UserAgentReplacementSettings, UserAgentReplacementSetting{\n\t\t\t\tMatchRe: regexp.MustCompile(rep.MatchRe),\n\t\t\t\tReplacements: rep.Replacements,\n\t\t\t})\n\t\t} else if rep.Match != \"\" {\n\t\t\tcfg.Global.UserAgentReplacementSettings = append(cfg.Global.UserAgentReplacementSettings, UserAgentReplacementSetting{\n\t\t\t\tMatch: rep.Match,\n\t\t\t\tReplacements: rep.Replacements,\n\t\t\t})\n\t\t}\n\t}\n\n\tfor _, rep := range cfg.Global.RequestURIReplacementSettingsRaw {\n\t\tcfg.Global.RequestURIReplacementSettings = append(cfg.Global.RequestURIReplacementSettings, RequestURIReplacementSetting{\n\t\t\tMethod: rep.MatchMethod,\n\t\t\tRegexp: regexp.MustCompile(rep.MatchRe),\n\t\t\tReplacements: rep.Replacements,\n\t\t})\n\t}\n\n\treturn cfg, err\n}", "func ParseConfig(filepath string) error {\n\tf, err := ioutil.ReadFile(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconf := make(map[string]interface{})\n\n\terr = json.Unmarshal(f, &conf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconList := make(map[string]Elem)\n\tconfig = list{self: \"\", value: conList}\n\n\tlog.Printf(\"about to parse config\\n\")\n\tparseMap(conf, &config)\n\tlog.Printf(\"parsed config\\n\")\n\n\treturn nil\n}", "func ReadConfigFile(filename string) (Config, error) {\n\tconfig := DefaultConfig()\n\tif buf, err := ioutil.ReadFile(filename); err != nil {\n\t\treturn config, err\n\t} else if err := toml.Unmarshal(buf, &config); err != nil {\n\t\treturn config, err\n\t}\n\treturn config, nil\n}", "func (cfg *Config) Parse(file string) error {\n\tb, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = yaml.Unmarshal(b, cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func LoadConfig(file string, settings interface{}) error {\n\n\tif file != \"\" {\n\n\t\tabsConfPath, err := filepath.Abs(file)\n\t\tif err != nil {\n\t\t\tlog.Debug(err)\n\t\t\treturn err\n\t\t}\n\n\t\tif confData, err := ioutil.ReadFile(absConfPath); err != nil {\n\t\t\tlog.Debug(err)\n\t\t\treturn err\n\t\t} else {\n\t\t\tif err := yaml.Unmarshal(confData, settings); err != nil {\n\t\t\t\tlog.Debug(err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\treturn errors.New(\"file is nil\")\n}", "func Config() Configuration {\n\treturn NewConfig(\"config\", \".\", \"yml\")\n}", "func FromFile(path string) (*Config, error) {\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar cfg Config\n\tif err := json.Unmarshal(b, &cfg); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &cfg, nil\n}", "func LoadConfigFromFile(filePath string) (*Config, error) {\n\tif _, err := os.Stat(filePath); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar conf Config\n\tif _, err := toml.DecodeFile(filePath, &conf); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &conf, nil\n}", "func ReadConfigFile(cfgFile string, Cmd *cobra.Command, commandArgs *CommandArgs) error {\n\n\tviper.SetDefault(\"DockerAddress\", \"unix:///var/run/docker.sock\")\n\tviper.SetDefault(\"influxdb-host\", \"http://influxdb_master1:8086\")\n\tviper.SetDefault(\"influxdb-dbname\", \"sgms\")\n\tviper.SetDefault(\"influxdb-user\", \"sgms\")\n\tviper.SetDefault(\"log-level\", \"info\")\n\n\tif cfgFile == \"\" { // if a config file was not found, then construct a name\n\t\tdeployEnv := os.Getenv(\"DEPLOY_ENV\")\n\t\tif deployEnv == \"\" {\n\t\t\tviper.SetDefault(\"influxdb-password\", \"dev\") // NB: this will fail when not in dev unless password is specified elsewhere\n\t\t\tcommandArgs.ConfigFile = \"./configs/\" + Cmd.Use + \".yaml\"\n\t\t} else {\n\t\t\tviper.SetDefault(\"influxdb-password\", deployEnv) // NB: this will likely fail unless password is specified elsewhere\n\t\t\tcommandArgs.ConfigFile = \"./configs/\" + Cmd.Use + \"/\" + Cmd.Use + \"-\" + deployEnv + \".yaml\"\n\t\t}\n\t} else {\n\t\t// If a config file was specified, then use it\n\t\tcommandArgs.ConfigFile = cfgFile\n\t}\n\tviper.SetConfigFile(commandArgs.ConfigFile)\n\n\tc := viper.ReadInConfig()\n\n\t// config file may have specified a log level..\n\tl, _ := log.ParseLevel(viper.Get(\"log-level\").(string))\n\tlog.SetLevel(l)\n\n\treturn c\n}", "func NewConfig(filename *string) (ServiceConfig, error) {\n\tcfgFile, err := ioutil.ReadFile(*filename)\n\tif err != nil {\n\t\treturn ServiceConfig{}, err\n\t}\n\tc := ServiceConfig{}\n\terr = yaml.Unmarshal(cfgFile, &c)\n\tif err != nil {\n\t\treturn ServiceConfig{}, err\n\t}\n\n\tif len(c.Jobs) == 0 {\n\t\tlog.Fatalln(\"No jobs were configured!\")\n\t}\n\n\treturn c, nil\n}", "func parseRawConfig(filename string) rawConfig {\n\t// I read the file content...\n\tyamlFile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tlog.Fatalf(\"Cannot read config file: %v\", err)\n\t}\n\t// ... and I unmarshal the YAML into the raw structure\n\trawconfig := rawConfig{}\n\terr = yaml.Unmarshal(yamlFile, &rawconfig)\n\tif err != nil {\n\t\tlog.Fatalf(\"Cannot parse config file: %v\", err)\n\t}\n\t// Finally, I return the raw structure\n\treturn rawconfig\n}", "func parseConfig(file *os.File) (Config, error) {\n\tbuilderConfig := Config{}\n\ttomlMetadata, err := toml.NewDecoder(file).Decode(&builderConfig)\n\tif err != nil {\n\t\treturn Config{}, errors.Wrap(err, \"decoding toml contents\")\n\t}\n\n\tundecodedKeys := tomlMetadata.Undecoded()\n\tif len(undecodedKeys) > 0 {\n\t\tunknownElementsMsg := config.FormatUndecodedKeys(undecodedKeys)\n\n\t\treturn Config{}, errors.Errorf(\"%s in %s\",\n\t\t\tunknownElementsMsg,\n\t\t\tstyle.Symbol(file.Name()),\n\t\t)\n\t}\n\n\treturn builderConfig, nil\n}", "func NewConfig(configFile string) (*Config, error) {\n\n\tconfig := new(Config)\n\tdefaults.SetDefaults(config)\n\n\tconfigBytes, err := ioutil.ReadFile(configFile)\n\tif err == nil {\n\t\terr = yaml.Unmarshal(configBytes, &config)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif err := configor.Load(config); err != nil {\n\t\treturn nil, err\n\t}\n\treturn config, nil\n}", "func NewConfig(configFile string) Config {\n\tdata, err := ioutil.ReadFile(configFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tvar config Config\n\terr = json.Unmarshal(data, &config)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn config\n}", "func ParseFile(file string) (*Config, error) {\n\tdata, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn Parse(data)\n}", "func NewConfig(yamlFile string) (*Config, error) {\n\tconfig := Config{}\n\tsource, err := ioutil.ReadFile(yamlFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = yaml.Unmarshal(source, &config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Ensure a proper LogLevel was provided\n\tif config.LogLevel == \"\" {\n\t\tconfig.LogLevel = \"info\"\n\t} else {\n\t\t_, err := logrus.ParseLevel(config.LogLevel)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Set a default port for the HTTP listener\n\tif config.HTTPPort == 0 {\n\t\tconfig.HTTPPort = 8080\n\t}\n\n\t// Set a default port for the TCP listener\n\tif config.TCPPort == 0 {\n\t\tconfig.TCPPort = 6000\n\t}\n\n\treturn &config, nil\n}", "func ParseConfigFile(configFile string) (*Config, error) {\n\tvar config Config\n\t// attempt to read the given config file\n\tif _, err := toml.DecodeFile(configFile, &config); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// override values with environment variables if specified\n\tif err := envOverride(&config); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Check file perms from config\n\tif config.GoEnv == \"production\" {\n\t\tif err := checkFilePerms(configFile, config.FilterFile); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// validate all required fields have been populated\n\tif err := validateConfig(config); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &config, nil\n}", "func ReadConfig(file string) (entity.Config, error) {\n\n\tconfig := entity.Config{}\n\tlogger.Info(\"reading configuration file...\")\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\tlogger.Success(\"configuration file has been loaded successfully\")\n\n\t// parse yaml\n\terr = yaml.NewDecoder(f).Decode(&config)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\n\treturn config, nil\n}", "func parseConfig(path string) (*structs.Config, error) {\n\tyamlFile, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to open config file: %v\", err)\n\t}\n\tvar c *structs.Config\n\terr = yaml.Unmarshal(yamlFile, &c)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to parse config file: %v\", err)\n\t}\n\n\treturn c, nil\n}", "func LoadConfig(file string) (*Config, error) {\n\tb, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif ext := path.Ext(file); ext == \".yaml\" || ext == \".yml\" {\n\t\tb, err = yaml.YAMLToJSON(b)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tconfig := &Config{}\n\tif err = json.Unmarshal(b, config); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfixMbeanNames(config)\n\treturn config, nil\n}", "func loadConfigFromFile(path string) (*configuration, error) {\n\t// open config file\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\t// read config file\n\tbuf, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn unmarshalConfig(buf)\n}", "func readConfigFile(cfgFile string) (Config, error) {\n\n\tlog.Info(\"RabbitRelay: reading configuration from: \", cfgFile)\n\n\tconfig := Config{}\n\n\tvar err error\n\tfileContents, err := ioutil.ReadFile(cfgFile)\n\n\tif err != nil {\n\n\t\tlog.Critical(\"Error reading config file: \", err)\n\n\t} else {\n\n\t\t// This doesn't work, only the top level items are populated\n\t\t// err = jsonpointer.FindDecode(fileContents,\"\",&config)\n\t\terr = jsonpointer.FindDecode(fileContents, \"/masterRabbitServer\", &config.masterServer)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error reading master server config: \", err)\n\t\t\treturn config, err\n\t\t}\n\t\terr = jsonpointer.FindDecode(fileContents, \"/slaveRabbitServers\", &config.slaveServers)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error reading slave server config: \", err)\n\t\t\treturn config, err\n\t\t}\n\t}\n\treturn config, err\n}", "func (c Config) Parse(file string) (initializedConfig Config) {\n\tif _, err := os.Stat(file); os.IsNotExist(err) {\n\t\tlog.WithFields(log.Fields{\"file\": file, \"error\": err}).Panic(\"File does not exist\")\n\t}\n\n\tb, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\"file\": file, \"error\": err}).Panic(\"Can't parse config file\")\n\t}\n\n\tif err = json.Unmarshal(b, &initializedConfig); err != nil {\n\t\tlog.WithFields(log.Fields{\"file\": file, \"error\": err}).Panic(\"Can't unmarshal JSON\")\n\t}\n\n\treturn\n}", "func getConfigFromFile(fileName string) (config *BotConfig, err error) {\n\tfile, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdecoder := json.NewDecoder(file)\n\terr = decoder.Decode(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn config, err\n}", "func LoadFile(configs *[]load.Config, f os.FileInfo, dirPath string) error {\n\tfilePath := path.Join(dirPath, f.Name())\n\n\tb, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\tload.Logrus.WithFields(logrus.Fields{\n\t\t\t\"file\": filePath,\n\t\t\t\"err\": err,\n\t\t}).Error(\"config: failed to read config file\")\n\t\treturn err\n\t}\n\n\tymlStr := string(b)\n\tSubEnvVariables(&ymlStr)\n\tSubTimestamps(&ymlStr, time.Now())\n\n\terr = LoadV4IntegrationConfig(ymlStr, configs, f.Name(), dirPath)\n\tif err != nil {\n\t\t// load old configuration\n\t\tif errors.Is(err, errNoV4IntegrationsFound) {\n\t\t\tconfig, err := ReadYML(ymlStr)\n\t\t\tif err != nil {\n\t\t\t\tload.Logrus.WithFields(logrus.Fields{\n\t\t\t\t\t\"file\": filePath,\n\t\t\t\t}).WithError(err).Error(\"config: failed to load config file\")\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tapplyFlexMeta(&config)\n\n\t\t\tconfig.FileName = f.Name()\n\t\t\tconfig.FilePath = dirPath\n\t\t\tif config.Name == \"\" {\n\t\t\t\tload.Logrus.WithFields(logrus.Fields{\n\t\t\t\t\t\"file\": filePath,\n\t\t\t\t}).WithError(err).Error(\"config: flexConfig requires name\")\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tcheckIngestConfigs(&config)\n\n\t\t\t// if lookup files exist we need to potentially create multiple config files\n\t\t\tif config.LookupFile != \"\" {\n\t\t\t\terr = SubLookupFileData(configs, config)\n\t\t\t\tif err != nil {\n\t\t\t\t\tload.Logrus.WithFields(logrus.Fields{\n\t\t\t\t\t\t\"file\": filePath,\n\t\t\t\t\t}).WithError(err).Error(\"config: failed to sub lookup file data\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t*configs = append(*configs, config)\n\t\t\t}\n\t\t} else {\n\t\t\tload.Logrus.WithFields(logrus.Fields{\n\t\t\t\t\"file\": filePath,\n\t\t\t}).WithError(err).Error(\"config: failed to load v4 config file\")\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func NewConfigFromFile() *Config {\n\tfilename := os.ExpandEnv(configFilename)\n\tbytes, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tconfig := new(Config)\n\n\terr = json.Unmarshal(bytes, &config)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\treturn config\n}", "func ConfigFile(inp string) string {\n\tif inp != \"\" {\n\t\tpath := ExpandUser(inp)\n\t\tif FileExists(path) {\n\t\t\treturn path\n\t\t}\n\t}\n\n\tif env := os.Getenv(\"DOLA_CONFIG\"); env != \"\" {\n\t\tpath := ExpandUser(env)\n\t\tif FileExists(path) {\n\t\t\treturn path\n\t\t}\n\t}\n\n\tif path := ExpandUser(\"~/.dola/config.json\"); FileExists(path) {\n\t\treturn path\n\t}\n\n\treturn \"\"\n}", "func New() (*Config, error) {\n\tc := &Config{}\n\tconfigPath := os.Getenv(\"CONFIG_PATH\")\n\tconfigFile := filepath.Join(configPath, ConfigFileName)\n\tfile, err := os.Open(configFile)\n\tdefer file.Close()\n\tif err != nil {\n\t\treturn c, err\n\t}\n\n\tb, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\n\tif len(b) != 0 {\n\t\tyaml.Unmarshal(b, c)\n\t}\n\treturn c, nil\n}" ]
[ "0.6919763", "0.6766569", "0.6732922", "0.6692703", "0.66245663", "0.6600291", "0.6581049", "0.6539759", "0.6483543", "0.6477833", "0.6439898", "0.64042306", "0.6398328", "0.63772", "0.63758934", "0.63520354", "0.633113", "0.6304878", "0.6298197", "0.62972575", "0.62972575", "0.62972575", "0.62778306", "0.62730145", "0.6259533", "0.6258935", "0.62526697", "0.624573", "0.62451804", "0.6227105", "0.62235683", "0.6222649", "0.6213895", "0.61962795", "0.6168504", "0.6165366", "0.6162366", "0.61616373", "0.61577463", "0.615539", "0.6149017", "0.6110822", "0.60953826", "0.6084518", "0.60798055", "0.6044532", "0.6038092", "0.60321563", "0.6028261", "0.601775", "0.6012495", "0.60103315", "0.60075647", "0.6007091", "0.5987467", "0.59749305", "0.5969194", "0.59679496", "0.5966186", "0.5955583", "0.5952959", "0.5949843", "0.5944295", "0.5943489", "0.59376544", "0.5937451", "0.5928416", "0.5920632", "0.5916596", "0.5916089", "0.59132093", "0.5910563", "0.59100753", "0.59071076", "0.5907094", "0.59068036", "0.59037584", "0.5899838", "0.58909655", "0.58905846", "0.5887164", "0.5884758", "0.58839554", "0.5878951", "0.5874261", "0.58666897", "0.5863039", "0.5860368", "0.58599323", "0.5859064", "0.58525616", "0.58495647", "0.5847868", "0.584767", "0.5843579", "0.5843405", "0.5837014", "0.5836743", "0.58366245", "0.5834616" ]
0.77319026
0
Apply creates a new Config with nonempty values from the provided Config overriding the options of the base Config
func (c *Config) Apply(b *Config) *Config { newCfg := new(Config) if b.Token == "" { newCfg.Token = c.Token } else { newCfg.Token = b.Token } if b.URL == "" { newCfg.URL = c.URL } else { newCfg.URL = b.URL } return newCfg }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Config) Apply(cfg *Config) {\n\tif cfg == nil {\n\t\treturn\n\t}\n\n\tc.JrnlCtrlConfig.Apply(&cfg.JrnlCtrlConfig)\n\tc.PipesConfig.Apply(&cfg.PipesConfig)\n\n\tif cfg.BaseDir != \"\" {\n\t\tc.BaseDir = cfg.BaseDir\n\t}\n\tif cfg.HostHostId > 0 {\n\t\tc.HostHostId = cfg.HostHostId\n\t}\n\tif !reflect.DeepEqual(c.PublicApiRpc, cfg.PublicApiRpc) {\n\t\tc.PublicApiRpc = cfg.PublicApiRpc\n\t}\n\tif !reflect.DeepEqual(c.PrivateApiRpc, cfg.PrivateApiRpc) {\n\t\tc.PrivateApiRpc = cfg.PrivateApiRpc\n\t}\n\tif cfg.HostLeaseTTLSec > 0 {\n\t\tc.HostLeaseTTLSec = cfg.HostLeaseTTLSec\n\t}\n\tif cfg.HostRegisterTimeoutSec > 0 {\n\t\tc.HostRegisterTimeoutSec = cfg.HostRegisterTimeoutSec\n\t}\n}", "func (cfg *Config) Apply(opts ...Option) error {\n\tfor _, opt := range opts {\n\t\tif opt == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif err := opt(cfg); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (c Config) Merge(newcfg *Config) *Config {\n\tif newcfg == nil {\n\t\treturn &c\n\t}\n\n\tcfg := Config{}\n\n\tif newcfg.Credentials != nil {\n\t\tcfg.Credentials = newcfg.Credentials\n\t} else {\n\t\tcfg.Credentials = c.Credentials\n\t}\n\n\tif newcfg.Endpoint != \"\" {\n\t\tcfg.Endpoint = newcfg.Endpoint\n\t} else {\n\t\tcfg.Endpoint = c.Endpoint\n\t}\n\n\tif newcfg.Region != \"\" {\n\t\tcfg.Region = newcfg.Region\n\t} else {\n\t\tcfg.Region = c.Region\n\t}\n\n\tif newcfg.DisableSSL {\n\t\tcfg.DisableSSL = newcfg.DisableSSL\n\t} else {\n\t\tcfg.DisableSSL = c.DisableSSL\n\t}\n\n\tif newcfg.ManualSend {\n\t\tcfg.ManualSend = newcfg.ManualSend\n\t} else {\n\t\tcfg.ManualSend = c.ManualSend\n\t}\n\n\tif newcfg.HTTPClient != nil {\n\t\tcfg.HTTPClient = newcfg.HTTPClient\n\t} else {\n\t\tcfg.HTTPClient = c.HTTPClient\n\t}\n\n\tif newcfg.LogHTTPBody {\n\t\tcfg.LogHTTPBody = newcfg.LogHTTPBody\n\t} else {\n\t\tcfg.LogHTTPBody = c.LogHTTPBody\n\t}\n\n\tif newcfg.LogLevel != 0 {\n\t\tcfg.LogLevel = newcfg.LogLevel\n\t} else {\n\t\tcfg.LogLevel = c.LogLevel\n\t}\n\n\tif newcfg.Logger != nil {\n\t\tcfg.Logger = newcfg.Logger\n\t} else {\n\t\tcfg.Logger = c.Logger\n\t}\n\n\tif newcfg.MaxRetries != DefaultRetries {\n\t\tcfg.MaxRetries = newcfg.MaxRetries\n\t} else {\n\t\tcfg.MaxRetries = c.MaxRetries\n\t}\n\n\tif newcfg.DisableParamValidation {\n\t\tcfg.DisableParamValidation = newcfg.DisableParamValidation\n\t} else {\n\t\tcfg.DisableParamValidation = c.DisableParamValidation\n\t}\n\n\tif newcfg.DisableComputeChecksums {\n\t\tcfg.DisableComputeChecksums = newcfg.DisableComputeChecksums\n\t} else {\n\t\tcfg.DisableComputeChecksums = c.DisableComputeChecksums\n\t}\n\n\tif newcfg.S3ForcePathStyle {\n\t\tcfg.S3ForcePathStyle = newcfg.S3ForcePathStyle\n\t} else {\n\t\tcfg.S3ForcePathStyle = c.S3ForcePathStyle\n\t}\n\n\tif newcfg.DomainMode {\n\t\tcfg.DomainMode = newcfg.DomainMode\n\t} else {\n\t\tcfg.DomainMode = c.DomainMode\n\t}\n\tif newcfg.SignerVersion != \"\" {\n\t\tcfg.SignerVersion = newcfg.SignerVersion\n\t} else {\n\t\tcfg.SignerVersion = c.SignerVersion\n\t}\n\treturn &cfg\n}", "func (cfg Config) Merge(override Config) Config {\n\tmerged := Config{\n\t\tID: cfg.ID,\n\t\tName: cfg.Name,\n\t\tDiscoveryImpl: cfg.DiscoveryImpl,\n\t\tDiscoveryFlagsByImpl: map[string]map[string]string{},\n\t\tTabletFQDNTmplStr: cfg.TabletFQDNTmplStr,\n\t\tVtSQLFlags: map[string]string{},\n\t\tVtctldFlags: map[string]string{},\n\t\tBackupReadPoolConfig: cfg.BackupReadPoolConfig.merge(override.BackupReadPoolConfig),\n\t\tSchemaReadPoolConfig: cfg.SchemaReadPoolConfig.merge(override.SchemaReadPoolConfig),\n\t\tTopoReadPoolConfig: cfg.TopoReadPoolConfig.merge(override.TopoReadPoolConfig),\n\t\tTopoRWPoolConfig: cfg.TopoRWPoolConfig.merge(override.TopoRWPoolConfig),\n\t\tWorkflowReadPoolConfig: cfg.WorkflowReadPoolConfig.merge(override.WorkflowReadPoolConfig),\n\t\tEmergencyFailoverPoolConfig: cfg.EmergencyFailoverPoolConfig.merge(override.EmergencyFailoverPoolConfig),\n\t\tFailoverPoolConfig: cfg.FailoverPoolConfig.merge(override.FailoverPoolConfig),\n\t\tSchemaCacheConfig: mergeCacheConfigs(cfg.SchemaCacheConfig, override.SchemaCacheConfig),\n\t}\n\n\tif override.ID != \"\" {\n\t\tmerged.ID = override.ID\n\t}\n\n\tif override.Name != \"\" {\n\t\tmerged.Name = override.Name\n\t}\n\n\tif override.DiscoveryImpl != \"\" {\n\t\tmerged.DiscoveryImpl = override.DiscoveryImpl\n\t}\n\n\tif override.TabletFQDNTmplStr != \"\" {\n\t\tmerged.TabletFQDNTmplStr = override.TabletFQDNTmplStr\n\t}\n\n\t// first, the default flags\n\tmerged.DiscoveryFlagsByImpl.Merge(cfg.DiscoveryFlagsByImpl)\n\t// then, apply any overrides\n\tmerged.DiscoveryFlagsByImpl.Merge(override.DiscoveryFlagsByImpl)\n\n\tmergeStringMap(merged.VtSQLFlags, cfg.VtSQLFlags)\n\tmergeStringMap(merged.VtSQLFlags, override.VtSQLFlags)\n\n\tmergeStringMap(merged.VtctldFlags, cfg.VtctldFlags)\n\tmergeStringMap(merged.VtctldFlags, override.VtctldFlags)\n\n\treturn merged\n}", "func (o *Options) ApplyTo(c *config.Config) error {\n\tcfg, err := loadConfigFromFile(o.ConfigFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.ComponentConfig = *cfg\n\n\treturn nil\n}", "func (c *Config) Merge(b *Config) *Config {\n\tresult := *c\n\n\tif b.LogLevel != \"\" {\n\t\tresult.LogLevel = b.LogLevel\n\t}\n\tif b.BindAddr != \"\" {\n\t\tresult.BindAddr = b.BindAddr\n\t}\n\tif b.EnableDebug {\n\t\tresult.EnableDebug = true\n\t}\n\t\n\t// Apply the server config\n\tif result.Server == nil && b.Server != nil {\n\t\tserver := *b.Server\n\t\tresult.Server = &server\n\t} else if b.Server != nil {\n\t\tresult.Server = result.Server.Merge(b.Server)\n\t}\n\n\t// Apply the ports config\n\tif result.Ports == nil && b.Ports != nil {\n\t\tports := *b.Ports\n\t\tresult.Ports = &ports\n\t} else if b.Ports != nil {\n\t\tresult.Ports = result.Ports.Merge(b.Ports)\n\t}\n\n\t// Apply the address config\n\tif result.Addresses == nil && b.Addresses != nil {\n\t\taddrs := *b.Addresses\n\t\tresult.Addresses = &addrs\n\t} else if b.Addresses != nil {\n\t\tresult.Addresses = result.Addresses.Merge(b.Addresses)\n\t}\n\t\n\treturn &result\n}", "func (c *Config) Merge(b *Config) *Config {\n\tconfig := *c\n\n\tif b.Nomad != \"\" {\n\t\tconfig.Nomad = b.Nomad\n\t}\n\n\tif b.Consul != \"\" {\n\t\tconfig.Consul = b.Consul\n\t}\n\n\tif b.LogLevel != \"\" {\n\t\tconfig.LogLevel = b.LogLevel\n\t}\n\n\tif b.ScalingInterval > 0 {\n\t\tconfig.ScalingInterval = b.ScalingInterval\n\t}\n\n\tif b.Region != \"\" {\n\t\tconfig.Region = b.Region\n\t}\n\n\t// Apply the ClusterScaling config\n\tif config.ClusterScaling == nil && b.ClusterScaling != nil {\n\t\tclusterScaling := *b.ClusterScaling\n\t\tconfig.ClusterScaling = &clusterScaling\n\t} else if b.ClusterScaling != nil {\n\t\tconfig.ClusterScaling = config.ClusterScaling.Merge(b.ClusterScaling)\n\t}\n\n\t// Apply the JobScaling config\n\tif config.JobScaling == nil && b.JobScaling != nil {\n\t\tjobScaling := *b.JobScaling\n\t\tconfig.JobScaling = &jobScaling\n\t} else if b.JobScaling != nil {\n\t\tconfig.JobScaling = config.JobScaling.Merge(b.JobScaling)\n\t}\n\n\t// Apply the Telemetry config\n\tif config.Telemetry == nil && b.Telemetry != nil {\n\t\ttelemetry := *b.Telemetry\n\t\tconfig.Telemetry = &telemetry\n\t} else if b.Telemetry != nil {\n\t\tconfig.Telemetry = config.Telemetry.Merge(b.Telemetry)\n\t}\n\n\t// Apply the Notification config\n\tif config.Notification == nil && b.Notification != nil {\n\t\tnotification := *b.Notification\n\t\tconfig.Notification = &notification\n\t} else if b.Notification != nil {\n\t\tconfig.Notification = config.Notification.Merge(b.Notification)\n\t}\n\n\treturn &config\n}", "func (g *generator) ApplyConfig(config *generation.Config) generation.Generator {\n\tif config == nil || config.SchemaPatch == nil {\n\t\treturn g\n\t}\n\n\tfeatureSets := []sets.String{}\n\tfor _, featureSet := range config.SchemaPatch.RequiredFeatureSets {\n\t\tfeatureSets = append(featureSets, sets.NewString(strings.Split(featureSet, \",\")...))\n\t}\n\n\treturn NewGenerator(Options{\n\t\tControllerGen: g.controllerGen,\n\t\tDisabled: config.SchemaPatch.Disabled,\n\t\tRequiredFeatureSets: featureSets,\n\t\tVerify: g.verify,\n\t})\n}", "func (config *Config) Apply() {\n\tconfig.SetContext()\n\tconfig.SetNamespace()\n\tconfig.SetEnv()\n}", "func (this *Config) Apply() error {\n\tinternet.ApplyGlobalNetworkSettings(this.NetworkSettings)\n\treturn nil\n}", "func Apply(c Config) {\n\t// Normalize values\n\tif c.StdErrThreshold == 0 {\n\t\tc.StdErrThreshold = DefaultConfig.StdErrThreshold\n\t}\n\n\tif c.Verbosity == 0 {\n\t\tc.Verbosity = DefaultConfig.Verbosity\n\t}\n\n\tif c.OutputDir == \"\" {\n\t\tc.OutputDir = DefaultConfig.OutputDir\n\t}\n\n\t// Mimic flag.Set\n\tlogging.toStderr = (c.Output == OutputStdErr)\n\tlogging.alsoToStderr = (c.Output == OutputBoth)\n\tlogging.stderrThreshold.Set(strconv.FormatInt(int64(c.StdErrThreshold), 10))\n\tlogging.verbosity.Set(strconv.FormatInt(int64(c.Verbosity), 10))\n\n\tvmodules := make([]string, len(c.VerbosityModules))\n\tfor i, vm := range c.VerbosityModules {\n\t\tvmodules[i] = fmt.Sprintf(\"%s=%s\", vm.Module, vm.Verbosity)\n\t}\n\tlogging.vmodule.Set(strings.Join(vmodules, \",\"))\n\n\t// See glog_file.go\n\tlogDirs = []string{c.OutputDir}\n}", "func (o *Options) Apply() {\n\tif o == nil {\n\t\treturn\n\t}\n\tif len(o.ShowHiddenMetricsForVersion) > 0 {\n\t\tSetShowHidden()\n\t}\n\t// set disabled metrics\n\tfor _, metricName := range o.DisabledMetrics {\n\t\tSetDisabledMetric(metricName)\n\t}\n\tif o.AllowListMapping != nil {\n\t\tSetLabelAllowListFromCLI(o.AllowListMapping)\n\t}\n}", "func (c ProducerConfig) Apply(kafkaConf *kafkalib.ConfigMap) {\n\tif timeout := c.DeliveryTimeout; timeout > 0 {\n\t\t_ = kafkaConf.SetKey(\"delivery.timeout.ms\", int(timeout.Milliseconds()))\n\t}\n\n\tif size := c.BatchSize; size > 0 {\n\t\t_ = kafkaConf.SetKey(\"queue.buffering.max.messages\", size)\n\t}\n\n\tif period := c.FlushPeriod; period > 0 {\n\t\t_ = kafkaConf.SetKey(\"queue.buffering.max.ms\", int(period.Milliseconds()))\n\t}\n}", "func (nc *NabtoClient) ApplyConfig() {\n\n}", "func (c *SetClusterConfigCommand) Apply(context raft.Context) (interface{}, error) {\n\tps, _ := context.Server().Context().(*PeerServer)\n\tps.SetClusterConfig(c.Config)\n\treturn nil, nil\n}", "func (c *Config) Merge(newConfig *Config) {\n\tif newConfig.SitePath != \"\" {\n\t\tc.SitePath = newConfig.SitePath\n\t}\n\n\tif newConfig.TmpDir != \"\" {\n\t\tc.TmpDir = newConfig.TmpDir\n\t}\n\n\tif newConfig.ApplicationName != \"\" {\n\t\tc.ApplicationName = newConfig.ApplicationName\n\t}\n\n\tif newConfig.ConfigFilePath != \"\" {\n\t\tc.ConfigFilePath = newConfig.ConfigFilePath\n\t}\n\n\tif newConfig.GitPath != \"\" {\n\t\tc.GitPath = newConfig.GitPath\n\t}\n\tc.CanEdit = newConfig.CanEdit\n}", "func (c *DedupConfig) Merge(o *DedupConfig) *DedupConfig {\n\tif c == nil {\n\t\tif o == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn o.Copy()\n\t}\n\n\tif o == nil {\n\t\treturn c.Copy()\n\t}\n\n\tr := c.Copy()\n\n\tif o.Enabled != nil {\n\t\tr.Enabled = o.Enabled\n\t}\n\n\tif o.MaxStale != nil {\n\t\tr.MaxStale = o.MaxStale\n\t}\n\n\tif o.Prefix != nil {\n\t\tr.Prefix = o.Prefix\n\t}\n\n\tif o.TTL != nil {\n\t\tr.TTL = o.TTL\n\t}\n\n\tif o.BlockQueryWaitTime != nil {\n\t\tr.BlockQueryWaitTime = o.BlockQueryWaitTime\n\t}\n\n\treturn r\n}", "func (e *Explore) ApplyConfig(cfg *config.Config) error {\n\tjobs := make([]string, 0, len(cfg.ScrapeConfigs))\n\tfor _, j := range cfg.ScrapeConfigs {\n\t\tjobs = append(jobs, j.JobName)\n\t}\n\n\te.targetsLock.Lock()\n\tdefer e.targetsLock.Unlock()\n\n\tnewTargets := map[string]map[uint64]*exploringTarget{}\n\tfor k, v := range e.targets {\n\t\tif types.FindString(k, jobs...) {\n\t\t\tnewTargets[k] = v\n\t\t}\n\t}\n\te.targets = newTargets\n\treturn nil\n}", "func ApplyLegacyConfig(cfg config.Provider, conf *Config) error {\n\tif conf.Style == DefaultConfig.Style {\n\t\tif s := cfg.GetString(\"pygmentsStyle\"); s != \"\" {\n\t\t\tconf.Style = s\n\t\t}\n\t}\n\n\tif conf.NoClasses == DefaultConfig.NoClasses && cfg.IsSet(\"pygmentsUseClasses\") {\n\t\tconf.NoClasses = !cfg.GetBool(\"pygmentsUseClasses\")\n\t}\n\n\tif conf.CodeFences == DefaultConfig.CodeFences && cfg.IsSet(\"pygmentsCodeFences\") {\n\t\tconf.CodeFences = cfg.GetBool(\"pygmentsCodeFences\")\n\t}\n\n\tif conf.GuessSyntax == DefaultConfig.GuessSyntax && cfg.IsSet(\"pygmentsCodefencesGuessSyntax\") {\n\t\tconf.GuessSyntax = cfg.GetBool(\"pygmentsCodefencesGuessSyntax\")\n\t}\n\n\tif cfg.IsSet(\"pygmentsOptions\") {\n\t\tif err := applyOptionsFromString(cfg.GetString(\"pygmentsOptions\"), conf); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *Config) Adjust(meta *toml.MetaData) {\n\tif len(c.Log.Format) == 0 {\n\t\tc.Log.Format = defaultLogFormat\n\t}\n\tif !meta.IsDefined(\"round\") {\n\t\tconfigutil.AdjustInt(&c.Round, defaultRound)\n\t}\n\n\tif !meta.IsDefined(\"store-count\") {\n\t\tconfigutil.AdjustInt(&c.StoreCount, defaultStoreCount)\n\t}\n\tif !meta.IsDefined(\"region-count\") {\n\t\tconfigutil.AdjustInt(&c.RegionCount, defaultRegionCount)\n\t}\n\n\tif !meta.IsDefined(\"key-length\") {\n\t\tconfigutil.AdjustInt(&c.KeyLength, defaultKeyLength)\n\t}\n\n\tif !meta.IsDefined(\"replica\") {\n\t\tconfigutil.AdjustInt(&c.Replica, defaultReplica)\n\t}\n\n\tif !meta.IsDefined(\"leader-update-ratio\") {\n\t\tconfigutil.AdjustFloat64(&c.LeaderUpdateRatio, defaultLeaderUpdateRatio)\n\t}\n\tif !meta.IsDefined(\"epoch-update-ratio\") {\n\t\tconfigutil.AdjustFloat64(&c.EpochUpdateRatio, defaultEpochUpdateRatio)\n\t}\n\tif !meta.IsDefined(\"space-update-ratio\") {\n\t\tconfigutil.AdjustFloat64(&c.SpaceUpdateRatio, defaultSpaceUpdateRatio)\n\t}\n\tif !meta.IsDefined(\"flow-update-ratio\") {\n\t\tconfigutil.AdjustFloat64(&c.FlowUpdateRatio, defaultFlowUpdateRatio)\n\t}\n\tif !meta.IsDefined(\"sample\") {\n\t\tc.Sample = defaultSample\n\t}\n}", "func (c *AppConfig) Apply(opts []AppOption) error {\r\n\tfor _, o := range opts {\r\n\t\tif err := o(c); err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\t}\r\n\treturn nil\r\n}", "func (m *Manager) ApplyConfig(cfg map[string]sd_config.ServiceDiscoveryConfig) error {\n\tm.mtx.Lock()\n\tdefer m.mtx.Unlock()\n\n\tm.cancelDiscoverers()\n\tfor name, scfg := range cfg {\n\t\tfor provName, prov := range m.providersFromConfig(scfg) {\n\t\t\tm.startProvider(m.ctx, poolKey{setName: name, provider: provName}, prov)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s *Storage) ApplyConfig(conf *config.Config) error {\n\ts.mtx.Lock()\n\tdefer s.mtx.Unlock()\n\n\ts.externalLabels = conf.GlobalConfig.ExternalLabels\n\treturn nil\n}", "func (self *RRSMNode) ApplyConfig(nodes []string) error {\n\tif len(nodes) <= 0 {\n\t\treturn fmt.Errorf(\"config err: amounts of nodes needed to be a positive number!\")\n\t}\n\tself.config.Nodes = nodes\n\n\t// rebuild a node\n\t// ....\n\n\treturn nil\n}", "func (o *Options) applyDefaults(in *componentconfig.CoordinatorConfiguration) (*componentconfig.CoordinatorConfiguration, error) {\n\tcomponentconfig.SetDefaultsCoordinatorConfiguration(in)\n\treturn in, nil\n}", "func (config *Config) Merge(conf2 *Config) {\n\tconfig.Delay = setInt(config.Delay, conf2.Delay)\n\tconfig.Domains = setStringSlice([]*string(config.Domains), []*string(conf2.Domains))\n\tconfig.DynamodbTableName = setString(config.DynamodbTableName, conf2.DynamodbTableName)\n\tconfig.Email = setString(config.Email, conf2.Email)\n\tconfig.Fortios = setBool(config.Fortios, conf2.Fortios)\n\tconfig.FortiosAdminServerCert = setBool(config.FortiosAdminServerCert, conf2.FortiosAdminServerCert)\n\tconfig.FortiosBaseURL = setString(config.FortiosBaseURL, conf2.FortiosBaseURL)\n\tconfig.FortiosSslSSHProfiles = setStringSlice(config.FortiosSslSSHProfiles, conf2.FortiosSslSSHProfiles)\n\tconfig.Local = setBool(config.Local, conf2.Local)\n\tconfig.OutputLocation = setString(config.OutputLocation, conf2.OutputLocation)\n\tconfig.Prefix = setString(config.Prefix, conf2.Prefix)\n}", "func (m *Manager) ApplyConfig(cfg *config.Config) error {\n\t// Update only if a config change is detected. If TLS configuration is\n\t// set, we have to restart the manager to make sure that new TLS\n\t// certificates are picked up.\n\tvar blankTLSConfig config_util.TLSConfig\n\tif reflect.DeepEqual(m.config, cfg.TracingConfig) && m.config.TLSConfig == blankTLSConfig {\n\t\treturn nil\n\t}\n\n\tif m.shutdownFunc != nil {\n\t\tif err := m.shutdownFunc(); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to shut down the tracer provider: %w\", err)\n\t\t}\n\t}\n\n\t// If no endpoint is set, assume tracing should be disabled.\n\tif cfg.TracingConfig.Endpoint == \"\" {\n\t\tm.config = cfg.TracingConfig\n\t\tm.shutdownFunc = nil\n\t\totel.SetTracerProvider(trace.NewNoopTracerProvider())\n\t\tlevel.Info(m.logger).Log(\"msg\", \"Tracing provider uninstalled.\")\n\t\treturn nil\n\t}\n\n\ttp, shutdownFunc, err := buildTracerProvider(context.Background(), cfg.TracingConfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to install a new tracer provider: %w\", err)\n\t}\n\n\tm.shutdownFunc = shutdownFunc\n\tm.config = cfg.TracingConfig\n\totel.SetTracerProvider(tp)\n\n\tlevel.Info(m.logger).Log(\"msg\", \"Successfully installed a new tracer provider.\")\n\treturn nil\n}", "func (s *ServerGroup) ApplyConfig(cfg *Config) error {\n\ts.Cfg = cfg\n\n\t// Copy/paste from upstream prometheus/common until https://github.com/prometheus/common/issues/144 is resolved\n\ttlsConfig, err := config_util.NewTLSConfig(&cfg.HTTPConfig.HTTPConfig.TLSConfig)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error loading TLS client config\")\n\t}\n\t// The only timeout we care about is the configured scrape timeout.\n\t// It is applied on request. So we leave out any timings here.\n\tvar rt http.RoundTripper = &http.Transport{\n\t\tProxy: http.ProxyURL(cfg.HTTPConfig.HTTPConfig.ProxyURL.URL),\n\t\tMaxIdleConns: 20000,\n\t\tMaxIdleConnsPerHost: 1000, // see https://github.com/golang/go/issues/13801\n\t\tDisableKeepAlives: false,\n\t\tTLSClientConfig: tlsConfig,\n\t\t// 5 minutes is typically above the maximum sane scrape interval. So we can\n\t\t// use keepalive for all configurations.\n\t\tIdleConnTimeout: 5 * time.Minute,\n\t\tDialContext: (&net.Dialer{Timeout: cfg.HTTPConfig.DialTimeout}).DialContext,\n\t\tResponseHeaderTimeout: cfg.Timeout,\n\t}\n\n\t// If a bearer token is provided, create a round tripper that will set the\n\t// Authorization header correctly on each request.\n\tif len(cfg.HTTPConfig.HTTPConfig.BearerToken) > 0 {\n\t\trt = config_util.NewAuthorizationCredentialsRoundTripper(\"Bearer\", cfg.HTTPConfig.HTTPConfig.BearerToken, rt)\n\t} else if len(cfg.HTTPConfig.HTTPConfig.BearerTokenFile) > 0 {\n\t\trt = config_util.NewAuthorizationCredentialsFileRoundTripper(\"Bearer\", cfg.HTTPConfig.HTTPConfig.BearerTokenFile, rt)\n\t}\n\n\tif cfg.HTTPConfig.HTTPConfig.BasicAuth != nil {\n\t\trt = config_util.NewBasicAuthRoundTripper(cfg.HTTPConfig.HTTPConfig.BasicAuth.Username, cfg.HTTPConfig.HTTPConfig.BasicAuth.Password, cfg.HTTPConfig.HTTPConfig.BasicAuth.PasswordFile, rt)\n\t}\n\n\ts.client = &http.Client{Transport: rt}\n\n\tif err := s.targetManager.ApplyConfig(map[string]discovery.Configs{\"foo\": cfg.ServiceDiscoveryConfigs}); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (cfg *Config) ApplyDefaults() {\n\tif cfg.Role == \"\" {\n\t\tcfg.Role = \"client\"\n\t}\n\n\tif cfg.Addr == \"\" {\n\t\tcfg.Addr = \"localhost:8787\"\n\t}\n\n\tif cfg.UIAddr == \"\" {\n\t\tcfg.UIAddr = \"localhost:16823\"\n\t}\n\n\tif cfg.CloudConfig == \"\" {\n\t\tcfg.CloudConfig = fmt.Sprintf(\"https://s3.amazonaws.com/lantern_config/cloud.%v.yaml.gz\", countryPlaceholder)\n\t}\n\n\t// Default country\n\tif cfg.Country == \"\" {\n\t\tcfg.Country = *country\n\t}\n\n\t// Make sure we always have a stats config\n\tif cfg.Stats == nil {\n\t\tcfg.Stats = &statreporter.Config{}\n\t}\n\n\tif cfg.Stats.StatshubAddr == \"\" {\n\t\tcfg.Stats.StatshubAddr = *statshubAddr\n\t}\n\n\tif cfg.Client != nil && cfg.Role == \"client\" {\n\t\tcfg.applyClientDefaults()\n\t}\n\n\tif cfg.ProxiedSites == nil {\n\t\tlog.Debugf(\"Adding empty proxiedsites\")\n\t\tcfg.ProxiedSites = &proxiedsites.Config{\n\t\t\tDelta: &proxiedsites.Delta{\n\t\t\t\tAdditions: []string{},\n\t\t\t\tDeletions: []string{},\n\t\t\t},\n\t\t\tCloud: []string{},\n\t\t}\n\t}\n\n\tif cfg.ProxiedSites.Cloud == nil || len(cfg.ProxiedSites.Cloud) == 0 {\n\t\tlog.Debugf(\"Loading default cloud proxiedsites\")\n\t\tcfg.ProxiedSites.Cloud = defaultProxiedSites\n\t}\n\n\tif cfg.TrustedCAs == nil || len(cfg.TrustedCAs) == 0 {\n\t\tcfg.TrustedCAs = defaultTrustedCAs\n\t}\n}", "func populateConfig(c Config) Config {\n\tif c.MaxBody <= 0 {\n\t\tlog.Println(\"MAX_BODY unspecified. Defaulting to 5kb\")\n\t\tc.MaxBody = 5 * 1024\n\t}\n\tif c.Endpoint == \"\" {\n\t\tlog.Println(\"ENDPOINT unspecified. Defaulting to ':8080'\")\n\t\tc.Endpoint = \":8080\"\n\t}\n\tif c.DefaultInterval == 0 {\n\t\tlog.Println(\"DEFAULT_INTERVAL unspecified. Defaulting to '60s'\")\n\t\tc.DefaultInterval = 60\n\t}\n\treturn c\n}", "func (o *Config) Copy(s Config) {\n o.Enable = s.Enable\n o.RouterId = s.RouterId\n o.AsNumber = s.AsNumber\n o.BfdProfile = s.BfdProfile\n o.RejectDefaultRoute = s.RejectDefaultRoute\n o.InstallRoute = s.InstallRoute\n o.AggregateMed = s.AggregateMed\n o.DefaultLocalPreference = s.DefaultLocalPreference\n o.AsFormat = s.AsFormat\n o.AlwaysCompareMed = s.AlwaysCompareMed\n o.DeterministicMedComparison = s.DeterministicMedComparison\n o.EcmpMultiAs = s.EcmpMultiAs\n o.EnforceFirstAs = s.EnforceFirstAs\n o.EnableGracefulRestart = s.EnableGracefulRestart\n o.StaleRouteTime = s.StaleRouteTime\n o.LocalRestartTime = s.LocalRestartTime\n o.MaxPeerRestartTime = s.MaxPeerRestartTime\n o.ReflectorClusterId = s.ReflectorClusterId\n o.ConfederationMemberAs = s.ConfederationMemberAs\n o.AllowRedistributeDefaultRoute = s.AllowRedistributeDefaultRoute\n}", "func (conf *OrchestratorConfig) Merge(other *OrchestratorConfig) {\n\tif other == nil {\n\t\treturn\n\t}\n\n\tif other.ID != \"\" {\n\t\tconf.ID = other.ID\n\t}\n\n\tif other.Addr != \"\" {\n\t\tconf.Addr = other.Addr\n\t}\n}", "func (config *Configuration) ApplyOverrides(overrides map[string]string) error {\n\tmatch := func(s1 string) func(string) bool {\n\t\treturn func(s2 string) bool {\n\t\t\treturn strings.ToLower(s2) == s1\n\t\t}\n\t}\n\telem := reflect.ValueOf(config).Elem()\n\tfor k, v := range overrides {\n\t\tsplit := strings.Split(strings.ToLower(k), \".\")\n\t\tif len(split) != 2 {\n\t\t\treturn fmt.Errorf(\"Bad option format: %s\", k)\n\t\t}\n\t\tfield := elem.FieldByNameFunc(match(split[0]))\n\t\tif !field.IsValid() {\n\t\t\treturn fmt.Errorf(\"Unknown config field: %s\", split[0])\n\t\t} else if field.Kind() != reflect.Struct {\n\t\t\treturn fmt.Errorf(\"Unsettable config field: %s\", split[0])\n\t\t}\n\t\tfield = field.FieldByNameFunc(match(split[1]))\n\t\tif !field.IsValid() {\n\t\t\treturn fmt.Errorf(\"Unknown config field: %s\", split[1])\n\t\t}\n\t\tswitch field.Kind() {\n\t\tcase reflect.String:\n\t\t\tfield.Set(reflect.ValueOf(v))\n\t\tcase reflect.Bool:\n\t\t\tv = strings.ToLower(v)\n\t\t\t// Mimics the set of truthy things gcfg accepts in our config file.\n\t\t\tfield.SetBool(v == \"true\" || v == \"yes\" || v == \"on\" || v == \"1\")\n\t\tcase reflect.Int:\n\t\t\ti, err := strconv.Atoi(v)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Invalid value for an integer field: %s\", v)\n\t\t\t}\n\t\t\tfield.Set(reflect.ValueOf(i))\n\t\tcase reflect.Int64:\n\t\t\tvar d cli.Duration\n\t\t\tif err := d.UnmarshalText([]byte(v)); err != nil {\n\t\t\t\treturn fmt.Errorf(\"Invalid value for a duration field: %s\", v)\n\t\t\t}\n\t\t\tfield.Set(reflect.ValueOf(d))\n\t\tcase reflect.Slice:\n\t\t\t// We only have to worry about slices of strings. Comma-separated values are accepted.\n\t\t\tfield.Set(reflect.ValueOf(strings.Split(v, \",\")))\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"Can't override config field %s (is %s)\", k, field.Kind())\n\t\t}\n\t}\n\treturn nil\n}", "func (c *Channel) Apply(configtx *common.ConfigEnvelope) error {\n\tc.applyLock.Lock()\n\tdefer c.applyLock.Unlock()\n\n\tconfigTxValidator := c.Resources().ConfigtxValidator()\n\terr := configTxValidator.Validate(configtx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbundle, err := channelconfig.NewBundle(configTxValidator.ChannelID(), configtx.Config, c.cryptoProvider)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tchannelconfig.LogSanityChecks(bundle)\n\terr = c.bundleSource.ValidateNew(bundle)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcapabilitiesSupportedOrPanic(bundle)\n\n\tc.bundleSource.Update(bundle)\n\treturn nil\n}", "func (f flags) Merge(config Config) Config {\n\tif len(f.IncludePkgs) > 0 {\n\t\tconfig.IncludePkgs = f.IncludePkgs\n\t}\n\n\tif len(f.RuleNames) > 0 {\n\t\tfor _, ruleName := range f.RuleNames {\n\t\t\tconfig.Rules = append(config.Rules, Rule{\n\t\t\t\tRuleName: ruleName,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn config\n}", "func (c Config) Merge(defaults Config) Config {\n\tret := Config{ClientID: wdef(c.ClientID, defaults.ClientID),\n\t\tClientSecret: wdef(c.ClientSecret, defaults.ClientSecret),\n\t\tCallbackURL: wdef(c.CallbackURL, defaults.CallbackURL)}\n\tret.ServerProfile = c.ServerProfile.Merge(defaults.ServerProfile)\n\treturn ret\n}", "func mergeAndPopulateConfig(c *Config) (*Config, error) {\n\tfinal := newDefaultConfig()\n\n\tif c == nil {\n\t\tc = &Config{}\n\t}\n\tif c.LoggerName != \"\" {\n\t\tfinal.LoggerName = c.LoggerName\n\t} else if s := os.Getenv(\"LOG_NAME\"); s != \"\" {\n\t\tfinal.LoggerName = s\n\t}\n\n\tif c.ServiceName != \"\" {\n\t\tfinal.ServiceName = c.ServiceName\n\t} else if s := os.Getenv(\"SERVICE_NAME\"); s != \"\" {\n\t\tfinal.ServiceName = s\n\t}\n\n\tif c.LogLevel != 0 {\n\t\tfinal.LogLevel = c.LogLevel\n\t} else if s := os.Getenv(\"LOG_LEVEL\"); s != \"\" {\n\t\terr := final.LogLevel.Set(s)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif c.EnableDevLogging != nil {\n\t\tfinal.EnableDevLogging = c.EnableDevLogging\n\t} else if s := os.Getenv(\"LOG_ENABLE_DEV\"); s != \"\" {\n\t\tb, err := strconv.ParseBool(s)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfinal.EnableDevLogging = &b\n\t}\n\n\tif c.KinesisStreamMonitoring != \"\" {\n\t\tfinal.KinesisStreamMonitoring = c.KinesisStreamMonitoring\n\t} else if s := os.Getenv(\"LOG_STREAM_MONITORING\"); s != \"\" {\n\t\tfinal.KinesisStreamMonitoring = s\n\t}\n\n\tif c.KinesisStreamReporting != \"\" {\n\t\tfinal.KinesisStreamReporting = c.KinesisStreamReporting\n\t} else if s := os.Getenv(\"LOG_STREAM_REPORTING\"); s != \"\" {\n\t\tfinal.KinesisStreamReporting = s\n\t}\n\n\tif c.DisableKinesis != nil {\n\t\tfinal.DisableKinesis = c.DisableKinesis\n\t} else if s := os.Getenv(\"LOG_DISABLE_KINESIS\"); s != \"\" {\n\t\tb, err := strconv.ParseBool(s)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfinal.DisableKinesis = &b\n\t}\n\n\tif c.BufferSize != 0 {\n\t\tfinal.BufferSize = c.BufferSize\n\t} else if s := os.Getenv(\"LOG_BUFFER_SIZE\"); s != \"\" {\n\t\ti, err := strconv.ParseInt(s, 0, 64)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfinal.BufferSize = i\n\t}\n\n\tif c.FlushInterval != 0 {\n\t\tfinal.FlushInterval = c.FlushInterval\n\t} else if s := os.Getenv(\"LOG_FLUSH_INTERVAL\"); s != \"\" {\n\t\ti, err := strconv.ParseInt(s, 0, 64)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfinal.FlushInterval = time.Duration(i) * time.Second\n\t}\n\n\tif c.Env != \"\" {\n\t\tfinal.Env = c.Env\n\t} else if s := os.Getenv(\"ENV\"); s != \"\" {\n\t\tfinal.Env = s\n\t}\n\n\treturn final, nil\n}", "func (config *Config) Merge(newconfig Config) {\n\tif newconfig.Kubeconfig != \"\" {\n\t\tkubeconfig := newconfig.Kubeconfig\n\t\tcwd, err := os.Getwd()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tif kubeconfig[0] != '/' {\n\t\t\tkubeconfig = filepath.Join(cwd, kubeconfig)\n\t\t}\n\n\t\tconfig.Kubeconfig = kubeconfig\n\t}\n\tif newconfig.Context != \"\" {\n\t\tconfig.Context = newconfig.Context\n\t}\n\tif newconfig.Namespace != \"\" {\n\t\tconfig.Namespace = newconfig.Namespace\n\t}\n\tif newconfig.Command != \"\" {\n\t\tconfig.Command = newconfig.Command\n\t}\n\n\tfor k, v := range newconfig.Environment {\n\t\tif config.Environment == nil {\n\t\t\tconfig.Environment = make(map[string]string)\n\t\t}\n\n\t\tconfig.Environment[k] = v\n\t}\n}", "func (h *PrometheusStatusHandler) ApplyConfig(conf *config.Config) {\n\th.mu.Lock()\n\th.Config = conf.String()\n\th.mu.Unlock()\n}", "func (c *DogStatsDConfig) Merge(o *DogStatsDConfig) *DogStatsDConfig {\n\tif c == nil {\n\t\tif o == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn o.Copy()\n\t}\n\n\tif o == nil {\n\t\treturn c.Copy()\n\t}\n\n\tr := c.Copy()\n\n\tif o.Address != nil {\n\t\tr.Address = StringCopy(o.Address)\n\t}\n\n\tif o.Period != nil {\n\t\tr.Period = TimeDurationCopy(o.Period)\n\t}\n\n\treturn r\n}", "func overrideConfig(config1 *Config, config2 *Config) {\n\n}", "func buildConfig(opts []Option) config {\r\n\tc := config{\r\n\t\tclock: clock.New(),\r\n\t\tmaxSlack: 10,\r\n\t\tper: time.Second,\r\n\t}\r\n\tfor _, opt := range opts {\r\n\t\topt.apply(&c)\r\n\t}\r\n\treturn c\r\n}", "func buildConfig(opts []Option) config {\n\tc := config{\n\t\tclock: clock.New(),\n\t\tslack: 10,\n\t\tper: time.Second,\n\t}\n\n\tfor _, opt := range opts {\n\t\topt.apply(&c)\n\t}\n\treturn c\n}", "func (c *ResolverConfig) Merge(in *ResolverConfig) *ResolverConfig {\n\tres := *c\n\tif in.Logger != nil {\n\t\tres.Logger = in.Logger\n\t}\n\tif in.Model != nil {\n\t\tres.Model = in.Model\n\t}\n\tif in.SecretResolver != nil {\n\t\tres.SecretResolver = in.SecretResolver\n\t}\n\tif in.PolicyResolver != nil {\n\t\tres.PolicyResolver = in.PolicyResolver\n\t}\n\treturn &res\n}", "func (o *Config) Copy(s Config) {\n\to.Enable = s.Enable\n\to.RouterId = s.RouterId\n\to.AsNumber = s.AsNumber\n\to.BfdProfile = s.BfdProfile\n\to.RejectDefaultRoute = s.RejectDefaultRoute\n\to.InstallRoute = s.InstallRoute\n\to.AggregateMed = s.AggregateMed\n\to.DefaultLocalPreference = s.DefaultLocalPreference\n\to.AsFormat = s.AsFormat\n\to.AlwaysCompareMed = s.AlwaysCompareMed\n\to.DeterministicMedComparison = s.DeterministicMedComparison\n\to.EcmpMultiAs = s.EcmpMultiAs\n\to.EnforceFirstAs = s.EnforceFirstAs\n\to.EnableGracefulRestart = s.EnableGracefulRestart\n\to.StaleRouteTime = s.StaleRouteTime\n\to.LocalRestartTime = s.LocalRestartTime\n\to.MaxPeerRestartTime = s.MaxPeerRestartTime\n\to.ReflectorClusterId = s.ReflectorClusterId\n\to.ConfederationMemberAs = s.ConfederationMemberAs\n\to.AllowRedistributeDefaultRoute = s.AllowRedistributeDefaultRoute\n}", "func MergeConfig(a, b *Config) *Config {\n\tresult := *a\n\n\tif b.Address != \"\" {\n\t\tresult.Address = b.Address\n\t}\n\tif b.Port != 0 {\n\t\tresult.Port = b.Port\n\t}\n\tif b.LogLevel != \"\" {\n\t\tresult.LogLevel = b.LogLevel\n\t}\n\tif b.EnableSyslog {\n\t\tresult.EnableSyslog = true\n\t}\n\tif b.SyslogFacility != \"\" {\n\t\tresult.SyslogFacility = b.SyslogFacility\n\t}\n\tif b.ConsulAddr != \"\" {\n\t\tresult.ConsulAddr = b.ConsulAddr\n\t}\n\tif b.ConsulPort != 0 {\n\t\tresult.ConsulPort = b.ConsulPort\n\t}\n\tif b.ConsulDatacenter != \"\" {\n\t\tresult.ConsulDatacenter = b.ConsulDatacenter\n\t}\n\tif b.LogstashHost != \"\" {\n\t\tresult.LogstashHost = b.LogstashHost\n\t}\n\tif b.LogstashPort != 0 {\n\t\tresult.LogstashPort = b.LogstashPort\n\t}\n\n\tif b.ResourcePath != \"\" {\n\t\tresult.ResourcePath = b.ResourcePath\n\t}\n\n\tif b.Env != \"\" {\n\t\tresult.Env = b.Env\n\t}\n\n\tif b.ConnectionString != \"\" {\n\t\tresult.ConnectionString = b.ConnectionString\n\t}\n\n\tif b.RabbitMQURI != \"\" {\n\t\tresult.RabbitMQURI = b.RabbitMQURI\n\t}\n\n\tif b.Schema != \"\" {\n\t\tresult.Schema = b.Schema\n\t}\n\n\tif b.Parameters != nil && len(b.Parameters) > 0 {\n\t\tif result.Parameters == nil {\n\t\t\tresult.Parameters = make(map[string]string)\n\t\t}\n\t\tfor k, v := range b.Parameters {\n\t\t\tresult.Parameters[k] = v\n\t\t}\n\t}\n\n\tif result.Declarations == nil {\n\t\tresult.Declarations = essentials.NewDeclarationsConfig()\n\t}\n\n\tif b.Declarations != nil && b.Declarations.Exchanges != nil && len(b.Declarations.Exchanges) > 0 {\n\t\tfor k, v := range b.Declarations.Exchanges {\n\t\t\tresult.Declarations.Exchanges[k] = v\n\t\t}\n\t}\n\n\tif b.Declarations != nil && b.Declarations.Queues != nil && len(b.Declarations.Queues) > 0 {\n\t\tfor k, v := range b.Declarations.Queues {\n\t\t\tresult.Declarations.Queues[k] = v\n\t\t}\n\t}\n\n\treturn &result\n}", "func (conf *ThrapConfig) Merge(other *ThrapConfig) {\n\tif other == nil {\n\t\treturn\n\t}\n\n\tif other.VCS != nil {\n\t\tfor k, v := range other.VCS {\n\t\t\tif cv, ok := conf.VCS[k]; ok {\n\t\t\t\tcv.Merge(v)\n\t\t\t} else {\n\t\t\t\tconf.VCS[k] = other.VCS[k]\n\t\t\t}\n\t\t}\n\t}\n\n\tif other.Orchestrator != nil {\n\t\tfor k, v := range other.Orchestrator {\n\t\t\tif cv, ok := conf.Orchestrator[k]; ok {\n\t\t\t\tcv.Merge(v)\n\t\t\t} else {\n\t\t\t\tconf.Orchestrator[k] = other.Orchestrator[k]\n\t\t\t}\n\t\t}\n\t}\n\n\tif other.Registry != nil {\n\t\tfor k, v := range other.Registry {\n\t\t\tif cv, ok := conf.Registry[k]; ok {\n\t\t\t\tcv.Merge(v)\n\t\t\t} else {\n\t\t\t\tconf.Registry[k] = other.Registry[k]\n\t\t\t}\n\t\t}\n\t}\n\n\tif other.Secrets != nil {\n\t\tfor k, v := range other.Secrets {\n\t\t\tif cv, ok := conf.Secrets[k]; ok {\n\t\t\t\tcv.Merge(v)\n\t\t\t} else {\n\t\t\t\tconf.Secrets[k] = other.Secrets[k]\n\t\t\t}\n\t\t}\n\t}\n\n}", "func (c *Config) Copy() *Config {\n\tconfigCopy := &Config{\n\t\tFilter: c.Filter,\n\t\tIncludeMsgTypes: util.CopyStringSlice(c.IncludeMsgTypes),\n\t\tSubject: c.Subject,\n\t}\n\tif c.Email != nil {\n\t\tconfigCopy.Email = &EmailNotifierConfig{\n\t\t\tEmails: util.CopyStringSlice(c.Email.Emails),\n\t\t}\n\t}\n\tif c.Chat != nil {\n\t\tconfigCopy.Chat = &ChatNotifierConfig{\n\t\t\tRoomID: c.Chat.RoomID,\n\t\t}\n\t}\n\tif c.PubSub != nil {\n\t\tconfigCopy.PubSub = &PubSubNotifierConfig{\n\t\t\tTopic: c.PubSub.Topic,\n\t\t}\n\t}\n\tif c.Monorail != nil {\n\t\tconfigCopy.Monorail = &MonorailNotifierConfig{\n\t\t\tProject: c.Monorail.Project,\n\t\t\tOwner: c.Monorail.Owner,\n\t\t\tCC: util.CopyStringSlice(c.Monorail.CC),\n\t\t\tComponents: util.CopyStringSlice(c.Monorail.Components),\n\t\t\tLabels: util.CopyStringSlice(c.Monorail.Labels),\n\t\t}\n\t}\n\treturn configCopy\n}", "func (c *Config) Backfill(configMap map[string]interface{}) *Config {\n\tb := *c.commonBackfill(configMap)\n\n\tif _, exists := configMap[\"log_file_name\"]; !exists {\n\t\tb.LogFileName = DefaultConfig.LogFileName\n\t}\n\tif _, exists := configMap[\"log_file_max_megabytes\"]; !exists {\n\t\tb.LogFileMaxMegabytes = DefaultConfig.LogFileMaxMegabytes\n\t}\n\tif _, exists := configMap[\"log_max_files\"]; !exists {\n\t\tb.LogMaxFiles = DefaultConfig.LogMaxFiles\n\t}\n\tif _, exists := configMap[\"log_to_journal\"]; !exists {\n\t\tb.LogToJournal = DefaultConfig.LogToJournal\n\t}\n\tif _, exists := configMap[\"monitor_socket_filename\"]; !exists {\n\t\tb.MonitorSocketFilename = DefaultConfig.MonitorSocketFilename\n\t}\n\tif _, exists := configMap[\"cups_max_connections\"]; !exists {\n\t\tb.CUPSMaxConnections = DefaultConfig.CUPSMaxConnections\n\t}\n\tif _, exists := configMap[\"cups_connect_timeout\"]; !exists {\n\t\tb.CUPSConnectTimeout = DefaultConfig.CUPSConnectTimeout\n\t}\n\tif _, exists := configMap[\"cups_printer_attributes\"]; !exists {\n\t\tb.CUPSPrinterAttributes = DefaultConfig.CUPSPrinterAttributes\n\t} else {\n\t\t// Make sure all required attributes are present.\n\t\ts := make(map[string]struct{}, len(b.CUPSPrinterAttributes))\n\t\tfor _, a := range b.CUPSPrinterAttributes {\n\t\t\ts[a] = struct{}{}\n\t\t}\n\t\tfor _, a := range DefaultConfig.CUPSPrinterAttributes {\n\t\t\tif _, exists := s[a]; !exists {\n\t\t\t\tb.CUPSPrinterAttributes = append(b.CUPSPrinterAttributes, a)\n\t\t\t}\n\t\t}\n\t}\n\tif _, exists := configMap[\"cups_job_full_username\"]; !exists {\n\t\tb.CUPSJobFullUsername = DefaultConfig.CUPSJobFullUsername\n\t}\n\tif _, exists := configMap[\"cups_ignore_raw_printers\"]; !exists {\n\t\tb.CUPSIgnoreRawPrinters = DefaultConfig.CUPSIgnoreRawPrinters\n\t}\n\tif _, exists := configMap[\"cups_ignore_class_printers\"]; !exists {\n\t\tb.CUPSIgnoreClassPrinters = DefaultConfig.CUPSIgnoreClassPrinters\n\t}\n\tif _, exists := configMap[\"copy_printer_info_to_display_name\"]; !exists {\n\t\tb.CUPSCopyPrinterInfoToDisplayName = DefaultConfig.CUPSCopyPrinterInfoToDisplayName\n\t}\n\n\treturn &b\n}", "func applyConfigDefaults(config map[string]string) {\n\tb, err := strconv.ParseBool(config[confKey.sslEnabled])\n\tif err != nil {\n\t\tglog.Warning(log(\"failed to parse param sslEnabled, setting it to false\"))\n\t\tb = false\n\t}\n\tconfig[confKey.sslEnabled] = strconv.FormatBool(b)\n\tconfig[confKey.storageMode] = defaultString(config[confKey.storageMode], \"ThinProvisioned\")\n\tconfig[confKey.fsType] = defaultString(config[confKey.fsType], \"xfs\")\n\tb, err = strconv.ParseBool(config[confKey.readOnly])\n\tif err != nil {\n\t\tglog.Warning(log(\"failed to parse param readOnly, setting it to false\"))\n\t\tb = false\n\t}\n\tconfig[confKey.readOnly] = strconv.FormatBool(b)\n}", "func newConfig(opts ...Option) config {\n\tc := config{\n\t\tMeterProvider: otel.GetMeterProvider(),\n\t}\n\tfor _, opt := range opts {\n\t\topt.apply(&c)\n\t}\n\treturn c\n}", "func (o *Options) Apply(opts ...Option) error {\n\tfor i, opt := range opts {\n\t\tif err := opt(o); err != nil {\n\t\t\treturn fmt.Errorf(\"dht option %d failed: %s\", i, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *EphemeralVolumeControllerOptions) ApplyTo(cfg *ephemeralvolumeconfig.EphemeralVolumeControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentEphemeralVolumeSyncs = o.ConcurrentEphemeralVolumeSyncs\n\n\treturn nil\n}", "func (d *DefaultConfig) apply(c *RestClient) error {\n\tif c.User == \"\" && d.User != \"\" {\n\t\tc.User = d.User\n\t}\n\n\tif c.Password == \"\" && d.Password != \"\" {\n\t\tc.Password = d.Password\n\t}\n\n\tif c.User == \"\" && d.User != \"\" {\n\t\tc.User = d.User\n\t}\n\n\tif c.transport.ResponseHeaderTimeout == 10*time.Second && d.Timeout != 0 {\n\t\tc.transport.ResponseHeaderTimeout = d.Timeout\n\t\tc.http.Timeout = c.transport.ResponseHeaderTimeout\n\t}\n\n\tif len(c.signingKey) == 0 && d.SigningKey != \"\" {\n\t\tif err := c.SetSigningKey(d.SigningKey); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif c.transport.TLSClientConfig.RootCAs == nil && d.RootCA != \"\" {\n\t\tif err := c.SetRootCA(d.RootCA); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func mergeConfig(cfgs ...apiv1.Config) apiv1.Config {\n\tn := apiv1.Config{}\n\tfor _, cfg := range cfgs {\n\t\tfor k, v2 := range cfg {\n\t\t\tif v1, ok := n[k]; ok {\n\t\t\t\tif nv1, ok1 := v1.(apiv1.Config); ok1 {\n\t\t\t\t\tif nv2, ok2 := v2.(apiv1.Config); ok2 {\n\t\t\t\t\t\tn[k] = mergeConfig(nv1, nv2)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tn[k] = v2\n\t\t}\n\t}\n\n\treturn n\n}", "func (c *StdoutConfig) Merge(o *StdoutConfig) *StdoutConfig {\n\tif c == nil {\n\t\tif o == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn o.Copy()\n\t}\n\n\tif o == nil {\n\t\treturn c.Copy()\n\t}\n\n\tr := c.Copy()\n\n\tif o.Period != nil {\n\t\tr.Period = TimeDurationCopy(o.Period)\n\t}\n\n\tif o.PrettyPrint != nil {\n\t\tr.PrettyPrint = BoolCopy(o.PrettyPrint)\n\t}\n\n\tif o.DoNotPrintTime != nil {\n\t\tr.DoNotPrintTime = BoolCopy(o.DoNotPrintTime)\n\t}\n\n\treturn r\n}", "func ApplyResouceToConfig(cfg interface{}) error {\n\tdp := GetDataplaneResource()\n\tagentRes := GetAgentResource()\n\tif dp == nil || agentRes == nil {\n\t\treturn nil\n\t}\n\n\tif objInterface, ok := cfg.(config.IResourceConfigCallback); ok {\n\t\terr := objInterface.ApplyResources(dp, agentRes)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// If the parameter is of struct pointer, use indirection to get the\n\t// real value object\n\tv := reflect.ValueOf(cfg)\n\tif v.Kind() == reflect.Ptr {\n\t\tv = reflect.Indirect(v)\n\t}\n\n\t// Look for Validate method on struct properties and invoke it\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tif v.Field(i).CanInterface() {\n\t\t\tfieldInterface := v.Field(i).Interface()\n\t\t\tif objInterface, ok := fieldInterface.(config.IResourceConfigCallback); ok {\n\t\t\t\terr := ApplyResouceToConfig(objInterface)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (b *Backend) ApplyConfiguration(config gw.GatewayConfiguration) error {\n\tfor i := range config.Channels {\n\t\tloRaModConfig := config.Channels[i].GetLoraModulationConfig()\n\t\tif loRaModConfig != nil {\n\t\t\tloRaModConfig.Bandwidth = loRaModConfig.Bandwidth * 1000\n\t\t}\n\n\t\tfskModConfig := config.Channels[i].GetFskModulationConfig()\n\t\tif fskModConfig != nil {\n\t\t\tfskModConfig.Bandwidth = fskModConfig.Bandwidth * 1000\n\t\t}\n\t}\n\n\tlog.WithFields(log.Fields{\n\t\t\"version\": config.Version,\n\t}).Info(\"backend/concentratord: forwarding configuration command\")\n\n\t_, err := b.commandRequest(\"config\", &config)\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"backend/concentratord: send configuration command error\")\n\t}\n\n\tcommandCounter(\"config\").Inc()\n\n\treturn nil\n}", "func (cfg *RPCPoolConfig) merge(override *RPCPoolConfig) *RPCPoolConfig {\n\tif cfg == nil && override == nil {\n\t\treturn nil\n\t}\n\n\tmerged := &RPCPoolConfig{\n\t\tSize: -1,\n\t\tWaitTimeout: -1,\n\t}\n\n\tfor _, c := range []*RPCPoolConfig{cfg, override} { // First apply the base config, then any overrides.\n\t\tif c != nil {\n\t\t\tif c.Size >= 0 {\n\t\t\t\tmerged.Size = c.Size\n\t\t\t}\n\n\t\t\tif c.WaitTimeout > 0 {\n\t\t\t\tmerged.WaitTimeout = c.WaitTimeout\n\t\t\t}\n\t\t}\n\t}\n\n\treturn merged\n}", "func (conf *RegistryConfig) Merge(other *RegistryConfig) {\n\tif other == nil {\n\t\treturn\n\t}\n\n\tif other.ID != \"\" {\n\t\tconf.ID = other.ID\n\t}\n\n\tif other.Addr != \"\" {\n\t\tconf.Addr = other.Addr\n\t}\n\n\tif other.Provider != \"\" {\n\t\tconf.Provider = other.Provider\n\t}\n\n\tconf.Repo.Merge(other.Repo)\n\n\tif other.Config != nil {\n\t\tif conf.Config == nil {\n\t\t\tconf.Config = make(map[string]interface{})\n\t\t}\n\t\tfor k, v := range other.Config {\n\t\t\tconf.Config[k] = v\n\t\t}\n\t}\n}", "func (c ConsumerConfig) Apply(kafkaConf *kafkalib.ConfigMap) {\n\tif id := c.GroupID; id != \"\" {\n\t\t_ = kafkaConf.SetKey(\"group.id\", id)\n\t}\n}", "func (c *Config) ApplyDefaults() error {\n\tif c.WALDir == \"\" {\n\t\treturn errors.New(\"no wal_directory configured\")\n\t}\n\n\tif c.ServiceConfig.Enabled && len(c.Configs) > 0 {\n\t\treturn errors.New(\"cannot use configs when scraping_service mode is enabled\")\n\t}\n\n\tusedNames := map[string]struct{}{}\n\n\tfor i := range c.Configs {\n\t\tname := c.Configs[i].Name\n\t\tif err := c.Configs[i].ApplyDefaults(&c.Global); err != nil {\n\t\t\t// Try to show a helpful name in the error\n\t\t\tif name == \"\" {\n\t\t\t\tname = fmt.Sprintf(\"at index %d\", i)\n\t\t\t}\n\n\t\t\treturn fmt.Errorf(\"error validating instance %s: %w\", name, err)\n\t\t}\n\n\t\tif _, ok := usedNames[name]; ok {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"prometheus instance names must be unique. found multiple instances with name %s\",\n\t\t\t\tname,\n\t\t\t)\n\t\t}\n\t\tusedNames[name] = struct{}{}\n\t}\n\treturn nil\n}", "func (c *ConfigureOpener) Merge(other ConfigureOpener) {\n\tif c.ErrorThresholdPercentage == 0 {\n\t\tc.ErrorThresholdPercentage = other.ErrorThresholdPercentage\n\t}\n\tif c.RequestVolumeThreshold == 0 {\n\t\tc.RequestVolumeThreshold = other.RequestVolumeThreshold\n\t}\n\tif c.Now == nil {\n\t\tc.Now = other.Now\n\t}\n\tif c.RollingDuration == 0 {\n\t\tc.RollingDuration = other.RollingDuration\n\t}\n\tif c.NumBuckets == 0 {\n\t\tc.NumBuckets = other.NumBuckets\n\t}\n}", "func Apply(cmd *cli.Cmd) {\n\tcmd.Spec = \"[-f=<FILENAME>] [--keep-weights] [--allowed-actions=<ACTIONS_SPEC>]\"\n\tvar (\n\t\tapplyFile = cmd.StringOpt(\"f\", \"/etc/ipvsctl.yaml\", \"File to apply. Use - for STDIN\")\n\t\tkeepWeights = cmd.BoolOpt(\"keep-weights\", false, \"Leave weights as they are when updating destinations\")\n\t\tactionSpec = cmd.StringOpt(\"allowed-actions\", \"*\", `\nComma-separated list of allowed actions.\nas=Add service, us=update service, ds=delete service,\nad=Add destination, ud=update destination, dd=delete destination.\nDefault * for all actions.\n`)\n\t)\n\n\tcmd.Action = func() {\n\n\t\tif *applyFile == \"\" {\n\t\t\tfmt.Fprintf(os.Stderr, \"Must specify an input file or - for stdin\\n\")\n\t\t\tos.Exit(exitInvalidFile)\n\t\t}\n\n\t\t// read new config from file\n\t\tnewConfig, err := readModelFromInput(applyFile)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error reading model: %s\\n\", err)\n\t\t\tos.Exit(exitValidateErr)\n\t\t}\n\n\t\tresolvedConfig, err := resolveParams(newConfig)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error resolving parameters: %s\\n\", err)\n\t\t\tos.Exit(exitParamErr)\n\t\t}\n\n\t\t// validate model before applying\n\t\terr = resolvedConfig.Validate()\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error validation model: %s\\n\", err)\n\t\t\tos.Exit(exitValidateErr)\n\t\t}\n\n\t\tallowedSet, err := parseAllowedActions(actionSpec)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"unable to process allowed actions: %s\\n\", err)\n\t\t\tos.Exit(exitInvalidInput)\n\t\t}\n\n\t\t// apply new configuration\n\t\terr = MustGetCurrentConfig().Apply(resolvedConfig, integration.ApplyOpts{\n\t\t\tKeepWeights: *keepWeights,\n\t\t\tAllowedActions: allowedSet,\n\t\t})\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error applying updates: %s\\n\", err)\n\t\t\tos.Exit(exitApplyErr)\n\t\t}\n\t\tfmt.Printf(\"Applied configuration from %s\\n\", *applyFile)\n\t}\n}", "func (opts *Options) Apply(options ...Option) error {\n\tfor _, o := range options {\n\t\tif err := o(opts); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func ReadConfig(conf *api.ConfigMap) config.Configuration {\n\tif len(conf.Data) == 0 {\n\t\treturn config.NewDefault()\n\t}\n\n\tvar errors []int\n\tvar skipUrls []string\n\tvar whitelist []string\n\n\tif val, ok := conf.Data[customHTTPErrors]; ok {\n\t\tdelete(conf.Data, customHTTPErrors)\n\t\tfor _, i := range strings.Split(val, \",\") {\n\t\t\tj, err := strconv.Atoi(i)\n\t\t\tif err != nil {\n\t\t\t\tglog.Warningf(\"%v is not a valid http code: %v\", i, err)\n\t\t\t} else {\n\t\t\t\terrors = append(errors, j)\n\t\t\t}\n\t\t}\n\t}\n\tif val, ok := conf.Data[skipAccessLogUrls]; ok {\n\t\tdelete(conf.Data, skipAccessLogUrls)\n\t\tskipUrls = strings.Split(val, \",\")\n\t}\n\tif val, ok := conf.Data[whitelistSourceRange]; ok {\n\t\tdelete(conf.Data, whitelistSourceRange)\n\t\twhitelist = append(whitelist, strings.Split(val, \",\")...)\n\t}\n\n\tto := config.Configuration{}\n\tto.Backend = defaults.Backend{\n\t\tCustomHTTPErrors: filterErrors(errors),\n\t\tSkipAccessLogURLs: skipUrls,\n\t\tWhitelistSourceRange: whitelist,\n\t}\n\tdef := config.NewDefault()\n\tif err := mergo.Merge(&to, def); err != nil {\n\t\tglog.Warningf(\"unexpected error merging defaults: %v\", err)\n\t}\n\n\tmetadata := &mapstructure.Metadata{}\n\tdecoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{\n\t\tTagName: \"structs\",\n\t\tResult: &to,\n\t\tWeaklyTypedInput: true,\n\t\tMetadata: metadata,\n\t})\n\n\terr = decoder.Decode(conf.Data)\n\tif err != nil {\n\t\tglog.Infof(\"%v\", err)\n\t}\n\treturn to\n}", "func (c Config) Copy() Config {\n\tdst := Config{}\n\tdst.Credentials = c.Credentials\n\tdst.Endpoint = c.Endpoint\n\tdst.Region = c.Region\n\tdst.DisableSSL = c.DisableSSL\n\tdst.ManualSend = c.ManualSend\n\tdst.HTTPClient = c.HTTPClient\n\tdst.LogHTTPBody = c.LogHTTPBody\n\tdst.LogLevel = c.LogLevel\n\tdst.Logger = c.Logger\n\tdst.MaxRetries = c.MaxRetries\n\tdst.DisableParamValidation = c.DisableParamValidation\n\tdst.DisableComputeChecksums = c.DisableComputeChecksums\n\tdst.S3ForcePathStyle = c.S3ForcePathStyle\n\tdst.DomainMode = c.DomainMode\n\tdst.SignerVersion = c.SignerVersion\n\treturn dst\n}", "func (s *Storage) ApplyConfig(conf *config.Config) error {\n\ts.mtx.Lock()\n\tdefer s.mtx.Unlock()\n\n\tif err := s.rws.ApplyConfig(conf); err != nil {\n\t\treturn err\n\t}\n\n\t// Update read clients\n\treadHashes := make(map[string]struct{})\n\tqueryables := make([]storage.SampleAndChunkQueryable, 0, len(conf.RemoteReadConfigs))\n\tfor _, rrConf := range conf.RemoteReadConfigs {\n\t\thash, err := toHash(rrConf)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Don't allow duplicate remote read configs.\n\t\tif _, ok := readHashes[hash]; ok {\n\t\t\treturn fmt.Errorf(\"duplicate remote read configs are not allowed, found duplicate for URL: %s\", rrConf.URL)\n\t\t}\n\t\treadHashes[hash] = struct{}{}\n\n\t\t// Set the queue name to the config hash if the user has not set\n\t\t// a name in their remote write config so we can still differentiate\n\t\t// between queues that have the same remote write endpoint.\n\t\tname := hash[:6]\n\t\tif rrConf.Name != \"\" {\n\t\t\tname = rrConf.Name\n\t\t}\n\n\t\tc, err := NewReadClient(name, &ClientConfig{\n\t\t\tURL: rrConf.URL,\n\t\t\tTimeout: rrConf.RemoteTimeout,\n\t\t\tHTTPClientConfig: rrConf.HTTPClientConfig,\n\t\t\tHeaders: rrConf.Headers,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\texternalLabels := conf.GlobalConfig.ExternalLabels\n\t\tif !rrConf.FilterExternalLabels {\n\t\t\texternalLabels = labels.EmptyLabels()\n\t\t}\n\t\tqueryables = append(queryables, NewSampleAndChunkQueryableClient(\n\t\t\tc,\n\t\t\texternalLabels,\n\t\t\tlabelsToEqualityMatchers(rrConf.RequiredMatchers),\n\t\t\trrConf.ReadRecent,\n\t\t\ts.localStartTimeCallback,\n\t\t))\n\t}\n\ts.queryables = queryables\n\n\treturn nil\n}", "func (c *Config) Update(c2 Config) {\n\tif c2.ClientID != \"\" {\n\t\tc.ClientID = c2.ClientID\n\t}\n\tif c2.Quality != \"\" {\n\t\tc.Quality = c2.Quality\n\t}\n\tif c2.StartTime != \"\" {\n\t\tc.StartTime = c2.StartTime\n\t}\n\tif c2.EndTime != \"\" {\n\t\tc.EndTime = c2.EndTime\n\t}\n\tif c2.Length != \"\" {\n\t\tc.EndTime = c2.Length\n\t}\n\tif c2.VodID != 0 {\n\t\tc.VodID = c2.VodID\n\t}\n\tif c2.FilePrefix != \"\" {\n\t\tc.FilePrefix = c2.FilePrefix\n\t}\n\tif c2.OutputFolder != \"\" {\n\t\tc.OutputFolder = c2.OutputFolder\n\t}\n\tif c2.Workers != 0 {\n\t\tc.Workers = c2.Workers\n\t}\n}", "func (c *CheckpointAdvancer) UpdateConfigWith(f func(*config.Config)) {\n\tcfg := c.cfg\n\tf(&cfg)\n\tc.UpdateConfig(cfg)\n}", "func NewConfig(opts ...Option) Config {\n\tvar config Config\n\tfor _, o := range opts {\n\t\tconfig = o.applyInstrument(config)\n\t}\n\treturn config\n}", "func TestStartupConfigMerge(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tconfig StartupConfig\n\t\toverride StartupConfig\n\t\texpected StartupConfig\n\t}{\n\t\t{\n\t\t\tname: \"Override *ConfigDuration\",\n\t\t\tconfig: StartupConfig{Bootstrap: BootstrapConfig{ConfigUpdateFrequency: base.NewConfigDuration(time.Second * 5)}},\n\t\t\toverride: StartupConfig{Bootstrap: BootstrapConfig{ConfigUpdateFrequency: base.NewConfigDuration(time.Second * 10)}},\n\t\t\texpected: StartupConfig{Bootstrap: BootstrapConfig{ConfigUpdateFrequency: base.NewConfigDuration(time.Second * 10)}},\n\t\t},\n\t\t{\n\t\t\tname: \"Override empty *ConfigDuration\",\n\t\t\tconfig: StartupConfig{},\n\t\t\toverride: StartupConfig{Bootstrap: BootstrapConfig{ConfigUpdateFrequency: base.NewConfigDuration(time.Second * 10)}},\n\t\t\texpected: StartupConfig{Bootstrap: BootstrapConfig{ConfigUpdateFrequency: base.NewConfigDuration(time.Second * 10)}},\n\t\t},\n\t\t{\n\t\t\tname: \"Keep original *ConfigDuration\",\n\t\t\tconfig: StartupConfig{Bootstrap: BootstrapConfig{ConfigUpdateFrequency: base.NewConfigDuration(time.Second * 10)}},\n\t\t\toverride: StartupConfig{},\n\t\t\texpected: StartupConfig{Bootstrap: BootstrapConfig{ConfigUpdateFrequency: base.NewConfigDuration(time.Second * 10)}},\n\t\t},\n\t\t{\n\t\t\tname: \"Override string\",\n\t\t\tconfig: StartupConfig{Bootstrap: BootstrapConfig{Server: \"test.com\"}},\n\t\t\toverride: StartupConfig{Bootstrap: BootstrapConfig{Server: \"test.net\"}},\n\t\t\texpected: StartupConfig{Bootstrap: BootstrapConfig{Server: \"test.net\"}},\n\t\t},\n\t\t{\n\t\t\tname: \"Override empty string\",\n\t\t\tconfig: StartupConfig{},\n\t\t\toverride: StartupConfig{Bootstrap: BootstrapConfig{Server: \"test.net\"}},\n\t\t\texpected: StartupConfig{Bootstrap: BootstrapConfig{Server: \"test.net\"}},\n\t\t},\n\t\t{\n\t\t\tname: \"Keep original string\",\n\t\t\tconfig: StartupConfig{Bootstrap: BootstrapConfig{Server: \"test.net\"}},\n\t\t\toverride: StartupConfig{},\n\t\t\texpected: StartupConfig{Bootstrap: BootstrapConfig{Server: \"test.net\"}},\n\t\t},\n\t\t{\n\t\t\tname: \"Keep original bool\",\n\t\t\tconfig: StartupConfig{Bootstrap: BootstrapConfig{ServerTLSSkipVerify: true}},\n\t\t\toverride: StartupConfig{},\n\t\t\texpected: StartupConfig{Bootstrap: BootstrapConfig{ServerTLSSkipVerify: true}},\n\t\t},\n\t\t{\n\t\t\tname: \"Override bool\",\n\t\t\tconfig: StartupConfig{Bootstrap: BootstrapConfig{ServerTLSSkipVerify: true}},\n\t\t\toverride: StartupConfig{Bootstrap: BootstrapConfig{ServerTLSSkipVerify: false}},\n\t\t\texpected: StartupConfig{Bootstrap: BootstrapConfig{ServerTLSSkipVerify: false}},\n\t\t},\n\t\t{\n\t\t\tname: \"Override unset bool\",\n\t\t\tconfig: StartupConfig{},\n\t\t\toverride: StartupConfig{Bootstrap: BootstrapConfig{ServerTLSSkipVerify: true}},\n\t\t\texpected: StartupConfig{Bootstrap: BootstrapConfig{ServerTLSSkipVerify: true}},\n\t\t},\n\t\t{\n\t\t\tname: \"Keep original *ConsoleLoggerConfig\",\n\t\t\tconfig: StartupConfig{Logging: logger.LoggingConfig{Console: &logger.ConsoleLoggerConfig{LogKeys: []string{\"HTTP\", \"Config\", \"CRUD\", \"DCP\", \"Sync\"}}}},\n\t\t\toverride: StartupConfig{Logging: logger.LoggingConfig{Console: &logger.ConsoleLoggerConfig{}}},\n\t\t\texpected: StartupConfig{Logging: logger.LoggingConfig{Console: &logger.ConsoleLoggerConfig{LogKeys: []string{\"HTTP\", \"Config\", \"CRUD\", \"DCP\", \"Sync\"}}}},\n\t\t}, {\n\t\t\tname: \"Override empty logging\",\n\t\t\tconfig: StartupConfig{Logging: logger.LoggingConfig{Trace: &logger.FileLoggerConfig{}}},\n\t\t\toverride: StartupConfig{Logging: logger.LoggingConfig{Trace: &logger.FileLoggerConfig{Enabled: true}}},\n\t\t\texpected: StartupConfig{Logging: logger.LoggingConfig{Trace: &logger.FileLoggerConfig{Enabled: true}}},\n\t\t},\n\t\t{\n\t\t\tname: \"Keep original *CORSconfig\",\n\t\t\tconfig: StartupConfig{API: APIConfig{CORS: &CORSConfig{MaxAge: 5, Origin: []string{\"Test\"}}}},\n\t\t\toverride: StartupConfig{API: APIConfig{CORS: &CORSConfig{}}},\n\t\t\texpected: StartupConfig{API: APIConfig{CORS: &CORSConfig{MaxAge: 5, Origin: []string{\"Test\"}}}},\n\t\t},\n\t\t{\n\t\t\tname: \"Keep original *CORSConfig from override nil value\",\n\t\t\tconfig: StartupConfig{API: APIConfig{CORS: &CORSConfig{MaxAge: 5, Origin: []string{\"Test\"}}}},\n\t\t\toverride: StartupConfig{},\n\t\t\texpected: StartupConfig{API: APIConfig{CORS: &CORSConfig{MaxAge: 5, Origin: []string{\"Test\"}}}},\n\t\t},\n\t\t{\n\t\t\tname: \"Override unset ConfigDuration\",\n\t\t\tconfig: StartupConfig{},\n\t\t\toverride: StartupConfig{Replicator: ReplicatorConfig{MaxHeartbeat: base.NewConfigDuration(time.Second * 5)}},\n\t\t\texpected: StartupConfig{Replicator: ReplicatorConfig{MaxHeartbeat: base.NewConfigDuration(time.Second * 5)}},\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\terr := test.config.Merge(&test.override)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tassert.Equal(t, test.expected, test.config)\n\t\t})\n\t}\n}", "func TestStartupConfigMerge(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tconfig StartupConfig\n\t\toverride StartupConfig\n\t\texpected StartupConfig\n\t}{\n\t\t{\n\t\t\tname: \"Override *ConfigDuration\",\n\t\t\tconfig: StartupConfig{Bootstrap: BootstrapConfig{ConfigUpdateFrequency: base.NewConfigDuration(time.Second * 5)}},\n\t\t\toverride: StartupConfig{Bootstrap: BootstrapConfig{ConfigUpdateFrequency: base.NewConfigDuration(time.Second * 10)}},\n\t\t\texpected: StartupConfig{Bootstrap: BootstrapConfig{ConfigUpdateFrequency: base.NewConfigDuration(time.Second * 10)}},\n\t\t},\n\t\t{\n\t\t\tname: \"Override empty *ConfigDuration\",\n\t\t\tconfig: StartupConfig{},\n\t\t\toverride: StartupConfig{Bootstrap: BootstrapConfig{ConfigUpdateFrequency: base.NewConfigDuration(time.Second * 10)}},\n\t\t\texpected: StartupConfig{Bootstrap: BootstrapConfig{ConfigUpdateFrequency: base.NewConfigDuration(time.Second * 10)}},\n\t\t},\n\t\t{\n\t\t\tname: \"Keep original *ConfigDuration\",\n\t\t\tconfig: StartupConfig{Bootstrap: BootstrapConfig{ConfigUpdateFrequency: base.NewConfigDuration(time.Second * 10)}},\n\t\t\toverride: StartupConfig{},\n\t\t\texpected: StartupConfig{Bootstrap: BootstrapConfig{ConfigUpdateFrequency: base.NewConfigDuration(time.Second * 10)}},\n\t\t},\n\t\t{\n\t\t\tname: \"Override string\",\n\t\t\tconfig: StartupConfig{Bootstrap: BootstrapConfig{Server: \"test.com\"}},\n\t\t\toverride: StartupConfig{Bootstrap: BootstrapConfig{Server: \"test.net\"}},\n\t\t\texpected: StartupConfig{Bootstrap: BootstrapConfig{Server: \"test.net\"}},\n\t\t},\n\t\t{\n\t\t\tname: \"Override empty string\",\n\t\t\tconfig: StartupConfig{},\n\t\t\toverride: StartupConfig{Bootstrap: BootstrapConfig{Server: \"test.net\"}},\n\t\t\texpected: StartupConfig{Bootstrap: BootstrapConfig{Server: \"test.net\"}},\n\t\t},\n\t\t{\n\t\t\tname: \"Keep original string\",\n\t\t\tconfig: StartupConfig{Bootstrap: BootstrapConfig{Server: \"test.net\"}},\n\t\t\toverride: StartupConfig{},\n\t\t\texpected: StartupConfig{Bootstrap: BootstrapConfig{Server: \"test.net\"}},\n\t\t},\n\t\t{\n\t\t\tname: \"Keep original *bool\",\n\t\t\tconfig: StartupConfig{Bootstrap: BootstrapConfig{ServerTLSSkipVerify: base.BoolPtr(true)}},\n\t\t\toverride: StartupConfig{},\n\t\t\texpected: StartupConfig{Bootstrap: BootstrapConfig{ServerTLSSkipVerify: base.BoolPtr(true)}},\n\t\t},\n\t\t{\n\t\t\tname: \"Override *bool\",\n\t\t\tconfig: StartupConfig{Bootstrap: BootstrapConfig{ServerTLSSkipVerify: base.BoolPtr(true)}},\n\t\t\toverride: StartupConfig{Bootstrap: BootstrapConfig{ServerTLSSkipVerify: base.BoolPtr(false)}},\n\t\t\texpected: StartupConfig{Bootstrap: BootstrapConfig{ServerTLSSkipVerify: base.BoolPtr(false)}},\n\t\t},\n\t\t{\n\t\t\tname: \"Override unset *bool\",\n\t\t\tconfig: StartupConfig{},\n\t\t\toverride: StartupConfig{Bootstrap: BootstrapConfig{ServerTLSSkipVerify: base.BoolPtr(true)}},\n\t\t\texpected: StartupConfig{Bootstrap: BootstrapConfig{ServerTLSSkipVerify: base.BoolPtr(true)}},\n\t\t},\n\t\t{\n\t\t\tname: \"Keep original *ConsoleLoggerConfig\",\n\t\t\tconfig: StartupConfig{Logging: base.LoggingConfig{Console: &base.ConsoleLoggerConfig{LogKeys: []string{\"HTTP\", \"Config\", \"CRUD\", \"DCP\", \"Sync\"}}}},\n\t\t\toverride: StartupConfig{Logging: base.LoggingConfig{Console: &base.ConsoleLoggerConfig{}}},\n\t\t\texpected: StartupConfig{Logging: base.LoggingConfig{Console: &base.ConsoleLoggerConfig{LogKeys: []string{\"HTTP\", \"Config\", \"CRUD\", \"DCP\", \"Sync\"}}}},\n\t\t}, {\n\t\t\tname: \"Override empty logging\",\n\t\t\tconfig: StartupConfig{Logging: base.LoggingConfig{Trace: &base.FileLoggerConfig{}}},\n\t\t\toverride: StartupConfig{Logging: base.LoggingConfig{Trace: &base.FileLoggerConfig{Enabled: base.BoolPtr(true)}}},\n\t\t\texpected: StartupConfig{Logging: base.LoggingConfig{Trace: &base.FileLoggerConfig{Enabled: base.BoolPtr(true)}}},\n\t\t},\n\t\t{\n\t\t\tname: \"Keep original *CORSconfig\",\n\t\t\tconfig: StartupConfig{API: APIConfig{CORS: &auth.CORSConfig{MaxAge: 5, Origin: []string{\"Test\"}}}},\n\t\t\toverride: StartupConfig{API: APIConfig{CORS: &auth.CORSConfig{}}},\n\t\t\texpected: StartupConfig{API: APIConfig{CORS: &auth.CORSConfig{MaxAge: 5, Origin: []string{\"Test\"}}}},\n\t\t},\n\t\t{\n\t\t\tname: \"Keep original *auth.CORSConfig from override nil value\",\n\t\t\tconfig: StartupConfig{API: APIConfig{CORS: &auth.CORSConfig{MaxAge: 5, Origin: []string{\"Test\"}}}},\n\t\t\toverride: StartupConfig{},\n\t\t\texpected: StartupConfig{API: APIConfig{CORS: &auth.CORSConfig{MaxAge: 5, Origin: []string{\"Test\"}}}},\n\t\t},\n\t\t{\n\t\t\tname: \"Override unset ConfigDuration\",\n\t\t\tconfig: StartupConfig{},\n\t\t\toverride: StartupConfig{Replicator: ReplicatorConfig{MaxHeartbeat: base.NewConfigDuration(time.Second * 5)}},\n\t\t\texpected: StartupConfig{Replicator: ReplicatorConfig{MaxHeartbeat: base.NewConfigDuration(time.Second * 5)}},\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\terr := test.config.Merge(&test.override)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tassert.Equal(t, test.expected, test.config)\n\t\t})\n\t}\n}", "func (c *VaultConfig) Merge(o *VaultConfig) *VaultConfig {\n\tif c == nil {\n\t\tif o == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn o.Copy()\n\t}\n\n\tif o == nil {\n\t\treturn c.Copy()\n\t}\n\n\tr := c.Copy()\n\n\tif o.Address != nil {\n\t\tr.Address = o.Address\n\t}\n\n\tif o.Enabled != nil {\n\t\tr.Enabled = o.Enabled\n\t}\n\n\tif o.Namespace != nil {\n\t\tr.Namespace = o.Namespace\n\t}\n\n\tif o.RenewToken != nil {\n\t\tr.RenewToken = o.RenewToken\n\t}\n\n\tif o.Retry != nil {\n\t\tr.Retry = r.Retry.Merge(o.Retry)\n\t}\n\n\tif o.SSL != nil {\n\t\tr.SSL = r.SSL.Merge(o.SSL)\n\t}\n\n\tif o.Token != nil {\n\t\tr.Token = o.Token\n\t}\n\n\tif o.VaultAgentTokenFile != nil {\n\t\tr.VaultAgentTokenFile = o.VaultAgentTokenFile\n\t}\n\n\tif o.Transport != nil {\n\t\tr.Transport = r.Transport.Merge(o.Transport)\n\t}\n\n\tif o.UnwrapToken != nil {\n\t\tr.UnwrapToken = o.UnwrapToken\n\t}\n\n\tif o.DefaultLeaseDuration != nil {\n\t\tr.DefaultLeaseDuration = o.DefaultLeaseDuration\n\t}\n\n\tif o.LeaseRenewalThreshold != nil {\n\t\tr.LeaseRenewalThreshold = o.LeaseRenewalThreshold\n\t}\n\n\tif o.K8SAuthRoleName != nil {\n\t\tr.K8SAuthRoleName = o.K8SAuthRoleName\n\t}\n\n\tif o.K8SServiceAccountToken != nil {\n\t\tr.K8SServiceAccountToken = o.K8SServiceAccountToken\n\t}\n\n\tif o.K8SServiceAccountTokenPath != nil {\n\t\tr.K8SServiceAccountTokenPath = o.K8SServiceAccountTokenPath\n\t}\n\n\tif o.K8SServiceMountPath != nil {\n\t\tr.K8SServiceMountPath = o.K8SServiceMountPath\n\t}\n\n\treturn r\n}", "func (s *Service) ApplyConfiguration(config interface{}) error {\n\tif err := s.CheckConfiguration(config); err != nil {\n\t\treturn err\n\t}\n\tvar ok bool\n\ts.Cfg, ok = config.(Configuration)\n\tif !ok {\n\t\treturn fmt.Errorf(\"Invalid configuration\")\n\t}\n\n\ts.ServiceName = s.Cfg.Name\n\ts.ServiceType = sdk.TypeUI\n\ts.HTTPURL = s.Cfg.URL\n\ts.MaxHeartbeatFailures = s.Cfg.API.MaxHeartbeatFailures\n\ts.Router.Config = s.Cfg.HTTP\n\n\t// HTMLDir must contains the ui dist directory.\n\t// ui.tar.gz contains the dist directory\n\ts.HTMLDir = filepath.Join(s.Cfg.Staticdir, \"dist\")\n\ts.DocsDir = filepath.Join(s.Cfg.Staticdir, \"docs\")\n\ts.Cfg.BaseURL = strings.TrimSpace(s.Cfg.BaseURL)\n\tif s.Cfg.BaseURL == \"\" { // s.Cfg.BaseURL could not be empty\n\t\ts.Cfg.BaseURL = \"/\"\n\t}\n\n\treturn nil\n}", "func (bo *BoolOptions) Apply(n models.ConfigurationMap, changed ChangedFunc, data interface{}) int {\n\tchanges := []changedOptions{}\n\n\tbo.optsMU.Lock()\n\tfor k, v := range n {\n\t\tval, ok := bo.Opts[k]\n\n\t\tif boolVal, _ := NormalizeBool(v); boolVal {\n\t\t\t/* Only enable if not enabled already */\n\t\t\tif !ok || !val {\n\t\t\t\tbo.enable(k)\n\t\t\t\tchanges = append(changes, changedOptions{key: k, value: true})\n\t\t\t}\n\t\t} else {\n\t\t\t/* Only disable if enabled already */\n\t\t\tif ok && val {\n\t\t\t\tbo.disable(k)\n\t\t\t\tchanges = append(changes, changedOptions{key: k, value: false})\n\t\t\t}\n\t\t}\n\t}\n\tbo.optsMU.Unlock()\n\n\tfor _, change := range changes {\n\t\tchanged(change.key, change.value, data)\n\t}\n\n\treturn len(changes)\n}", "func MergeHealthcheckConfig(a, b Healthcheck) Healthcheck {\n\tresult := b\n\tif result.Interval == \"\" {\n\t\tresult.Interval = a.Interval\n\t}\n\tif result.Timeout == \"\" {\n\t\tresult.Timeout = a.Timeout\n\t}\n\tif len(result.Rules) == 0 {\n\t\tresult.Rules = a.Rules\n\t}\n\treturn result\n}", "func (a *ServerConfig) Merge(b *ServerConfig) *ServerConfig {\n\tresult := *a\n\n\tif b.Enabled {\n\t\tresult.Enabled = true\n\t}\n\n\treturn &result\n}", "func (o *Options) Apply(opts ...Option) error {\n\tfor i, opt := range opts {\n\t\tif err := opt(o); err != nil {\n\t\t\treturn fmt.Errorf(\"option %d failed: %s\", i, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (c *PrometheusConfig) Merge(o *PrometheusConfig) *PrometheusConfig {\n\tif c == nil {\n\t\tif o == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn o.Copy()\n\t}\n\n\tif o == nil {\n\t\treturn c.Copy()\n\t}\n\n\tr := c.Copy()\n\n\tif o.Port != nil {\n\t\tr.Port = UintCopy(o.Port)\n\t}\n\n\tif o.CachePeriod != nil {\n\t\tr.CachePeriod = TimeDurationCopy(o.CachePeriod)\n\t}\n\n\treturn r\n}", "func (o *SAControllerOptions) ApplyTo(cfg *serviceaccountconfig.SAControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ServiceAccountKeyFile = o.ServiceAccountKeyFile\n\tcfg.ConcurrentSATokenSyncs = o.ConcurrentSATokenSyncs\n\tcfg.RootCAFile = o.RootCAFile\n\n\treturn nil\n}", "func (c *TelemetryConfig) Merge(o *TelemetryConfig) *TelemetryConfig {\n\tif c == nil {\n\t\tif o == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn o.Copy()\n\t}\n\n\tif o == nil {\n\t\treturn c.Copy()\n\t}\n\n\tr := c.Copy()\n\n\tif o.MetricsPrefix != nil {\n\t\tr.MetricsPrefix = StringCopy(o.MetricsPrefix)\n\t}\n\n\tif o.Stdout != nil {\n\t\tr.Stdout = o.Stdout.Copy()\n\t}\n\n\tif o.DogStatsD != nil {\n\t\tr.DogStatsD = o.DogStatsD.Copy()\n\t}\n\n\tif o.Prometheus != nil {\n\t\tr.Prometheus = o.Prometheus.Copy()\n\t}\n\n\treturn r\n}", "func (c *Config) adjust(meta *toml.MetaData) error {\n\tconfigMetaData := configutil.NewConfigMetadata(meta)\n\tif err := configMetaData.CheckUndecoded(); err != nil {\n\t\tc.WarningMsgs = append(c.WarningMsgs, err.Error())\n\t}\n\n\tif c.Name == \"\" {\n\t\thostname, err := os.Hostname()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tconfigutil.AdjustString(&c.Name, fmt.Sprintf(\"%s-%s\", defaultName, hostname))\n\t}\n\tconfigutil.AdjustString(&c.DataDir, fmt.Sprintf(\"default.%s\", c.Name))\n\tconfigutil.AdjustPath(&c.DataDir)\n\n\tif err := c.validate(); err != nil {\n\t\treturn err\n\t}\n\n\tconfigutil.AdjustString(&c.BackendEndpoints, defaultBackendEndpoints)\n\tconfigutil.AdjustString(&c.ListenAddr, defaultListenAddr)\n\tconfigutil.AdjustString(&c.AdvertiseListenAddr, c.ListenAddr)\n\n\tif !configMetaData.IsDefined(\"enable-grpc-gateway\") {\n\t\tc.EnableGRPCGateway = utils.DefaultEnableGRPCGateway\n\t}\n\n\tc.adjustLog(configMetaData.Child(\"log\"))\n\tc.Security.Encryption.Adjust()\n\n\tif len(c.Log.Format) == 0 {\n\t\tc.Log.Format = utils.DefaultLogFormat\n\t}\n\n\tconfigutil.AdjustInt64(&c.LeaderLease, utils.DefaultLeaderLease)\n\n\tif err := c.Schedule.Adjust(configMetaData.Child(\"schedule\"), false); err != nil {\n\t\treturn err\n\t}\n\treturn c.Replication.Adjust(configMetaData.Child(\"replication\"))\n}", "func (old ContainerConfig) Copy() ContainerConfig {\n\t// Copy all fields\n\tres := old\n\n\t// Make deep copy of slices\n\t// none yet - placeholder\n\n\treturn res\n}", "func (cc *CredsConfig) Merge(other *CredsConfig) {\n\tif other == nil {\n\t\treturn\n\t}\n\tcc.Registry = merge(cc.Registry, other.Registry)\n\tcc.VCS = merge(cc.VCS, other.VCS)\n\tcc.Secrets = merge(cc.Secrets, other.Secrets)\n\tcc.Orchestrator = merge(cc.Orchestrator, other.Orchestrator)\n}", "func (cfg *Config) Merge(add *Config) {\n\tC.al_merge_config_into((*C.ALLEGRO_CONFIG)(cfg), (*C.ALLEGRO_CONFIG)(add))\n}", "func (c *Config) Copy() (*Config, error) {\n\tnewC := New()\n\tc.Viper.Unmarshal(&newC.plainTextConfig)\n\tc.Viper.Unmarshal(&newC.secureConfig)\n\treturn newC, nil\n}", "func (c *ApplicationConfig) FixupConfig() error {\n\t// var emptyConfig ApplicationConfig\n\n\treturn nil\n}", "func (sl *Slice) ConfigCopy(n Ki, frm Slice) {\n\tsz := len(frm)\n\tif sz > 0 || n == nil {\n\t\tcfg := make(kit.TypeAndNameList, sz)\n\t\tfor i, kid := range frm {\n\t\t\tcfg[i].Type = kid.Type()\n\t\t\tcfg[i].Name = kid.UniqueName() // use unique so guaranteed to have something\n\t\t}\n\t\tmods, updt := sl.Config(n, cfg, true) // use unique names -- this means name = uniquname\n\t\tfor i, kid := range frm {\n\t\t\tmkid := (*sl)[i]\n\t\t\tmkid.SetNameRaw(kid.Name()) // restore orig user-names\n\t\t}\n\t\tif mods && n != nil {\n\t\t\tn.UpdateEnd(updt)\n\t\t}\n\t} else {\n\t\tn.DeleteChildren(true)\n\t}\n}", "func WithConfig(cfg Config) Opt {\n\treturn func(t *Tortoise) {\n\t\tt.cfg = cfg\n\t}\n}", "func (service *retrierMockService) ApplyConfiguration(_ interface{}) error {\n\tservice.applyConfCount++\n\treturn nil\n}", "func (c *Cluster) ApplyConfigChange(cc raftpb.ConfChange) {\n\tswitch cc.Type {\n\tcase raftpb.ConfChangeAddNode, raftpb.ConfChangeAddLearnerNode:\n\t\tc.AddMember(cc.NodeID, string(cc.Context))\n\tcase raftpb.ConfChangeRemoveNode:\n\t\tc.RemoveMember(cc.NodeID)\n\t}\n}", "func WithConfig(c *Config) OptionFunc {\n\treturn func(b *Bot) {\n\t\tb.conf = c\n\t}\n}", "func (cfg *NetworkServiceConfig) MergeWithConfigOptions(conf *Config) error {\n\t// Update mechanism if not specified\n\tif cfg.Mechanism == \"\" && conf.Mechanism == \"\" {\n\t\treturn errors.New(\"no mechanism specified\")\n\t}\n\n\tif cfg.Mechanism == \"\" && conf.Mechanism != \"\" {\n\t\tm, ok := configMechanisms[conf.Mechanism]\n\t\tif !ok {\n\t\t\treturn errors.Errorf(\"invalid mechanism specified %v. Supported: %v\", conf.Mechanism, configMechanisms)\n\t\t}\n\t\tcfg.Mechanism = m\n\t}\n\t// Add labels from root config if not specified.\n\tfor _, kv := range conf.Labels {\n\t\tkeyValue := strings.Split(kv, \"=\")\n\t\tif len(keyValue) != 2 {\n\t\t\tkeyValue = []string{\"\", \"\"}\n\t\t}\n\t\tkey := strings.Trim(keyValue[0], \" \")\n\t\tif _, ok := cfg.Labels[key]; !ok {\n\t\t\tif cfg.Labels == nil {\n\t\t\t\tcfg.Labels = map[string]string{}\n\t\t\t}\n\t\t\tcfg.Labels[key] = strings.Trim(keyValue[1], \" \")\n\t\t}\n\t}\n\treturn cfg.IsValid()\n}", "func Apply(config Config, plugin plugins.PluginSpec, evt Wait) error {\n\terr := handleYaml(config, apply, plugin)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif evt != nil {\n\t\tevt.Process(plugin.Labels)\n\t}\n\treturn nil\n}", "func configDefault(config ...Config) Config {\n\t// Return default config if nothing provided\n\tif len(config) < 1 {\n\t\treturn ConfigDefault\n\t}\n\n\t// Override default config\n\tcfg := config[0]\n\n\t// Set default values\n\tif cfg.XSSProtection == \"\" {\n\t\tcfg.XSSProtection = ConfigDefault.XSSProtection\n\t}\n\n\tif cfg.ContentTypeNosniff == \"\" {\n\t\tcfg.ContentTypeNosniff = ConfigDefault.ContentTypeNosniff\n\t}\n\n\tif cfg.XFrameOptions == \"\" {\n\t\tcfg.XFrameOptions = ConfigDefault.XFrameOptions\n\t}\n\n\tif cfg.ReferrerPolicy == \"\" {\n\t\tcfg.ReferrerPolicy = ConfigDefault.ReferrerPolicy\n\t}\n\n\tif cfg.CrossOriginEmbedderPolicy == \"\" {\n\t\tcfg.CrossOriginEmbedderPolicy = ConfigDefault.CrossOriginEmbedderPolicy\n\t}\n\n\tif cfg.CrossOriginOpenerPolicy == \"\" {\n\t\tcfg.CrossOriginOpenerPolicy = ConfigDefault.CrossOriginOpenerPolicy\n\t}\n\n\tif cfg.CrossOriginResourcePolicy == \"\" {\n\t\tcfg.CrossOriginResourcePolicy = ConfigDefault.CrossOriginResourcePolicy\n\t}\n\n\tif cfg.OriginAgentCluster == \"\" {\n\t\tcfg.OriginAgentCluster = ConfigDefault.OriginAgentCluster\n\t}\n\n\tif cfg.XDNSPrefetchControl == \"\" {\n\t\tcfg.XDNSPrefetchControl = ConfigDefault.XDNSPrefetchControl\n\t}\n\n\tif cfg.XDownloadOptions == \"\" {\n\t\tcfg.XDownloadOptions = ConfigDefault.XDownloadOptions\n\t}\n\n\tif cfg.XPermittedCrossDomain == \"\" {\n\t\tcfg.XPermittedCrossDomain = ConfigDefault.XPermittedCrossDomain\n\t}\n\n\treturn cfg\n}", "func populateConfig(config *Config) (*Config, error) {\n\terr := recursivelySet(reflect.ValueOf(config), \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn config, nil\n}", "func (c *config) ApplyWithoutParallel(ex *terraform.Executor) error {\n\tif err := c.terraformInitialize(ex); err != nil {\n\t\treturn fmt.Errorf(\"initializing Terraform configuration: %w\", err)\n\t}\n\n\treturn c.terraformSmartApply(ex, c.DNS, []string{terraform.WithoutParallelism})\n}", "func (c *C7000) ApplyCfg(config *cfgresources.ResourcesConfig) (err error) {\n\treturn nil\n}", "func configDefault(config ...Config) Config {\n\t// Return default config if nothing provided\n\tif len(config) < 1 {\n\t\treturn ConfigDefault\n\t}\n\n\t// Override default config\n\tcfg := config[0]\n\n\t// Set default values\n\tif cfg.Host == \"\" {\n\t\tcfg.Host = ConfigDefault.Host\n\t}\n\tif cfg.Port <= 0 {\n\t\tcfg.Port = ConfigDefault.Port\n\t}\n\tif cfg.Database == \"\" {\n\t\tcfg.Database = ConfigDefault.Database\n\t}\n\tif cfg.Table == \"\" {\n\t\tcfg.Table = ConfigDefault.Table\n\t}\n\tif int(cfg.GCInterval.Seconds()) <= 0 {\n\t\tcfg.GCInterval = ConfigDefault.GCInterval\n\t}\n\treturn cfg\n}" ]
[ "0.73127514", "0.67873657", "0.64981467", "0.649096", "0.6404134", "0.63580257", "0.6339305", "0.6257569", "0.6216042", "0.61683244", "0.6146557", "0.60011595", "0.5992788", "0.5992379", "0.59857476", "0.59723055", "0.5962117", "0.5898599", "0.58887976", "0.58766055", "0.58452684", "0.5823959", "0.58149", "0.5791373", "0.5772987", "0.57544935", "0.5718256", "0.5694609", "0.56799835", "0.5679498", "0.5667948", "0.5661483", "0.56604296", "0.56530833", "0.56388086", "0.55994356", "0.55980664", "0.5589496", "0.55839753", "0.54897946", "0.548712", "0.5472782", "0.54700273", "0.5462542", "0.545748", "0.54495496", "0.54282236", "0.5414494", "0.5380432", "0.5377424", "0.5365538", "0.5346736", "0.53452504", "0.5316082", "0.52973384", "0.5296661", "0.5295782", "0.52955544", "0.5290795", "0.5290675", "0.5284375", "0.52768594", "0.52664024", "0.52431154", "0.52398443", "0.52362317", "0.5231096", "0.52256614", "0.5225446", "0.52241546", "0.52235734", "0.5221127", "0.5221127", "0.5206265", "0.51761067", "0.51525533", "0.51501554", "0.51481164", "0.5130548", "0.5124532", "0.51073134", "0.51045537", "0.5089005", "0.5088803", "0.50787926", "0.50715303", "0.50658447", "0.5062279", "0.50596714", "0.5048248", "0.5048023", "0.50466186", "0.5045024", "0.50313836", "0.50259495", "0.50161636", "0.50139827", "0.50129825", "0.49928403", "0.49878418" ]
0.7006665
1
ConfigPath returns the path to the user config file
func ConfigPath() string { if path, err := homedir.Expand(MKtmpioCfgFile); err == nil { return path } return "" }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func getConfigFilePath() string {\n\t// get current system user\n\tu, err := user.Current()\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\treturn path.Join(u.HomeDir, configFileName)\n}", "func UserConfigDir() (string, error)", "func configPath() (string, error) {\n\thome, err := sys.GetHomeDir()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(home, \".keeper\", \"config.json\"), nil\n}", "func ConfigPath() string {\n\treturn defaultConfig.ConfigPath()\n}", "func GetUserConfigFilePath() string {\n\treturn strings.Replace(DefaultConfigFile, \"~/\", getHome()+\"/\", 1)\n}", "func (c *Config) ConfigPath() string {\n\treturn filepath.Join(c.Dir, \"config.ini\")\n}", "func ConfigPath(ctx *types.SystemContext) string {\n\tconfPath := systemRegistriesConfPath\n\tif ctx != nil {\n\t\tif ctx.SystemRegistriesConfPath != \"\" {\n\t\t\tconfPath = ctx.SystemRegistriesConfPath\n\t\t} else if ctx.RootForImplicitAbsolutePaths != \"\" {\n\t\t\tconfPath = filepath.Join(ctx.RootForImplicitAbsolutePaths, systemRegistriesConfPath)\n\t\t}\n\t}\n\treturn confPath\n}", "func UserConfig() string {\n\thome, _ := HomeDir()\n\n\tif home != \"\" {\n\t\tfor _, n := range []string{\".choriarc\", \".mcollective\"} {\n\t\t\thomeCfg := filepath.Join(home, n)\n\n\t\t\tif FileExist(homeCfg) {\n\t\t\t\treturn homeCfg\n\t\t\t}\n\t\t}\n\t}\n\n\tif runtime.GOOS == \"windows\" {\n\t\treturn filepath.Join(\"C:\\\\\", \"ProgramData\", \"choria\", \"etc\", \"client.conf\")\n\t}\n\n\tif FileExist(\"/etc/choria/client.conf\") {\n\t\treturn \"/etc/choria/client.conf\"\n\t}\n\n\tif FileExist(\"/usr/local/etc/choria/client.conf\") {\n\t\treturn \"/usr/local/etc/choria/client.conf\"\n\t}\n\n\treturn \"/etc/puppetlabs/mcollective/client.cfg\"\n}", "func getUserConfigFolderPath() string {\n\n\tuserName := getUserName()\n\n if userName == \"\" {\n return \"\"\n }\n\n\tcfgFolder := getConfigFolderPath()\n\tsep := string(filepath.Separator)\n\n\tpath := cfgFolder + userName + sep\n\n\treturn path\n}", "func GetUserConfigPath() string {\n\treturn \".go-habits.yml\"\n}", "func (i *Instance) ConfigPath() string {\n\treturn i.appDataDir\n}", "func ConfigDir() string {\n\treturn filepath.Join(userSettingsDir, \"kopia\")\n}", "func (c *Config) ConfigPath() string {\n\tif c.options.ConfigPath == \"\" {\n\t\tif fs.PathExists(filepath.Join(c.StoragePath(), \"settings\")) {\n\t\t\treturn filepath.Join(c.StoragePath(), \"settings\")\n\t\t}\n\n\t\treturn filepath.Join(c.StoragePath(), \"config\")\n\t}\n\n\treturn fs.Abs(c.options.ConfigPath)\n}", "func (a *Application) GetConfigPath() string {\n\treturn filepath.Join(a.GetHomeDir(), DefaultApplicationConfigPath)\n}", "func UserConfigDir(tc Context) (string, error) {\n\treturn os.UserConfigDir()\n}", "func GetConfigPath() (p string, err error) {\n\td, err := GetPassDir()\n\tif err == nil {\n\t\tp = filepath.Join(d, ConfigFileName)\n\t}\n\treturn\n}", "func getConfigPath() (string, error) {\n\thome, homeErr := os.UserHomeDir()\n\tif homeErr == nil {\n\t\tif _, err := os.Stat(filepath.Join(home, \".bin\", \"config.json\")); !os.IsNotExist(err) {\n\t\t\treturn filepath.Join(path.Join(home, \".bin\")), nil\n\t\t}\n\t}\n\n\tc := os.Getenv(\"XDG_CONFIG_HOME\")\n\tif _, err := os.Stat(c); !os.IsNotExist(err) {\n\t\treturn filepath.Join(c, \"bin\"), nil\n\t}\n\n\tif homeErr != nil {\n\t\treturn \"\", homeErr\n\t}\n\tc = filepath.Join(home, \".config\")\n\tif _, err := os.Stat(c); !os.IsNotExist(err) {\n\t\treturn filepath.Join(c, \"bin\"), nil\n\t}\n\n\treturn filepath.Join(home, \".bin\"), nil\n}", "func (c Calendars) configPath() (string, error) {\n\tconfDir, err := configDirectory()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn filepath.Join(confDir, \"calendars.txt\"), nil\n}", "func configDirPath() string {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\tlogging.LogFatal(\"config/configDirPath() - Can't find current user: \", err)\n\t}\n\n\t// println(\"usr.HomeDir: \", usr.HomeDir)\n\tconfigDirPath := paths.GetFilePath(usr.HomeDir, configDirName)\n\n\treturn configDirPath\n}", "func getConfigPath(path string) (file string) {\r\n\treturn fmt.Sprintf(\"%s/%s\", path, \"app.ini\")\r\n}", "func ConfigurationPath(profile string) (string, error) {\n\tpath, err := ConfigurationDirectoryPath()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tp, err := path_helper.Fullpath(filepath.Join(path, profile+\".toml\"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn p, nil\n}", "func ConfigFilePath() string {\n\treturn ConfigDir + \"/\" + ConfigFile\n}", "func (cfg *Configurator) ConfigFilePath() string {\n\treturn cfg.configFilePath\n}", "func UserPath(homeDir string) string {\n\treturn filepath.Join(\n\t\thomeDir,\n\t\t\".config\",\n\t\t\"schism\",\n\t\t\"cli.toml\",\n\t)\n}", "func UserConfig() string {\n\treturn util.UserConfig()\n}", "func UserConfig() string {\n\treturn util.UserConfig()\n}", "func configPath() (string, error) {\n\tconfigPath := strings.TrimSpace(os.Getenv(confPathVar))\n\tif len(configPath) == 0 {\n\t\thomeDir, err := os.UserHomeDir()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tconfigPath = homeDir + \"/\" + defaultConfigDir\n\t}\n\n\tif exists(configPath) {\n\t\treturn configPath, nil\n\t}\n\n\treturn configPath, os.Mkdir(configPath, confDirFileMode)\n}", "func getConfigPath() (string, error) {\n\treturn \"./veille.yaml\", nil\n}", "func GetConfigPath(configPath string) string {\n\tif configPath == \"docker\" {\n\t\treturn \"./config/config-docker\"\n\t}\n\treturn \"./config/config-local\"\n}", "func ConfigPath() (string, error) {\n\tconfigOnce.Do(func() {\n\t\t// getting home directory.\n\t\thome, err := homedir.Dir()\n\t\tif err != nil {\n\t\t\tconfigErr = fmt.Errorf(\"[err] ConfigPath %w\", err)\n\t\t\treturn\n\t\t}\n\n\t\t// make config directory\n\t\tpath := filepath.Join(home, \".findgs\")\n\t\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\t\tif suberr := os.MkdirAll(path, os.ModePerm); suberr != nil {\n\t\t\t\tconfigErr = fmt.Errorf(\"[err] NewSearcher %w\", suberr)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tconfigPath = path\n\t})\n\treturn configPath, configErr\n}", "func Path() string {\n\tconfigPath := os.Getenv(EnvironmentPrefix() + configDir)\n\tif configPath == \"\" {\n\t\tconfigPath = config\n\t}\n\treturn configPath\n}", "func configPath() string {\n\tenv := os.Getenv(configPathEnv)\n\tif env == \"\" {\n\t\treturn defaultConfigFile\n\t}\n\treturn env\n}", "func (u *userGitConfig) GetUserConfigBasePath() string {\n\treturn strings.TrimLeft(u.basePath, \"/\")\n}", "func PathConfig(homeDir string) string {\n\treturn fmt.Sprintf(\"%s/%s\", homeDir, ConfigSubDir)\n}", "func ConfigPath() string {\n\n\tif flagConfig == nil {\n\t\tpanic(\"ConfigPath called before init\")\n\t}\n\n\tif !flag.Parsed() {\n\t\tpanic(\"ConfigPath called before flag.Parse\")\n\t}\n\n\treturn *flagConfig\n}", "func GetConfigFilePath() string {\n\tpath, _ := osext.ExecutableFolder()\n\tpath = fmt.Sprintf(\"%s/eremetic.yml\", path)\n\tif _, err := os.Open(path); err == nil {\n\t\treturn path\n\t}\n\tglobalPath := \"/etc/eremetic/eremetic.yml\"\n\tif _, err := os.Open(globalPath); err == nil {\n\t\treturn globalPath\n\t}\n\n\treturn \"\"\n}", "func wslConfigFilePath() (string, error) {\n\thome, err := userHomeDirectory()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn path.Join(home, wslConfigFile), nil\n}", "func GetConfigFilePath(override string) string {\n\tif len(override) > 0 {\n\t\treturn override\n\t}\n\tglobalPath := \"/etc/fusion/fusion.yml\"\n\tif _, err := os.Open(globalPath); err == nil {\n\t\treturn globalPath\n\t}\n\n\treturn \"\"\n}", "func GetConfigPath() string {\n\treturn os.Getenv(CONFIGPATHVAR)\n}", "func (cc *CollectdConfig) ConfigFilePath() string {\n\treturn filepath.Join(cc.InstanceConfigDir(), \"collectd.conf\")\n}", "func (conf blah) Path() string {\n\treturn configPath\n}", "func getCfgPath(name string) string {\n\treturn configDir + \"/\" + name + \".conf\"\n}", "func ConfigDirPath(envContainer EnvContainer) (string, error) {\n\treturn xdgDirPath(envContainer, \"XDG_CONFIG_HOME\", \".config\")\n}", "func getConfigFilePath() (string, error) {\n var err error\n configPath := configdir.LocalConfig(\"road-trip\")\n err = configdir.MakePath(configPath) // Ensure it exists.\n if err != nil {\n return \"\", errors.New(\"Cannot access folder: '\" + configPath + \"' to store config file.\")\n }\n\n return configPath + string(os.PathSeparator) + \"player.yaml\", nil\n}", "func path() string {\n\tif len(configPath) != 0 {\n\t\treturn configPath\n\t}\n\treturn \"config/database.yml\"\n}", "func (tc *TestConfig) Path() string {\n\treturn tc.configPath\n}", "func (c Config) GetConfigDirPath() (string, error) {\n\t// Get home directory.\n\thome := os.Getenv(homeKey)\n\tif home != \"\" {\n\t\treturn filepath.Join(home, \".mstreamb0t\"), nil\n\t}\n\tu, err := user.Current()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(u.HomeDir, \".mstreamb0t\"), nil\n}", "func ConfigFile(inp string) string {\n\tif inp != \"\" {\n\t\tpath := ExpandUser(inp)\n\t\tif FileExists(path) {\n\t\t\treturn path\n\t\t}\n\t}\n\n\tif env := os.Getenv(\"DOLA_CONFIG\"); env != \"\" {\n\t\tpath := ExpandUser(env)\n\t\tif FileExists(path) {\n\t\t\treturn path\n\t\t}\n\t}\n\n\tif path := ExpandUser(\"~/.dola/config.json\"); FileExists(path) {\n\t\treturn path\n\t}\n\n\treturn \"\"\n}", "func ConfigFile() string {\n\treturn configFile\n}", "func GetConfigPath() (string, error) {\n\tvar carriageReturn string\n\tconfigFile := \"/api.conf\"\n\tdir, err := filepath.Abs(filepath.Dir(os.Args[0]))\n\tif err != nil {\n\t\tos.Exit(EXIT_FLAG_ERROR)\n\t}\n\tconfigPath := dir + configFile\n\tif _, err := os.Stat(configPath); err == nil {\n\t\treturn configPath, nil\n\t}\n\tvar cmdName string\n\tif runtime.GOOS == \"windows\" {\n\t\tcmdName = \"where\"\n\t\tcarriageReturn = \"\\r\\n\"\n\t} else {\n\t\tcmdName = \"which\"\n\t\tcarriageReturn = \"\\n\"\n\t}\n\tresponse, err := GetCommandOutput(cmdName, 2*time.Second, os.Args[0])\n\tpath := string(bytes.Split(response, []byte(carriageReturn))[0])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// check if is a symlink\n\tfile, err := os.Lstat(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif file.Mode()&os.ModeSymlink == os.ModeSymlink {\n\t\t// This is a symlink\n\t\tpath, err = filepath.EvalSymlinks(path)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\treturn filepath.Dir(path) + configFile, nil\n}", "func ConfigDir() string {\n\treturn configDir\n}", "func getConfigFilePath() string {\n\tpathList := [5]string{\n\t\t\"config.json\",\n\t\t\"../config.json\",\n\t\t\"../../config.json\",\n\t\t\"../../../config.json\",\n\t\t\"../../../../config.json\",\n\t}\n\n\t_, b, _, _ := runtime.Caller(0)\n\tfilePath := filepath.Dir(b)\n\tfilePath = filepath.Join(filePath, \"../config.json\")\n\n\tpath, err := os.Getwd()\n\tif err == nil {\n\t\tfor _, configPath := range pathList {\n\t\t\tprocessFilePath := filepath.Join(path, configPath)\n\t\t\texist, _ := exists(processFilePath)\n\t\t\tif exist == true {\n\t\t\t\tfilePath = processFilePath\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn filePath\n}", "func GetConfigFolder() string {\n\treturn filepath.Join(helper.Home(), configPath)\n}", "func getConfigFilePath() string {\n\tvar configFile string\n\tflag.StringVar(&configFile, \"config\", \"./config.json\", \"JSON config file path\")\n\tflag.Parse()\n\n\tlog.Printf(\"Using config file %s\", configFile)\n\n\treturn configFile\n}", "func GetConfigPath(fileName string) string {\n\tif len(fileName) > 0 {\n\t\tfilepath, err := filepath.Abs(fileName)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"WARNING: No chef configuration file found at %s \\n\", fileName)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tif !doesDirExist(filepath) {\n\t\t\tfmt.Printf(\"WARNING: No chef configuration file found at %s \\n\", fileName)\n\t\t\tos.Exit(1)\n\t\t}\n\t\treturn filepath\n\t}\n\tex, err := os.Getwd()\n\tif err != nil {\n\t\treturn GetDefaultConfigPath()\n\t}\n\n\treturn filepath.Join(ex, configPath)\n\n}", "func (a AppConfig) ConfigDir() string {\n\tconfigDirMutex.RLock()\n\tdefer configDirMutex.RUnlock()\n\treturn configDir\n}", "func (c *client) GetProvidersConfigFilePath() (string, error) {\n\tprovidersDir, err := c.GetTKGProvidersDirectory()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn filepath.Join(providersDir, constants.LocalProvidersConfigFileName), nil\n}", "func SetConfigPath(p string) {\n\tconfigPath = p\n}", "func PathCfgDir() string {\n\tdir := os.Getenv(ENV_CFG_DIR)\n\tif dir != \"\" {\n\t\treturn dir\n\t}\n\thomeDir, err := Home()\n\tif err != nil {\n\t\tlog.Fatal(\"can not fetch home directory\")\n\t}\n\treturn filepath.Join(homeDir, DEFAULT_CFG_DIR)\n}", "func getConfigFile() (string, error) {\n\tconfigDir, err := os.UserConfigDir()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tappDir := configDir + \"/whatphone\"\n\tif _, err := os.Stat(appDir); os.IsNotExist(err) {\n\t\terr = os.Mkdir(appDir, 0744)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\treturn appDir + \"/config.json\", nil\n}", "func (g *Generator) ConfigUser() string {\n\treturn g.image.Config.User\n}", "func (c *Context) KubeConfigPath() string {\n\t// TODO(bentheelder): Windows?\n\t// configDir matches the standard directory expected by kubectl etc\n\tconfigDir := filepath.Join(os.Getenv(\"HOME\"), \".kube\")\n\t// note that the file name however does not, we do not want to overwite\n\t// the standard config, though in the future we may (?) merge them\n\tfileName := fmt.Sprintf(\"kind-config-%s\", c.name)\n\treturn filepath.Join(configDir, fileName)\n}", "func getConfigFolderPath() string {\n\tsep := string(filepath.Separator)\n\twd, _ := os.Getwd()\n\n\twdPath := strings.Split(wd, sep)\n\tindexOfSrc := lastIndexOf(wdPath, \"src\")\n\tindexOfBin := lastIndexOf(wdPath, \"bin\")\n\n\tcfgPath := \"\"\n\tvar pathEl []string\n\tif indexOfBin > -1 && indexOfBin > indexOfSrc {\n\t\tpathEl = wdPath[:indexOfBin] // take up to bin (exclusive)\n\t} else if indexOfSrc > -1 {\n\t\tpathEl = wdPath[:indexOfSrc] // take up to src (exclusive)\n\t}\n\n\tif len(pathEl) > 0 {\n\t\tcfgPath = strings.Join(pathEl, sep) + sep\n\t\tcfgPath += \"config\" + sep\n\t}\n\n\treturn cfgPath\n}", "func ConfigDir() string {\n\tdir := \".\"\n\tswitch goos {\n\tcase \"darwin\":\n\t\tdir = path.Join(envFunc(\"HOME\"), \"Library\", \"Application Support\", \"shade\")\n\tcase \"linux\", \"freebsd\":\n\t\tdir = path.Join(envFunc(\"HOME\"), \".shade\")\n\tdefault:\n\t\tlog.Printf(\"TODO: ConfigDir on GOOS %q\", goos)\n\t}\n\treturn dir\n}", "func SetConfigPath(path string) {\n\tconfigPath = path\n}", "func (p Plans) ConfigFile() Path {\n\treturn p.Expand().Join(\"config.json\")\n}", "func getConfFilePath(profile string) string {\n\tpwd, e := os.Getwd()\n\tutil.LogPanic(e)\n\n\tpath := pwd + defaultConfPath\n\tif profile != \"\" {\n\t\tpath += \"-\" + profile\n\t}\n\treturn path + defaultConfFilesSuffix\n}", "func getMcConfigPath() (string, error) {\n\tdir, err := getMcConfigDir()\n\tif err != nil {\n\t\treturn \"\", NewIodine(iodine.New(err, nil))\n\t}\n\treturn filepath.Join(dir, mcConfigFile), nil\n}", "func DetermineConfigFilePath() string {\n\tdir := util.ExeDirectory()\n\tr := lookForConfigFile(dir)\n\tif len(r) != 0 {\n\t\treturn r\n\t}\n\n\tdir, err := homedir.Dir()\n\tif err != nil {\n\t\tlog.Printf(\"failed to get home dir: %v\\n\", err)\n\t\treturn \"\"\n\t}\n\treturn lookForConfigFile(dir)\n}", "func (config *SQLConfiguration) GetPath() string {\n\tvar path, defaultFile, customFile string\n\tpath = \"database/\"\n\tdefaultFile = path + \"default.json\"\n\tcustomFile = path + \"custom.json\"\n\tif _, err := os.Open(\"conf/\" + customFile); err == nil {\n\t\treturn customFile\n\t}\n\treturn defaultFile\n}", "func getConfFilePath(root, clusterName string) string {\n\treturn fmt.Sprintf(\"%s/%s.config\", root, clusterName)\n}", "func configLocation() string {\n\tif configFileLocation == \"\" {\n\t\thome, err := homedir.Dir()\n\t\terrorExit(err)\n\t\treturn fmt.Sprintf(\"%s/%s\", home, configFileLocation)\n\t}\n\treturn configFileLocation\n}", "func Dir() (string, error) {\n\tc, err := os.UserConfigDir()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(c, appName), nil\n}", "func (c *client) GetTKGConfigPath() (string, error) {\n\ttkgDir, err := c.GetTKGDirectory()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(tkgDir, constants.TKGConfigFileName), nil\n}", "func KubeConfigPath() string {\n\tkubeconfigEnv := os.Getenv(\"KUBECONFIG\")\n\tif kubeconfigEnv == \"\" {\n\t\thome := os.Getenv(\"HOMEDRIVE\") + os.Getenv(\"HOMEPATH\")\n\t\tif home == \"\" {\n\t\t\tfor _, h := range []string{\"HOME\", \"USERPROFILE\"} {\n\t\t\t\tif home = os.Getenv(h); home != \"\" {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tkubeconfigPath := filepath.Join(home, \".kube\", \"config\")\n\t\treturn kubeconfigPath\n\t}\n\treturn kubeconfigEnv\n}", "func (c *Config) Path() string {\n\treturn c.asset.Layout().config + \"/.env.\" + os.Getenv(\"APPY_ENV\")\n}", "func Path(sys string) (string, error) {\n\n\tvar paths []string\n\n\t// if CHEAT_CONFIG_PATH is set, return it\n\tif os.Getenv(\"CHEAT_CONFIG_PATH\") != \"\" {\n\n\t\t// expand ~\n\t\texpanded, err := homedir.Expand(os.Getenv(\"CHEAT_CONFIG_PATH\"))\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to expand ~: %v\", err)\n\t\t}\n\n\t\treturn expanded, nil\n\n\t\t// OSX config paths\n\t} else if sys == \"darwin\" {\n\n\t\tpaths = []string{\n\t\t\tpath.Join(os.Getenv(\"XDG_CONFIG_HOME\"), \"/cheat/conf.yml\"),\n\t\t\tpath.Join(os.Getenv(\"HOME\"), \".config/cheat/conf.yml\"),\n\t\t\tpath.Join(os.Getenv(\"HOME\"), \".cheat/conf.yml\"),\n\t\t}\n\n\t\t// Linux config paths\n\t} else if sys == \"linux\" {\n\n\t\tpaths = []string{\n\t\t\tpath.Join(os.Getenv(\"XDG_CONFIG_HOME\"), \"/cheat/conf.yml\"),\n\t\t\tpath.Join(os.Getenv(\"HOME\"), \".config/cheat/conf.yml\"),\n\t\t\tpath.Join(os.Getenv(\"HOME\"), \".cheat/conf.yml\"),\n\t\t\t\"/etc/cheat/conf.yml\",\n\t\t}\n\n\t\t// Windows config paths\n\t} else if sys == \"windows\" {\n\n\t\tpaths = []string{\n\t\t\tfmt.Sprintf(\"%s/cheat/conf.yml\", os.Getenv(\"APPDATA\")),\n\t\t\tfmt.Sprintf(\"%s/cheat/conf.yml\", os.Getenv(\"PROGRAMDATA\")),\n\t\t}\n\n\t\t// Unsupported platforms\n\t} else {\n\t\treturn \"\", fmt.Errorf(\"unsupported os: %s\", sys)\n\t}\n\n\t// check if the config file exists on any paths\n\tfor _, p := range paths {\n\t\tif _, err := os.Stat(p); err == nil {\n\t\t\treturn p, nil\n\t\t}\n\t}\n\n\t// we can't find the config file if we make it this far\n\treturn \"\", fmt.Errorf(\"could not locate config file\")\n}", "func ProjectConfigPath(c context.Context) string {\n\treturn svcconfig.ProjectConfigPath(cfgclient.CurrentServiceName(c))\n}", "func GetDefaultConfigPath() string {\n\thomeDir, err := os.UserHomeDir()\n\tif err != nil {\n\t\treturn filepath.Join(\"/etc/chef\", configPath)\n\t}\n\tif !checkChefDirExists(homeDir) {\n\t\tfmt.Printf(\"WARNING: No chef configuration file found at %s\", homeDir)\n\t\tos.Exit(1)\n\t}\n\treturn filepath.Join(homeDir, configPath)\n\n}", "func GetConfigFile() (string, string) {\n\tdefaultConfig := filepath.Join(file.UserHome(), config.DefaultConfigDir, config.DefaultConfig)\n\tdefaultAppDir, _ := filepath.Split(defaultConfig)\n\treturn defaultAppDir, defaultConfig\n}", "func (c *Config) Filepath() string {\n\treturn c.loadedFromFilepath\n}", "func GetConfigDir() string {\n\treturn configDir\n}", "func (c *FileConfigReader) Path() string {\n\treturn c.path\n}", "func (w *Writer) configPath(configDigest digest.Digest) string {\n\treturn configDigest.Hex() + \".json\"\n}", "func getDefaultConfigPath() (string, error) {\n\tfile := \"efc-agent.conf\"\n\tetcfile := \"/etc/efc-agent/efc-agent.conf\"\n\treturn getPath(file, etcfile)\n}", "func (s *SoftHSMSetup) GetConfigFilename() string {\n\treturn s.statedir + \"/softhsm2.conf\"\n}", "func Config(path string) (conf []byte, err error) {\n\tconf, err = ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn conf, nil\n}", "func GetCfgPath(c domain.CLIContext) string {\n\treturn c.String(cfgPathKey)\n}", "func GetConfDir() string {\n\treturn fileutil.GetConfDir()\n}", "func getUserXfconfDir(u *user.User) string {\n\tuserConfigDir := os.Getenv(\"XDG_CONFIG_HOME\")\n\tif userConfigDir != \"\" {\n\t\treturn filepath.Join(userConfigDir, xfconfChannelXmlPath)\n\t}\n\n\treturn filepath.Join(u.HomeDir, \".config\", xfconfChannelXmlPath)\n}", "func getConfFile() string {\n\tconf := \"Chrystoki.conf\"\n\tconfPath := os.Getenv(\"ChrystokiConfigurationPath\")\n\tif confPath == \"\" {\n\t\tconfPath = \"/etc\"\n\t}\n\treturn filepath.Join(confPath, conf)\n}", "func (s *Scope) configDir() (string, error) {\n\tp, err := s.dataDir()\n\tif err != nil {\n\t\treturn p, err\n\t}\n\n\treturn filepath.Join(p, \"Config\"), nil\n}", "func TouchConfigFile() string {\n\tpath := GetUserConfigPath()\n\n\terr := ioutil.WriteFile(path, []byte(\"\\n\"), 0644)\n\tExpect(err).ShouldNot(HaveOccurred())\n\n\treturn path\n}", "func (g *GenericVaultBackend) EncryptionConfigPath() string {\n\treturn filepath.Join(g.Path(), \"encryption-config\")\n}", "func getProviderConfigFile() string {\n\n\t// get the current user.\n\thome, err := homedir.Dir()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// based on user data or test flag declare the config file.\n\tvar sgdir string\n\tvar sgconfig string\n\tif testMode() {\n\t\tsgdir = \"/tmp/.supergiant\"\n\t\tsgconfig = \"\" + sgdir + \"/provider.json\"\n\t} else {\n\t\tsgdir = \"\" + home + \"/.supergiant\"\n\t\tsgconfig = \"\" + sgdir + \"/provider.json\"\n\t}\n\n\t// Make sure the sgconfig directory exists.\n\t_, err = os.Stat(sgdir)\n\t// else create it.\n\tif os.IsNotExist(err) {\n\t\terr := os.Mkdir(sgdir, 0700)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\t// Make sure sgconfig file exists.\n\t_, err = os.Stat(sgconfig)\n\t// else create it.\n\tif os.IsNotExist(err) {\n\t\t_, err := os.Create(sgconfig)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t} else {\n\t\t\treturn sgconfig\n\t\t}\n\t}\n\n\treturn sgconfig\n\n}", "func (c *tokenConfig) Path() string {\n\treturn c.Dir\n}", "func (c *Config) ConfigFile() string {\n\tif c.options.ConfigFile == \"\" || !fs.FileExists(c.options.ConfigFile) {\n\t\treturn filepath.Join(c.ConfigPath(), \"options.yml\")\n\t}\n\n\treturn c.options.ConfigFile\n}", "func DefaultPersisConfigPath(v *viper.Viper) string {\n\t// persist using config\n\tf := v.ConfigFileUsed() // ./conf/.sole.yaml\n\tif f == \"\" {\n\t\treturn \".use.yaml\"\n\t}\n\tdir := filepath.Dir(f)\n\tbase := filepath.Base(f)\n\text := filepath.Ext(f)\n\tname := strings.TrimPrefix(strings.TrimSuffix(base, ext), \".\")\n\n\treturn filepath_.Pathify(filepath.Join(dir, \".use.\"+name+\".yaml\")) // /root/.use.sole.yaml\n}", "func filePath() []byte {\n\tconfigFileName := \"config.dev.json\"\n\tif isProd() {\n\t\tconfigFileName = \"config.prod.json\"\n\t}\n\treturn []byte(fmt.Sprintf(\"%s/%s\", directoryPath, configFileName))\n}", "func GetClusterConfigPath(cluster string) (string, error) {\n\thome, err := GetHomeDir()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn home + \"/.kcm/\" + cluster + \"/config\", nil\n}" ]
[ "0.78871745", "0.7830641", "0.76966554", "0.76597065", "0.7624136", "0.76101524", "0.75013083", "0.74757475", "0.7412091", "0.7372235", "0.7363509", "0.736189", "0.73549765", "0.73051214", "0.7268334", "0.7248684", "0.7237965", "0.72199416", "0.71782047", "0.7148685", "0.706768", "0.70550436", "0.7038422", "0.69605005", "0.69602203", "0.69602203", "0.69343567", "0.6923022", "0.6914399", "0.6912509", "0.69095016", "0.6889472", "0.6875893", "0.68215203", "0.6817445", "0.68054205", "0.6760901", "0.6758145", "0.67504495", "0.67357373", "0.6731076", "0.66871345", "0.66682583", "0.6624876", "0.65887606", "0.65548563", "0.65430325", "0.65241855", "0.65080374", "0.64838815", "0.6462527", "0.6459155", "0.6449604", "0.6440445", "0.6425174", "0.6348738", "0.63434416", "0.63120836", "0.6306433", "0.6300537", "0.62956494", "0.6288336", "0.62485725", "0.6234692", "0.6231842", "0.62301576", "0.62283325", "0.6206546", "0.61948466", "0.6190097", "0.61837", "0.6164268", "0.6161876", "0.6160418", "0.6155202", "0.61518586", "0.61496705", "0.6135572", "0.6113674", "0.6101141", "0.6100767", "0.6065077", "0.6056638", "0.6041195", "0.6036199", "0.6028463", "0.60122085", "0.5992869", "0.598936", "0.5988413", "0.59878206", "0.5978437", "0.59774405", "0.59680545", "0.5959846", "0.5953792", "0.59065723", "0.5897202", "0.5890863", "0.58800834" ]
0.75068724
6
Save stores the given configuration in ~/.mktmpio.yml, overwriting the current contents if the file exists.
func (c *Config) Save(cfgPath string) error { cfgFile, err := yaml.Marshal(c) if err == nil { err = ioutil.WriteFile(cfgPath, cfgFile, 0600) } return err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c Configuration) Save() {\n\tbuf := new(bytes.Buffer)\n\tif err := toml.NewEncoder(buf).Encode(c); err != nil {\n\t\tlog.Fatalln(\"Failed to encode config\", err)\n\t}\n\tf, err := os.Create(configFile)\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed to create file\", err)\n\t\treturn\n\t}\n\n\tw := bufio.NewWriter(f)\n\tbuf.WriteTo(w)\n\tw.Flush()\n}", "func Save(filePath string, t Tomler, secure bool) error {\n\tvar fd *os.File\n\tvar err error\n\tif secure {\n\t\tfd, err = fs.CreateSecureFile(filePath)\n\t} else {\n\t\tfd, err = os.Create(filePath)\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"config: can't save %s to %s: %w\", reflect.TypeOf(t).String(), filePath, err)\n\t}\n\tdefer fd.Close()\n\treturn toml.NewEncoder(fd).Encode(t.TOML())\n}", "func (s yamlStore) SaveTo(path string) error {\n\t// If yamlStore is unset, none of New, Load, or LoadFrom were called successfully\n\tif s.cfg == nil {\n\t\treturn store.SaveError{Err: fmt.Errorf(\"undefined config, use one of the initializers: New, Load, LoadFrom\")}\n\t}\n\n\t// If it is a new configuration, the path should not exist yet\n\tif s.mustNotExist {\n\t\t// Lets check that the file doesn't exist\n\t\t_, err := s.fs.Stat(path)\n\t\tif os.IsNotExist(err) {\n\t\t\t// This is exactly what we want\n\t\t} else if err == nil || os.IsExist(err) {\n\t\t\treturn store.SaveError{Err: fmt.Errorf(\"configuration already exists in %q\", path)}\n\t\t} else {\n\t\t\treturn store.SaveError{Err: fmt.Errorf(\"unable to check for file prior existence: %w\", err)}\n\t\t}\n\t}\n\n\t// Marshall into YAML\n\tcontent, err := s.cfg.MarshalYAML()\n\tif err != nil {\n\t\treturn store.SaveError{Err: fmt.Errorf(\"unable to marshal to YAML: %w\", err)}\n\t}\n\n\t// Prepend warning comment for the 'PROJECT' file\n\tcontent = append([]byte(commentStr), content...)\n\n\t// Write the marshalled configuration\n\terr = afero.WriteFile(s.fs, path, content, 0600)\n\tif err != nil {\n\t\treturn store.SaveError{Err: fmt.Errorf(\"failed to save configuration to %q: %w\", path, err)}\n\t}\n\n\treturn nil\n}", "func (tc *ThingConfig) Save(name string) error {\n\n\td, err := yaml.Marshal(&tc)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn errors.Wrap(ioutil.WriteFile(fmt.Sprintf(\"%s.yaml\", name), d, 0600), \"Failed to save thing config\")\n}", "func (c *Config) Save(path string) error {\n\tconfigBytes, err := yaml.Marshal(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(path, configBytes, 0600)\n}", "func (config *Config) Save() error {\n\tconfigYaml, err := yaml.Marshal(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not get working directory: %v\", err)\n\t}\n\treturn ioutil.WriteFile(filepath.Join(pwd, \"wrp.yaml\"), configYaml, 0644)\n}", "func Save() {\n\tc := Config{viper.GetString(\"email\"), viper.GetString(\"platform\"), viper.GetDuration(\"timeout\")}\n\tdata, err := json.MarshalIndent(c, \"\", \" \")\n\tif err != nil {\n\t\treturn\n\t}\n\n\t_ = ioutil.WriteFile(viper.GetString(\"file_config\"), data, 0600)\n}", "func Save(cfg *Config) error {\n\tfile, err := Location()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdir := filepath.Dir(file)\n\terr = os.MkdirAll(dir, os.FileMode(0755))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't create directory %s: %v\", dir, err)\n\t}\n\tdata, err := json.MarshalIndent(cfg, \"\", \" \")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't marshal config: %v\", err)\n\t}\n\terr = os.WriteFile(file, data, 0600)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't write file '%s': %v\", file, err)\n\t}\n\treturn nil\n}", "func (c Config) Save() error {\n\td, err := yaml.Marshal(&c)\n\tif err != nil {\n\t\treturn err\n\t}\n\tos.Remove(\"handshake.yaml\")\n\treturn ioutil.WriteFile(\"handshake.yaml\", d, 0644)\n}", "func (c *Config) Save(file *os.File) error {\n\tif file == nil && c.file != nil {\n\t\tfile = c.file\n\t}\n\n\tif err := file.Truncate(0); err != nil {\n\t\treturn err\n\t}\n\tif _, err := file.Seek(0, 0); err != nil {\n\t\treturn err\n\t}\n\tif err := yaml.NewEncoder(file).Encode(c); err != nil {\n\t\treturn err\n\t}\n\n\treturn file.Sync()\n}", "func (cfg *Config) Save(fpath string) error {\n\t// create a copy\n\tconfig2 := cfg\n\t// clear, setup setting\n\tconfig2.Password = \"\"\n\tconfig2.Iterations = ConfigHashIterations\n\n\t// save to file\n\tbyteDat2, err := json.MarshalIndent(config2, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(fpath, byteDat2, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Config) Save() error {\n\tcontents, _ := yaml.Marshal(&c)\n\terr := ioutil.WriteFile(c.file, []byte(contents), 0644)\n\tif err != nil {\n\t\treturn errors.Newf(\"Failed to write: %s\", c.file)\n\t}\n\treturn nil\n}", "func (c *Configfile) Save(filename string) error {\n\tif filename == \"\" {\n\t\tfilename = c.filename\n\t}\n\tb, err := yaml.Marshal(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(filename, b, 0755)\n}", "func (c *Passward) Save() error {\n\n\tif !util.DirectoryExists(c.Path) {\n\t\tif err := os.MkdirAll(c.Path, 0700); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfile, err := os.Create(c.configPath())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\tif err := toml.NewEncoder(file).Encode(c); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func SaveConfig(c *Config) {\n\tvar f *os.File\n\tvar err error\n\tif f, err = os.Create(\"conf.toml\"); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tenc := toml.NewEncoder(f)\n\tif err = enc.Encode(c); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}", "func (c *MetaConfig) Save() error {\n\tdata, err := json.Marshal(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(MetaConfigPath, data, 0644)\n}", "func (c *DeploymentConfig) Save() error {\n\tfn := c.FileName()\n\tbuf, err := yaml.Marshal(c)\n\tif err != nil {\n\t\tlog.S(\"fn\", fn).Error(err)\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(fn, buf, 0644)\n}", "func (c *Config) Save() error {\n\tpath := filepath.Dir(c.filePath)\n\terr := os.MkdirAll(path, directoryPermissions)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\traw, err := json.MarshalIndent(c, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ioutil.WriteFile(c.filePath, raw, filePermissions)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func SaveConfig(path string) error {\n\tdir := filepath.Dir(path)\n\tif _, err := os.Stat(dir); os.IsNotExist(err) {\n\t\terr := os.Mkdir(dir, 0775)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"creating dir %s\", dir)\n\t\t}\n\t}\n\n\tcf, err := os.Create(path)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\"type\": consts.IOError, \"error\": err}).Error(\"Create config file failed\")\n\t\treturn err\n\t}\n\tdefer cf.Close()\n\n\terr = toml.NewEncoder(cf).Encode(Config)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Save(c Config) error {\n\tb, err := toml.Marshal(c)\n\tif err != nil {\n\t\treturn errors.Wrap(errReadConfigFile, err)\n\t}\n\tfile := dfltFile\n\tif c.File != \"\" {\n\t\tfile = c.File\n\t}\n\tif err := os.WriteFile(file, b, 0644); err != nil {\n\t\treturn errors.Wrap(errWritingConfigFile, err)\n\t}\n\n\treturn nil\n}", "func (hc *Hailconfig) Save() error {\n\terr := hc.f.Reset()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to reset\")\n\t}\n\treturn toml.NewEncoder(hc.f).Encode(&hc.config)\n}", "func (cfg *Configuration) Save() error {\n\tcfg.locker.Lock()\n\tdefer cfg.locker.Unlock()\n\tif cfg.FilePath == \"\" {\n\t\treturn errors.New(\"Configuration.FilePath was not set\")\n\t}\n\treturn gonfig.Write(cfg, true)\n}", "func (cfg OpenVpnCfg) Save() error {\n\tcfgPath := getCfgPath(cfg.Name)\n\tkeyPath := getKeyPath(cfg.Name)\n\n\tcfgFile, err := os.OpenFile(cfgPath, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tcfgFile.Close()\n\t\tif err != nil {\n\t\t\tos.Remove(cfgPath)\n\t\t}\n\t}()\n\tkeyFile, err := os.OpenFile(keyPath, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tkeyFile.Close()\n\t\tif err != nil {\n\t\t\tos.Remove(keyPath)\n\t\t}\n\t}()\n\targ := templateArg{\n\t\tOpenVpnCfg: cfg,\n\t\tLibexecdir: staticconfig.Libexecdir,\n\t}\n\tif err = openVpnCfgTpl.Execute(cfgFile, arg); err != nil {\n\t\treturn err\n\t}\n\t_, err = keyFile.Write([]byte(cfg.Key))\n\treturn err\n}", "func (c *Config) Save(filename string) error {\n\tvar b bytes.Buffer\n\tenc := json.NewEncoder(&b)\n\tenc.SetIndent(\"\", \"\\t\")\n\tif err := enc.Encode(c); err != nil {\n\t\treturn fmt.Errorf(\"error encoding configuration: %w\", err)\n\t}\n\tif err := os.WriteFile(filename, b.Bytes(), 0600); err != nil {\n\t\treturn fmt.Errorf(\"error writing %q: %w\", filename, err)\n\t}\n\treturn nil\n}", "func (c *Config) ConfigSave() error {\n\tif c.Filename == \"\" {\n\t\treturn ErrNotFound\n\t}\n\n\t// create directory if missing\n\tdir := filepath.Dir(c.Filename)\n\tif err := os.MkdirAll(dir, 0700); err != nil {\n\t\treturn err\n\t}\n\n\t// use a temp file\n\ttmp, err := ioutil.TempFile(dir, filepath.Base(c.Filename))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\ttmp.Close()\n\t\tos.Remove(tmp.Name())\n\t}()\n\n\t// write as user formatted json\n\tif err := c.ConfigSaveWriter(tmp); err != nil {\n\t\treturn err\n\t}\n\ttmp.Close()\n\n\t// follow symlink if it exists\n\tfilename := c.Filename\n\tif link, err := os.Readlink(filename); err == nil {\n\t\tfilename = link\n\t}\n\n\t// default file perms are 0600 owned by current user\n\tmode := os.FileMode(0600)\n\tuid := os.Getuid()\n\tgid := os.Getgid()\n\t// adjust defaults based on existing file if available\n\tstat, err := os.Stat(filename)\n\tif err == nil {\n\t\t// adjust mode to existing file\n\t\tif stat.Mode().IsRegular() {\n\t\t\tmode = stat.Mode()\n\t\t}\n\t\tuid, gid, _ = getFileOwner(stat)\n\t} else if !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\n\t// update mode and owner of temp file\n\tif err := os.Chmod(tmp.Name(), mode); err != nil {\n\t\treturn err\n\t}\n\tif uid > 0 && gid > 0 {\n\t\t_ = os.Chown(tmp.Name(), uid, gid)\n\t}\n\n\t// move temp file to target filename\n\treturn os.Rename(tmp.Name(), filename)\n}", "func Persist() error {\n\tJSON, err := json.MarshalIndent(instance, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.WriteFile(filepath.Join(GetConfigFolder(), configName), JSON, 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func SaveConfig(conf ClientConfig) error {\n configFilePath, err := getConfigFilePath()\n if err != nil {\n return err\n }\n\n d, err := yaml.Marshal(&conf)\n if err != nil {\n return err\n }\n writeErr := os.WriteFile(configFilePath, d, 0666)\n if writeErr != nil {\n return writeErr\n }\n\n return nil\n}", "func (c *Context) Save() []byte {\n\tif c.Tournament.Name != \"\" {\n\t\td := &data{\n\t\t\tApplications: c.Sound.AppNames(),\n\t\t\tTournament: c.Tournament,\n\t\t\tJingles: c.Jingles.JingleStorageList(),\n\t\t}\n\t\tout, err := yaml.Marshal(d)\n\t\tif err != nil {\n\t\t\tc.Log.Error(err.Error())\n\t\t}\n\n\t\tf, err := os.Create(path.Join(c.StorageDir(), \"config.yml\"))\n\n\t\tif err != nil {\n\t\t\tc.Log.Error(err.Error())\n\t\t} else {\n\t\t\tdefer f.Close()\n\t\t\tf.Write(out)\n\t\t}\n\n\t\tc.Archive()\n\t\treturn out\n\t}\n\treturn []byte{}\n}", "func (s *Settings) Save(cf string) (string, error) {\n\tsettings := settingsFile{Username: s.Username, VerifySSL: s.Client.VerifySSL,\n\t\tController: s.Client.ControllerURL.String(), Token: s.Client.Token, Limit: s.Limit}\n\n\tsettingsContents, err := json.Marshal(settings)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif err = os.MkdirAll(filepath.Join(FindHome(), executable.Config()), 0700); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfilename := locateSettingsFile(cf)\n\n\treturn filename, ioutil.WriteFile(filename, settingsContents, 0600)\n}", "func save() {\n\tnaksuIniPath := getIniFilePath()\n\n\terr := cfg.SaveTo(naksuIniPath)\n\tif err != nil {\n\t\tlog.Error(\"%s save failed: %v\", naksuIniPath, err)\n\t}\n}", "func (c *Config) Save() error {\n\tdir, err := getConfigDir()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfile, err := json.MarshalIndent(c, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp := path.Join(dir, configFile)\n\treturn ioutil.WriteFile(p, file, 0644)\n}", "func SaveConfig(file string, conf AppConfig) error {\n\tvar confBuf bytes.Buffer\n\n\te := toml.NewEncoder(&confBuf)\n\tif err := e.Encode(conf); err != nil {\n\t\treturn err\n\t}\n\treturn utils.WriteFile(file, confBuf.Bytes(), 0644)\n}", "func Save() error {\n\treturn defaultConfig.Save()\n}", "func (k KMP) Save(filepath, format string) error {\n\tvar err error\n\tswitch format {\n\tcase \"json\":\n\t\tf, err := os.Open(filepath)\n\t\tif err != nil {\n\t\t\tf, err = os.Create(filepath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tdefer f.Close()\n\t\tout, err := json.Marshal(k)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = f.Write(out)\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid save format, %s\", format)\n\t}\n\treturn err\n}", "func (c *Config) Save() (err error) {\n\tc.init()\n\tlog.Infof(\"save config to %v\", c.Filename)\n\tdir := filepath.Dir(c.Filename)\n\tif _, e := os.Stat(dir); os.IsNotExist(e) {\n\t\terr = os.MkdirAll(dir, os.ModePerm)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"save config to %v fail with %v\", c.Filename, err)\n\t\t\treturn\n\t\t}\n\t}\n\terr = marshal(c.Filename, c)\n\tif err == nil {\n\t\tlog.Infof(\"save config to %v success\", c.Filename)\n\t} else {\n\t\tlog.Errorf(\"save config to %v fail with %v\", c.Filename, err)\n\t}\n\treturn\n}", "func (c *Configuration) Save(filename string) error {\n\tb, err := json.MarshalIndent(c, \"\", \"\\t\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\t_, err = f.Write([]byte(configHeader))\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = f.Write(b)\n\treturn err\n}", "func (config *Config) Save(file string) error {\n\tbts, err := json.Marshal(*config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar out bytes.Buffer\n\tjson.Indent(&out, bts, \"\", \"\\t\")\n\n\treturn ioutil.WriteFile(file, out.Bytes(), 0600)\n}", "func (otp *OTPConfig) Save() (data []byte, err error) {\n\totp.GC()\n\tvar b bytes.Buffer\n\terr = gob.NewEncoder(&b).Encode(*otp)\n\treturn b.Bytes(), err\n}", "func (c *Config) Save(filename string) (err error) {\n\tlog.Println(\"[DEBUG] Save\", filename)\n\n\tbody, err := json.MarshalIndent(c, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = c.writeFile(filename, body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func SaveConfig(path string) error {\n\t// TODO: Implement\n\n\treturn nil\n}", "func (c *ConfigFile) Save() error {\n\trw, err := NewConfigReadWriter(c.version)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfilename := rw.Filename(c)\n\tif filename == \"\" {\n\t\treturn fmt.Errorf(\"Can't save config with empty filename\")\n\t}\n\tif err := os.MkdirAll(filepath.Dir(filename), 0700); err != nil {\n\t\treturn err\n\t}\n\tfile, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\treturn rw.SaveToWriter(file, c)\n}", "func SaveConfig(config *Config) error {\n\tloadedConfigMutex.Lock()\n\tdefer loadedConfigMutex.Unlock()\n\n\tif testDontSaveConfig {\n\t\treturn nil\n\t}\n\n\tworkdir, _ := os.Getwd()\n\tdata, err := yaml.Marshal(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconfigPath := filepath.Join(workdir, ConfigPath)\n\terr = os.MkdirAll(filepath.Dir(configPath), 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ioutil.WriteFile(configPath, data, 0666)\n}", "func SaveConfigToFile(name string, data interface{}) error {\n\tvar (\n\t\tbuffer bytes.Buffer\n\t\tsaveErr error\n\t)\n\tpath := filepath.Join(ConfigDir, name)\n\t// Create our buffer and encoder\n\twriter := bufio.NewWriter(&buffer)\n\tencoder := toml.NewEncoder(writer)\n\t// Encode the struct as toml\n\tif saveErr = encoder.Encode(data); saveErr == nil {\n\t\t// Write to the blacklist file\n\t\tsaveErr = ioutil.WriteFile(path, buffer.Bytes(), 0644)\n\t}\n\treturn saveErr\n}", "func saveConfig(config *utils.Config) {\n\n\tfid, err := os.Create(path.Join(config.LogDir, \"config.json\"))\n\tif err != nil {\n\t\tmsg := \"Error in saveConfig, see log files for details.\"\n\t\tos.Stderr.WriteString(msg)\n\t\tlog.Fatal(err)\n\t}\n\tdefer fid.Close()\n\tenc := json.NewEncoder(fid)\n\terr = enc.Encode(config)\n\tif err != nil {\n\t\tmsg := \"Error in saveConfig, see log files for details.\"\n\t\tos.Stderr.WriteString(msg)\n\t\tlog.Fatal(err)\n\t}\n\tconfigFilePath = path.Join(config.LogDir, \"config.json\")\n}", "func Save(filePath string, content []byte) error {\n\tkh, err := KymaHome()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not save file\")\n\t}\n\n\tfilePath = fp.Join(kh, filePath)\n\n\terr = os.MkdirAll(fp.Dir(filePath), 0700)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not save file\")\n\t}\n\n\tif err = ioutil.WriteFile(filePath, content, 0644); err != nil {\n\t\treturn errors.Wrap(err, \"Could not save file\")\n\t}\n\treturn nil\n}", "func (c *Config) Save(filename string) {\n\tconfigFile, err := os.Create(filename)\n\tif err != nil {\n\t\tlogrus.Error(\"creating config file\", err.Error())\n\t}\n\n\tlogrus.Info(\"Save config: \", c)\n\tvar out bytes.Buffer\n\tb, err := json.MarshalIndent(c, \"\", \"\\t\")\n\tif err != nil {\n\t\tlogrus.Error(\"error marshal json\", err)\n\t}\n\tjson.Indent(&out, b, \"\", \"\\t\")\n\tout.WriteTo(configFile)\n}", "func (ps *PayeeSubstitutions) Persist(path string) {\n\tdata, err := yaml.Marshal(*ps)\n\tif err != nil {\n\t\tlog.Fatalf(\"marshal payee substitutions: %v\", err)\n\t}\n\n\tif err := ioutil.WriteFile(path, data, 0644); err != nil {\n\t\tlog.Fatalf(\"While writing payee substitutions to file '%v': %v\", path, err)\n\t}\n}", "func SaveConfig(conf *Config) {\n\tbytes, err := json.MarshalIndent(conf, \"\", \" \")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tfilename := os.ExpandEnv(configFilename)\n\terr = os.MkdirAll(path.Dir(filename), 0755)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\terr = ioutil.WriteFile(filename, bytes, 0755)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}", "func (t *TemplateConfig) Write() error {\n\tfp := filepath.Join(t.ProjectPath, \"template.yml\")\n\t// make sure directory exists\n\tif _, err := os.Stat(t.ProjectPath); os.IsNotExist(err) {\n\t\tif err := os.MkdirAll(t.ProjectPath, 0755); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tyml, err := yaml.Marshal(t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ioutil.WriteFile(fp, yml, 0644)\n}", "func (m *Machine) Save(n string) error {\n\tf, err := os.Create(n)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to create vm config file\")\n\t}\n\tdefer f.Close()\n\n\tif err := json.NewEncoder(f).Encode(m); err != nil {\n\t\treturn errors.Wrap(err, \"failed to serialize machine object\")\n\t}\n\n\treturn nil\n}", "func Save(writer io.Writer, settings Settings) error {\n\tb, err := yaml.Marshal(settings)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t_, err = writer.Write(b)\n\n\treturn err\n}", "func (c *Config) SaveFile(path string) error {\r\n\tEnsurePath(path, DefaultDirMod)\r\n\tcfg, err := yaml.Marshal(c)\r\n\tif err != nil {\r\n\t\tlog.Error().Msgf(\"[Config] Unable to save EnvManager config file: %v\", err)\r\n\t\treturn err\r\n\t}\r\n\treturn ioutil.WriteFile(path, cfg, 0644)\r\n}", "func (cfg *Config) SaveConfig() error {\n\t// Find home directory.\n\thome, err := homedir.Dir()\n\tif err != nil {\n\t\tlog.Printf(\"Error when fetching home directory\\n%v\", err)\n\t\treturn err\n\t}\n\n\tviper.SetConfigName(\".alfred\")\n\tviper.AddConfigPath(home)\n\tviper.Set(\"output_format\", cfg.OutputFormat)\n\tviper.Set(\"slack_token\", cfg.SlackToken)\n\tviper.Set(\"todoist_token\", cfg.TodoistToken)\n\treturn viper.WriteConfig()\n}", "func Save(pushURL string, tart config.Tart) {\n\tif config.All().Tarts == nil {\n\t\tconfig.All().Tarts = map[string]config.Tart{}\n\t}\n\tconfig.All().Tarts[pushURL] = tart\n\tconfig.Flush()\n}", "func SaveConf(conf *Conf) {\r\n\tfmt.Println(\"Saving conf.yml ...\")\r\n\tyamlChanged, err := yaml.Marshal(conf)\r\n\tif err != nil {\r\n\t\tfmt.Printf(\"Error while saving conf.yml :\\n\")\r\n\t\tfmt.Printf(\"\\t%c[0;31m%s%c[0m\\n\", 0x1B, err, 0x1B)\r\n\t}\r\n\terr = ioutil.WriteFile(\"conf.yml\", yamlChanged, 0644)\r\n}", "func (c *ConfigurationFile) Save() error {\n\tcontent, err := json.Marshal(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(c.location.get(), content, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *Config) save() {\n\tconst file = \"access.json\"\n\n\tc.logger.Printf(\"Save file %s\\n\", file)\n\n\tcfg := conf{\n\t\tIP: c.GetString(\"ip\"),\n\t\tPort: c.GetString(\"port\"),\n\t\tToken: c.GetString(\"token\"),\n\t\tWait: c.GetBool(\"wait\"),\n\t}\n\n\tb, err := json.Marshal(cfg)\n\tif err != nil {\n\t\tc.logger.Error(err)\n\t}\n\n\tif err = ioutil.WriteFile(file, b, 0644); err != nil {\n\t\tc.logger.Error(err)\n\t}\n}", "func (ach *AppConfigHelper) Save() error {\n\n\tif ach.LoadedConfig == nil {\n\t\treturn fmt.Errorf(\"Loaded Config was nil\")\n\t}\n\n\tif len(ach.FilePath) <= 0 {\n\t\treturn fmt.Errorf(\"Config File Path was not set could not save\")\n\t}\n\n\tif err := ach.LoadedConfig.Save(ach.FilePath); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s yamlStore) Save() error {\n\treturn s.SaveTo(DefaultPath)\n}", "func PersistConfigTo(v *viper.Viper, filename string) error {\n\tif filename == \"\" {\n\t\treturn fmt.Errorf(\"persist skiped, for no config file used\")\n\t}\n\terr := v.WriteConfigAs(filename)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"write using config file[%s]: %w\", filename, err)\n\t}\n\treturn nil\n}", "func (cm *fileConfigManager) Save() error {\n\tkuttilog.Printf(\n\t\t4,\n\t\t\"[DEBUG]Saving config file '%s'...\",\n\t\tcm.configfilename,\n\t)\n\tdata, err := cm.configdata.Serialize()\n\tif err != nil {\n\t\tkuttilog.Printf(\n\t\t\t4,\n\t\t\t\"[DEBUG]Error Saving config file '%s': %v.\",\n\t\t\tcm.configfilename,\n\t\t\terr,\n\t\t)\n\t\treturn err\n\t}\n\n\treturn SaveConfigfile(cm.configfilename, data)\n}", "func (settings *Settings) Save(path string) error {\n\tcontent, err := json.Marshal(settings)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ioutil.WriteFile(path, content, 0644)\n}", "func SaveConfigToFile(configFile *os.File, v interface{}) error {\n\tif _, err := configFile.Seek(0, 0); err != nil {\n\t\treturn fmt.Errorf(\"cannot seek config file, error msg:(%v)\", err)\n\t}\n\tif err := configFile.Truncate(0); err != nil {\n\t\treturn fmt.Errorf(\"cannot truncate config file, error msg:(%v)\", err)\n\t}\n\tif err := Save(configFile, v); err != nil {\n\t\treturn fmt.Errorf(\"cannot save config file, error msg:(%v)\", err)\n\t}\n\treturn nil\n}", "func (defaultStorage) Save() error {\n\tpanic(noConfigStorage)\n}", "func (a Account) Save(filePath string) error {\n\td, err := yaml.Marshal(a)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ioutil.WriteFile(filePath, d, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (smCfg *smConfiguration) Save(settings *Settings) error {\n\tsmCfg.viperEnv.Set(\"url\", settings.URL)\n\tsmCfg.viperEnv.Set(\"user\", settings.User)\n\tsmCfg.viperEnv.Set(\"ssl_disabled\", settings.SSLDisabled)\n\tsmCfg.viperEnv.Set(\"token_basic_auth\", settings.TokenBasicAuth)\n\n\tsmCfg.viperEnv.Set(\"access_token\", settings.AccessToken)\n\tsmCfg.viperEnv.Set(\"refresh_token\", settings.RefreshToken)\n\tsmCfg.viperEnv.Set(\"expiry\", settings.ExpiresIn.Format(time.RFC1123Z))\n\n\tsmCfg.viperEnv.Set(\"client_id\", settings.ClientID)\n\tsmCfg.viperEnv.Set(\"client_secret\", settings.ClientSecret)\n\tsmCfg.viperEnv.Set(\"issuer_url\", settings.IssuerURL)\n\tsmCfg.viperEnv.Set(\"token_url\", settings.TokenEndpoint)\n\tsmCfg.viperEnv.Set(\"auth_url\", settings.AuthorizationEndpoint)\n\tsmCfg.viperEnv.Set(\"auth_flow\", string(settings.AuthFlow))\n\n\tcfgFile := smCfg.viperEnv.ConfigFileUsed()\n\tif err := smCfg.viperEnv.WriteConfig(); err != nil {\n\t\treturn fmt.Errorf(\"could not save config file %s: %s\", cfgFile, err)\n\t}\n\tconst ownerAccessOnly = 0600\n\tif err := os.Chmod(cfgFile, ownerAccessOnly); err != nil {\n\t\treturn fmt.Errorf(\"could not set access rights of config file %s: %s\", cfgFile, err)\n\t}\n\treturn nil\n}", "func SaveYaml(v interface{}, fname string) (err error) {\n\tbuf, err := yaml.Marshal(v)\n\tif err == nil {\n\t\terr = ioutil.WriteFile(fname, buf, 0666)\n\t}\n\treturn\n}", "func (p *Project) Save(path string) error {\n\tybuf, err := yaml.Marshal(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfp, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, err = fp.Write(ybuf); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (k *Kluster) Save() error {\n\t// we load the nil defaults so that future versions\n\t// don't have to deal with the backwards compatibility with omitted values\n\tif k.Config != nil {\n\t\tk.Config.LoadNilDefault()\n\t}\n\n\tdir := k.Dir()\n\tif _, err := os.Stat(dir); os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"base directory %s does not exists\", dir)\n\t\t// Or?:\n\t\t// os.MkdirAll(dir, 0755)\n\t}\n\n\tformat := k.format()\n\tvar data []byte\n\tvar err error\n\n\t// Get platform configurations\n\n\t// Update configuration\n\t// pConfig := make(map[string]interface{}, len(k.Platforms))\n\tname := k.Platform()\n\tif p, ok := k.provisioner[name]; ok {\n\t\tplatform := p\n\t\tk.Platforms[name] = platform.Config()\n\t\t// c := platform.Config()\n\t\t// // TODO: Workaround to not save the vSphere credentials, cannot have metadata to '-' because the Configurator takes the credentials from there.\n\t\t// if name == \"vsphere\" {\n\t\t// \tcVsphere := c.(*vsphere.Config)\n\t\t// \tcVsphere.VspherePassword = \"\"\n\t\t// \tcVsphere.VsphereUsername = \"\"\n\t\t// \tcVsphere.VsphereServer = \"\"\n\t\t// \tk.Platforms[name] = cVsphere\n\t\t// } else {\n\t\t// \tk.Platforms[name] = c\n\t\t// }\n\n\t\terr := k.LoadState()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tk.UpdateState(name)\n\n\t\tk.ui.Log.Debugf(\"update state for %s: %v\", name, k.State[name])\n\t}\n\n\t// k.Platforms = pConfig\n\n\t// Do not use String() because:\n\t// (1) returns string and []byte is needed, and\n\t// (2) pretty print (pp=true) is needed with JSON format\n\tswitch format {\n\tcase \"yaml\":\n\t\tdata, err = k.YAML()\n\tcase \"json\":\n\t\tdata, err = k.JSON(true)\n\tcase \"toml\":\n\t\tdata, err = k.TOML()\n\tdefault:\n\t\terr = fmt.Errorf(\"can't stringify the Kluster, unknown format %q\", format)\n\t}\n\n\tlock, err := lockFile(k.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer lock.Unlock()\n\n\tk.ui.Log.Debugf(\"updating cluster configuration file %s\", k.path)\n\treturn ioutil.WriteFile(k.path, data, 0644)\n}", "func (self *Yaml) Save() error {\n\n\treturn nil\n}", "func (m *Config) WriteToFile(fname string) {\n\tif len((*m).Images) == 0 {\n\t\tif err := DeleteYaml(fname); err != nil {\n\t\t\tfmt.Println(err)\n\t\t\texit(1)\n\t\t}\n\t\tif isV {\n\t\t\tfmt.Println(\"Delete config file. :\", fname)\n\t\t}\n\t\treturn\n\t}\n\t//renewal commands\n\tcc := make(map[string]string)\n\tfor key, val := range (*m).Images {\n\t\tfor com := range val.Commands {\n\t\t\tif cnt, ok := cc[com]; ok {\n\t\t\t\tfmt.Println(\"Confrict command name.:\", com)\n\t\t\t\tfmt.Printf(\" image [%s] and [%s]\\n\", cnt, key)\n\t\t\t\tfmt.Printf(\" in file:%s\\n\", fname)\n\t\t\t\texit(1)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcc[com] = key\n\t\t}\n\t}\n\t(*m).Commands = cc\n\n\t//write config file\n\tif err := SaveYaml(m, fname); err != nil {\n\t\tfmt.Println(err)\n\t\texit(1)\n\t\treturn\n\t}\n\tif isV {\n\t\tfmt.Println(\"Wrote config file. :\", fname)\n\t}\n}", "func (c Config) Save(writer io.Writer) error {\n\tlog.Printf(\"Saving config\")\n\tcontent, err := json.MarshalIndent(c, \"\", \" \")\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\t_, err = writer.Write(content)\n\treturn errors.WithStack(err)\n}", "func (elementConfiguration *ElementConfiguration) Save(filename string) error {\n\treturn util.SaveYAML(filename, elementConfiguration)\n}", "func AppendConfigToDisk(specObj *model.SpecObject, filename string) error {\n\t// Marshal spec object to yaml\n\tdata, err := yaml.Marshal(specObj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Check if file exists. We need to ammend the file if it does.\n\tif fileExists(filename) {\n\t\tf, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0600)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdefer func() {\n\t\t\t_ = f.Close()\n\t\t}()\n\n\t\t_, err = f.Write(append([]byte(\"---\\n\"), data...))\n\t\treturn err\n\t}\n\n\t// Create a new file with out specs\n\treturn ioutil.WriteFile(filename, data, 0755)\n}", "func saveStore(s dhtStore) {\n\tif s.path == \"\" {\n\t\treturn\n\t}\n\ttmp, err := ioutil.TempFile(s.path, \"marconi\")\n\tif err != nil {\n\t\tlog.Println(\"saveStore tempfile:\", err)\n\t\treturn\n\t}\n\terr = json.NewEncoder(tmp).Encode(s)\n\t// The file has to be closed already otherwise it can't be renamed on\n\t// Windows.\n\ttmp.Close()\n\tif err != nil {\n\t\tlog.Println(\"saveStore json encoding:\", err)\n\t\treturn\n\t}\n\n\t// Write worked, so replace the existing file. That's atomic in Linux, but\n\t// not on Windows.\n\tp := fmt.Sprintf(\"%v-%v\", s.path+\"/dht\", s.Port)\n\tif err := os.Rename(tmp.Name(), p); err != nil {\n\t\t// if os.IsExist(err) {\n\t\t// Not working for Windows:\n\t\t// http://code.google.com/p/go/issues/detail?id=3828\n\n\t\t// It's not possible to atomically rename files on Windows, so I\n\t\t// have to delete it and try again. If the program crashes between\n\t\t// the unlink and the rename operation, it loses the configuration,\n\t\t// unfortunately.\n\t\tif err := os.Remove(p); err != nil {\n\t\t\tlog.Println(\"saveStore failed to remove the existing config:\", err)\n\t\t\treturn\n\t\t}\n\t\tif err := os.Rename(tmp.Name(), p); err != nil {\n\t\t\tlog.Println(\"saveStore failed to rename file after deleting the original config:\", err)\n\t\t\treturn\n\t\t}\n\t\t// } else {\n\t\t// \tlog.Println(\"saveStore failed when replacing existing config:\", err)\n\t\t// }\n\t} else {\n\t\t// log.Println(\"Saved DHT routing table to the filesystem.\")\n\t}\n}", "func (c *ConfigManager) Save() error {\n\tlogger.V(1).Info(\"saving ConfigMap\")\n\n\tvar tmpOptions pomeriumconfig.Options\n\n\ttmpOptions, err := c.GetCurrentConfig()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not render current config: %w\", err)\n\t}\n\n\t// Make sure we can load the target configmap\n\tconfigObj := &corev1.ConfigMap{}\n\tif err := c.client.Get(context.Background(), types.NamespacedName{Name: c.configMap, Namespace: c.namespace}, configObj); err != nil {\n\t\terr = fmt.Errorf(\"output configmap not found: %w\", err)\n\t\treturn err\n\t}\n\n\tconfigBytes, err := yaml.Marshal(tmpOptions)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not serialize config: %w\", err)\n\t}\n\n\tconfigObj.Data = map[string]string{configKey: string(configBytes)}\n\n\t// TODO set deadline?\n\t// TODO use context from save?\n\terr = c.client.Update(context.Background(), configObj)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to update configmap: %w\", err)\n\t}\n\n\tlogger.Info(\"successfully saved ConfigMap\")\n\tc.pendingSave = false\n\treturn nil\n}", "func (self *JsonConfig) Save() (err error) {\n\tb, err := json.Marshal(self.Configurable.All())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := ioutil.WriteFile(self.Path, b, 0600); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *ConfigJSON) saveConfig(settingFile string) error {\n\t// let's write it back\n\tout, err := json.Marshal(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(settingFile, out, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func SaveToFile(data Data, filename string) error {\n\tbyteData, err := ToBytes(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := ioutil.WriteFile(filename, byteData, 0666); err != nil {\n\t\treturn fmt.Errorf(\"could not write config file: %w\", err)\n\t}\n\treturn nil\n}", "func (p FilePersister) Save(v *viper.Viper, basename string) error {\n\tv.SetConfigType(\"json\")\n\tv.AddConfigPath(p.Dir)\n\tv.SetConfigName(basename)\n\n\tif _, err := os.Stat(p.Dir); os.IsNotExist(err) {\n\t\tif err := os.MkdirAll(p.Dir, os.FileMode(0755)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// WriteConfig is broken.\n\t// Someone proposed a fix in https://github.com/spf13/viper/pull/503,\n\t// but the fix doesn't work yet.\n\t// When it's fixed and merged we can get rid of `path`\n\t// and use viperConfig.WriteConfig() directly.\n\tpath := filepath.Join(p.Dir, fmt.Sprintf(\"%s.json\", basename))\n\treturn v.WriteConfigAs(path)\n}", "func saveDonutConfig(donutConfigData *mcDonutConfig) error {\n\tjsonConfig, err := json.MarshalIndent(donutConfigData, \"\", \"\\t\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.MkdirAll(getMcConfigDir(), 0755)\n\tif !os.IsExist(err) && err != nil {\n\t\treturn err\n\t}\n\n\tconfigFile, err := os.OpenFile(getDonutConfigFilename(), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer configFile.Close()\n\n\t_, err = configFile.Write(jsonConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (viperConfig *Configurator) Save(sbConfig *config.SBConfiguration) error {\n\tviperConfig.viper.Set(\"url\", sbConfig.URL)\n\tviperConfig.viper.Set(\"authorization\", sbConfig.Authorization)\n\tviperConfig.viper.Set(\"room\", sbConfig.Room)\n\n\tif err := viperConfig.viper.WriteConfig(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func SaveConfig(c Config) error {\n\tdir := path.Dir(configPath)\n\tif _, err := os.Stat(dir); os.IsNotExist(err) {\n\t\terr := os.Mkdir(dir, os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\td, err := json.Marshal(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.Create(configPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = f.Write(d)\n\treturn err\n}", "func Save(fname string, scheme base16.Scheme, perm os.FileMode, writerArg ...Writer) error {\n\tvar fileWriter Writer = &FileWriter{}\n\tbase16Yaml := toBase16Yaml(scheme)\n\n\tif len(writerArg) == 1 {\n\t\tfileWriter = writerArg[0]\n\t}\n\n\tdata, err := MarshalBase16Yaml(base16Yaml)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = fileWriter.WriteFile(fname, data, perm)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *Syncthing) SaveConfig(dev *model.Dev) error {\n\tmarshalled, err := yaml.Marshal(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsyncthingInfoFile := getInfoFile(dev.Namespace, dev.Name)\n\tif err := os.WriteFile(syncthingInfoFile, marshalled, 0600); err != nil {\n\t\treturn fmt.Errorf(\"failed to write syncthing info file: %w\", err)\n\t}\n\n\treturn nil\n}", "func (c *Config) Save() error {\r\n\tlog.Debug().Msg(\"[Config] Saving configuration...\")\r\n\tc.Validate()\r\n\r\n\treturn c.SaveFile(EnvManagerConfigFile)\r\n}", "func (b *BlockCreator) save() error {\n\treturn persist.SaveJSON(settingsMetadata, b.persist, filepath.Join(b.persistDir, settingsFile))\n}", "func PersistOntoDisk(json string, file string) {\n\terr := ioutil.WriteFile(file, []byte(json), 0644)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (s *AuthConfigService) SaveConfig() error {\n\tfileName := s.FileName\n\tif fileName == \"\" {\n\t\treturn fmt.Errorf(\"No filename defined!\")\n\t}\n\tdata, err := yaml.Marshal(s.config)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(fileName, data, DefaultWritePermissions)\n}", "func SaveConfigs(p string, config *Config) error {\n\terr := os.MkdirAll(path.Dir(p), os.ModePerm)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfile, err := os.Create(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tencoder := json.NewEncoder(file)\n\tencoder.SetIndent(\"\", \" \")\n\treturn encoder.Encode(*config)\n}", "func (m *settings) saveToDisk() error {\n\tb, err := json.Marshal(m.redirects)\n\tif err != nil {\n\t\tlog.Printf(\"Error marshalling %s\", err)\n\t\treturn fmt.Errorf(\"error marshalling %s\", err)\n\t}\n\n\tif err := ioutil.WriteFile(m.filename, b, 0644); err != nil {\n\t\treturn fmt.Errorf(\"unable to open file %s\", err)\n\t}\n\tlog.Printf(\"saving to disk.\")\n\treturn nil\n}", "func (c Configuration) Store(userdetail *user.User) error {\n\tbytes, err := c.YAML()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfile, err := os.Create(filepath.Join(userdetail.HomeDir , configFile))\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tuserid, err := strconv.Atoi(userdetail.Uid)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tguid, err := strconv.Atoi(userdetail.Gid)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//Make sure the file is owned by the user we have looked up\n\terr = file.Chown(userid,guid)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer file.Close()\n\n\t_, err = file.Write(bytes)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func SaveConfigToFile(config models.Config) ([]byte, error) {\n\ty, err := yaml.Marshal(config)\n\n\tioutil.WriteFile(models.ConfigFile, y, 0644)\n\tj, _ := yaml.YAMLToJSON(y)\n\treturn j, err\n}", "func (c *Config) Write(path string) error {\r\n\tbytes, err := yaml.Marshal(c)\r\n\tif err == nil {\r\n\t\treturn ioutil.WriteFile(path, bytes, 0777)\r\n\t}\r\n\treturn err\r\n}", "func (r *App) SaveConfig() {\n\tif r == nil {\n\t\treturn\n\t}\n\tdatadir, ok := r.Cats[\"app\"][\"datadir\"].Value.Get().(string)\n\tif !ok {\n\t\treturn\n\t}\n\tconfigFile := util.CleanAndExpandPath(filepath.Join(datadir, \"config\"), \"\")\n\t// if util.EnsureDir(configFile) {\n\t// }\n\tfh, err := os.Create(configFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tj, e := json.MarshalIndent(r, \"\", \"\\t\")\n\tif e != nil {\n\t\tpanic(e)\n\t}\n\t_, err = fmt.Fprint(fh, string(j))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func saveConfig(configName string, data map[string]string) error {\n\tglog.V(4).Info(log(\"saving config file %s\", configName))\n\n\tdir := path.Dir(configName)\n\tif _, err := os.Stat(dir); err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn err\n\t\t}\n\t\tglog.V(4).Info(log(\"creating config dir for config data: %s\", dir))\n\t\tif err := os.MkdirAll(dir, 0750); err != nil {\n\t\t\tglog.Error(log(\"failed to create config data dir %v\", err))\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfile, err := os.Create(configName)\n\tif err != nil {\n\t\tglog.V(4).Info(log(\"failed to save config data file %s: %v\", configName, err))\n\t\treturn err\n\t}\n\tdefer file.Close()\n\tif err := gob.NewEncoder(file).Encode(data); err != nil {\n\t\tglog.Error(log(\"failed to save config %s: %v\", configName, err))\n\t\treturn err\n\t}\n\tglog.V(4).Info(log(\"config data file saved successfully as %s\", configName))\n\treturn nil\n}", "func (repo ConfigRepository) Save(configEntity *domain.Config) (string, error) {\n\tconfigData, err := json.MarshalIndent(configEntity, \"\", \" \")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfile, err := os.Create(config.ConfigFilePath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer file.Close()\n\t_, err = io.WriteString(file, string(configData))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn config.ConfigFilePath, file.Sync()\n}", "func (cfg *Config) Save(filename string) error {\n\tfilename_ := C.CString(filename)\n\tdefer freeString(filename_)\n\tok := bool(C.al_save_config_file(filename_, (*C.ALLEGRO_CONFIG)(cfg)))\n\tif !ok {\n\t\treturn fmt.Errorf(\"failed to save config file to '%s'\", filename)\n\t}\n\treturn nil\n}", "func (p *iniFileConfigProvider) Save() error {\n\tif p.opts.CustomConf == \"\" {\n\t\tif !p.opts.AllowEmpty {\n\t\t\treturn fmt.Errorf(\"custom config path must not be empty\")\n\t\t}\n\t\treturn nil\n\t}\n\n\tif p.newFile {\n\t\tif err := os.MkdirAll(filepath.Dir(CustomConf), os.ModePerm); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create '%s': %v\", CustomConf, err)\n\t\t}\n\t}\n\tif err := p.SaveTo(p.opts.CustomConf); err != nil {\n\t\treturn fmt.Errorf(\"failed to save '%s': %v\", p.opts.CustomConf, err)\n\t}\n\n\t// Change permissions to be more restrictive\n\tfi, err := os.Stat(CustomConf)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to determine current conf file permissions: %v\", err)\n\t}\n\n\tif fi.Mode().Perm() > 0o600 {\n\t\tif err = os.Chmod(CustomConf, 0o600); err != nil {\n\t\t\tlog.Warn(\"Failed changing conf file permissions to -rw-------. Consider changing them manually.\")\n\t\t}\n\t}\n\treturn nil\n}", "func (c *Config) Save(name, key, value string) (err error) {\n\treturn c.SaveGlobal(name, key, value)\n}" ]
[ "0.7148331", "0.68365914", "0.6825895", "0.6782348", "0.67542696", "0.66742766", "0.666755", "0.6634886", "0.6595215", "0.6586071", "0.6563475", "0.65591264", "0.6541441", "0.6478207", "0.64683884", "0.6382868", "0.6358131", "0.6343579", "0.6322763", "0.63109756", "0.6294303", "0.6287519", "0.62682855", "0.62647057", "0.6240538", "0.6233986", "0.6223664", "0.619878", "0.61808217", "0.61484295", "0.6144394", "0.6126065", "0.6124193", "0.6118884", "0.6111107", "0.60961753", "0.6093985", "0.60878545", "0.6038248", "0.6030516", "0.6017739", "0.6000163", "0.59982914", "0.5969978", "0.59672886", "0.5949374", "0.5923792", "0.5896848", "0.58933026", "0.5885717", "0.58581495", "0.58536553", "0.5848274", "0.5837106", "0.5826384", "0.5819964", "0.5776728", "0.57710975", "0.5760002", "0.57595336", "0.57531637", "0.5740782", "0.5724682", "0.5723137", "0.57199115", "0.5696906", "0.56926894", "0.56818366", "0.56783426", "0.5674067", "0.5661321", "0.56559604", "0.56215256", "0.56091833", "0.56075406", "0.5594195", "0.5592858", "0.55768865", "0.55735517", "0.55636156", "0.5555233", "0.55540115", "0.5553011", "0.55459213", "0.5526333", "0.5523049", "0.5519635", "0.5515543", "0.5501736", "0.5499187", "0.54890394", "0.5488301", "0.54821736", "0.5481321", "0.5473649", "0.5456758", "0.5448938", "0.5448863", "0.5437159", "0.5418177" ]
0.6554888
12
getAlbums responds with the list of all albums as JSON.
func getCourses(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "List": "List of all courses!", }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func getAlbums(c *gin.Context) {\n\tc.IndentedJSON(http.StatusOK, albums)\n}", "func (c Album) GetAlbums() revel.Result {\n\tre := albumService.GetAlbums(c.GetUserId())\n\treturn c.RenderJSON(re)\n}", "func getAlbums(c *gin.Context) {\n\n\tvar albums []album.Album\n\n\tdbClient.Select(&albums, \"SELECT id, title, artist, price FROM album;\")\n\n\tc.IndentedJSON(http.StatusOK, albums)\n}", "func getAlbums(c *gin.Context) {\n\talbums := GetAlbums()\n\n\tif albums == nil {\n\t\tc.IndentedJSON(http.StatusNotFound, gin.H{\"message\": \"Can not obtain list of albums\"})\n\t\treturn\n\t}\n\n\tc.IndentedJSON(http.StatusOK, albums)\n}", "func getAlbums(c *gin.Context) {\n\t// serialize the struct into JSON and add it to the response.\n\tc.IndentedJSON(http.StatusOK, albums)\n}", "func GetAlbums(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tname := vars[\"name\"]\n\n\tsite, err := database.GetSiteByName(name)\n\tif err != nil {\n\t\tutils.RespondWithJSON(w, http.StatusNotFound, \"not_found\", nil)\n\t\treturn\n\t}\n\n\talbums, err := database.GetAlbums(site.ID)\n\tif err != nil {\n\t\tutils.RespondWithJSON(w, http.StatusInternalServerError, \"error\", nil)\n\t\treturn\n\t}\n\n\tutils.RespondWithJSON(w, http.StatusOK, \"success\", albums)\n\treturn\n}", "func getAlbums(c *gin.Context) {\n\tc.Header(\"Access-Control-Allow-Origin\", \"*\")\n\tc.Header(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\tc.IndentedJSON(http.StatusOK, albums)\n\n\trows, err := db.Query(\"SELECT * FROM department\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tfmt.Println(string(1))\n\t\tvar department Department\n\t\tif err := rows.Scan(&department.id, &department.name); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tfmt.Println(\"Name: \", department.name)\n\t}\n}", "func (c *GetImagesByAlbumApiController) GetImagesByAlbum(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tid := params[\"id\"]\n\tresult, err := c.service.GetImagesByAlbum(id)\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), constants.ErrorDBRecordNotFound) || strings.Contains(err.Error(), constants.ErrorDBNoSuchTable) {\n\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tEncodeJSONResponse(result, http.StatusOK, w)\n}", "func (s *Service) List(ctx context.Context) ([]Album, error) {\n\tvar result []Album\n\talbumsListCall := s.photos.List().PageSize(maxAlbumsPerPage).ExcludeNonAppCreatedData()\n\terr := albumsListCall.Pages(ctx, func(response *photoslibrary.ListAlbumsResponse) error {\n\t\tfor _, res := range response.Albums {\n\t\t\tresult = append(result, toAlbum(res))\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tvar emptyResult []Album\n\t\treturn emptyResult, fmt.Errorf(\"listing albums: %w\", err)\n\t}\n\treturn result, nil\n}", "func (r *AlbumsService) List() *AlbumsListCall {\n\tc := &AlbumsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\treturn c\n}", "func GetAlbums() *[]models.Album{\n\tvar albums []models.Album\n\tvar album models.Album\n\n\tdb, err := open()\n\tdefer db.Close()\n\tutil.CheckErr(\"GetAlbums\", err, true)\n\n\trows, err := db.Query(\"SELECT * FROM albums\")\n\n\tutil.CheckErr(\"GetAlbums\", err, true)\n\n\tfor rows.Next() {\n\t\terr = rows.Scan(&album.Id,\n\t\t\t&album.Name,\n\t\t\t&album.ArtistId,\n\t\t\t&album.Year)\n\t\tutil.CheckErr(\"GetAlbums\", err, true)\n\t\talbums = append(albums, album)\n\t}\n\n\terr = rows.Err()\n\tutil.CheckErr(\"GetAlbums\", err, true)\n\treturn & albums\n}", "func showImagesInAlbum(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\",\"application/json\")\n\tparam := mux.Vars(r)\n\titer:=Session.Query(\"SELECT imagelist FROM albumtable WHERE albname=?;\",param[\"album\"]).Iter()\n\tvar data []string\n\tfor iter.Scan(&data){\n\t\tjson.NewEncoder(w).Encode(data)\n\t}\n\tif err := iter.Close(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func GetImagesForAlbumV1(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tuuidParam := params[\"uuid\"]\n\n\timageModels := service.CreateDefaultImageService().GetAllImagesForAlbum(uuid.MustParse(uuidParam))\n\tdata, _ := json.Marshal(imageModels)\n\t_, _ = w.Write(data)\n\n}", "func GetAlbums() []*Album {\n\tlastFmDetails := GetLastFmConfiguration()\n\tvar albums []*Album\n\n\tapi := lastfm.New(lastFmDetails.ApiKey, lastFmDetails.ApiSecret)\n\tresult, _ := api.User.GetTopAlbums(lastfm.P{\"user\": \"jessicaward25\"}) //discarding error\n\n\tfor _, album := range result.Albums {\n\t\talbums = append(albums, NewAlbum(album.Name, album.Artist.Name, album.Rank, album.Images[0].Url, album.PlayCount))\n\t}\n\n\treturn albums\n}", "func (r *SharedAlbumsService) List() *SharedAlbumsListCall {\n\tc := &SharedAlbumsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\treturn c\n}", "func (c *Client) GetArtistAlbums(id string, options *Options) ([]SimpleAlbum, error) {\n\tvar albums SimpleAlbumPage\n\n\turl := constructURL(options, c.baseURL, \"artists\", id, \"albums\")\n\terr := c.get(url, &albums)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(albums.Next) != 0 {\n\t\tid, offset, err := getURLParams(albums.Next)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\toptions.Offset = offset\n\t\ta, err := c.GetArtistAlbums(id, options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\talbums.Albums = append(albums.Albums, a...)\n\t}\n\n\treturn albums.Albums, nil\n}", "func (r *AlbumsService) Get(albumId string) *AlbumsGetCall {\n\tc := &AlbumsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.albumId = albumId\n\treturn c\n}", "func GetAlbum(urlArgs url.Values, db *neoism.Database) string {\n\t// Pull selection data from url arguments\n\tas := AlbumSelect{Name: urlArgs.Get(\"name\"), Year: urlArgs.Get(\"year\"), Genre: urlArgs.Get(\"genre\"), Artist: urlArgs.Get(\"artist\")}\n\n\t// Pull Neo4j nodes from DB matching selecton params\n\tres := []struct {\n\t\tN string `json:\"n.name\"`\n\t\tY string `json:\"n.year\"`\n\t\tS int32 `json:\"n.submitted\"`\n\t}{}\n\n\tcq := neoism.CypherQuery{\n\t\t// We use regex matches (=~) to gracefully account for\n\t\t// missing fields, so we can use .*\n\t\tStatement: `\n\t\t\tMATCH (n:Album)\n\t\t\tWHERE n.name =~ {name} AND n.year =~ {year}\n\t\t\tRETURN n.name, n.year, n.submitted;\n\t\t`,\n\t\t// DefMatch is substituting .* for us when necessary\n\t\tParameters: neoism.Props{\"name\": DefMatch(as.Name), \"year\": DefMatch(as.Year)},\n\t\tResult: &res,\n\t}\n\tdb.Cypher(&cq)\n\n\t// Turn the list of Nodes into a list of Albums\n\talbums := make([]Album, 1)\n\tfor _, el := range res {\n\t\tname := el.N\n\t\tyear := el.Y\n\t\tsubmitted := el.S\n\n\t\ta := Album{Name: name, Year: year, Submitted: submitted}\n\t\talbums = append(albums, a)\n\t}\n\n\t// Turn the list of albums into a json representation\n\tjsonReturn, err := json.Marshal(albums)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\treturn string(jsonReturn)\n}", "func (s *KSession) GetAlbum(id int64) (results Album, err error) {\n\tresults = Album{}\n\tres, err := s.request(\"GET\", EndpointLyricsAlbum(id), nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(res, &results)\n\treturn\n}", "func GetAlbumsForArtist(artistID string) (pa SimpleAlbumsPaged, err error) {\n\tt := getAccessToken()\n\n\tr := buildRequest(\"GET\", apiURLBase+\"artists/\"+artistID+\"/albums\", nil, nil)\n\tr.Header.Add(\"Authorization\", \"Bearer \"+t)\n\n\terr = makeRequest(r, &pa)\n\n\treturn pa, err\n}", "func ShowAlbum() ([]string, *utils.ApplicationError) {\n\treturn model.ShowAlbum()\n}", "func postAlbums(c *gin.Context) {\n\t// deserialize the JSON into the album struct.\n\tvar newAlbum album\n\n\terr := c.BindJSON(&newAlbum)\n\tif err != nil {\n\t\tc.AbortWithError(http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\t// add the album to the slice of albums.\n\talbums = append(albums, newAlbum)\n\n\t// serialize the struct into JSON and add it to the response.\n\tc.IndentedJSON(http.StatusCreated, newAlbum)\n}", "func NewGetImagesByAlbumApiController(s GetImagesByAlbumApiServicer) Router {\n\treturn &GetImagesByAlbumApiController{service: s}\n}", "func (s MockedRepository) ListAll(ctx context.Context) ([]Album, error) {\n\treturn s.ListAllFn(ctx)\n}", "func (l *Lidarr) GetAlbum(mbID string) ([]*Album, error) {\n\treturn l.GetAlbumContext(context.Background(), mbID)\n}", "func getAllSongs(w http.ResponseWriter, req *http.Request) {\n\t// songs is an array of Song\n\tvar songs []Song\n\t// Query is uesed for actions wihch returns rows\n\t// Store all records in result from DB songs, if any\n\tresult, err := db.Query(\"SELECT * from songs\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tdefer result.Close()\n\n\t// Checking each record stored in result and append it to songs\n\tfor result.Next() {\n\t\tvar song Song\n\t\terr := result.Scan(&song.ID, &song.Title, &song.Duration, &song.Singer)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\tsongs = append(songs, song)\n\t}\n\tlenSong = len(songs)\n\n\t// setting the header “Content-Type” to “application/json”.\n\tw.Header().Set(\"Content-type\", \"application/json\")\n\t// encode songs to JSON and send them to interface\n\tjson.NewEncoder(w).Encode(songs)\n}", "func ListAlbum() ([]YearSchema, []AlbumSchema, error) {\n\tvar err error\n\tyearList := []YearSchema{}\n\tif err = configure.SQL.Select(&yearList, `\n\t\tSELECT a.year as year, COUNT(DISTINCT a.id) as event_number, COUNT(p.id) as photo_number\n\t\tFROM Album AS a LEFT JOIN Photo AS p\n\t\tON a.id = p.album_id \n\t\tGROUP BY a.year\n\t`); err != nil {\n\t\tlog.Println(\"Failed on YearSchema\")\n\t}\n\n\tlog.Println(\"yearList: \", yearList)\n\n\tphotoList := []PhotoSchema{}\n\tif err = configure.SQL.Select(&photoList, `\n\t\tSELECT a.id as id, a.year as year, a.title as title, a.date as date, p.path as path\n\t\tFROM Album AS a LEFT JOIN Photo AS p \n\t\tON a.id = p.album_id\n\t`); err != nil {\n\t\tlog.Println(\"Failed on PhotoSchema\")\n\t}\n\n\tlog.Println(\"photoList: \", photoList)\n\n\talbumMap := map[int]AlbumSchema{}\n\tfor _, photo := range photoList {\n\t\tif album, ok := albumMap[photo.AlbumID]; ok {\n\t\t\talbum.PhotoNumber++\n\t\t\talbum.Photos = append(album.Photos, photo.Path)\n\t\t\talbumMap[photo.AlbumID] = album\n\t\t} else {\n\t\t\tnewAlbum := AlbumSchema{\n\t\t\t\tphoto.AlbumID,\n\t\t\t\tphoto.AlbumYear,\n\t\t\t\tphoto.AlbumTitle,\n\t\t\t\tphoto.AlbumDate,\n\t\t\t\t1,\n\t\t\t\t[]string{photo.Path},\n\t\t\t}\n\t\t\talbumMap[newAlbum.ID] = newAlbum\n\t\t}\n\t}\n\talbumList := []AlbumSchema{}\n\tfor _, album := range albumMap {\n\t\talbumList = append(albumList, album)\n\t}\n\tlog.Println(\"albumList: \", albumList)\n\treturn yearList, albumList, err\n}", "func GetAlbum(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tid := vars[\"short_id\"]\n\n\talbum, err := database.GetAlbumByShortID(id)\n\tif err != nil {\n\t\tutils.RespondWithJSON(w, http.StatusInternalServerError, \"error\", nil)\n\t\treturn\n\t}\n\n\tutils.RespondWithJSON(w, http.StatusOK, \"success\", album)\n\treturn\n}", "func (p *Provider) GetFavoriteAlbums(limit, offset int) (syla.FavoriteAlbumsResponse, error) {\n\n\tvar favoriteAlbums []AlbumInformation\n\n\talbumsList, err := p.Client.CurrentUsersAlbumsOpt(&spotify.Options{\n\t\tLimit: &limit,\n\t\tOffset: &offset,\n\t})\n\tif err != nil {\n\t\tlog.Error(\"Error getting current albums\")\n\t\treturn FavoriteAlbumsResponse{}, nil\n\t}\n\n\tfor _, album := range albumsList.Albums {\n\t\talbumInformation := AlbumInformation{\n\t\t\tName: album.Name,\n\t\t\tReleaseDate: album.ReleaseDate,\n\t\t\tURLs: album.ExternalURLs,\n\t\t\tGenres: album.Genres,\n\t\t}\n\n\t\tvar artists []string\n\t\tfor _, artist := range album.Artists {\n\t\t\tartists = append(artists, artist.Name)\n\t\t}\n\t\talbumInformation.Artists = artists\n\n\t\tfavoriteAlbums = append(favoriteAlbums, albumInformation)\n\t}\n\n\treturn FavoriteAlbumsResponse{\n\t\tLimit: albumsList.Limit,\n\t\tOffset: albumsList.Offset,\n\t\tFavoriteAlbums: favoriteAlbums,\n\t}, nil\n}", "func postAlbums(c *gin.Context) {\n\tvar newAlbum Album\n\n\t// Call bindjson to bind received json to newAlbum\n\tif err := c.BindJSON(&newAlbum); err != nil {\n\t\treturn\n\t}\n\n\t// Add the new album to the slice\n\talbums = append(albums, newAlbum)\n\tc.IndentedJSON(http.StatusCreated, newAlbum)\n}", "func (ar AlbumDbRepository) GetAlbumsForArtist(artistId int, hydrate bool) (entities domain.Albums, err error) {\n\t_, err = ar.AppContext.DB.Select(&entities, \"SELECT * FROM albums WHERE artist_id = ? ORDER BY year\", artistId)\n\tif err == nil && hydrate {\n\t\tfor i := range entities {\n\t\t\tar.populateTracks(&entities[i])\n\t\t}\n\t}\n\n\treturn\n}", "func GetNextAlbumsForArtist(url string) (pa SimpleAlbumsPaged, err error) {\n\tt := getAccessToken()\n\n\tr, err := http.NewRequest(\"GET\", url, nil)\n\tr.Header.Add(\"Authorization\", \"Bearer \"+t)\n\n\terr = makeRequest(r, &pa)\n\n\treturn pa, err\n}", "func postAlbums(c *gin.Context) {\n\tvar newAlbum album\n\n\t// Call BindJSON to bind the received JSON to\n\t// newAlbum.\n\tif err := c.BindJSON(&newAlbum); err != nil {\n\t\treturn\n\t}\n\n\t// Add the new album to the slice.\n\talbums = append(albums, newAlbum)\n\tc.IndentedJSON(http.StatusCreated, newAlbum)\n}", "func ArtistAlbum(id string, page, limit int) (string, error) {\n\t_offset, _limit := formatParams(page, limit)\n\tpreParams := \"{\\\"offset\\\": \"+ _offset +\", \\\"limit\\\": \"+_limit +\", \\\"total\\\": true, \\\"csrf_token\\\": \\\"\\\"}\"\n\tparams, encSecKey, encErr := EncParams(preParams)\n\tif encErr != nil {\n\t\treturn \"\", encErr\n\t}\n\tres, resErr := post(\"http://music.163.com/weapi/artist/albums/\"+id, params, encSecKey)\n\tif resErr != nil {\n\t\treturn \"\", resErr\n\t}\n\treturn res, nil\n}", "func (h *Handler) listSongs(w http.ResponseWriter, r *http.Request) {\n\tr.ParseForm()\n\tartist, ok1 := r.Form[\"artist\"]\n\talbum, ok2 := r.Form[\"album\"]\n\n\tvar songs []map[string]string\n\tvar err error\n\n\tif ok1 && ok2 {\n\t\tsongs, err = h.MpdClient.GetSongs(artist[0], album[0])\n\t} else if ok1 && !ok2 {\n\t\tsongs, err = h.MpdClient.GetSongs(artist[0], \"\")\n\t} else {\n\t\tsongs, err = h.MpdClient.GetFiles()\n\t}\n\n\tif err != nil {\n\t\tprintError(w, \"An error occured while processing your request\", err)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, jsoniffy(songs))\n}", "func GetAllSongs(w http.ResponseWriter, r *http.Request) {\n\tvar test foo\n\n\tif err := json.NewDecoder(r.Body).Decode(&test); err != nil {\n\t\terr := fmt.Errorf(\"error when reading request body: %w\", err)\n\t\tlog.Logger.Errorf(\"GetAllSongs failed: %v\", err)\n\t\treturn\n\t}\n\n\tif test.Search == \"\" {\n\t\tlog.Logger.Infof(\"GetAllSongs: request body was empty: %v\", test)\n\n\t\thttp.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlog.Logger.Infof(\"GetAllSongs: successfully read request body: %v\", test)\n\n\tid, err := internal.GetArtistID(test.Search)\n\tif err != nil {\n\t\terr := fmt.Errorf(\"error when retrieving artist id: %w\", err)\n\t\tlog.Logger.Errorf(\"GetAllSongs failed: %v\", err)\n\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tsongs, err := internal.SongsByArtist(*id)\n\tif err != nil {\n\t\terr := fmt.Errorf(\"error when searching songs by artist: %w\", err)\n\t\tlog.Logger.Errorf(\"GetAllSongs failed: %v\", err)\n\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif err := json.NewEncoder(w).Encode(songs); err != nil {\n\t\terr := fmt.Errorf(\"error when encoding response: %w\", err)\n\t\tlog.Logger.Errorf(\"GetAllSongs failed: %v\", err)\n\n\t\thttp.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\n\t\treturn\n\t}\n}", "func GetPhotosByAlbumKeyHandler(w http.ResponseWriter, r *http.Request) {\n\tfuncTag := \"GetPhotosByAlbumKeyHandler\"\n\n\t// process request params\n\tmp, err := requester.GetRequestParams(r, nil, routeKeyAlbumID)\n\tif err != nil {\n\t\terr = apierr.Errorf(err, funcTag, \"process request params\")\n\t\tresponder.SendJSONError(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\t// get the photos\n\tps, err := photoDB.GetPhotosByAlbumKey(mp[routeKeyAlbumID])\n\tif err != nil {\n\t\terr = apierr.Errorf(err, funcTag, \"get photos by album key\")\n\t\tresponder.SendJSONError(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\t// give the photos their url from s3\n\t// TODO: have the client pass in a quality filter via query params (\"1024\" below)\n\tfor _, p := range ps {\n\t\trelativePath := fmt.Sprintf(\"%s/%s\", \"1024\", p.Src)\n\t\tp.Src = aws.S3PublicAssetURL(relativePath)\n\t}\n\n\t// build the return data\n\tres := &GetPhotosResponse{}\n\tres.Photos = ps\n\n\t// return\n\tresponder.SendJSON(w, res)\n}", "func ShowImagesInAlbum(albName string) ([]string, *utils.ApplicationError) {\n\treturn model.ShowImagesInAlbum(albName)\n}", "func GetAlbumFromAPI(id dna.Int) (*Album, error) {\n\tvar album *Album = NewAlbum()\n\talbum.Id = id\n\tapialbum, err := GetAPIAlbum(id)\n\tif err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tif apialbum.Response.MsgCode == 1 {\n\t\t\tif GetKey(apialbum.Id) != GetKey(album.Id) {\n\t\t\t\terrMes := dna.Sprintf(\"Resulted key and computed key are not match. %v =/= %v , id: %v =/= %v\", GetKey(apialbum.Id), GetKey(album.Id), id, apialbum.Id)\n\t\t\t\tpanic(errMes.String())\n\t\t\t}\n\n\t\t\talbum.Title = apialbum.Title\n\t\t\talbum.Artists = dna.StringArray(apialbum.Artists.Split(\" , \").Map(func(val dna.String, idx dna.Int) dna.String {\n\t\t\t\treturn val.Trim()\n\t\t\t}).([]dna.String)).SplitWithRegexp(\",\").Filter(func(v dna.String, i dna.Int) dna.Bool {\n\t\t\t\tif v != \"\" {\n\t\t\t\t\treturn true\n\t\t\t\t} else {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t})\n\n\t\t\talbum.Topics = dna.StringArray(apialbum.Topics.Split(\", \").Map(func(val dna.String, idx dna.Int) dna.String {\n\t\t\t\treturn val.Trim()\n\t\t\t}).([]dna.String)).SplitWithRegexp(\" / \").Unique().Filter(func(v dna.String, i dna.Int) dna.Bool {\n\t\t\t\tif v != \"\" {\n\t\t\t\t\treturn true\n\t\t\t\t} else {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t})\n\t\t\talbum.Plays = apialbum.Plays\n\t\t\t// album.Songids\n\t\t\t// album.Nsongs\n\t\t\t// album.EncodedKey\n\t\t\t// album.Coverart\n\t\t\t// album.DateCreated\n\t\t\talbum.YearReleased = apialbum.YearReleased\n\t\t\talbum.Description = apialbum.Description.RemoveHtmlTags(\"\")\n\n\t\t\talbum.ArtistIds = apialbum.ArtistIds.Split(\",\").ToIntArray()\n\t\t\talbum.IsAlbum = apialbum.IsAlbum\n\t\t\talbum.IsHit = apialbum.IsHit\n\t\t\talbum.IsOfficial = apialbum.IsOfficial\n\t\t\talbum.Likes = apialbum.Likes\n\t\t\talbum.StatusId = apialbum.StatusId\n\t\t\talbum.Comments = apialbum.Comments\n\t\t\talbum.Checktime = time.Now()\n\t\t\treturn album, nil\n\t\t} else {\n\t\t\treturn nil, errors.New(\"Message code invalid \" + apialbum.Response.MsgCode.ToString().String())\n\t\t}\n\t}\n}", "func albumsByArtist(name string) ([]Album, error) {\n\t// An albums slice to hold data from returned rows.\n\tvar albums []Album\n\n\trows, err := db.Query(\"SELECT * FROM album WHERE artist = ?\", name)\n\tif nil != err {\n\t\t\treturn nil, fmt.Errorf(\"albumsByArtist %q: %v\", name, err)\n\t}\n\tdefer rows.Close()\n\t// Loop through rows, using Scan to assign column data to struct fields.\n\tfor rows.Next() {\n\t\t\tvar album Album\n\t\t\tif err := rows.Scan(&album.ID, &album.Title, &album.Artist, &album.Price); nil != err {\n\t\t\t\t\treturn nil, fmt.Errorf(\"albumsByArtist %q: %v\", name, err)\n\t\t\t}\n\t\t\talbums = append(albums, album)\n\t}\n\tif err := rows.Err(); nil != err {\n\t\t\treturn nil, fmt.Errorf(\"albumsByArtist %q: %v\", name, err)\n\t}\n\treturn albums, nil\n}", "func postAlbums(c *gin.Context) {\n\tvar newAlbum album\n\n\t// Call BinsJSON to bind the received JSON to\n\t// newAlbum.\n\tif err := c.BindJSON(&newAlbum); err != nil {\n\t\treturn\n\t}\n\n\t// Add the new album to the albums.json.\n\tif result := AddAlbum(newAlbum); result == false {\n\t\tc.IndentedJSON(http.StatusNotAcceptable, gin.H{\"message\": \"ID not avaible\"})\n\t\treturn\n\t}\n\n\tc.IndentedJSON(http.StatusCreated, newAlbum)\n}", "func albumsByArtist(name string, db *sql.DB) ([]Album, error) {\n\t// An albums slice to hold data from returned rows.\n\tvar albums []Album\n\n\trows, err := db.Query(\"SELECT id,title,artist,price FROM album WHERE artist = ?\", name)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"albumsByArtist %q: %v\", name, err)\n\t}\n\tdefer rows.Close()\n\n\t// Loop through rows, using Scan to assign column data to struct fields.\n\tfor rows.Next() {\n\t\tvar alb Album\n\t\tif err := rows.Scan(&alb.ID, &alb.Title, &alb.Artist, &alb.Price); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"albumsByArtist %q: %v\", name, err)\n\t\t}\n\t\talbums = append(albums, alb)\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, fmt.Errorf(\"albumsByArtist %q: %v\", name, err)\n\t}\n\treturn albums, nil\n}", "func postAlbums(c *gin.Context) {\n\n\tvar newAlbum album.Album\n\n\tif err := c.BindJSON(&newAlbum); err != nil {\n\t\treturn\n\t}\n\n\tres, err := dbClient.Exec(\"INSERT INTO album (id, title, artist, price) VALUES (?, ?, ?, ?);\",\n\t\tnewAlbum.ID, newAlbum.Title, newAlbum.Artist, newAlbum.Price)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tid, err := res.LastInsertId()\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tnewAlbum.ID = int(id)\n\n\tc.IndentedJSON(http.StatusCreated, newAlbum)\n}", "func (a API) GetSongs(c *gin.Context) (int, interface{}, error) {\n\te := a.err.Fn(\"GetSongs\")\n\tsongs, err := a.s.getSongs()\n\tif err != nil {\n\t\treturn 500, songs, e.UK(err)\n\t}\n\treturn 200, songs, nil\n}", "func getTracks(c *gin.Context) {\n\tartists := database.GetArtists()\n\talbums := database.GetAlbums()\n\ttracks := database.GetTracks()\n\tfull := fullJson{artists, albums, tracks}\n\n c.JSON(200, full)\n}", "func (ar AlbumDbRepository) GetAll(hydrate bool) (entities domain.Albums, err error) {\n\tif !hydrate {\n\t\tquery := \"SELECT id, title, year, artist_id, cover_id, created_at FROM albums\"\n\t\t_, err = ar.AppContext.DB.Select(&entities, query)\n\n\t} else {\n\t\ttype gorpResult struct {\n\t\t\tAlbumId int\n\t\t\tAlbumTitle string\n\t\t\tAlbumYear string\n\t\t\tAlbumArtistId int\n\t\t\tAlbumCreatedAt int64\n\t\t\tdomain.Track\n\t\t\t// Cannot select domain.album.ArtistId or domain.track.AlbumId because of a Gorp error...\n\t\t\t// So we have to join on trk.album_id, but then Gorp cannot do the mapping with gorpResult, so we have\n\t\t\t// to add this property in the struct. TODO get rid of gorp.\n\t\t\tAlbum_id int\n\t\t}\n\t\tvar results []gorpResult\n\n\t\tquery := \"SELECT alb.Id AlbumId, alb.Title AlbumTitle, alb.Year AlbumYear, alb.artist_id AlbumArtistId, alb.created_at AlbumCreatedAt, trk.* \" +\n\t\t\t \"FROM albums alb, tracks trk WHERE alb.id = trk.album_id\"\n\n\t\t_, err = ar.AppContext.DB.Select(&results, query)\n\t\tif err == nil {\n\t\t\t// Deduplicate stuff.\n\t\t\tvar current domain.Album\n\t\t\tfor _, r := range results {\n\t\t\t\ttrack := domain.Track{\n\t\t\t\t\tId: r.Id,\n\t\t\t\t\tTitle: r.Title,\n\t\t\t\t\tAlbumId: r.AlbumId,\n\t\t\t\t\tArtistId: r.ArtistId,\n\t\t\t\t\tCoverId: r.CoverId,\n\t\t\t\t\tDisc: r.Disc,\n\t\t\t\t\tNumber: r.Number,\n\t\t\t\t\tDuration: r.Duration,\n\t\t\t\t\tGenre: r.Genre,\n\t\t\t\t\tPath: r.Path,\n\t\t\t\t\tDateAdded: r.DateAdded,\n\t\t\t\t}\n\n\t\t\t\tif current.Id == 0 {\n\t\t\t\t\tcurrent = domain.Album{\n\t\t\t\t\t\tId: r.AlbumId,\n\t\t\t\t\t\tTitle: r.AlbumTitle,\n\t\t\t\t\t\tYear: r.AlbumYear,\n\t\t\t\t\t\tArtistId: r.AlbumArtistId,\n\t\t\t\t\t\tDateAdded: r.AlbumCreatedAt,\n\t\t\t\t\t}\n\t\t\t\t} else if r.Id != current.Id {\n\t\t\t\t\tentities = append(entities, current)\n\t\t\t\t\t// Then change the current album\n\t\t\t\t\tcurrent = domain.Album{\n\t\t\t\t\t\tId: r.AlbumId,\n\t\t\t\t\t\tTitle: r.AlbumTitle,\n\t\t\t\t\t\tYear: r.AlbumYear,\n\t\t\t\t\t\tArtistId: r.AlbumArtistId,\n\t\t\t\t\t\tDateAdded: r.AlbumCreatedAt,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrent.Tracks = append(current.Tracks, track)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}", "func (s *Service) PaginatedList(ctx context.Context, options *PaginatedListOptions) (albums []Album, nextPageToken string, err error) {\n\tvar pageToken string\n\tvar limit int64\n\n\tif options != nil {\n\t\tlimit = options.Limit\n\t\tpageToken = options.PageToken\n\t}\n\n\tif limit == 0 {\n\t\tlimit = maxAlbumsPerPage\n\t}\n\n\tlistAlbumsResponse, err := s.photos.List().PageSize(limit).PageToken(pageToken).ExcludeNonAppCreatedData().Context(ctx).Do()\n\n\tif err != nil {\n\t\tvar emptyResult []Album\n\t\treturn emptyResult, \"\", fmt.Errorf(\"listing albums by page: %w\", err)\n\t}\n\n\treturn toAlbums(listAlbumsResponse.Albums), listAlbumsResponse.NextPageToken, nil\n}", "func GetAlbum(id dna.Int) (*Album, error) {\n\tapiAlbum, err := GetAPIAlbum(id)\n\tif err != nil {\n\t\treturn nil, err\n\t} else {\n\t\talbum := apiAlbum.ToAlbum()\n\t\tif album.Id == 0 {\n\t\t\treturn nil, errors.New(dna.Sprintf(\"Keeng - Album ID: %v not found\", id).String())\n\t\t} else {\n\t\t\treturn album, nil\n\t\t}\n\t}\n}", "func getAlbumByID(c *gin.Context) {\n\tid := c.Param(\"id\")\n\n\t// Loop over the list of albums, looking for an album whose id value matches the parameter\n\tfor _, a := range albums {\n\t\tif a.ID == id {\n\t\t\tc.IndentedJSON(http.StatusOK, a)\n\t\t\treturn\n\t\t}\n\t}\n\tc.IndentedJSON(http.StatusNotFound, gin.H{\"message\": \"album not found\"})\n}", "func getAlbumByID(c *gin.Context) {\n\tid := c.Param(\"id\")\n\ta := GetAlbum(id)\n\n\tif a != nil {\n\t\tc.IndentedJSON(http.StatusOK, a)\n\t\treturn\n\t}\n\n\tc.IndentedJSON(http.StatusNotFound, gin.H{\"message\": \"album not found\"})\n}", "func (r *SharedAlbumsService) Get(shareToken string) *SharedAlbumsGetCall {\n\tc := &SharedAlbumsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.shareToken = shareToken\n\treturn c\n}", "func getAlbumByID(c *gin.Context) {\n\tid := c.Param(\"id\")\n\n\t// Loop over the list of albums, looking for\n\t// an album whose ID value matches the parameter.\n\tfor _, a := range albums {\n\t\tif a.ID == id {\n\t\t\tc.IndentedJSON(http.StatusOK, a)\n\t\t\treturn\n\t\t}\n\t}\n\tc.IndentedJSON(http.StatusNotFound, gin.H{\"message\": \"album not found\"})\n}", "func getAlbumFromAPI(album *Album) <-chan bool {\n\tchannel := make(chan bool, 1)\n\tgo func() {\n\t\tapialbum, err := GetAlbumFromAPI(album.Id)\n\t\tif err == nil {\n\t\t\talbum.Title = apialbum.Title\n\t\t\talbum.Artists = apialbum.Artists\n\t\t\talbum.Topics = apialbum.Topics\n\t\t\talbum.Plays = apialbum.Plays\n\t\t\talbum.YearReleased = apialbum.YearReleased\n\t\t\talbum.Description = apialbum.Description\n\t\t\talbum.ArtistIds = apialbum.ArtistIds\n\t\t\talbum.IsAlbum = apialbum.IsAlbum\n\t\t\talbum.IsHit = apialbum.IsHit\n\t\t\talbum.IsOfficial = apialbum.IsOfficial\n\t\t\talbum.Likes = apialbum.Likes\n\t\t\talbum.StatusId = apialbum.StatusId\n\t\t\talbum.Comments = apialbum.Comments\n\t\t\talbum.Checktime = time.Now()\n\t\t}\n\t\tchannel <- true\n\n\t}()\n\treturn channel\n}", "func (s MockedRepository) Get(ctx context.Context, albumId string) (*Album, error) {\n\treturn s.GetFn(ctx, albumId)\n}", "func (s *Server) getMusicFolders(w http.ResponseWriter, r *http.Request) {\n\twriteXML(w, func(c *container) {\n\t\tc.MusicFolders = &musicFoldersContainer{\n\t\t\tMusicFolders: []musicFolder{{\n\t\t\t\tID: 0,\n\t\t\t\tName: filepath.Base(s.cfg.MusicDirectory),\n\t\t\t}},\n\t\t}\n\t})\n}", "func (h *Handler) getUpcomingSongs(w http.ResponseWriter, r *http.Request) {\n\tupcoming, err := h.MpdClient.GetUpcoming()\n\tif err != nil {\n\t\tprintError(w, \"Couldn't get upcoming playlist\", err)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, jsoniffy(upcoming))\n}", "func (c MockedCache) GetAlbum(ctx context.Context, title string) (Album, error) {\n\treturn c.GetAlbumFn(ctx, title)\n}", "func (l *Lidarr) GetAlbumContext(ctx context.Context, mbID string) ([]*Album, error) {\n\treq := starr.Request{Query: make(url.Values), URI: bpAlbum}\n\tif mbID != \"\" {\n\t\treq.Query.Add(\"ForeignAlbumId\", mbID)\n\t}\n\n\tvar output []*Album\n\n\tif err := l.GetInto(ctx, req, &output); err != nil {\n\t\treturn nil, fmt.Errorf(\"api.Get(%s): %w\", &req, err)\n\t}\n\n\treturn output, nil\n}", "func (s *Service) getSongs() (api.Songs, error) {\n\te := s.err.Fn(\"getSongs\")\n\tsongs, err := s.db.get(\"\")\n\tif err != nil {\n\t\treturn api.Songs{}, e.Wrap(err, \"getting songs from db\")\n\t}\n\treturn songs, nil\n}", "func GetAllPodcast(cfg *config.Config) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tpodcasts, err := models.Podcasts{}.GetAll(cfg)\n\t\tif err != nil {\n\t\t\tutils.ErrorWithJSON(w, \"Error Retrieving From Podcast Collection\", http.StatusNotFound)\n\t\t}\n\n\t\tjsonBytes, err := json.Marshal(podcasts)\n\t\tif err != nil {\n\t\t\tutils.ErrorWithJSON(w, \"Error Marshaling JSON\", http.StatusInternalServerError)\n\t\t}\n\t\tutils.ResponseWithJSON(w, jsonBytes, http.StatusOK)\n\t}\n\treturn http.HandlerFunc(fn)\n}", "func (dh *DogHandler) GetAllDogs(w http.ResponseWriter, r *http.Request) {\n\n\tdogs, err := dh.DogService.GetAllDogs()\n\tif err != nil {\n\t\terrorRespond(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\tjsonRespond(w, http.StatusOK, dogs)\n\n}", "func handlePodcastsGet(w http.ResponseWriter, r *http.Request) error {\n\tctx := r.Context()\n\n\tacct, err := authenticate(ctx, r)\n\tif err != nil {\n\t\treturn apiError(\"Not authorized\", http.StatusUnauthorized)\n\t}\n\n\tpodcasts, err := store.LoadPodcasts(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsubs, err := store.LoadSubscriptionIDs(ctx, acct)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlist := podcastList{}\n\tfor _, podcast := range podcasts {\n\t\t_, is_subbed := subs[podcast.ID]\n\t\tlist.Podcasts = append(list.Podcasts, &podcastDetails{*podcast, is_subbed})\n\t}\n\terr = json.NewEncoder(w).Encode(&list)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func GetPhotos() http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tconn, err := middleware.ExtractSession(r)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), 500)\n\t\t\treturn\n\t\t}\n\t\tdao := model.PhotoDao{DB: conn}\n\t\tphotos, err := dao.Read()\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), 500)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tjson.NewEncoder(w).Encode(photos)\n\t})\n}", "func getBackups(w http.ResponseWriter, r *http.Request) {\n\tlogrus.Debugf(\"GetBackups r=%s\", r)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tgab, err := currentBackuper.GetAllBackups()\n\tif err != nil {\n\t\tlogrus.Warnf(\"Error calling getAllBackups(). err=%s\", err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\terr = json.NewEncoder(w).Encode(gab)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}", "func (k *Kairos) ListGalleries() (*ResponseListGalleries, error) {\n\treq, reqErr := k.newRequest(\"POST\", \"gallery/list_all\", nil)\n\tif reqErr != nil {\n\t\treturn nil, reqErr\n\t}\n\n\tresp, doErr := k.do(req)\n\tif doErr != nil {\n\t\treturn nil, doErr\n\t}\n\n\tre := &ResponseListGalleries{}\n\tuErr := json.Unmarshal(resp, &re)\n\tif uErr != nil {\n\t\treturn nil, uErr\n\t}\n\n\tre.RawResponse = resp\n\treturn re, nil\n}", "func GetResponseImages(albumID string, clientID string) (imageLink string) { // removed: (imageLink interface{})\n\n\t// This hash is the albumID hash\n\turl := \"https://api.imgur.com/3/album/\" + albumID + \"/images.json\"\n\tmethod := \"GET\"\n\n\tpayload := &bytes.Buffer{}\n\twriter := multipart.NewWriter(payload)\n\terr := writer.Close()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(method, url, payload)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\treq.Header.Add(\"Authorization\", \"Client-ID \"+clientID)\n\n\treq.Header.Set(\"Content-Type\", writer.FormDataContentType())\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\tfmt.Println(\"[-] Error connecting:\", err)\n\t}\n\tdefer res.Body.Close()\n\tbody, err := ioutil.ReadAll(res.Body)\n\n\tvar results AlbumImages\n\terrr := json.Unmarshal([]byte(body), &results)\n\tif errr != nil {\n\t\tfmt.Println(\"[!] Error unmarshalling::\", errr)\n\t}\n\n\tdatavalues := results.Data\n\tif results.Success == true {\n\t\tfor field := range datavalues {\n\t\t\tif strings.Contains(datavalues[field].Description, \"response\") {\n\n\t\t\t\tfmt.Println(\"[+] ImageID:\", datavalues[field].ID)\n\t\t\t\tfmt.Println(\"[+] ImageTitle:\", datavalues[field].Title)\n\t\t\t\tfmt.Println(\"[+] Description:\", datavalues[field].Description)\n\t\t\t\tfmt.Println(\"[+] ImageLink:\", datavalues[field].Link)\n\t\t\t\tfmt.Println(\" \")\n\n\t\t\t\tresponseURL = datavalues[field].Link\n\t\t\t}\n\n\t\t\t//\tfmt.Println(\"[+] Logic worked and got a response from a client: \", datavalues[field].Link)\n\t\t}\n\n\t}\n\treturn responseURL\n}", "func (f Flickr) PhotosetsGetPhotos(photosetID string, userID string, page int) jsonstruct.PhotosetsGetPhotos {\n\targs := make(map[string]string)\n\targs[\"method\"] = \"flickr.photosets.getPhotos\"\n\targs[\"photoset_id\"] = photosetID\n\targs[\"user_id\"] = userID\n\targs[\"per_page\"] = strconv.Itoa(perPage)\n\targs[\"page\"] = strconv.Itoa(page)\n\n\tjsonData := f.HTTPGet(utils.APIURL, args)\n\n\tvar data jsonstruct.PhotosetsGetPhotos\n\tif err := json.Unmarshal(jsonData, &data); err != nil {\n\t\tlog.Println(err)\n\t}\n\treturn data\n}", "func (a *AlbumMethods) Search(album string, page, limit int) (*AlbumSearchResults, error) {\n\twrapper := struct {\n\t\tResults *AlbumSearchResults `xml:\"results\"`\n\t}{}\n\tquery := map[string]string{\n\t\t\"method\": a.method(\"search\"),\n\t\t\"album\": album,\n\t\t\"page\": string(page),\n\t\t\"limit\": string(limit),\n\t}\n\terr := a.Client.Execute(query, &wrapper)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn wrapper.Results, nil\n}", "func (c MockedCache) InvalidateAllAlbums(ctx context.Context) error {\n\treturn c.InvalidateAllAlbumsFn(ctx)\n}", "func NewAlbumList(selectAlbum func(album *models.Album)) *AlbumList {\n\ta := &AlbumList{\n\t\tBanner: twidgets.NewBanner(),\n\t\tprevious: &previous{},\n\t\tselectFunc: selectAlbum,\n\t\tartist: &models.Artist{},\n\t\tname: tview.NewTextView(),\n\t\tprevBtn: newButton(\"Back\"),\n\t\tprevFunc: nil,\n\t\tplayBtn: newButton(\"Play all\"),\n\t\tsimilarBtn: newButton(\"Similar\"),\n\t}\n\ta.paging = NewPageSelector(a.selectPage)\n\ta.list = twidgets.NewScrollList(a.selectAlbum)\n\ta.list.ItemHeight = 3\n\n\ta.SetBorder(true)\n\ta.SetBorderColor(config.Color.Border)\n\ta.SetBackgroundColor(config.Color.Background)\n\ta.list.SetBackgroundColor(config.Color.Background)\n\ta.list.SetBorder(true)\n\ta.list.SetBorderColor(config.Color.Border)\n\ta.list.Grid.SetColumns(-1, 5)\n\ta.SetBorderColor(config.Color.Border)\n\n\tbtns := []*button{a.prevBtn, a.playBtn, a.similarBtn, a.paging.Previous, a.paging.Next}\n\tselectables := []twidgets.Selectable{a.prevBtn, a.playBtn, a.paging.Previous, a.paging.Next, a.list}\n\tfor _, v := range btns {\n\t\tv.SetBackgroundColor(config.Color.ButtonBackground)\n\t\tv.SetLabelColor(config.Color.ButtonLabel)\n\t\tv.SetBackgroundColorActivated(config.Color.ButtonBackgroundSelected)\n\t\tv.SetLabelColorActivated(config.Color.ButtonLabelSelected)\n\t}\n\n\ta.prevBtn.SetSelectedFunc(a.goBack)\n\n\ta.Banner.Selectable = selectables\n\n\ta.Grid.SetRows(1, 1, 1, 1, -1)\n\ta.Grid.SetColumns(6, 2, 10, -1, 10, -1, 10, -3)\n\ta.Grid.SetMinSize(1, 6)\n\ta.Grid.SetBackgroundColor(config.Color.Background)\n\ta.name.SetBackgroundColor(config.Color.Background)\n\ta.name.SetTextColor(config.Color.Text)\n\n\ta.list.Grid.SetColumns(1, -1)\n\n\ta.Grid.AddItem(a.prevBtn, 0, 0, 1, 1, 1, 5, false)\n\ta.Grid.AddItem(a.name, 0, 2, 2, 6, 1, 10, false)\n\ta.Grid.AddItem(a.playBtn, 3, 2, 1, 1, 1, 10, false)\n\ta.Grid.AddItem(a.paging, 3, 4, 1, 3, 1, 10, false)\n\t//a.Grid.AddItem(a.similarBtn, 3, 4, 1, 1, 1, 10, false)\n\ta.Grid.AddItem(a.list, 4, 0, 1, 8, 6, 20, false)\n\n\ta.listFocused = false\n\ta.pagingEnabled = true\n\treturn a\n}", "func getSets(flickrOAuth FlickrOAuth) PhotosetsResponse {\n\n\tbody, err := makeGetRequest(func() string { return generateGetSetsUrl(flickrOAuth) })\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tsets := PhotosetsResponse{}\n\terr = xml.Unmarshal(body, &sets)\n\tif err != nil {\n\t\tlogMessage(\"Could not unmarshal body, check logs for body detail.\", true)\n\t\tlogMessage(string(body), false)\n\t\tpanic(err)\n\t}\n\n\tsort.Sort(ByDateCreated(sets.SetContainer.Sets))\n\n\treturn sets\n}", "func NewAlbum() *Album {\n\talbum := new(Album)\n\talbum.Id = 0\n\talbum.Key = \"\"\n\talbum.Title = \"\"\n\talbum.Artists = dna.StringArray{}\n\talbum.Plays = 0\n\talbum.Songids = dna.IntArray{}\n\talbum.Nsongs = 0\n\talbum.Description = \"\"\n\talbum.Coverart = \"\"\n\talbum.DateCreated = time.Time{}\n\talbum.Checktime = time.Time{}\n\treturn album\n}", "func NewAlbum() *Album {\n\talbum := new(Album)\n\talbum.Key = \"\"\n\talbum.Id = 0\n\talbum.EncodedKey = \"\"\n\talbum.Title = \"\"\n\talbum.Artists = dna.StringArray{}\n\talbum.Coverart = \"\"\n\talbum.Topics = dna.StringArray{}\n\talbum.Plays = 0\n\talbum.Songids = dna.IntArray{}\n\talbum.YearReleased = \"\"\n\talbum.Nsongs = 0\n\talbum.Description = \"\"\n\talbum.DateCreated = time.Time{}\n\talbum.Checktime = time.Time{}\n\t// add more 6 fields\n\talbum.IsAlbum = 0\n\talbum.IsHit = 0\n\talbum.IsOfficial = 0\n\talbum.Likes = 0\n\talbum.StatusId = 0\n\talbum.Comments = 0\n\talbum.ArtistIds = dna.IntArray{}\n\treturn album\n}", "func (a *TeamsApiService) GetAllClientGroupAssociations(ctx context.Context, clientId string) ( *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)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/team/associations/\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\n\tlocalVarQueryParams.Add(\"clientId\", parameterToString(clientId, \"\"))\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/x-www-form-urlencoded\", }\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\t\t\"application/json\",\n\t\t}\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\tdefer localVarHttpResponse.Body.Close()\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tbodyBytes, _ := ioutil.ReadAll(localVarHttpResponse.Body)\n\t\treturn localVarHttpResponse, reportError(\"Status: %v, Body: %s\", localVarHttpResponse.Status, bodyBytes)\n\t}\n\n\treturn localVarHttpResponse, err\n}", "func getAllPhotos(flickrOAuth FlickrOAuth, apiName string, setId string) map[string]Photo {\n\n\tvar err error\n\tvar body []byte\n\tphotos := map[string]Photo{}\n\tcurrentPage := 1\n\tpageSize := 500\n\n\tfor {\n\n\t\textras := map[string]string{\"page\": strconv.Itoa(currentPage)}\n\t\textras[\"per_page\"] = strconv.Itoa(pageSize)\n\t\textras[\"extras\"] = \"media,url_o\"\n\t\tif len(setId) > 0 {\n\t\t\textras[\"photoset_id\"] = setId\n\t\t}\n\n\t\tbody, err = makeGetRequest(func() string { return generateOAuthUrl(apiBaseUrl, apiName, flickrOAuth, extras) })\n\t\tif err != nil {\n\t\t\tlogMessage(\"Could not unmarshal body, check logs for body detail.\", true)\n\t\t\tlogMessage(string(body), false)\n\t\t\treturn map[string]Photo{}\n\t\t}\n\n\t\tresponsePhotos := []Photo{}\n\t\tvar err error\n\t\tif apiName == getPhotosNotInSetName {\n\t\t\tresponse := PhotosNotInSetResponse{}\n\t\t\terr = xml.Unmarshal(body, &response)\n\t\t\tif err == nil {\n\t\t\t\tresponsePhotos = response.Photos\n\t\t\t}\n\t\t} else {\n\t\t\tresponse := PhotosResponse{}\n\t\t\terr = xml.Unmarshal(body, &response)\n\t\t\tif err == nil {\n\t\t\t\tresponsePhotos = response.Set.Photos\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\n\t\t\t// We couldn't unmarshal the response as photos, but it might be the case\n\t\t\t// that we just ran out of photos, i.e. the set has a multiple of 500 photos in it\n\t\t\t// Lets try to unmarshal the response as an error, and if it is, error code \"1\" means\n\t\t\t// we're good and we can take what we've got and roll on.\n\t\t\terrorResponse := FlickrErrorResponse{}\n\t\t\terr = xml.Unmarshal(body, &errorResponse)\n\t\t\tif err != nil {\n\n\t\t\t\tlogMessage(\"Could not unmarshal body, check logs for body detail.\", true)\n\t\t\t\tlogMessage(string(body), false)\n\t\t\t\treturn map[string]Photo{}\n\t\t\t}\n\n\t\t\t// The \"good\" error code\n\t\t\tif errorResponse.Error.Code == \"1\" {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tlogMessage(\"An error occurred while getting photos for the set. Check the body in the logs.\", false)\n\t\t\tlogMessage(string(body), false)\n\t\t}\n\n\t\tfor _, v := range responsePhotos {\n\t\t\tphotos[v.Id] = v\n\t\t}\n\n\t\t// If we didn't get 500 photos, then we're done.\n\t\t// There are no more photos to get.\n\t\tif len(responsePhotos) < pageSize {\n\t\t\tbreak\n\t\t}\n\n\t\tcurrentPage++\n\t}\n\n\treturn photos\n}", "func getBooks(w http.ResponseWriter, r *http.Request) {\n\tvar b []Book = RetrieveBooks()\n\n\tjson.NewEncoder(w).Encode(b)\n}", "func GetAllAuthors(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"Endpoint Hit: return all authors\")\n\n\tvar authors []models.Author\n\tresult := DB.Find(&authors)\n\tif result.Error != nil {\n\t\tresponses.RespondWithError(w, http.StatusBadRequest, result.Error)\n\t\treturn\n\t}\n\n\tresponses.RespondWithJSON(w, http.StatusOK, authors)\n}", "func GetAllBook(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Context-Type\", \"application/x-www-form-urlencoded\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t// get all the books in the db\n\tbooks, err := getAllBooks()\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to get all book. %v\", err)\n\t}\n\n\t// send all the books as response\n\tjson.NewEncoder(w).Encode(books)\n}", "func getBooks(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(books)\n}", "func getBooks(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(books)\n}", "func (b *BookDao) GetAll() ([]models.Book, error) {\n\treturn parseJSONFile(dataSrc)\n}", "func (ar AlbumDbRepository) Get(id int) (entity domain.Album, err error) {\n\tobject, err := ar.AppContext.DB.Get(domain.Album{}, id)\n\tif err == nil && object != nil {\n\t\tentity = *object.(*domain.Album)\n\t\tar.populateTracks(&entity)\n\t} else {\n\t\terr = errors.New(\"no album found\")\n\t}\n\n\treturn\n}", "func getAllflavours(w http.ResponseWriter, r *http.Request) {\r\n\tw.Header().Set(\"Content-Type\", \"application/json\")\r\n\tjson.NewEncoder(w).Encode(flavours)\r\n}", "func ListAssetSummaries(settings *playfab.Settings, postData *ListAssetSummariesRequestModel, entityToken string) (*ListAssetSummariesResponseModel, error) {\n if entityToken == \"\" {\n return nil, playfab.NewCustomError(\"entityToken should not be an empty string\", playfab.ErrorGeneric)\n }\n b, errMarshal := json.Marshal(postData)\n if errMarshal != nil {\n return nil, playfab.NewCustomError(errMarshal.Error(), playfab.ErrorMarshal)\n }\n\n sourceMap, err := playfab.Request(settings, b, \"/MultiplayerServer/ListAssetSummaries\", \"X-EntityToken\", entityToken)\n if err != nil {\n return nil, err\n }\n \n result := &ListAssetSummariesResponseModel{}\n\n config := mapstructure.DecoderConfig{\n DecodeHook: playfab.StringToDateTimeHook,\n Result: result,\n }\n \n decoder, errDecoding := mapstructure.NewDecoder(&config)\n if errDecoding != nil {\n return nil, playfab.NewCustomError(errDecoding.Error(), playfab.ErrorDecoding)\n }\n \n errDecoding = decoder.Decode(sourceMap)\n if errDecoding != nil {\n return nil, playfab.NewCustomError(errDecoding.Error(), playfab.ErrorDecoding)\n }\n\n return result, nil\n}", "func GetBooks(w http.ResponseWriter, r *http.Request) {\n\tfmt.Printf(\"Getting all books.\\n\")\n json.NewEncoder(w).Encode(books)\n}", "func (c *AlbumsListCall) Pages(ctx context.Context, f func(*ListAlbumsResponse) error) error {\n\tc.ctx_ = ctx\n\tdefer c.PageToken(c.urlParams_.Get(\"pageToken\")) // reset paging to original point\n\tfor {\n\t\tx, err := c.Do()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := f(x); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif x.NextPageToken == \"\" {\n\t\t\treturn nil\n\t\t}\n\t\tc.PageToken(x.NextPageToken)\n\t}\n}", "func (c *GetImagesByAlbumApiController) Routes() Routes {\n\treturn Routes{\n\t\t{\n\t\t\t\"GetImagesByAlbum\",\n\t\t\tstrings.ToUpper(\"Get\"),\n\t\t\t\"/albums/{id}/images\",\n\t\t\tc.GetImagesByAlbum,\n\t\t},\n\t}\n}", "func (app *application) getAssets(w http.ResponseWriter, r *http.Request) {\n\tdata, err := app.assets.GetAssets()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tj, err := json.Marshal(data)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Write(j)\n}", "func AllContainers(endpoint, authToken string) (*[]Container, error) {\n\tvar containers *[]Container\n\n\treq, err := http.NewRequest(\"GET\", endpoint+\"?format=json\", nil)\n\tif err != nil {\n\t\treturn containers, err\n\t}\n\treq.Header.Add(\"X-Auth-Token\", authToken)\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn containers, err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Decode the json response.\n\tdec := json.NewDecoder(resp.Body)\n\tfor {\n\t\tif err := dec.Decode(&containers); err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn containers, err\n\t\t}\n\t}\n\n\treturn containers, nil\n}", "func getBooks(w http.ResponseWriter, r *http.Request){\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(books)\n}", "func handleGetMusicians(\n\tparams operations.GetMusiciansParams,\n) middleware.Responder {\n\n\t// init db connection\n\tdb, err := sql.Open(\"postgres\", connStr)\n\tif err != nil {\n\t\tlog.Printf(\"pg-connect error: %v\", err)\n\t\treturn operations.NewGetPiecesIDInternalServerError()\n\t}\n\tdefer db.Close()\n\n\trows, err := db.Query(`\n\t\tSELECT id, first, COALESCE(middle, ''), last\n\t\tFROM musicians\n\t`)\n\tif err != nil {\n\t\tlog.Printf(\"pg-query error: %v\", err)\n\t\treturn operations.NewGetPiecesIDInternalServerError()\n\t}\n\tdefer rows.Close()\n\n\tresult := []*models.Musician{}\n\tfor rows.Next() {\n\t\tm := &models.Musician{}\n\t\terr = rows.Scan(&m.ID, &m.First, &m.Middle, &m.Last)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"pg-scan error: %v\", err)\n\t\t\treturn operations.NewGetPiecesIDInternalServerError()\n\t\t}\n\t\tresult = append(result, m)\n\t}\n\n\treturn operations.NewGetMusiciansOK().WithPayload(result)\n\n}", "func (api *bucketAPI) ApisrvList(ctx context.Context, opts *api.ListWatchOptions) ([]*objstore.Bucket, 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 nil, err\n\t\t}\n\n\t\treturn apicl.ObjstoreV1().Bucket().List(context.Background(), opts)\n\t}\n\n\t// List from local cache\n\tctkitObjs, err := api.List(ctx, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar ret []*objstore.Bucket\n\tfor _, obj := range ctkitObjs {\n\t\tret = append(ret, &obj.Bucket)\n\t}\n\treturn ret, nil\n}", "func GetBooks(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(books)\n}", "func GetAPODs(dt DateRange) []ResponseData {\n\n\tstartDt := stringToDate(dt.Start)\n\tendDt := stringToDate(dt.End)\n\n\tvar r []ResponseData\n\tfor startDt.Before(endDt) == true || startDt == endDt {\n\t\ttmp := startDt.Format(\"2006-01-02\")\n\t\turl := \"https://api.nasa.gov/planetary/apod?api_key=\" + apiKey\n\t\turl += \"&date=\" + tmp\n\t\tch := make(chan []byte)\n\t\tgo makeRequest(url, ch)\n\t\tvar res ResponseData\n\t\terr := json.Unmarshal(<-ch, &res)\n\t\tcheckError(err)\n\t\tr = append(r, res)\n\t\tstartDt = startDt.AddDate(0, 0, 1)\n\t}\n\treturn r\n}", "func GetCampaigns(w http.ResponseWriter, r *http.Request) {\n\tjson.NewEncoder(w).Encode(db.GetCampaigns())\n}", "func (controller controller) GetBooks() {\n\tgroup := controller.createNewGroup()\n\tgroup.Get(\"/\", func(c *fiber.Ctx) {\n\t\tbooksRepo := BooksRepository{DB: controller.db}\n\t\tbooks := booksRepo.GetAll()\n\t\tresponse := core.Response{Status: \"OK\", Code: 200, Data: books}\n\t\tc.Status(200).JSON(response)\n\t})\n}", "func (q Query) GetAllTalks(w http.ResponseWriter, r *http.Request) {\n\tdata, err := q.store.GetAllTalks()\n\n\tif err != nil {\n\t\tlog.Println(\"fail to get all talks, error: \", err)\n\t\tupdateHeader(w, err)\n\t\treturn\n\t}\n\n\twriteJsonBody(w, data)\n}", "func GetAllOrgEndpoint(w http.ResponseWriter, r *http.Request) {\n\n\tvar orgs []models.Organization\n\torgs = db.GetAllOrg()\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(orgs)\n\n}", "func (a *App) GetAllMeta(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(types.ContentType, types.ContentTypeApplicationJSON)\n\tdocs, err := a.Meta.GetMetaDocAll(a.correlationID)\n\tif err != nil {\n\t\trespondWithError(err, http.StatusNotFound, w)\n\t\treturn\n\t}\n\tdocs, _ = StripBlobStore(docs)\n\terr = json.NewEncoder(w).Encode(docs)\n\tif err != nil {\n\t\trespondWithError(err, http.StatusInternalServerError, w)\n\t\treturn\n\t}\n}", "func (*ListAlbumResponse) Descriptor() ([]byte, []int) {\n\treturn file_service_proto_rawDescGZIP(), []int{4}\n}", "func fillDatabase() {\n\n\tfor _, album := range albums {\n\n\t\tfmt.Println(album)\n\n\t\t_, err := dbClient.Exec(\"INSERT INTO album (id, title, artist, price) VALUES ($1, $2, $3, $4)\", album.ID, album.Title, album.Artist, album.Price)\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tfmt.Println(\"Database filled: \", albums)\n}" ]
[ "0.85289204", "0.83897734", "0.8245549", "0.8198997", "0.81667846", "0.7953926", "0.7672748", "0.7402946", "0.7328272", "0.7280202", "0.7192736", "0.71719384", "0.69887376", "0.6941905", "0.6801857", "0.6407454", "0.6396264", "0.6330194", "0.62474614", "0.62474173", "0.62028295", "0.61607224", "0.61525613", "0.6140032", "0.6134095", "0.6105293", "0.60243565", "0.6001603", "0.58980995", "0.58822286", "0.5871612", "0.58440596", "0.58355445", "0.5810018", "0.58083075", "0.5712879", "0.5651999", "0.56442624", "0.56386507", "0.55791646", "0.55772406", "0.5565766", "0.55544454", "0.5499781", "0.5489802", "0.54570246", "0.5438162", "0.5358621", "0.535825", "0.5350519", "0.53178", "0.53105354", "0.5308328", "0.52240306", "0.5174279", "0.51227903", "0.51070917", "0.5093518", "0.5082561", "0.50486743", "0.503307", "0.50048107", "0.4973406", "0.49532905", "0.49372312", "0.49317256", "0.4928584", "0.49226508", "0.49165094", "0.4913292", "0.49099812", "0.48801646", "0.48775592", "0.48600104", "0.4846785", "0.48451036", "0.48395228", "0.48349547", "0.48333195", "0.48333195", "0.48307785", "0.4808625", "0.4807982", "0.47974277", "0.47948903", "0.47879884", "0.4783974", "0.4780971", "0.47562245", "0.47467953", "0.47427586", "0.47393635", "0.4733231", "0.47213158", "0.4719807", "0.47139952", "0.47019193", "0.4700373", "0.46885276", "0.4679563", "0.46674478" ]
0.0
-1
AddInterfaceAPIRoutes adds Interface routes
func (s *RestServer) AddInterfaceAPIRoutes(r *mux.Router) { r.Methods("GET").Subrouter().HandleFunc("/", httputils.MakeHTTPHandler(s.listInterfaceHandler)) r.Methods("GET").Subrouter().HandleFunc("/{ObjectMeta.Tenant}/{ObjectMeta.Namespace}/{ObjectMeta.Name}", httputils.MakeHTTPHandler(s.getInterfaceHandler)) r.Methods("POST").Subrouter().HandleFunc("/", httputils.MakeHTTPHandler(s.postInterfaceHandler)) r.Methods("DELETE").Subrouter().HandleFunc("/{ObjectMeta.Tenant}/{ObjectMeta.Namespace}/{ObjectMeta.Name}", httputils.MakeHTTPHandler(s.deleteInterfaceHandler)) r.Methods("PUT").Subrouter().HandleFunc("/{ObjectMeta.Tenant}/{ObjectMeta.Namespace}/{ObjectMeta.Name}", httputils.MakeHTTPHandler(s.putInterfaceHandler)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (Interface) ApiRoutes() []string {\n\treturn []string{\n\t\t\"/api/objects/interface/bridge/\",\n\t\t\"/api/objects/interface/bridge/{ref}\",\n\t\t\"/api/objects/interface/bridge/{ref}/usedby\",\n\t\t\"/api/objects/interface/ethernet/\",\n\t\t\"/api/objects/interface/ethernet/{ref}\",\n\t\t\"/api/objects/interface/ethernet/{ref}/usedby\",\n\t\t\"/api/objects/interface/group/\",\n\t\t\"/api/objects/interface/group/{ref}\",\n\t\t\"/api/objects/interface/group/{ref}/usedby\",\n\t\t\"/api/objects/interface/ppp3g/\",\n\t\t\"/api/objects/interface/ppp3g/{ref}\",\n\t\t\"/api/objects/interface/ppp3g/{ref}/usedby\",\n\t\t\"/api/objects/interface/pppmodem/\",\n\t\t\"/api/objects/interface/pppmodem/{ref}\",\n\t\t\"/api/objects/interface/pppmodem/{ref}/usedby\",\n\t\t\"/api/objects/interface/pppoa/\",\n\t\t\"/api/objects/interface/pppoa/{ref}\",\n\t\t\"/api/objects/interface/pppoa/{ref}/usedby\",\n\t\t\"/api/objects/interface/pppoe/\",\n\t\t\"/api/objects/interface/pppoe/{ref}\",\n\t\t\"/api/objects/interface/pppoe/{ref}/usedby\",\n\t\t\"/api/objects/interface/tunnel/\",\n\t\t\"/api/objects/interface/tunnel/{ref}\",\n\t\t\"/api/objects/interface/tunnel/{ref}/usedby\",\n\t\t\"/api/objects/interface/vlan/\",\n\t\t\"/api/objects/interface/vlan/{ref}\",\n\t\t\"/api/objects/interface/vlan/{ref}/usedby\",\n\t}\n}", "func addAPIListingsRoute(r *mux.Router, srv *RestServer) {\n\tr.Methods(\"GET\").Subrouter().HandleFunc(\"/\", MakeHTTPHandler(srv.listInterfaceHandler))\n}", "func AddRoutes(router *gin.Engine, db storage.Storage, tracer tracer.Tracer) {\n\tapiRoutes := router.Group(\"/v0\")\n\t// routes.GET(\"/\", ReturnData(db))\n\t// routes.GET(\"/key/:key\", ReturnSingleObject(db))\n\tapiRoutes.GET(\"/graph\", routes.GetGraph(db))\n\tapiRoutes.GET(\"/metrics\", routes.GetMetrics(db))\n\tapiRoutes.POST(\"/start\", routes.AddTrace(db, tracer))\n\tapiRoutes.DELETE(\"/stop\", routes.StopTrace(db, tracer))\n}", "func RegisterRoutes(router *mux.Router, service ServiceInterface) {\n\tsubRouter := router.PathPrefix(\"/v1\").Subrouter()\n\troutes.AddRoutes(newRoutes(service), subRouter)\n}", "func (c *controlAPI) AddRoutes(router *gin.Engine) {\n\trouter.GET(\"/health\", c.CheckHealth)\n\trouter.GET(\"/version\", c.VersionInfo)\n}", "func AddRoutes(app *server.App) {\n\t// Internal routes\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"POST /phone\",\n\t\tType: server.RouteTypeCustom,\n\t\tPublic: true,\n\t\tNoProtoCheck: true,\n\t\tHandler: controllers.PhoneController,\n\t}, server.RouteInternal)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /locked\",\n\t\tType: server.RouteTypeCustom,\n\t\tPublic: true,\n\t\tNoProtoCheck: true,\n\t\tHandler: controllers.LockedController,\n\t}, server.RouteInternal)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /cloud-init/*\",\n\t\tType: server.RouteTypeCustom,\n\t\tPublic: true,\n\t\tNoProtoCheck: true,\n\t\tHandler: controllers.CloudInitController,\n\t}, server.RouteInternal)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /env\",\n\t\tType: server.RouteTypeCustom,\n\t\tPublic: true,\n\t\tNoProtoCheck: true,\n\t\tHandler: controllers.EnvController,\n\t}, server.RouteInternal)\n\n\t// API routes\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /log/history\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.GetLogHistoryController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /log\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.LogController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /vm\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.ListVMsController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /vm/search\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.SearchVMsController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /vm/config/*\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.GetVMConfigController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /vm/infos/*\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.GetVMInfosController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /vm/do-actions/*\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.GetVMDoActionsController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /vm/console/*\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.GetVMConsoleController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"POST /vm\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.NewVMSyncController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"POST /vm-async\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.NewVMAsyncController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"POST /vm/*\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.ActionVMController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"DELETE /vm/*\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.DeleteVMController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /version\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.VersionController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /seed\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.ListSeedController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /seed/*\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.GetSeedStatusController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"POST /seed/*\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.ActionSeedController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /backup\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.ListBackupsController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"POST /backup\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.UploadBackupController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"POST /backup/expire/*\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.SetBackupExpireController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /backup/*\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.DownloadBackupController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"DELETE /backup/*\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.DeleteBackupController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /key\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.ListKeysController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"POST /key\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.NewKeyController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /key/right/*\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.ListKeyRightsController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"POST /key/right/*\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.NewKeyRightController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"DELETE /key/right/*\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.DeleteKeyRightController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /sshpair\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.GetKeyPairController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /status\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.GetStatusController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /state/zip\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.GetStateZipController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /peer\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.ListPeersController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /secret\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.ListSecretsController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /secret/*\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.GetSecretController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"POST /secret/*\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.SetSecretController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"DELETE /secret/*\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.DeleteSecretController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"POST /secret-sync\",\n\t\tHandler: controllers.SyncSecretsController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /vm/with-secret/*\",\n\t\tHandler: controllers.GetVMsUsingSecretsController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"GET /greenhouse\",\n\t\tType: server.RouteTypeCustom,\n\t\tHandler: controllers.ListGreenhouseVMsController,\n\t}, server.RouteAPI)\n\n\tapp.AddRoute(&server.Route{\n\t\tRoute: \"DELETE /greenhouse/*\",\n\t\tType: server.RouteTypeStream,\n\t\tHandler: controllers.AbordGreenhouseVMController,\n\t}, server.RouteAPI)\n\n}", "func (p *proxyAPI) AddRoutes(router *gin.Engine) {\n\trouter.POST(\"/pool\", p.createPool)\n\trouter.DELETE(\"/pool/:poolId\", p.deletePool)\n\trouter.POST(\"/pool/:poolId\", p.addToPool)\n\trouter.DELETE(\"/pool/:poolId/:endpointId\", p.deleteFromPool)\n\trouter.Any(\"/api/:id/*path\", p.proxy)\n\trouter.GET(\"/ws/:id/*path\", p.proxy)\n}", "func RegisterAPIRoute(ginEngine *gin.Engine, controllers []IBaseController) {\n\troutesControllerMapping(ginEngine, controllers)\n}", "func GetpendingInterfaceRoutes(r *mux.Router, i GetpendingInterface) {\n\tr.HandleFunc(\"/getpending\", i.Get).Methods(\"GET\")\n}", "func UsersInterfaceRoutes(r *mux.Router, i UsersInterface) {\n\tr.Handle(\"/users\", alice.New(newOauth2oauth_2_0Middleware([]string{}).Handler).Then(http.HandlerFunc(i.Post))).Methods(\"POST\")\n\tr.Handle(\"/users/{username}/validate\", alice.New(newOauth2oauth_2_0Middleware([]string{}).Handler).Then(http.HandlerFunc(i.usernamevalidateGet))).Methods(\"GET\")\n\tr.Handle(\"/users/{username}/name\", alice.New(newOauth2oauth_2_0Middleware([]string{}).Handler).Then(http.HandlerFunc(i.UpdateName))).Methods(\"PUT\")\n\tr.Handle(\"/users/{username}/password\", alice.New(newOauth2oauth_2_0Middleware([]string{}).Handler).Then(http.HandlerFunc(i.UpdatePassword))).Methods(\"PUT\")\n\tr.Handle(\"/users/{username}/phonenumbers\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.usernamephonenumbersGet))).Methods(\"GET\")\n\tr.Handle(\"/users/{username}/phonenumbers\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.RegisterNewPhonenumber))).Methods(\"POST\")\n\tr.Handle(\"/users/{username}/phonenumbers/{label}\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.usernamephonenumberslabelGet))).Methods(\"GET\")\n\tr.Handle(\"/users/{username}/phonenumbers/{label}\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.UpdatePhonenumber))).Methods(\"PUT\")\n\tr.Handle(\"/users/{username}/phonenumbers/{label}\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.DeletePhonenumber))).Methods(\"DELETE\")\n\tr.Handle(\"/users/{username}/phonenumbers/{label}/validate\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.ValidatePhoneNumber))).Methods(\"POST\")\n\tr.Handle(\"/users/{username}/phonenumbers/{label}/validate\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.VerifyPhoneNumber))).Methods(\"PUT\")\n\tr.Handle(\"/users/{username}/banks\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.usernamebanksGet))).Methods(\"GET\")\n\tr.Handle(\"/users/{username}/banks\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.usernamebanksPost))).Methods(\"POST\")\n\tr.Handle(\"/users/{username}/notifications\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.usernamenotificationsGet))).Methods(\"GET\")\n\tr.Handle(\"/users/{username}\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.usernameGet))).Methods(\"GET\")\n\tr.Handle(\"/users/{username}/apikeys\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.ListAPIKeys))).Methods(\"GET\")\n\tr.Handle(\"/users/{username}/apikeys\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.AddAPIKey))).Methods(\"POST\")\n\tr.Handle(\"/users/{username}/apikeys/{label}\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.GetAPIKey))).Methods(\"GET\")\n\tr.Handle(\"/users/{username}/apikeys/{label}\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.UpdateAPIKey))).Methods(\"PUT\")\n\tr.Handle(\"/users/{username}/apikeys/{label}\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.DeleteAPIKey))).Methods(\"DELETE\")\n\tr.Handle(\"/users/{username}/facebook\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.DeleteFacebookAccount))).Methods(\"DELETE\")\n\tr.Handle(\"/users/{username}/emailaddresses\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.RegisterNewEmailAddress))).Methods(\"POST\")\n\tr.Handle(\"/users/{username}/emailaddresses/{label}\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.UpdateEmailAddress))).Methods(\"PUT\")\n\tr.Handle(\"/users/{username}/emailaddresses/{label}\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.DeleteEmailAddress))).Methods(\"DELETE\")\n\tr.Handle(\"/users/{username}/github\", alice.New(newOauth2oauth_2_0Middleware([]string{}).Handler).Then(http.HandlerFunc(i.DeleteGithubAccount))).Methods(\"DELETE\")\n\tr.Handle(\"/users/{username}/info\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:info\", \"user:admin\"}).Handler).Then(http.HandlerFunc(i.GetUserInformation))).Methods(\"GET\")\n\tr.Handle(\"/users/{username}/addresses\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.usernameaddressesGet))).Methods(\"GET\")\n\tr.Handle(\"/users/{username}/addresses\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.RegisterNewAddress))).Methods(\"POST\")\n\tr.Handle(\"/users/{username}/addresses/{label}\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.usernameaddresseslabelGet))).Methods(\"GET\")\n\tr.Handle(\"/users/{username}/addresses/{label}\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.UpdateAddress))).Methods(\"PUT\")\n\tr.Handle(\"/users/{username}/addresses/{label}\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.DeleteAddress))).Methods(\"DELETE\")\n\tr.Handle(\"/users/{username}/banks/{label}\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.usernamebankslabelGet))).Methods(\"GET\")\n\tr.Handle(\"/users/{username}/banks/{label}\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.usernamebankslabelPut))).Methods(\"PUT\")\n\tr.Handle(\"/users/{username}/banks/{label}\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.usernamebankslabelDelete))).Methods(\"DELETE\")\n\tr.Handle(\"/users/{username}/contracts\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.usernamecontractsGet))).Methods(\"GET\")\n\tr.Handle(\"/users/{username}/authorizations\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.GetAllAuthorizations))).Methods(\"GET\")\n\tr.Handle(\"/users/{username}/authorizations/{grantedTo}\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.GetAuthorization))).Methods(\"GET\")\n\tr.Handle(\"/users/{username}/authorizations/{grantedTo}\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.UpdateAuthorization))).Methods(\"PUT\")\n\tr.Handle(\"/users/{username}/authorizations/{grantedTo}\", alice.New(newOauth2oauth_2_0Middleware([]string{\"user:admin\"}).Handler).Then(http.HandlerFunc(i.DeleteAuthorization))).Methods(\"DELETE\")\n}", "func RegisterAPIRoutes(g *echo.Group, bind context.Binder) {\n\t// Store endpoints first since they are the most active\n\t//e.GET(\"/api/store/\", storeGetView)\n\t//e.POST(\"/api/store/\", storePostView)\n\n\t// TODO Can not register same handler for two different routes\n\t//g = g.Group(\"/store\")\n\t//g.GET(\"/\", storeGetView)\n\t//g.POST(\"/\", storePostView)\n\t// :project_id is [\\w_-]+\n\tg = g.Group(\"/:project_id/store\")\n\tg.GET(\"/\", storeGetView)\n\tg.POST(\"/\", bind.Base(storePostView))\n\t// :project_id is \\d+\n\tg = g.Group(\"/:project_id/csp-report\")\n\t// TODO is CspReportGetView needed?\n\tg.GET(\"/\", cspReportGetView)\n\tg.POST(\"/\", cspReportPostView)\n}", "func (Itfparams) ApiRoutes() []string {\n\treturn []string{\n\t\t\"/api/objects/itfparams/bridge_port/\",\n\t\t\"/api/objects/itfparams/bridge_port/{ref}\",\n\t\t\"/api/objects/itfparams/bridge_port/{ref}/usedby\",\n\t\t\"/api/objects/itfparams/group/\",\n\t\t\"/api/objects/itfparams/group/{ref}\",\n\t\t\"/api/objects/itfparams/group/{ref}/usedby\",\n\t\t\"/api/objects/itfparams/link_aggregation_group/\",\n\t\t\"/api/objects/itfparams/link_aggregation_group/{ref}\",\n\t\t\"/api/objects/itfparams/link_aggregation_group/{ref}/usedby\",\n\t\t\"/api/objects/itfparams/primary/\",\n\t\t\"/api/objects/itfparams/primary/{ref}\",\n\t\t\"/api/objects/itfparams/primary/{ref}/usedby\",\n\t\t\"/api/objects/itfparams/secondary/\",\n\t\t\"/api/objects/itfparams/secondary/{ref}\",\n\t\t\"/api/objects/itfparams/secondary/{ref}/usedby\",\n\t}\n}", "func (this *RouteServiceProvider) mapApiRoutes() {\n\tFacades.Route().Group(map[string]string{\"prefix\": \"api\"}, Routes.Api)\n}", "func (service *Service) RegisterRoutes() {\n\tvar (\n\t\tbaseEndpoint = \"/api/\"\n\t\tconvertEndpoint = baseEndpoint + \"convert\"\n\t\thealthEndpoint = baseEndpoint + \"health\"\n\t)\n\n\tservice.router.GET(healthEndpoint, business.Health)\n\n\t// The snapmatic files usually are less than 1 MB but buffer for 2 just to be safe\n\tservice.router.MaxMultipartMemory = 2 << 20 // 2 MiB\n\tservice.router.POST(convertEndpoint, business.Convert)\n}", "func RegisterAPIRoutes(router *mux.Router) {\n\trouter.HandleFunc(\"/api/v1/word/today/\", GetWordToday).Methods(\"GET\")\n}", "func (RemoteSyslog) ApiRoutes() []string {\n\treturn []string{\n\t\t\"/api/objects/remote_syslog/group/\",\n\t\t\"/api/objects/remote_syslog/group/{ref}\",\n\t\t\"/api/objects/remote_syslog/group/{ref}/usedby\",\n\t\t\"/api/objects/remote_syslog/server/\",\n\t\t\"/api/objects/remote_syslog/server/{ref}\",\n\t\t\"/api/objects/remote_syslog/server/{ref}/usedby\",\n\t}\n}", "func RegisterRoutes(router *mux.Router, service ServiceInterface) {\n\troutes.AddRoutes(newRoutes(service), router)\n}", "func (s *RestServer) AddIPv6FlowBehavioralMetricsAPIRoutes(r *mux.Router) {\n\tr.Methods(\"GET\").Subrouter().HandleFunc(\"/{Meta.Tenant}/{Meta.Name}/\", httputils.MakeHTTPHandler(s.getIPv6FlowBehavioralMetricsHandler))\n\tr.Methods(\"GET\").Subrouter().HandleFunc(\"/\", httputils.MakeHTTPHandler(s.listIPv6FlowBehavioralMetricsHandler))\n}", "func InitAPI() {\n\tBaseRoutes = &Routes{}\n\tBaseRoutes.Root = mux.NewRouter()\n\tBaseRoutes.Root.Handle(\"/\", http.HandlerFunc(indexHandler))\n\tBaseRoutes.Recipe = BaseRoutes.Root.PathPrefix(\"/recipe\").Subrouter()\n\tBaseRoutes.NeedRecipe = BaseRoutes.Recipe.PathPrefix(\"/{recipe-id:[0-9]+}\").Subrouter()\n\tBaseRoutes.Recipes = BaseRoutes.Root.PathPrefix(\"/recipes\").Subrouter()\n\tInitRecipe()\n}", "func AddRoutes(r api.RoomserverInternalAPI, internalAPIMux *mux.Router) {\n\tinternalAPIMux.Handle(RoomserverInputRoomEventsPath,\n\t\thttputil.MakeInternalAPI(\"inputRoomEvents\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.InputRoomEventsRequest\n\t\t\tvar response api.InputRoomEventsResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tr.InputRoomEvents(req.Context(), &request, &response)\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverPerformInvitePath,\n\t\thttputil.MakeInternalAPI(\"performInvite\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformInviteRequest\n\t\t\tvar response api.PerformInviteResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := r.PerformInvite(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverPerformJoinPath,\n\t\thttputil.MakeInternalAPI(\"performJoin\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformJoinRequest\n\t\t\tvar response api.PerformJoinResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tr.PerformJoin(req.Context(), &request, &response)\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverPerformLeavePath,\n\t\thttputil.MakeInternalAPI(\"performLeave\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformLeaveRequest\n\t\t\tvar response api.PerformLeaveResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := r.PerformLeave(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverPerformPeekPath,\n\t\thttputil.MakeInternalAPI(\"performPeek\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformPeekRequest\n\t\t\tvar response api.PerformPeekResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tr.PerformPeek(req.Context(), &request, &response)\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverPerformInboundPeekPath,\n\t\thttputil.MakeInternalAPI(\"performInboundPeek\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformInboundPeekRequest\n\t\t\tvar response api.PerformInboundPeekResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := r.PerformInboundPeek(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverPerformPeekPath,\n\t\thttputil.MakeInternalAPI(\"performUnpeek\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformUnpeekRequest\n\t\t\tvar response api.PerformUnpeekResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tr.PerformUnpeek(req.Context(), &request, &response)\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverPerformRoomUpgradePath,\n\t\thttputil.MakeInternalAPI(\"performRoomUpgrade\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformRoomUpgradeRequest\n\t\t\tvar response api.PerformRoomUpgradeResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tr.PerformRoomUpgrade(req.Context(), &request, &response)\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverPerformPublishPath,\n\t\thttputil.MakeInternalAPI(\"performPublish\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformPublishRequest\n\t\t\tvar response api.PerformPublishResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tr.PerformPublish(req.Context(), &request, &response)\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryPublishedRoomsPath,\n\t\thttputil.MakeInternalAPI(\"queryPublishedRooms\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryPublishedRoomsRequest\n\t\t\tvar response api.QueryPublishedRoomsResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryPublishedRooms(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryLatestEventsAndStatePath,\n\t\thttputil.MakeInternalAPI(\"queryLatestEventsAndState\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryLatestEventsAndStateRequest\n\t\t\tvar response api.QueryLatestEventsAndStateResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryLatestEventsAndState(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryStateAfterEventsPath,\n\t\thttputil.MakeInternalAPI(\"queryStateAfterEvents\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryStateAfterEventsRequest\n\t\t\tvar response api.QueryStateAfterEventsResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryStateAfterEvents(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryEventsByIDPath,\n\t\thttputil.MakeInternalAPI(\"queryEventsByID\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryEventsByIDRequest\n\t\t\tvar response api.QueryEventsByIDResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryEventsByID(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryMembershipForUserPath,\n\t\thttputil.MakeInternalAPI(\"QueryMembershipForUser\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryMembershipForUserRequest\n\t\t\tvar response api.QueryMembershipForUserResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryMembershipForUser(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryMembershipsForRoomPath,\n\t\thttputil.MakeInternalAPI(\"queryMembershipsForRoom\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryMembershipsForRoomRequest\n\t\t\tvar response api.QueryMembershipsForRoomResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryMembershipsForRoom(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryServerJoinedToRoomPath,\n\t\thttputil.MakeInternalAPI(\"queryServerJoinedToRoom\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryServerJoinedToRoomRequest\n\t\t\tvar response api.QueryServerJoinedToRoomResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryServerJoinedToRoom(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryServerAllowedToSeeEventPath,\n\t\thttputil.MakeInternalAPI(\"queryServerAllowedToSeeEvent\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryServerAllowedToSeeEventRequest\n\t\t\tvar response api.QueryServerAllowedToSeeEventResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryServerAllowedToSeeEvent(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryMissingEventsPath,\n\t\thttputil.MakeInternalAPI(\"queryMissingEvents\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryMissingEventsRequest\n\t\t\tvar response api.QueryMissingEventsResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryMissingEvents(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryStateAndAuthChainPath,\n\t\thttputil.MakeInternalAPI(\"queryStateAndAuthChain\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryStateAndAuthChainRequest\n\t\t\tvar response api.QueryStateAndAuthChainResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryStateAndAuthChain(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverPerformBackfillPath,\n\t\thttputil.MakeInternalAPI(\"PerformBackfill\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformBackfillRequest\n\t\t\tvar response api.PerformBackfillResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.PerformBackfill(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverPerformForgetPath,\n\t\thttputil.MakeInternalAPI(\"PerformForget\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformForgetRequest\n\t\t\tvar response api.PerformForgetResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.PerformForget(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryRoomVersionCapabilitiesPath,\n\t\thttputil.MakeInternalAPI(\"QueryRoomVersionCapabilities\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryRoomVersionCapabilitiesRequest\n\t\t\tvar response api.QueryRoomVersionCapabilitiesResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryRoomVersionCapabilities(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverQueryRoomVersionForRoomPath,\n\t\thttputil.MakeInternalAPI(\"QueryRoomVersionForRoom\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryRoomVersionForRoomRequest\n\t\t\tvar response api.QueryRoomVersionForRoomResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.QueryRoomVersionForRoom(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverSetRoomAliasPath,\n\t\thttputil.MakeInternalAPI(\"setRoomAlias\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.SetRoomAliasRequest\n\t\t\tvar response api.SetRoomAliasResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.SetRoomAlias(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverGetRoomIDForAliasPath,\n\t\thttputil.MakeInternalAPI(\"GetRoomIDForAlias\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.GetRoomIDForAliasRequest\n\t\t\tvar response api.GetRoomIDForAliasResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.GetRoomIDForAlias(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverGetCreatorIDForAliasPath,\n\t\thttputil.MakeInternalAPI(\"GetCreatorIDForAlias\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.GetCreatorIDForAliasRequest\n\t\t\tvar response api.GetCreatorIDForAliasResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.GetCreatorIDForAlias(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverGetAliasesForRoomIDPath,\n\t\thttputil.MakeInternalAPI(\"getAliasesForRoomID\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.GetAliasesForRoomIDRequest\n\t\t\tvar response api.GetAliasesForRoomIDResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.GetAliasesForRoomID(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tRoomserverRemoveRoomAliasPath,\n\t\thttputil.MakeInternalAPI(\"removeRoomAlias\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.RemoveRoomAliasRequest\n\t\t\tvar response api.RemoveRoomAliasResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := r.RemoveRoomAlias(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverQueryCurrentStatePath,\n\t\thttputil.MakeInternalAPI(\"queryCurrentState\", func(req *http.Request) util.JSONResponse {\n\t\t\trequest := api.QueryCurrentStateRequest{}\n\t\t\tresponse := api.QueryCurrentStateResponse{}\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := r.QueryCurrentState(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverQueryRoomsForUserPath,\n\t\thttputil.MakeInternalAPI(\"queryRoomsForUser\", func(req *http.Request) util.JSONResponse {\n\t\t\trequest := api.QueryRoomsForUserRequest{}\n\t\t\tresponse := api.QueryRoomsForUserResponse{}\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := r.QueryRoomsForUser(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverQueryBulkStateContentPath,\n\t\thttputil.MakeInternalAPI(\"queryBulkStateContent\", func(req *http.Request) util.JSONResponse {\n\t\t\trequest := api.QueryBulkStateContentRequest{}\n\t\t\tresponse := api.QueryBulkStateContentResponse{}\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := r.QueryBulkStateContent(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverQuerySharedUsersPath,\n\t\thttputil.MakeInternalAPI(\"querySharedUsers\", func(req *http.Request) util.JSONResponse {\n\t\t\trequest := api.QuerySharedUsersRequest{}\n\t\t\tresponse := api.QuerySharedUsersResponse{}\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := r.QuerySharedUsers(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverQueryKnownUsersPath,\n\t\thttputil.MakeInternalAPI(\"queryKnownUsers\", func(req *http.Request) util.JSONResponse {\n\t\t\trequest := api.QueryKnownUsersRequest{}\n\t\t\tresponse := api.QueryKnownUsersResponse{}\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := r.QueryKnownUsers(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverQueryServerBannedFromRoomPath,\n\t\thttputil.MakeInternalAPI(\"queryServerBannedFromRoom\", func(req *http.Request) util.JSONResponse {\n\t\t\trequest := api.QueryServerBannedFromRoomRequest{}\n\t\t\tresponse := api.QueryServerBannedFromRoomResponse{}\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := r.QueryServerBannedFromRoom(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(RoomserverQueryAuthChainPath,\n\t\thttputil.MakeInternalAPI(\"queryAuthChain\", func(req *http.Request) util.JSONResponse {\n\t\t\trequest := api.QueryAuthChainRequest{}\n\t\t\tresponse := api.QueryAuthChainResponse{}\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := r.QueryAuthChain(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n}", "func AddRoutes(intAPI api.FederationInternalAPI, internalAPIMux *mux.Router) {\n\tinternalAPIMux.Handle(\n\t\tFederationAPIQueryJoinedHostServerNamesInRoomPath,\n\t\thttputil.MakeInternalAPI(\"QueryJoinedHostServerNamesInRoom\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryJoinedHostServerNamesInRoomRequest\n\t\t\tvar response api.QueryJoinedHostServerNamesInRoomResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tif err := intAPI.QueryJoinedHostServerNamesInRoom(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIPerformJoinRequestPath,\n\t\thttputil.MakeInternalAPI(\"PerformJoinRequest\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformJoinRequest\n\t\t\tvar response api.PerformJoinResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tintAPI.PerformJoin(req.Context(), &request, &response)\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIPerformLeaveRequestPath,\n\t\thttputil.MakeInternalAPI(\"PerformLeaveRequest\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformLeaveRequest\n\t\t\tvar response api.PerformLeaveResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := intAPI.PerformLeave(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIPerformInviteRequestPath,\n\t\thttputil.MakeInternalAPI(\"PerformInviteRequest\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformInviteRequest\n\t\t\tvar response api.PerformInviteResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := intAPI.PerformInvite(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIPerformDirectoryLookupRequestPath,\n\t\thttputil.MakeInternalAPI(\"PerformDirectoryLookupRequest\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformDirectoryLookupRequest\n\t\t\tvar response api.PerformDirectoryLookupResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := intAPI.PerformDirectoryLookup(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIPerformServersAlivePath,\n\t\thttputil.MakeInternalAPI(\"PerformServersAliveRequest\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformServersAliveRequest\n\t\t\tvar response api.PerformServersAliveResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := intAPI.PerformServersAlive(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIPerformBroadcastEDUPath,\n\t\thttputil.MakeInternalAPI(\"PerformBroadcastEDU\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.PerformBroadcastEDURequest\n\t\t\tvar response api.PerformBroadcastEDUResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := intAPI.PerformBroadcastEDU(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIGetUserDevicesPath,\n\t\thttputil.MakeInternalAPI(\"GetUserDevices\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request getUserDevices\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.GetUserDevices(req.Context(), request.S, request.UserID)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.Res = &res\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIClaimKeysPath,\n\t\thttputil.MakeInternalAPI(\"ClaimKeys\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request claimKeys\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.ClaimKeys(req.Context(), request.S, request.OneTimeKeys)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.Res = &res\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIQueryKeysPath,\n\t\thttputil.MakeInternalAPI(\"QueryKeys\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request queryKeys\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.QueryKeys(req.Context(), request.S, request.Keys)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.Res = &res\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIBackfillPath,\n\t\thttputil.MakeInternalAPI(\"Backfill\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request backfill\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.Backfill(req.Context(), request.S, request.RoomID, request.Limit, request.EventIDs)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.Res = &res\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPILookupStatePath,\n\t\thttputil.MakeInternalAPI(\"LookupState\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request lookupState\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.LookupState(req.Context(), request.S, request.RoomID, request.EventID, request.RoomVersion)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.Res = &res\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPILookupStateIDsPath,\n\t\thttputil.MakeInternalAPI(\"LookupStateIDs\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request lookupStateIDs\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.LookupStateIDs(req.Context(), request.S, request.RoomID, request.EventID)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.Res = &res\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPILookupMissingEventsPath,\n\t\thttputil.MakeInternalAPI(\"LookupMissingEvents\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request lookupMissingEvents\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.LookupMissingEvents(req.Context(), request.S, request.RoomID, request.Missing, request.RoomVersion)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, event := range res.Events {\n\t\t\t\tjs, err := json.Marshal(event)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn util.MessageResponse(http.StatusInternalServerError, err.Error())\n\t\t\t\t}\n\t\t\t\trequest.Res.Events = append(request.Res.Events, js)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIGetEventPath,\n\t\thttputil.MakeInternalAPI(\"GetEvent\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request getEvent\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.GetEvent(req.Context(), request.S, request.EventID)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.Res = &res\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIGetEventAuthPath,\n\t\thttputil.MakeInternalAPI(\"GetEventAuth\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request getEventAuth\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.GetEventAuth(req.Context(), request.S, request.RoomVersion, request.RoomID, request.EventID)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.Res = &res\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIQueryServerKeysPath,\n\t\thttputil.MakeInternalAPI(\"QueryServerKeys\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request api.QueryServerKeysRequest\n\t\t\tvar response api.QueryServerKeysResponse\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := intAPI.QueryServerKeys(req.Context(), &request, &response); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPILookupServerKeysPath,\n\t\thttputil.MakeInternalAPI(\"LookupServerKeys\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request lookupServerKeys\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.LookupServerKeys(req.Context(), request.S, request.KeyRequests)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.ServerKeys = res\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPIEventRelationshipsPath,\n\t\thttputil.MakeInternalAPI(\"MSC2836EventRelationships\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request eventRelationships\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.MSC2836EventRelationships(req.Context(), request.S, request.Req, request.RoomVer)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.Res = res\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(\n\t\tFederationAPISpacesSummaryPath,\n\t\thttputil.MakeInternalAPI(\"MSC2946SpacesSummary\", func(req *http.Request) util.JSONResponse {\n\t\t\tvar request spacesReq\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tres, err := intAPI.MSC2946Spaces(req.Context(), request.S, request.RoomID, request.SuggestedOnly)\n\t\t\tif err != nil {\n\t\t\t\tferr, ok := err.(*api.FederationClientError)\n\t\t\t\tif ok {\n\t\t\t\t\trequest.Err = ferr\n\t\t\t\t} else {\n\t\t\t\t\trequest.Err = &api.FederationClientError{\n\t\t\t\t\t\tErr: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.Res = res\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: request}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(FederationAPIQueryPublicKeyPath,\n\t\thttputil.MakeInternalAPI(\"queryPublicKeys\", func(req *http.Request) util.JSONResponse {\n\t\t\trequest := api.QueryPublicKeysRequest{}\n\t\t\tresponse := api.QueryPublicKeysResponse{}\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tkeys, err := intAPI.FetchKeys(req.Context(), request.Requests)\n\t\t\tif err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\tresponse.Results = keys\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n\tinternalAPIMux.Handle(FederationAPIInputPublicKeyPath,\n\t\thttputil.MakeInternalAPI(\"inputPublicKeys\", func(req *http.Request) util.JSONResponse {\n\t\t\trequest := api.InputPublicKeysRequest{}\n\t\t\tresponse := api.InputPublicKeysResponse{}\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&request); err != nil {\n\t\t\t\treturn util.MessageResponse(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t\tif err := intAPI.StoreKeys(req.Context(), request.Keys); err != nil {\n\t\t\t\treturn util.ErrorResponse(err)\n\t\t\t}\n\t\t\treturn util.JSONResponse{Code: http.StatusOK, JSON: &response}\n\t\t}),\n\t)\n}", "func (service *ImageService) registerRoutes() {\n\t// We need a router to extract IDs for expiring links and image fetching.\n\tr := mux.NewRouter()\n\tamw := AuthMiddleware{\n\t\taccessToken: service.accessToken,\n\t}\n\n\tephemeralEndpoint := fmt.Sprintf(\"%s/{id}\", service.uploadLinkPrefix)\n\tr.HandleFunc(ephemeralEndpoint, service.handleImageUpload).Methods(\"POST\")\n\tr.HandleFunc(\"/images/{id}\", service.fetchImage).Methods(\"GET\")\n\n\t// Endpoints that require an access token are behind the auth middleware.\n\ts := r.PathPrefix(\"/admin\").Subrouter()\n\ts.Use(amw.Middleware)\n\n\ts.HandleFunc(\"/ephemeral-links\", service.handleLinkCreation).Methods(\"POST\")\n\ts.HandleFunc(\"/stats\", service.fetchStats).Methods(\"GET\")\n\n\thttp.Handle(\"/\", r)\n}", "func (Snmp) ApiRoutes() []string {\n\treturn []string{\n\t\t\"/api/objects/snmp/group/\",\n\t\t\"/api/objects/snmp/group/{ref}\",\n\t\t\"/api/objects/snmp/group/{ref}/usedby\",\n\t\t\"/api/objects/snmp/trap/\",\n\t\t\"/api/objects/snmp/trap/{ref}\",\n\t\t\"/api/objects/snmp/trap/{ref}/usedby\",\n\t}\n}", "func (s *RestServer) AddIPv4FlowBehavioralMetricsAPIRoutes(r *mux.Router) {\n\tr.Methods(\"GET\").Subrouter().HandleFunc(\"/{Meta.Tenant}/{Meta.Name}/\", httputils.MakeHTTPHandler(s.getIPv4FlowBehavioralMetricsHandler))\n\tr.Methods(\"GET\").Subrouter().HandleFunc(\"/\", httputils.MakeHTTPHandler(s.listIPv4FlowBehavioralMetricsHandler))\n}", "func (r *RestRouter) Add(s restinterface.IRestRoutes) {\n\tr.add(s.GetRoutes())\n}", "func (s *RestServer) AddIPv6FlowPerformanceMetricsAPIRoutes(r *mux.Router) {\n\tr.Methods(\"GET\").Subrouter().HandleFunc(\"/{Meta.Tenant}/{Meta.Name}/\", httputils.MakeHTTPHandler(s.getIPv6FlowPerformanceMetricsHandler))\n\tr.Methods(\"GET\").Subrouter().HandleFunc(\"/\", httputils.MakeHTTPHandler(s.listIPv6FlowPerformanceMetricsHandler))\n}", "func (Http) ApiRoutes() []string {\n\treturn []string{\n\t\t\"/api/objects/http/cff_action/\",\n\t\t\"/api/objects/http/cff_action/{ref}\",\n\t\t\"/api/objects/http/cff_action/{ref}/usedby\",\n\t\t\"/api/objects/http/cff_profile/\",\n\t\t\"/api/objects/http/cff_profile/{ref}\",\n\t\t\"/api/objects/http/cff_profile/{ref}/usedby\",\n\t\t\"/api/objects/http/device_auth/\",\n\t\t\"/api/objects/http/device_auth/{ref}\",\n\t\t\"/api/objects/http/device_auth/{ref}/usedby\",\n\t\t\"/api/objects/http/domain_regex/\",\n\t\t\"/api/objects/http/domain_regex/{ref}\",\n\t\t\"/api/objects/http/domain_regex/{ref}/usedby\",\n\t\t\"/api/objects/http/exception/\",\n\t\t\"/api/objects/http/exception/{ref}\",\n\t\t\"/api/objects/http/exception/{ref}/usedby\",\n\t\t\"/api/objects/http/group/\",\n\t\t\"/api/objects/http/group/{ref}\",\n\t\t\"/api/objects/http/group/{ref}/usedby\",\n\t\t\"/api/objects/http/local_site/\",\n\t\t\"/api/objects/http/local_site/{ref}\",\n\t\t\"/api/objects/http/local_site/{ref}/usedby\",\n\t\t\"/api/objects/http/lsl_tag/\",\n\t\t\"/api/objects/http/lsl_tag/{ref}\",\n\t\t\"/api/objects/http/lsl_tag/{ref}/usedby\",\n\t\t\"/api/objects/http/pac_file/\",\n\t\t\"/api/objects/http/pac_file/{ref}\",\n\t\t\"/api/objects/http/pac_file/{ref}/usedby\",\n\t\t\"/api/objects/http/parent_proxy/\",\n\t\t\"/api/objects/http/parent_proxy/{ref}\",\n\t\t\"/api/objects/http/parent_proxy/{ref}/usedby\",\n\t\t\"/api/objects/http/profile/\",\n\t\t\"/api/objects/http/profile/{ref}\",\n\t\t\"/api/objects/http/profile/{ref}/usedby\",\n\t\t\"/api/objects/http/sp_category/\",\n\t\t\"/api/objects/http/sp_category/{ref}\",\n\t\t\"/api/objects/http/sp_category/{ref}/usedby\",\n\t\t\"/api/objects/http/sp_subcat/\",\n\t\t\"/api/objects/http/sp_subcat/{ref}\",\n\t\t\"/api/objects/http/sp_subcat/{ref}/usedby\",\n\t}\n}", "func (h *WorkloadHandler) AddRoutes(e *gin.Engine) {\n\te.GET(WorkloadRoot, h.Get)\n}", "func (r *Router) AddRoutes(apiGroup string, routes []*Route) {\n\tklog.V(3).Infof(\"load apiGroup:%s\", apiGroup)\n\tfor _, route := range routes {\n\t\tswitch route.Method {\n\t\tcase \"GET\":\n\t\t\tr.GET(route.Path, route.Handler)\n\t\tcase \"POST\":\n\t\t\tr.POST(route.Path, route.Handler)\n\t\tcase \"DELETE\":\n\t\t\tr.DELETE(route.Path, route.Handler)\n\t\tcase \"Any\":\n\t\t\tr.Any(route.Path, route.Handler)\n\t\tdefault:\n\t\t\tklog.Warningf(\"no method:%s apiGroup:%s\", route.Method, apiGroup)\n\t\t}\n\t}\n\n\tif _, ok := r.Routes[apiGroup]; !ok {\n\t\tr.Routes[apiGroup] = routes\n\t}\n\n\tif apiGroup == \"health\" {\n\t\tr.AddProfile(\"GET\", LivePath, `liveness check: <br/>\n\t\t\t<a href=\"/live?full=true\"> query the full body`)\n\t\tr.AddProfile(\"GET\", ReadyPath, `readyness check: <br/>\n\t\t\t<a href=\"/ready?full=true\"> query the full body`)\n\t\tr.AddProfile(\"GET\", VersionPath, `version describe: <br/>\n <a href=\"/version\"> query version info`)\n\t} else if apiGroup == \"cluster\" {\n\t\tfor _, route := range routes {\n\t\t\tvar desc string\n\t\t\tif route.Desc == \"\" {\n\t\t\t\tdesc = fmt.Sprintf(\"name: the unique cluster name and all <br/> appName: the unique app name\")\n\t\t\t} else {\n\t\t\t\tdesc = route.Desc\n\t\t\t}\n\t\t\tr.AddProfile(route.Method, route.Path, desc)\n\t\t}\n\t}\n}", "func AddRoutes(app *fiber.App) {\n\tapp.Static(\"/\", \"./public\")\n\tapp.Get(\"/ws/status\", websocket.New(StatusWSView))\n\n\tapp.Put(\"/flight\", CreateFlightView)\n\tapp.Delete(\"/flight/:route\", DeleteFlightView)\n\tapp.Put(\"/flights/import/csv\", ImportFlightsView)\n\tapp.Get(\"/flights/search/:route\", CheapestRouteView)\n\n\tapp.Use(NotFoundView)\n}", "func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) {\n\t// this line is used by starport scaffolding # 1\n\tr.HandleFunc(\"/nym/gateway\", createGatewayHandler(cliCtx)).Methods(\"POST\")\n\tr.HandleFunc(\"/nym/gateway\", listGatewayHandler(cliCtx, \"nym\")).Methods(\"GET\")\n\tr.HandleFunc(\"/nym/gateway/{key}\", getGatewayHandler(cliCtx, \"nym\")).Methods(\"GET\")\n\tr.HandleFunc(\"/nym/gateway\", setGatewayHandler(cliCtx)).Methods(\"PUT\")\n\tr.HandleFunc(\"/nym/gateway\", deleteGatewayHandler(cliCtx)).Methods(\"DELETE\")\n\n\tr.HandleFunc(\"/nym/mixnode\", createMixnodeHandler(cliCtx)).Methods(\"POST\")\n\tr.HandleFunc(\"/nym/mixnode\", listMixnodeHandler(cliCtx, \"nym\")).Methods(\"GET\")\n\tr.HandleFunc(\"/nym/mixnode/{key}\", getMixnodeHandler(cliCtx, \"nym\")).Methods(\"GET\")\n\tr.HandleFunc(\"/nym/mixnode\", setMixnodeHandler(cliCtx)).Methods(\"PUT\")\n\tr.HandleFunc(\"/nym/mixnode\", deleteMixnodeHandler(cliCtx)).Methods(\"DELETE\")\n\n}", "func (s *server) RegisterRoutes(ws *web.Server) {\n\tfor _, subsystem := range s.handlers {\n\t\tif subsystem, ok := subsystem.(web.Registerer); ok {\n\t\t\tsubsystem.RegisterRoutes(ws)\n\t\t}\n\t}\n}", "func RegisterHandlers(router EchoRouter, si ServerInterface) {\n\n\twrapper := ServerInterfaceWrapper{\n\t\tHandler: si,\n\t}\n\n\trouter.GET(\"/gateways\", wrapper.ListGateways)\n\trouter.POST(\"/gateways\", wrapper.PostGateways)\n\trouter.PUT(\"/gateways\", wrapper.PutGateways)\n\trouter.DELETE(\"/gateways/:gatewayId\", wrapper.DeleteGatewayById)\n\trouter.GET(\"/gateways/:gatewayId\", wrapper.GetGatewayById)\n\trouter.PUT(\"/gateways/:gatewayId\", wrapper.PutGatewayById)\n\trouter.GET(\"/gateways/:gatewayId/endpoint\", wrapper.GetGatewayEndpoint1)\n\n}", "func (a *API) RegisterRoutes(r *mux.Router) {\n\tfor _, route := range []struct {\n\t\tname, method, path string\n\t\thandler http.HandlerFunc\n\t}{\n\t\t{\"get_config\", \"GET\", \"/api/v1/config\", a.getConfig},\n\t\t{\"set_config\", \"POST\", \"/api/v1/config\", a.setConfig},\n\t\t{\"deactivate_config\", \"DELETE\", \"/api/v1/config/deactivate\", a.deactivateConfig},\n\t\t{\"restore_config\", \"POST\", \"/api/v1/config/restore\", a.restoreConfig},\n\t} {\n\t\tr.Handle(route.path, route.handler).Methods(route.method).Name(route.name)\n\t}\n}", "func (r apiV1Router) RegisterRoutes(routerGroup *gin.RouterGroup) {\n\trouterGroup.GET(\"/\", r.Heartbeat)\n\n\tshopsGroup := routerGroup.Group(\"/shops\")\n\tshopsGroup.GET(\"/\", r.GetAllShops)\n\tshopsGroup.GET(\"/nearby\", r.GetNearbyShops)\n\n\titemGroupsGroup := routerGroup.Group(\"/itemgroups\")\n\titemGroupsGroup.GET(\"/\", r.GetItemGroups)\n}", "func RouteRootApis(acc *echo.Group, res *echo.Group, session *mgo.Session) {\n\n\t// instantiate new root controller\n\trootController := controllerv1.RootController{}\n\n\t// get resources home address\n\tacc.GET(\"/assethome\", rootController.GetAssetHomePath)\n}", "func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) {\n\tr.HandleFunc(\"/billboard/advertisement\", listAdvertisementHandler(cliCtx, \"billboard\")).Methods(\"GET\")\n\tr.HandleFunc(\"/billboard/advertisement/{key}\", getAdvertisementHandler(cliCtx, \"billboard\")).Methods(\"GET\")\n\n}", "func RegisterRoutes() {\n\t// API endpoint for getting a list of recent screenshot hashes.\n\tshared.AddRoute(\"/api/screenshots/hashes\", \"api-screenshots-hashes\",\n\t\tshared.WrapApplicationJSON(getHashesHandler))\n\n\t// PRIVATE API endpoint for creating a screenshot.\n\t// Only this AppEngine project can access.\n\tshared.AddRoute(\"/api/screenshots/upload\", \"api-screenshots-upload\", uploadScreenshotHandler)\n}", "func RegisterRoutes(router *gin.RouterGroup, logger lumber.Logger) {\n\trouter.GET(\"/hello\", middleware.Authentication(), versionedHello)\n\trouter.GET(\"/getAccounts\", controller.GetAccounts)\n\tlogger.Infof(\"v1.0 routes injected\")\n}", "func InitRoutes(router *gin.RouterGroup) {\n\trouter.GET(\":type/:id\", handler.GetIdentifiers)\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 registerRoutes(rs *lcd.RestServer) {\n\tregisterSwaggerUI(rs)\n\tclient.RegisterRoutes(rs.CliCtx, rs.Mux)\n\tauthrest.RegisterTxRoutes(rs.CliCtx, rs.Mux)\n\tapp.ModuleBasics.RegisterRESTRoutes(rs.CliCtx, rs.Mux)\n}", "func RegisterHandlers(router EchoRouter, si ServerInterface) {\n\n\twrapper := ServerInterfaceWrapper{\n\t\tHandler: si,\n\t}\n\n\trouter.GET(\"/v1/api/claims\", wrapper.GetClaims)\n\trouter.POST(\"/v1/api/claims\", wrapper.CreateClaim)\n\trouter.GET(\"/v1/api/claims/find\", wrapper.FindClaimByName)\n\trouter.DELETE(\"/v1/api/claims/:id\", wrapper.DeleteClaim)\n\trouter.GET(\"/v1/api/claims/:id\", wrapper.GetClaim)\n\trouter.PUT(\"/v1/api/claims/:id\", wrapper.UpdateClaim)\n\trouter.GET(\"/v1/api/scopes\", wrapper.GetScopes)\n\trouter.POST(\"/v1/api/scopes\", wrapper.CreateScope)\n\trouter.GET(\"/v1/api/scopes/find\", wrapper.FindScopeByName)\n\trouter.DELETE(\"/v1/api/scopes/:id\", wrapper.DeleteScope)\n\trouter.GET(\"/v1/api/scopes/:id\", wrapper.GetScope)\n\trouter.PUT(\"/v1/api/scopes/:id\", wrapper.UpdateScope)\n\trouter.POST(\"/v1/api/scopes/:id/claim\", wrapper.AddClaimToScope)\n\trouter.DELETE(\"/v1/api/scopes/:id/claim/:claimId\", wrapper.RemoveClaimFromScope)\n\trouter.GET(\"/v1/api/secretchannels\", wrapper.GetSecretChannels)\n\trouter.POST(\"/v1/api/secretchannels\", wrapper.CreateSecretChannel)\n\trouter.GET(\"/v1/api/secretchannels/find/algouse\", wrapper.FindSecretChannelByAlgouse)\n\trouter.GET(\"/v1/api/secretchannels/find/name\", wrapper.FindSecretChannelByName)\n\trouter.DELETE(\"/v1/api/secretchannels/:id\", wrapper.DeleteSecretChannel)\n\trouter.GET(\"/v1/api/secretchannels/:id\", wrapper.GetSecretChannel)\n\trouter.POST(\"/v1/api/secretchannels/:id\", wrapper.RenewSecretChannel)\n\trouter.GET(\"/v1/api/serviceproviders\", wrapper.GetServiceProviders)\n\trouter.POST(\"/v1/api/serviceproviders\", wrapper.CreateServiceProvider)\n\trouter.GET(\"/v1/api/serviceproviders/find\", wrapper.FindServiceProvider)\n\trouter.DELETE(\"/v1/api/serviceproviders/:id\", wrapper.DeleteServiceProvider)\n\trouter.GET(\"/v1/api/serviceproviders/:id\", wrapper.GetServiceProvider)\n\trouter.PATCH(\"/v1/api/serviceproviders/:id\", wrapper.PatchServiceProvider)\n\trouter.PUT(\"/v1/api/serviceproviders/:id\", wrapper.UpdateServiceProvider)\n\trouter.GET(\"/v1/api/serviceproviders/:id/credentials\", wrapper.GetCredentials)\n\trouter.POST(\"/v1/api/serviceproviders/:id/credentials\", wrapper.GenerateCredentials)\n\trouter.POST(\"/v1/api/serviceproviders/:id/status\", wrapper.UpdateServiceProviderStatus)\n\trouter.GET(\"/v1/api/users\", wrapper.GetUsers)\n\trouter.POST(\"/v1/api/users\", wrapper.CreateUser)\n\trouter.GET(\"/v1/api/users/find\", wrapper.FindUser)\n\trouter.POST(\"/v1/api/users/recover/password\", wrapper.InitiatePasswordRecovery)\n\trouter.PUT(\"/v1/api/users/recover/password\", wrapper.ResetUserPassword)\n\trouter.DELETE(\"/v1/api/users/:id\", wrapper.DeleteUser)\n\trouter.GET(\"/v1/api/users/:id\", wrapper.GetUser)\n\trouter.PUT(\"/v1/api/users/:id\", wrapper.UpdateUser)\n\trouter.POST(\"/v1/api/users/:id/password\", wrapper.ChangeUserPassword)\n\trouter.POST(\"/v1/api/users/:id/status\", wrapper.UpdateUserStatus)\n\n}", "func (e *Endpoint) RegisterRoutes(r gin.IRoutes) {\n\tr.POST(\"/github\", e.rateLimiter.Handler(), e.CreateGithubIssue)\n\tr.POST(\"/intercom\", e.rateLimiter.Handler(), e.CreateIntercomIssue)\n}", "func InterfacesHandler(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tT, _ := i18n.Tfunc(\"en-US\")\n\n\t// Build the snapd REST API URL\n\tconst serviceInterfacesURL = \"/v2/interfaces\"\n\tbaseURL := url.URL{Scheme: \"http\", Host: \"localhost\", Path: serviceInterfacesURL}\n\n\ttr := &http.Transport{\n\t\tDial: snapdDialer,\n\t}\n\tclient := &http.Client{Transport: tr}\n\n\tresp, err := client.Get(baseURL.String())\n\tif err != nil {\n\t\tlogMessage(\"interfaces\", \"snapd-url\", err.Error())\n\t\tresponse := ErrorResponse{Type: \"error\", Status: \"Internal Error\", StatusCode: 404, Result: T(\"application_error\")}\n\t\t// Encode the response as JSON\n\t\tif err := json.NewEncoder(w).Encode(response); err != nil {\n\t\t\tlog.Println(\"Error forming the error response.\")\n\t\t}\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlogMessage(\"interfaces\", \"snapd-response\", err.Error())\n\t\tresponse := ErrorResponse{Type: \"error\", Status: \"Not Found\", StatusCode: 404, Result: T(\"unknown\")}\n\t\t// Encode the response as JSON\n\t\tif err := json.NewEncoder(w).Encode(response); err != nil {\n\t\t\tlog.Println(\"Error forming the error response.\")\n\t\t}\n\t\treturn\n\t}\n\n\tfmt.Fprint(w, string(body))\n}", "func (h *Handler) serveInterfaces(w http.ResponseWriter, r *http.Request) {}", "func (s *RestServer) AddIPv6FlowRawMetricsAPIRoutes(r *mux.Router) {\n\tr.Methods(\"GET\").Subrouter().HandleFunc(\"/{Meta.Tenant}/{Meta.Name}/\", httputils.MakeHTTPHandler(s.getIPv6FlowRawMetricsHandler))\n\tr.Methods(\"GET\").Subrouter().HandleFunc(\"/\", httputils.MakeHTTPHandler(s.listIPv6FlowRawMetricsHandler))\n}", "func (s *RestServer) AddL2FlowBehavioralMetricsAPIRoutes(r *mux.Router) {\n\tr.Methods(\"GET\").Subrouter().HandleFunc(\"/{Meta.Tenant}/{Meta.Name}/\", httputils.MakeHTTPHandler(s.getL2FlowBehavioralMetricsHandler))\n\tr.Methods(\"GET\").Subrouter().HandleFunc(\"/\", httputils.MakeHTTPHandler(s.listL2FlowBehavioralMetricsHandler))\n}", "func (h *StaticHandler) AddRoutes(apply func(m, p string, h http.Handler, mws ...func(http.Handler) http.Handler)) {\n\tfileServer := http.FileServer(h.fs)\n\tapply(http.MethodGet, \"/*filepath\", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tr.URL.Path = routegroup.PathParam(r.Context(), \"filepath\")\n\t\tfileServer.ServeHTTP(w, r)\n\t}))\n}", "func (h *StorageClassHandler) AddRoutes(e *gin.Engine) {\n\te.GET(StorageClassesRoot, h.List)\n\te.GET(StorageClassesRoot+\"/\", h.List)\n\te.GET(StorageClassRoot, h.Get)\n}", "func AddRoutingUrls(router *gin.Engine) {\n\trouter.GET(\"/ping\", api.Ping)\n\trouter.GET(\"/ipinformation\", api.IpInfo)\n}", "func RegisterHandlers(router EchoRouter, si ServerInterface) {\n\n\twrapper := ServerInterfaceWrapper{\n\t\tHandler: si,\n\t}\n\n\trouter.GET(\"/architectures/:distribution\", wrapper.GetArchitectures)\n\trouter.POST(\"/compose\", wrapper.ComposeImage)\n\trouter.GET(\"/composes\", wrapper.GetComposes)\n\trouter.GET(\"/composes/:composeId\", wrapper.GetComposeStatus)\n\trouter.GET(\"/composes/:composeId/metadata\", wrapper.GetComposeMetadata)\n\trouter.GET(\"/distributions\", wrapper.GetDistributions)\n\trouter.GET(\"/openapi.json\", wrapper.GetOpenapiJson)\n\trouter.GET(\"/packages\", wrapper.GetPackages)\n\trouter.GET(\"/ready\", wrapper.GetReadiness)\n\trouter.GET(\"/version\", wrapper.GetVersion)\n\n}", "func (a *FrinxLoggingApiService) PutFrinxLoggingLoggingInterfacesInterface(ctx context.Context, interfaceId string, frinxLoggingLogginginterfacesstructuralInterfacesInterfaceBodyParam FrinxLoggingLogginginterfacesstructuralInterfacesInterfaceRequest, 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-logging:logging/frinx-logging:interfaces/frinx-logging:interface/{interface-id}/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"interface-id\"+\"}\", fmt.Sprintf(\"%v\", interfaceId), -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 = &frinxLoggingLogginginterfacesstructuralInterfacesInterfaceBodyParam\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 *RestServer) AddIPv4FlowPerformanceMetricsAPIRoutes(r *mux.Router) {\n\tr.Methods(\"GET\").Subrouter().HandleFunc(\"/{Meta.Tenant}/{Meta.Name}/\", httputils.MakeHTTPHandler(s.getIPv4FlowPerformanceMetricsHandler))\n\tr.Methods(\"GET\").Subrouter().HandleFunc(\"/\", httputils.MakeHTTPHandler(s.listIPv4FlowPerformanceMetricsHandler))\n}", "func RegisterGroupAPIRoute(basePath string, ginEngine *gin.Engine, controllers []IBaseController) {\n\tif !strings.HasPrefix(basePath, \"/\") {\n\t\tbasePath = \"/\" + basePath\n\t}\n\tg := ginEngine.Group(basePath)\n\t{\n\t\troutesControllerMapping(g, controllers)\n\t}\n}", "func (s *RestServer) AddIPv6FlowDropMetricsAPIRoutes(r *mux.Router) {\n\tr.Methods(\"GET\").Subrouter().HandleFunc(\"/{Meta.Tenant}/{Meta.Name}/\", httputils.MakeHTTPHandler(s.getIPv6FlowDropMetricsHandler))\n\tr.Methods(\"GET\").Subrouter().HandleFunc(\"/\", httputils.MakeHTTPHandler(s.listIPv6FlowDropMetricsHandler))\n}", "func (a *FrinxOpenconfigIfIpApiService) PutFrinxOpenconfigInterfacesInterfacesInterfaceRoutedVlanIpv4UnnumberedInterfaceRef(ctx context.Context, name string, frinxOpenconfigInterfacesInterfacerefInterfaceRefBodyParam FrinxOpenconfigInterfacesInterfacerefInterfaceRefRequest6, 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-interfaces:interfaces/frinx-openconfig-interfaces:interface/{name}/frinx-openconfig-vlan:routed-vlan/frinx-openconfig-if-ip:ipv4/frinx-openconfig-if-ip:unnumbered/frinx-openconfig-if-ip:interface-ref/\"\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 = &frinxOpenconfigInterfacesInterfacerefInterfaceRefBodyParam\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 *App) InitRoutes() {\n\ta.Router = mux.NewRouter()\n\n\tsrv := handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: &graph.Resolver{Service: a.Service}}))\n\ta.Router.Handle(\"/playground\", playground.Handler(\"GoNeo4jGql GraphQL playground\", \"/movies\"))\n\ta.Router.Handle(\"/movies\", srv)\n}", "func RegisterRoutes(ctx context.CLIContext, r *mux.Router, cdc *wire.Codec, kb keys.Keybase, storeName string) {\n\tr.HandleFunc(\"/assets\", createAssetHandlerFn(ctx, cdc, kb)).Methods(\"POST\")\n\tr.HandleFunc(\"/assets/{id}\", queryAssetRequestHandlerFn(ctx, storeName, cdc)).Methods(\"GET\")\n\tr.HandleFunc(\"/assets/{id}/owners/history\", queryHistoryOwnersHandlerFn(ctx, cdc)).Methods(\"GET\")\n\tr.HandleFunc(\"/assets/{id}/txs\", assetTxsHandlerFn(ctx, storeName, cdc)).Methods(\"GET\")\n\tr.HandleFunc(\"/assets/{id}/children\", queryAssetChildrensHandlerFn(ctx, storeName, cdc, kb)).Methods(\"GET\")\n\tr.HandleFunc(\"/assets/{id}/add\", addAssetQuantityHandlerFn(ctx, cdc, kb)).Methods(\"POST\")\n\tr.HandleFunc(\"/assets/{id}/subtract\", subtractQuantityBodyHandlerFn(ctx, cdc, kb)).Methods(\"POST\")\n\tr.HandleFunc(\"/assets/{id}/properties\", updateAttributeHandlerFn(ctx, cdc, kb)).Methods(\"POST\")\n\tr.HandleFunc(\"/assets/{id}/properties/{name}/history\", queryHistoryUpdatePropertiesHandlerFn(ctx, cdc)).Methods(\"GET\")\n\tr.HandleFunc(\"/assets/{id}/materials\", addMaterialsHandlerFn(ctx, cdc, kb)).Methods(\"POST\")\n\tr.HandleFunc(\"/assets/{id}/materials/history\", queryHistoryTransferMaterialsHandlerFn(ctx, cdc)).Methods(\"GET\")\n\tr.HandleFunc(\"/assets/{id}/finalize\", finalizeHandlerFn(ctx, cdc, kb)).Methods(\"POST\")\n\tr.HandleFunc(\"/assets/{id}/reporters/{address}/revoke\", revokeReporterHandlerFn(ctx, cdc, kb)).Methods(\"POST\")\n\tr.HandleFunc(\"/assets/{id}/proposals\", createProposalHandlerFn(ctx, cdc, kb)).Methods(\"POST\")\n\tr.HandleFunc(\"/assets/{id}/proposals\", queryProposalsHandlerFn(ctx, storeName, cdc, kb)).Methods(\"GET\")\n\tr.HandleFunc(\"/assets/{id}/proposals/{recipient}/answer\", answerProposalHandlerFn(ctx, cdc, kb)).Methods(\"POST\")\n\tr.HandleFunc(\"/accounts/{address}/assets\", queryAccountAssetsHandlerFn(ctx, storeName, cdc, kb)).Methods(\"GET\")\n\tr.HandleFunc(\"/accounts/{address}/proposals\", queryAccountProposalsHandlerFn(ctx, storeName, cdc, kb)).Methods(\"GET\")\n\tr.HandleFunc(\"/accounts/{address}/report-assets\", queryReporterAssetsHandlerFn(ctx, storeName, cdc, kb)).Methods(\"GET\")\n\n}", "func (res *Resource) addRoute(method string, route string) {\n\tres.Routes = append(res.Routes, fmt.Sprintf(\"%s - /%s%s\", method, res.Type, route))\n}", "func (Spx) ApiRoutes() []string {\n\treturn []string{\n\t\t\"/api/objects/spx/group/\",\n\t\t\"/api/objects/spx/group/{ref}\",\n\t\t\"/api/objects/spx/group/{ref}/usedby\",\n\t\t\"/api/objects/spx/template/\",\n\t\t\"/api/objects/spx/template/{ref}\",\n\t\t\"/api/objects/spx/template/{ref}/usedby\",\n\t}\n}", "func registerRoutes() {\n\tuserRoutes()\n\troleRoutes()\n}", "func (myAPI API) CreateRoutes(route ...api.Route) {\n\tfor _, myRoute := range route {\n\t\tif len(myRoute.Methods) > 0 {\n\t\t\tmyAPI.router.HandleFunc(myRoute.Path, myRoute.Handler).Methods(myRoute.Methods...)\n\t\t} else {\n\t\t\tmyAPI.router.HandleFunc(myRoute.Path, myRoute.Handler)\n\t\t}\n\t}\n}", "func RegisterAPI(r *mux.Router) {\n\tsr := r.PathPrefix(\"/api\").Subrouter().StrictSlash(true)\n\n\t// Handle invalid paths\n\tsr.NotFoundHandler = setupAPICall(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tw.WriteHeader(404)\n\t\tw.Write([]byte(`{\"message\": \"Not Found\"}`))\n\t}))\n\n\t// Root path\n\tsr.Handle(\"\", setupAPICall(http.HandlerFunc(apiHandler))).Methods(\"GET\")\n\tsr.Handle(\"\", setupAPICall(http.HandlerFunc(notAllowed))).Methods(\"POST\", \"PUT\", \"PATCH\", \"DELETE\")\n\n\t// Host\n\tsr.Handle(\"/host\", setupAPICall(http.HandlerFunc(hostHandler))).Methods(\"GET\")\n\tsr.Handle(\"/host\", setupAPICall(http.HandlerFunc(notAllowed))).Methods(\"POST\", \"PUT\", \"PATCH\", \"DELETE\")\n\n\t// Settings\n\tsr.Handle(\"/settings\", setupAPICall(http.HandlerFunc(apiSettingsHandler))).Methods(\"GET\")\n\tsr.Handle(\"/settings\", setupAPICall(http.HandlerFunc(notAllowed))).Methods(\"POST\", \"PUT\", \"PATCH\", \"DELETE\")\n\n\t// Settings\n\tsr.Handle(\"/metrics\", setupAPICall(http.HandlerFunc(metricsHandler))).Methods(\"GET\")\n\tsr.Handle(\"/metrics\", setupAPICall(http.HandlerFunc(notAllowed))).Methods(\"POST\", \"PUT\", \"PATCH\", \"DELETE\")\n\n}", "func (a *API) RegisterAPI(cfg interface{}) {\n\ta.RegisterRoute(\"/config\", configHandler(cfg), false)\n\ta.RegisterRoute(\"/\", http.HandlerFunc(indexHandler), false)\n}", "func SetupApiRoutes(r *mux.Router, cache job.JobCache, defaultOwner string, disableDeleteAll bool,\n\tdisableLocalJobs bool) {\n\t// Route for creating a job\n\tr.HandleFunc(ApiJobPath, HandleAddJob(cache, defaultOwner, disableLocalJobs)).Methods(httpPost)\n\t// Route for deleting all jobs\n\tr.HandleFunc(ApiJobPath+\"all/\", HandleDeleteAllJobs(cache, disableDeleteAll)).Methods(httpDelete)\n\t// Route for deleting, editing and getting a job\n\tr.HandleFunc(ApiJobPath+\"{id}/\", HandleJobRequest(cache, disableLocalJobs)).Methods(httpDelete, httpGet, httpPut)\n\t// Route for updating a remote job's parameters.\n\tr.HandleFunc(ApiJobPath+\"{id}/params/\", HandleJobParamsRequest(cache)).Methods(httpGet, httpPut)\n\t// Route for listing all jops\n\tr.HandleFunc(ApiJobPath, HandleListJobsRequest(cache)).Methods(httpGet)\n\t// Route for manually start a job\n\tr.HandleFunc(ApiJobPath+\"start/{id}/\", HandleStartJobRequest(cache)).Methods(httpPost)\n\t// Route for manually start a job\n\tr.HandleFunc(ApiJobPath+\"enable/{id}/\", HandleEnableJobRequest(cache)).Methods(httpPost)\n\t// Route for manually disable a job\n\tr.HandleFunc(ApiJobPath+\"disable/{id}/\", HandleDisableJobRequest(cache)).Methods(httpPost)\n\t// Route for getting app-level metrics\n\tr.HandleFunc(ApiUrlPrefix+\"stats/\", HandleKalaStatsRequest(cache)).Methods(httpGet)\n\t// Route for a single job execution actions\n\tr.HandleFunc(ApiJobPath+\"{job_id}/executions/{id}/\", HandleJobRunRequest(cache)).Methods(httpGet, httpPut)\n\t// Route for a single job execution actions\n\tr.HandleFunc(ApiJobPath+\"{id}/executions/\", HandleListJobRunsRequest(cache)).Methods(httpGet)\n\tr.Use(job.AuthHandler)\n}", "func (Condition) ApiRoutes() []string {\n\treturn []string{\n\t\t\"/api/objects/condition/group/\",\n\t\t\"/api/objects/condition/group/{ref}\",\n\t\t\"/api/objects/condition/group/{ref}/usedby\",\n\t\t\"/api/objects/condition/objref/\",\n\t\t\"/api/objects/condition/objref/{ref}\",\n\t\t\"/api/objects/condition/objref/{ref}/usedby\",\n\t}\n}", "func RegisterAPIHandlers(r pure.IRouteGroup) {\n\tr.Get(\"/token\", tokenGetAPI)\n}", "func (plugin *RouteConfigurator) ResolveCreatedInterface(ifName string, swIdx uint32) {\n\troutesWithIndex := plugin.rtCachedIndexes.LookupRouteAndIDByOutgoingIfc(ifName)\n\tif len(routesWithIndex) == 0 {\n\t\treturn\n\t}\n\tplugin.log.Infof(\"Route configurator: resolving new interface %v for %d routes\", ifName, len(routesWithIndex))\n\tfor _, routeWithIndex := range routesWithIndex {\n\t\troute := routeWithIndex.Route\n\t\tplugin.log.WithFields(logging.Fields{\n\t\t\t\"ifName\": ifName,\n\t\t\t\"swIdx\": swIdx,\n\t\t\t\"vrfID\": route.VrfId,\n\t\t\t\"dstIPAddr\": route.DstIpAddr,\n\t\t}).Debug(\"Remove routes from route cache - outgoing interface was added.\")\n\t\tvrf := strconv.FormatUint(uint64(route.VrfId), 10)\n\t\tif err := plugin.recreateRoute(route, vrf); err != nil {\n\t\t\tplugin.log.Errorf(\"Error recreating interface %s: %v\", ifName, err)\n\t\t}\n\t\tplugin.rtCachedIndexes.UnregisterName(routeWithIndex.RouteID)\n\t}\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 RegisterRoutes(router *apirouter.Router) {\n\n\t// Load the service dependencies\n\tloadService()\n\n\t// Set the main index page (navigating to slash)\n\trouter.HTTPRouter.GET(\"/\", router.Request(index))\n\trouter.HTTPRouter.OPTIONS(\"/\", router.SetCrossOriginHeaders)\n\n\t// Set the health request (used for load balancers)\n\trouter.HTTPRouter.GET(\"/\"+config.HealthRequestPath, router.Request(health))\n\trouter.HTTPRouter.OPTIONS(\"/\"+config.HealthRequestPath, router.SetCrossOriginHeaders)\n\trouter.HTTPRouter.HEAD(\"/\"+config.HealthRequestPath, router.SetCrossOriginHeaders)\n\n\t// Set the 404 handler (any request not detected)\n\trouter.HTTPRouter.NotFound = http.HandlerFunc(notFound)\n\n\t// Set the method not allowed\n\trouter.HTTPRouter.MethodNotAllowed = http.HandlerFunc(notAllowed)\n}", "func ConfigureIface(ifName string, res *types.Result) error {\n\tlink, err := netlink.LinkByName(ifName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to lookup %q: %v\", ifName, err)\n\t}\n\n\tif err := netlink.LinkSetUp(link); err != nil {\n\t\treturn fmt.Errorf(\"failed to set %q UP: %v\", ifName, err)\n\t}\n\n\t// TODO(eyakubovich): IPv6\n\taddr := &netlink.Addr{IPNet: &res.IP4.IP, Label: \"\"}\n\tif err = netlink.AddrAdd(link, addr); err != nil {\n\t\treturn fmt.Errorf(\"failed to add IP addr to %q: %v\", ifName, err)\n\t}\n\n\tfor _, r := range res.IP4.Routes {\n\t\tgw := r.GW\n\t\tif gw == nil {\n\t\t\tgw = res.IP4.Gateway\n\t\t}\n\t\tif err = ip.AddRoute(&r.Dst, gw, link); err != nil {\n\t\t\t// we skip over duplicate routes as we assume the first one wins\n\t\t\tif !os.IsExist(err) {\n\t\t\t\treturn fmt.Errorf(\"failed to add route '%v via %v dev %v': %v\", r.Dst, gw, ifName, err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func API(r *gin.Engine) {\n\tapi := r.Group(\"/api\")\n\t{\n\n\t\tapi.GET(\"/\", func(c *gin.Context) {\n\t\t\tc.JSON(http.StatusOK, gin.H{\"message\": \"/api\", \"status\": http.StatusOK})\n\t\t})\n\n\t\tAuthRoutes(api)\n\n\t\t// api.Use(jwt.JWT().MiddlewareFunc())\n\n\t\tUsersRoutes(api)\n\t\tPostsRoutes(api)\n\t}\n}", "func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) {\n\n\twrapper := ServerInterfaceWrapper{\n\t\tHandler: si,\n\t}\n\n\trouter.GET(baseURL+\"/customers\", wrapper.GetCustomers)\n\trouter.POST(baseURL+\"/customers\", wrapper.PostCustomers)\n\trouter.DELETE(baseURL+\"/customers/:id\", wrapper.DeleteCustomersId)\n\trouter.GET(baseURL+\"/customers/:id\", wrapper.GetCustomersId)\n\trouter.PUT(baseURL+\"/customers/:id\", wrapper.PutCustomersId)\n\trouter.GET(baseURL+\"/employees\", wrapper.GetEmployees)\n\trouter.POST(baseURL+\"/employees\", wrapper.PostEmployees)\n\trouter.DELETE(baseURL+\"/employees/:id\", wrapper.DeleteEmployeesId)\n\trouter.GET(baseURL+\"/employees/:id\", wrapper.GetEmployeesId)\n\trouter.PUT(baseURL+\"/employees/:id\", wrapper.PutEmployeesId)\n\trouter.GET(baseURL+\"/expenses\", wrapper.GetExpenses)\n\trouter.POST(baseURL+\"/expenses\", wrapper.PostExpenses)\n\trouter.DELETE(baseURL+\"/expenses/:id\", wrapper.DeleteExpensesId)\n\trouter.GET(baseURL+\"/expenses/:id\", wrapper.GetExpensesId)\n\trouter.PUT(baseURL+\"/expenses/:id\", wrapper.PutExpensesId)\n\trouter.GET(baseURL+\"/invoices\", wrapper.GetInvoices)\n\trouter.POST(baseURL+\"/invoices\", wrapper.PostInvoices)\n\trouter.DELETE(baseURL+\"/invoices/:id\", wrapper.DeleteInvoicesId)\n\trouter.GET(baseURL+\"/invoices/:id\", wrapper.GetInvoicesId)\n\trouter.PUT(baseURL+\"/invoices/:id\", wrapper.PutInvoicesId)\n\trouter.GET(baseURL+\"/misc_records\", wrapper.GetMiscRecords)\n\trouter.POST(baseURL+\"/misc_records\", wrapper.PostMiscRecords)\n\trouter.DELETE(baseURL+\"/misc_records/:id\", wrapper.DeleteMiscRecordsId)\n\trouter.GET(baseURL+\"/misc_records/:id\", wrapper.GetMiscRecordsId)\n\trouter.PUT(baseURL+\"/misc_records/:id\", wrapper.PutMiscRecordsId)\n\trouter.GET(baseURL+\"/projects\", wrapper.GetProjects)\n\trouter.POST(baseURL+\"/projects\", wrapper.PostProjects)\n\trouter.DELETE(baseURL+\"/projects/:id\", wrapper.DeleteProjectsId)\n\trouter.GET(baseURL+\"/projects/:id\", wrapper.GetProjectsId)\n\trouter.PUT(baseURL+\"/projects/:id\", wrapper.PutProjectsId)\n\n}", "func RegisterRoutes() arbor.RouteCollection {\n\troutes = append(routes, productServiceRoutes...)\n\treturn routes\n}", "func RegisterHandlers(router EchoRouter, si ServerInterface) {\n\n\twrapper := ServerInterfaceWrapper{\n\t\tHandler: si,\n\t}\n\n\trouter.POST(\"/search/apiCatalog/entries\", wrapper.SearchApiCatalog1)\n\trouter.GET(\"/search/apiCatalog/namespaces\", wrapper.GetApiNamespaces1)\n\trouter.POST(\"/search/apis\", wrapper.SearchApis1)\n\trouter.POST(\"/search/clients\", wrapper.SearchClients1)\n\trouter.POST(\"/search/organizations\", wrapper.SearchOrgs1)\n\trouter.POST(\"/search/roles\", wrapper.SearchRoles1)\n\trouter.POST(\"/search/users\", wrapper.SearchUsers1)\n\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 RegisterRoutes(rs *lcd.RestServer) {\n\tserver := rpc.NewServer()\n\taccountName := viper.GetString(flagUnlockKey)\n\taccountNames := strings.Split(accountName, \",\")\n\n\tvar privkeys []ethsecp256k1.PrivKey\n\tif len(accountName) > 0 {\n\t\tvar err error\n\t\tinBuf := bufio.NewReader(os.Stdin)\n\n\t\tkeyringBackend := viper.GetString(flags.FlagKeyringBackend)\n\t\tpassphrase := \"\"\n\t\tswitch keyringBackend {\n\t\tcase keys.BackendOS:\n\t\t\tbreak\n\t\tcase keys.BackendFile:\n\t\t\tpassphrase, err = input.GetPassword(\n\t\t\t\t\"Enter password to unlock key for RPC API: \",\n\t\t\t\tinBuf)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\n\t\tprivkeys, err = unlockKeyFromNameAndPassphrase(accountNames, passphrase)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\trpcapi := viper.GetString(flagRPCAPI)\n\trpcapi = strings.ReplaceAll(rpcapi, \" \", \"\")\n\trpcapiArr := strings.Split(rpcapi, \",\")\n\n\tapis := GetAPIs(rs.CliCtx, rpcapiArr, privkeys...)\n\n\t// Register all the APIs exposed by the namespace services\n\t// TODO: handle allowlist and private APIs\n\tfor _, api := range apis {\n\t\tif err := server.RegisterName(api.Namespace, api.Service); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\t// Web3 RPC API route\n\trs.Mux.HandleFunc(\"/\", server.ServeHTTP).Methods(\"POST\", \"OPTIONS\")\n\n\t// Register all other Cosmos routes\n\tclient.RegisterRoutes(rs.CliCtx, rs.Mux)\n\tevmrest.RegisterRoutes(rs.CliCtx, rs.Mux)\n\tapp.ModuleBasics.RegisterRESTRoutes(rs.CliCtx, rs.Mux)\n\n\t// start websockets server\n\twebsocketAddr := viper.GetString(flagWebsocket)\n\tws := websockets.NewServer(rs.CliCtx, websocketAddr)\n\tws.Start()\n}", "func (s *RestServer) AddIPv6FlowLatencyMetricsAPIRoutes(r *mux.Router) {\n\tr.Methods(\"GET\").Subrouter().HandleFunc(\"/{Meta.Tenant}/{Meta.Name}/\", httputils.MakeHTTPHandler(s.getIPv6FlowLatencyMetricsHandler))\n\tr.Methods(\"GET\").Subrouter().HandleFunc(\"/\", httputils.MakeHTTPHandler(s.listIPv6FlowLatencyMetricsHandler))\n}", "func ApplyRoutes(r *gin.Engine, auth *auth.Authenticator, db *gorm.DB) {\n\tmodels.SetRepoDB(db)\n\tauthenticator = auth\n\tapiV1 := r.Group(\"/v1\")\n\t{\n\t\tapiV1.GET(\"/ping\", pingHandler)\n\t\tapiV1.POST(\"/login\", loginHandler)\n\t\tapiV1.POST(\"/comment\", commentHandler)\n\t\tapiV1.DELETE(\"/comment\", commentHandler)\n\t\tapiV1.POST(\"/users\", userHandler)\n\t\tapiV1.DELETE(\"/users\", userHandler)\n\n\t}\n}", "func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) {\n\n\twrapper := ServerInterfaceWrapper{\n\t\tHandler: si,\n\t}\n\n\trouter.GET(baseURL+\"/inventory\", wrapper.GetInventory)\n\trouter.POST(baseURL+\"/inventory\", wrapper.UpsertInventory)\n\trouter.GET(baseURL+\"/products\", wrapper.ListProducts)\n\trouter.POST(baseURL+\"/products\", wrapper.UpsertProducts)\n\trouter.GET(baseURL+\"/productstock\", wrapper.ListProductStocks)\n\trouter.POST(baseURL+\"/sell\", wrapper.SellFromInventory)\n\n}", "func (s *RestServer) AddIPv4FlowRawMetricsAPIRoutes(r *mux.Router) {\n\tr.Methods(\"GET\").Subrouter().HandleFunc(\"/{Meta.Tenant}/{Meta.Name}/\", httputils.MakeHTTPHandler(s.getIPv4FlowRawMetricsHandler))\n\tr.Methods(\"GET\").Subrouter().HandleFunc(\"/\", httputils.MakeHTTPHandler(s.listIPv4FlowRawMetricsHandler))\n}", "func (b *vppbridge) AddInterface(vppinterface *vppinterface, portType l2.L2PortType) (err error) {\n\trequest := &l2.SwInterfaceSetL2Bridge{\n\t\tRxSwIfIndex: uint32(vppinterface.swifidx),\n\t\tBdID: b.ID,\n\t\tPortType: portType,\n\t\tEnable: 1,\n\t\tShg: 0,\n\t}\n\n\t// Dispatch request\n\tctx := b.Channel.SendRequest(request)\n\tresponse := &l2.SwInterfaceSetL2BridgeReply{}\n\tif err = ctx.ReceiveReply(response); err != nil {\n\t\terr = errors.Wrap(err, \"ctx.ReceiveReply()\")\n\t\treturn\n\t}\n\tif response.Retval != 0 {\n\t\terr = errors.Errorf(\"AddLoopBackReply: %d error\", response.Retval)\n\t\treturn\n\t}\n\n\t// Cache vppbridge segment\n\tb.segments = append(b.segments, vppinterface)\n\treturn\n}", "func (a* ApiEngine) GenerateAPIRoutesForService() {\n\tenv.Output.WriteChDebug(\"(ApiEngine::GenerateAPIRoutesForService)\")\n\ta.AddRoute(ui.GenerateRoute(\"allservices\",\"GET\",\"/api/services\",apiWriter(GetAllServices)))\n\ta.AddRoute(ui.GenerateRoute(\"service\",\"GET\",\"/api/services/{service}\",apiWriter(GetService)))\n}", "func (s *Service) GetRoutes() []routes.Route {\n\treturn []routes.Route{\n\t\t{\n\t\t\tName: \"register_app_form\",\n\t\t\tMethod: \"GET\",\n\t\t\tPattern: \"/register_app\",\n\t\t\tHandlerFunc: s.registerAppForm,\n\t\t\tMiddlewares: []negroni.Handler{\n\t\t\t\tnew(parseFormMiddleware),\n\t\t\t\tnewGuestMiddleware(s),\n\t\t\t\tnewClientMiddleware(s),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"login_app_form\",\n\t\t\tMethod: \"GET\",\n\t\t\tPattern: \"/login_app\",\n\t\t\tHandlerFunc: s.loginAppForm,\n\t\t\tMiddlewares: []negroni.Handler{\n\t\t\t\tnew(parseFormMiddleware),\n\t\t\t\tnewGuestMiddleware(s),\n\t\t\t\tnewClientMiddleware(s),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"login_app\",\n\t\t\tMethod: \"POST\",\n\t\t\tPattern: \"/login_app\",\n\t\t\tHandlerFunc: s.loginApp,\n\t\t\tMiddlewares: []negroni.Handler{\n\t\t\t\tnew(parseFormMiddleware),\n\t\t\t\tnewGuestMiddleware(s),\n\t\t\t\tnewClientMiddleware(s),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"register_app\",\n\t\t\tMethod: \"POST\",\n\t\t\tPattern: \"/register_app\",\n\t\t\tHandlerFunc: s.registerApp,\n\t\t\tMiddlewares: []negroni.Handler{\n\t\t\t\tnew(parseFormMiddleware),\n\t\t\t\tnewGuestMiddleware(s),\n\t\t\t\tnewClientMiddleware(s),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"home_app\",\n\t\t\tMethod: \"GET\",\n\t\t\tPattern: \"/home_app\",\n\t\t\tHandlerFunc: s.homeApp,\n\t\t\tMiddlewares: []negroni.Handler{\n\t\t\t\tnew(parseFormMiddleware),\n\t\t\t\tnewGuestMiddleware(s),\n\t\t\t\tnewClientMiddleware(s),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"login_app_validate_client\",\n\t\t\tMethod: \"POST\",\n\t\t\tPattern: \"/validateClient\",\n\t\t\tHandlerFunc: s.validateClient,\n\t\t\tMiddlewares: []negroni.Handler{\n\t\t\t\tnew(parseFormMiddleware),\n\t\t\t\tnewGuestMiddleware(s),\n\t\t\t\tnewClientMiddleware(s),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"sendMail\",\n\t\t\tMethod: \"POST\",\n\t\t\tPattern: \"/sendMail\",\n\t\t\tHandlerFunc: s.sendMailToken,\n\t\t\tMiddlewares: []negroni.Handler{\n\t\t\t\tnew(parseFormMiddleware),\n\t\t\t\tnewGuestMiddleware(s),\n\t\t\t\tnewClientMiddleware(s),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"index\",\n\t\t\tMethod: \"GET\",\n\t\t\tPattern: \"/\",\n\t\t\tHandlerFunc: s.index,\n\t\t\tMiddlewares: []negroni.Handler{\n\t\t\t\tnew(parseFormMiddleware),\n\t\t\t\tnewGuestMiddleware(s),\n\t\t\t\tnewClientMiddleware(s),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"register_form\",\n\t\t\tMethod: \"GET\",\n\t\t\tPattern: \"/register\",\n\t\t\tHandlerFunc: s.registerForm,\n\t\t\tMiddlewares: []negroni.Handler{\n\t\t\t\tnew(parseFormMiddleware),\n\t\t\t\tnewGuestMiddleware(s),\n\t\t\t\tnewClientMiddleware(s),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"register\",\n\t\t\tMethod: \"POST\",\n\t\t\tPattern: \"/register\",\n\t\t\tHandlerFunc: s.register,\n\t\t\tMiddlewares: []negroni.Handler{\n\t\t\t\tnew(parseFormMiddleware),\n\t\t\t\tnewGuestMiddleware(s),\n\t\t\t\tnewClientMiddleware(s),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"login_form\",\n\t\t\tMethod: \"GET\",\n\t\t\tPattern: \"/login\",\n\t\t\tHandlerFunc: s.loginForm,\n\t\t\tMiddlewares: []negroni.Handler{\n\t\t\t\tnew(parseFormMiddleware),\n\t\t\t\tnewGuestMiddleware(s),\n\t\t\t\tnewClientMiddleware(s),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"login\",\n\t\t\tMethod: \"POST\",\n\t\t\tPattern: \"/login\",\n\t\t\tHandlerFunc: s.login,\n\t\t\tMiddlewares: []negroni.Handler{\n\t\t\t\tnew(parseFormMiddleware),\n\t\t\t\tnewGuestMiddleware(s),\n\t\t\t\tnewClientMiddleware(s),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"logout\",\n\t\t\tMethod: \"GET\",\n\t\t\tPattern: \"/logout\",\n\t\t\tHandlerFunc: s.logout,\n\t\t\tMiddlewares: []negroni.Handler{\n\t\t\t\tnew(parseFormMiddleware),\n\t\t\t\tnewLoggedInMiddleware(s),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"authorize_form\",\n\t\t\tMethod: \"GET\",\n\t\t\tPattern: \"/authorize\",\n\t\t\tHandlerFunc: s.authorizeForm,\n\t\t\tMiddlewares: []negroni.Handler{\n\t\t\t\tnew(parseFormMiddleware),\n\t\t\t\tnewLoggedInMiddleware(s),\n\t\t\t\tnewClientMiddleware(s),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"authorize\",\n\t\t\tMethod: \"POST\",\n\t\t\tPattern: \"/authorize\",\n\t\t\tHandlerFunc: s.authorize,\n\t\t\tMiddlewares: []negroni.Handler{\n\t\t\t\tnew(parseFormMiddleware),\n\t\t\t\tnewLoggedInMiddleware(s),\n\t\t\t\tnewClientMiddleware(s),\n\t\t\t},\n\t\t},\n\t}\n}", "func NewRouting(cfg *config.APICfg, brk brokers.Broker, str stores.Store, mgr *oldPush.Manager, c push.Client, routes []APIRoute) *API {\n\t// Create the api Object\n\tar := API{}\n\t// Create a new router and reference him in API object\n\tar.Router = mux.NewRouter().StrictSlash(false)\n\t// reference routes input in API object too keep info centralized\n\tar.Routes = routes\n\n\t// For each route\n\tfor _, route := range ar.Routes {\n\n\t\t// prepare handle wrappers\n\t\tvar handler http.HandlerFunc\n\t\thandler = route.Handler\n\n\t\thandler = WrapLog(handler, route.Name)\n\n\t\t// skip authentication/authorization for the health status and profile api calls\n\t\tif route.Name != \"ams:healthStatus\" && \"users:profile\" != route.Name && route.Name != \"version:list\" {\n\t\t\thandler = WrapAuthorize(handler, route.Name)\n\t\t\thandler = WrapAuthenticate(handler)\n\t\t}\n\n\t\thandler = WrapValidate(handler)\n\t\thandler = WrapConfig(handler, cfg, brk, str, mgr, c)\n\n\t\tar.Router.\n\t\t\tPathPrefix(\"/v1\").\n\t\t\tMethods(route.Method).\n\t\t\tPath(route.Path).\n\t\t\tName(route.Name).\n\t\t\tHandler(gorillaContext.ClearHandler(handler))\n\t}\n\n\tlog.Info(\"API\", \"\\t\", \"API Router initialized! Ready to start listening...\")\n\t// Return reference to API object\n\treturn &ar\n}", "func (as *AdminServer) registerRoutes() {\n\trouter := mux.NewRouter()\n\t// Base Front-end routes\n\trouter.HandleFunc(\"/\", mid.Use(as.Base, mid.RequireLogin))\n\trouter.HandleFunc(\"/login\", mid.Use(as.Login, as.limiter.Limit))\n\trouter.HandleFunc(\"/logout\", mid.Use(as.Logout, mid.RequireLogin))\n\trouter.HandleFunc(\"/reset_password\", mid.Use(as.ResetPassword, mid.RequireLogin))\n\trouter.HandleFunc(\"/campaigns\", mid.Use(as.Campaigns, mid.RequireLogin))\n\trouter.HandleFunc(\"/campaigns/{id:[0-9]+}\", mid.Use(as.CampaignID, mid.RequireLogin))\n\trouter.HandleFunc(\"/templates\", mid.Use(as.Templates, mid.RequireLogin))\n\trouter.HandleFunc(\"/groups\", mid.Use(as.Groups, mid.RequireLogin))\n\trouter.HandleFunc(\"/landing_pages\", mid.Use(as.LandingPages, mid.RequireLogin))\n\trouter.HandleFunc(\"/sending_profiles\", mid.Use(as.SendingProfiles, mid.RequireLogin))\n\trouter.HandleFunc(\"/settings\", mid.Use(as.Settings, mid.RequireLogin))\n\trouter.HandleFunc(\"/users\", mid.Use(as.UserManagement, mid.RequirePermission(models.PermissionModifySystem), mid.RequireLogin))\n\trouter.HandleFunc(\"/webhooks\", mid.Use(as.Webhooks, mid.RequirePermission(models.PermissionModifySystem), mid.RequireLogin))\n\trouter.HandleFunc(\"/impersonate\", mid.Use(as.Impersonate, mid.RequirePermission(models.PermissionModifySystem), mid.RequireLogin))\n\t// Create the API routes\n\tapi := api.NewServer(\n\t\tapi.WithWorker(as.worker),\n\t\tapi.WithLimiter(as.limiter),\n\t)\n\trouter.PathPrefix(\"/api/\").Handler(api)\n\n\t// Setup static file serving\n\trouter.PathPrefix(\"/\").Handler(http.FileServer(unindexed.Dir(\"./static/\")))\n\n\t// Setup CSRF Protection\n\tcsrfKey := []byte(as.config.CSRFKey)\n\tif len(csrfKey) == 0 {\n\t\tcsrfKey = []byte(auth.GenerateSecureKey(auth.APIKeyLength))\n\t}\n\tcsrfHandler := csrf.Protect(csrfKey,\n\t\tcsrf.FieldName(\"csrf_token\"),\n\t\tcsrf.Secure(as.config.UseTLS))\n\tadminHandler := csrfHandler(router)\n\tadminHandler = mid.Use(adminHandler.ServeHTTP, mid.CSRFExceptions, mid.GetContext, mid.ApplySecurityHeaders)\n\n\t// Setup GZIP compression\n\tgzipWrapper, _ := gziphandler.NewGzipLevelHandler(gzip.BestCompression)\n\tadminHandler = gzipWrapper(adminHandler)\n\n\t// Respect X-Forwarded-For and X-Real-IP headers in case we're behind a\n\t// reverse proxy.\n\tadminHandler = handlers.ProxyHeaders(adminHandler)\n\n\t// Setup logging\n\tadminHandler = handlers.CombinedLoggingHandler(log.Writer(), adminHandler)\n\tas.server.Handler = adminHandler\n}", "func RegisterRoutes(srv *server.Server, accessGroup string, assets *rpcs.Assets) {\n\tif !srv.Options.Prod {\n\t\tsrv.Routes.Static(\"/static\", nil, http.Dir(\"./static\"))\n\t}\n\n\tui := UI{\n\t\tprod: srv.Options.Prod,\n\t\tversion: srv.Options.ImageVersion(),\n\t\tassets: assets,\n\t}\n\n\tmw := router.NewMiddlewareChain(\n\t\ttemplates.WithTemplates(ui.prepareTemplates()),\n\t\tauth.Authenticate(srv.CookieAuth),\n\t\tcheckAccess(accessGroup),\n\t)\n\n\tsrv.Routes.GET(\"/\", mw, wrapErr(ui.indexPage))\n\n\t// Help the router to route based on the suffix:\n\t//\n\t// /a/<AssetID> the asset page\n\t// /a/<AssetID>/history the history listing page\n\t// /a/<AssetID>/history/<ID> a single history entry\n\t//\n\t// Note that <AssetID> contains unknown number of path components.\n\tsrv.Routes.GET(\"/a/*Path\", mw, wrapErr(func(ctx *router.Context) error {\n\t\tpath := strings.TrimPrefix(ctx.Params.ByName(\"Path\"), \"/\")\n\t\tchunks := strings.Split(path, \"/\")\n\t\tl := len(chunks)\n\n\t\tif l > 1 && chunks[l-1] == \"history\" {\n\t\t\tassetID := strings.Join(chunks[:l-1], \"/\")\n\t\t\treturn ui.historyListingPage(ctx, assetID)\n\t\t}\n\n\t\tif l > 2 && chunks[l-2] == \"history\" {\n\t\t\tassetID := strings.Join(chunks[:l-2], \"/\")\n\t\t\thistoryID := chunks[l-1]\n\t\t\treturn ui.historyEntryPage(ctx, assetID, historyID)\n\t\t}\n\n\t\treturn ui.assetPage(ctx, path)\n\t}))\n}", "func InitialzeRoutes() *gin.Engine {\n\n\t// Setting Release mode in GIN\n\tgin.SetMode(gin.ReleaseMode)\n\n\t// Declaring and assigning router as gin default\n\trouter := gin.Default()\n\n\t// Adding logger to the console, Prints the request URL details\n\trouter.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {\n\n\t\t// printing URL parameters\n\t\treturn fmt.Sprintf(\"%s - [%s] \\\"%s %s %s %d %s \\\"%s\\\" %s\\\"\\n\",\n\t\t\t// Client IP\n\t\t\tparam.ClientIP,\n\n\t\t\t// Date and time of the URL request\n\t\t\tparam.TimeStamp.Format(time.RFC1123),\n\n\t\t\t// Method (GET / POST / PUT / PATCH )\n\t\t\tparam.Method,\n\n\t\t\t// URL Path\n\t\t\tparam.Path,\n\n\t\t\t// Requested Protocol (http / https)\n\t\t\tparam.Request.Proto,\n\n\t\t\t// Status code\n\t\t\tparam.StatusCode,\n\n\t\t\t// Latency of the client\n\t\t\tparam.Latency,\n\n\t\t\t// User agent of the client\n\t\t\tparam.Request.UserAgent(),\n\n\t\t\t// Error message\n\t\t\tparam.ErrorMessage,\n\t\t)\n\t}))\n\n\t// Allow all origins for dev\n\t// router.Use(cors.Default())\n\trouter.Use(cors.New(cors.Config{\n\t\tAllowOrigins: []string{\"*\"},\n\t\tAllowMethods: []string{\"GET\", \"HEAD\", \"OPTIONS\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"},\n\t\tAllowHeaders: []string{\"Origin\", \"X-Requested-With\", \"Content-Type\", \"Accept\", \"Authorization\"},\n\t\tExposeHeaders: []string{\"Content-Length\"},\n\t\tAllowCredentials: true,\n\t}))\n\n\t// Catching if any errors happens in the api call\n\trouter.Use(gin.Recovery())\n\t//\n\trouter.MaxMultipartMemory = 1 << 20 // Max 1mb files\n\n\t// Test Route URL\n\trouter.GET(\"/\", func(c *gin.Context) {\n\t\tc.Header(\"Title\", \"Campus Hiring\")\n\t\tc.JSON(http.StatusOK, \"Campus Hiring API is working\")\n\t})\n\n\tsubscription := router.Group(\"/s\")\n\tsubscription.Use(middleware.AuthorizeRequest())\n\n\tsubscription.POST(\"/subscribe\", controllers.Subscribe)\n\tsubscription.GET(\"/payment/:publishID\", controllers.GetSubscriptionPayment)\n\tsubscription.GET(\"/subscriptions\", controllers.GetAllSubscriptions)\n\tsubscription.GET(\"/campusInvites\", controllers.GetAllCampusInvites)\n\n\tsubscription.POST(\"/subscribe/unvInsight\", controllers.UnvInsightsController.SubscribeUnvInsight)\n\tsubscription.GET(\"/subscribe/unvInsight/:subscriptionID\", controllers.UnvInsightsController.GetSubscribedUnvInsight)\n\tsubscription.GET(\"/subscribe/unvInsight\", controllers.UnvInsightsController.GetAllSubscribedUnvInsight)\n\n\tsubscription.POST(\"/subscribe/hiringInsight\", controllers.HiringCriteriaController.Subscribe)\n\tsubscription.GET(\"/subscribe/hiringInsight/:subscriptionID\", controllers.HiringCriteriaController.GetHiringCriteriaByID)\n\tsubscription.GET(\"/subscribe/hiringInsight\", controllers.HiringCriteriaController.GetAllHiringInsights)\n\n\tsubscription.POST(\"/subscribe/unvStuData\", controllers.UnvStuDataController.SubscribeToStuData)\n\tsubscription.POST(\"/subscribe/unvStuData/queryStuData\", controllers.UnvStuDataController.QuerySubscribedStuData)\n\tsubscription.GET(\"/subscribe/unvStuData/:subID\", controllers.UnvStuDataController.FetchSubscribedStuData)\n\n\tsubscription.POST(\"/subscribe/campusDrive\", controllers.CampusDriveInvitationsController.Subscribe)\n\tsubscription.POST(\"/subscribe/campusDrive/invite\", controllers.CampusDriveInvitationsController.Invite)\n\tsubscription.POST(\"/subscribe/campusDrive/respond\", controllers.CampusDriveInvitationsController.Respond)\n\tsubscription.GET(\"/subscribe/campusDrive/emails/:campusDriveID\", controllers.CampusDriveInvitationsController.GetAllCDEmails)\n\t//subscription.GET(\"/subscribe/campusDrive/:subID\", controllers.CampusDriveInvitationsController.FetchSubscribedStuData)\n\n\treturn router\n}", "func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) {\r\n\t// this line is used by starport scaffolding\r\n\tr.HandleFunc(\"/voter/poll\", ListPollHandler(cliCtx, \"voter\")).Methods(\"GET\")\r\n\tr.HandleFunc(\"/voter/poll\", createPollHandler(cliCtx)).Methods(\"POST\")\r\n}", "func (a *DocRouter) RegisterAPI(app *gin.Engine) {\n\tapp.GET(\"/swagger/*any\", ginSwagger.WrapHandler(swaggerFiles.Handler))\n}", "func (s *RestServer) AddL2FlowPerformanceMetricsAPIRoutes(r *mux.Router) {\n\tr.Methods(\"GET\").Subrouter().HandleFunc(\"/{Meta.Tenant}/{Meta.Name}/\", httputils.MakeHTTPHandler(s.getL2FlowPerformanceMetricsHandler))\n\tr.Methods(\"GET\").Subrouter().HandleFunc(\"/\", httputils.MakeHTTPHandler(s.listL2FlowPerformanceMetricsHandler))\n}", "func RegisterRoutes(ctx client.Context, r *mux.Router, ns string) {\n\t// Get all orders\n\tr.HandleFunc(fmt.Sprintf(\"/%s/order/list\", ns), listOrdersHandler(ctx, ns)).Methods(\"GET\")\n\n\t// Get single order info\n\tr.HandleFunc(fmt.Sprintf(\"/%s/order/info\", ns), getOrderHandler(ctx, ns)).Methods(\"GET\")\n\n\t// Get all bids\n\tr.HandleFunc(fmt.Sprintf(\"/%s/bid/list\", ns), listBidsHandler(ctx, ns)).Methods(\"GET\")\n\n\t// Get single bid info\n\tr.HandleFunc(fmt.Sprintf(\"/%s/bid/info\", ns), getBidHandler(ctx, ns)).Methods(\"GET\")\n\n\t// Get all leases\n\tr.HandleFunc(fmt.Sprintf(\"/%s/lease/list\", ns), listLeasesHandler(ctx, ns)).Methods(\"GET\")\n\n\t// Get single order info\n\tr.HandleFunc(fmt.Sprintf(\"/%s/lease/info\", ns), getLeaseHandler(ctx, ns)).Methods(\"GET\")\n}", "func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) {\n\n\twrapper := ServerInterfaceWrapper{\n\t\tHandler: si,\n\t}\n\n\trouter.GET(baseURL+\"/accounts\", wrapper.GetAccounts)\n\trouter.GET(baseURL+\"/accounts/:account/:currency\", wrapper.GetAccountByTypeAndCurrency)\n\trouter.GET(baseURL+\"/deposits\", wrapper.GetDeposits)\n\trouter.POST(baseURL+\"/deposits/:currency\", wrapper.GetDepositAddress)\n\trouter.GET(baseURL+\"/deposits/:depositId\", wrapper.GetDepositById)\n\trouter.GET(baseURL+\"/fees\", wrapper.GetFees)\n\trouter.GET(baseURL+\"/fills\", wrapper.GetFills)\n\trouter.GET(baseURL+\"/l2/:symbol\", wrapper.GetL2OrderBook)\n\trouter.GET(baseURL+\"/l3/:symbol\", wrapper.GetL3OrderBook)\n\trouter.DELETE(baseURL+\"/orders\", wrapper.DeleteAllOrders)\n\trouter.GET(baseURL+\"/orders\", wrapper.GetOrders)\n\trouter.POST(baseURL+\"/orders\", wrapper.CreateOrder)\n\trouter.DELETE(baseURL+\"/orders/:orderId\", wrapper.DeleteOrder)\n\trouter.GET(baseURL+\"/orders/:orderId\", wrapper.GetOrderById)\n\trouter.GET(baseURL+\"/symbols\", wrapper.GetSymbols)\n\trouter.GET(baseURL+\"/symbols/:symbol\", wrapper.GetSymbolByName)\n\trouter.GET(baseURL+\"/tickers\", wrapper.GetTickers)\n\trouter.GET(baseURL+\"/tickers/:symbol\", wrapper.GetTickerBySymbol)\n\trouter.GET(baseURL+\"/trades\", wrapper.GetTrades)\n\trouter.GET(baseURL+\"/whitelist\", wrapper.GetWhitelist)\n\trouter.GET(baseURL+\"/whitelist/:currency\", wrapper.GetWhitelistByCurrency)\n\trouter.GET(baseURL+\"/withdrawals\", wrapper.GetWithdrawals)\n\trouter.POST(baseURL+\"/withdrawals\", wrapper.CreateWithdrawal)\n\trouter.GET(baseURL+\"/withdrawals/:withdrawalId\", wrapper.GetWithdrawalById)\n\n}", "func (s *RestServer) AddIPv4FlowDropMetricsAPIRoutes(r *mux.Router) {\n\tr.Methods(\"GET\").Subrouter().HandleFunc(\"/{Meta.Tenant}/{Meta.Name}/\", httputils.MakeHTTPHandler(s.getIPv4FlowDropMetricsHandler))\n\tr.Methods(\"GET\").Subrouter().HandleFunc(\"/\", httputils.MakeHTTPHandler(s.listIPv4FlowDropMetricsHandler))\n}", "func (agr *apiGatewayResource) updateAPIGateway(request *http.Request) (*restful.CustomRouteFuncResponse, error) {\n\n\tctx := request.Context()\n\tagr.Logger.WarnWithCtx(ctx, \"Updating api gateways via /api/apigateways has been deprecated. \"+\n\t\t\"Please use /api/apigateways/<apigateway-name>\")\n\n\t// get api gateway id from body\n\tbody, err := io.ReadAll(request.Body)\n\tif err != nil {\n\t\treturn nil, nuclio.WrapErrInternalServerError(errors.Wrap(err, \"Failed to read body\"))\n\t}\n\n\tapiGatewayInfoInstance := apiGatewayInfo{}\n\tif err = json.Unmarshal(body, &apiGatewayInfoInstance); err != nil {\n\t\treturn nil, nuclio.WrapErrBadRequest(errors.Wrap(err, \"Failed to parse JSON body\"))\n\t}\n\tapiGatewayId := apiGatewayInfoInstance.Meta.Name\n\n\t// retrieve request body so next handler can read it\n\trequest.Body.Close() // nolint: errcheck\n\trequest.Body = io.NopCloser(bytes.NewBuffer(body))\n\n\t// update api gateway\n\t_, err = agr.Update(request, apiGatewayId)\n\n\t// return the stuff\n\treturn &restful.CustomRouteFuncResponse{\n\t\tResourceType: \"apiGateway\",\n\t\tSingle: true,\n\t\tStatusCode: common.ResolveErrorStatusCodeOrDefault(err, http.StatusNoContent),\n\t\tHeaders: map[string]string{\n\t\t\t\"Deprecation\": \"true\",\n\t\t\t\"Link\": fmt.Sprintf(\"</api/apigateways/%s>; rel=\\\"alternate\\\"\", apiGatewayId),\n\t\t},\n\t}, err\n}", "func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *wire.Codec, storeName string, kb keys.Keybase, kafka bool, kafkaState rest.KafkaState) {\n\tr.HandleFunc(\"/issue/fiat\", IssueFiatHandlerFunction(cliCtx, cdc, kb, kafka, kafkaState)).Methods(\"POST\")\n\tr.HandleFunc(\"/fiat/{pegHash}\", QueryFiatRequestHandlerFn(storeName, cdc, r, fiatcmd.GetFiatPegDecoder(cdc), cliCtx)).Methods(\"GET\")\n\tr.HandleFunc(\"/redeem/fiat\", RedeemFiatHandlerFunction(cliCtx, cdc, kb, kafka, kafkaState)).Methods(\"POST\")\n\tr.HandleFunc(\"/send/fiat\", SendFiatHandlerFunction(cliCtx, cdc, kb, kafka, kafkaState)).Methods(\"POST\")\n\tr.HandleFunc(\"/execute/fiat\", ExecuteFiatHandlerFunction(cliCtx, cdc, kb, kafka, kafkaState)).Methods(\"POST\")\n}", "func registerRoutes(r *mux.Router) {\n\t// authed router that enforces authentication\n\tauthed := r.PathPrefix(conf.AuthedPathName).Subrouter()\n\n\t// attach middleware for all routes\n\tauthed.Use(auth)\n\n\t//Get Calendar\n\tauthed.HandleFunc(fmt.Sprintf(\"/c/{%s}/{%s}\", userIDStr, calendarIDStr), getCalendarHandler).Methods(\"GET\")\n\tauthed.HandleFunc(fmt.Sprintf(\"/c/{%s}\", calendarIDStr), getCalendarHandler).Methods(\"GET\")\n\tauthed.HandleFunc(\"/c\", getCalendarHandler).Methods(\"GET\")\n\tauthed.Handle(\"/calendar.xsl\", loadedXSLHandler(loaded.calendar)).Methods(\"GET\")\n\tauthed.Handle(\"/projectView.xsl\", loadedXSLHandler(loaded.project)).Methods(\"GET\")\n\tauthed.Handle(\"/editItem.xsl\", loadedXSLHandler(loaded.editItem)).Methods(\"GET\")\n\n\t//Get all Calendars of User\n\tauthed.HandleFunc(\"/calendars\", getUserCalendarsHandler).Methods(\"GET\")\n\tauthed.Handle(\"/showCalendars.xsl\", loadedXSLHandler(loaded.showCalendars)).Methods(\"GET\")\n\n\t// Modify Calendar\n\tauthed.HandleFunc(\"/c\", methodHandler(postCalendarHandler, putCalendarHandler, nil)).Methods(\"POST\")\n\tauthed.HandleFunc(fmt.Sprintf(\"/c/{%s}/{%s}\", userIDStr, calendarIDStr),\n\t\tmethodHandler(nil, putCalendarHandler, deleteCalendarHandler)).Methods(\"POST\")\n\tauthed.HandleFunc(fmt.Sprintf(\"/c/{%s}\", calendarIDStr),\n\t\tmethodHandler(nil, putCalendarHandler, deleteCalendarHandler)).Methods(\"POST\")\n\n\t// Delete User\n\tauthed.HandleFunc(\"/api/user\", methodHandler(nil, nil, deleteUserHandler)).Methods(\"POST\")\n\n\tauthed.HandleFunc(\"/api/sharing\", sharingHandler).Methods(\"POST\")\n\n\t// attach auto generated endpoint routes\n\tattachEndpoints(authed)\n\n\tauthed.HandleFunc(\"/logout\", logoutHandler).Methods(\"GET\")\n\n\tr.HandleFunc(\"/api/login\", loginHandler).Methods(\"POST\")\n\tr.HandleFunc(\"/api/register\", registerHandler).Methods(\"POST\")\n\n\t// serve static files (index, impressum, login, register ...). Note that this has to be registered last.\n\tr.PathPrefix(\"/\").Handler(http.FileServer(http.Dir(conf.FrontendDir)))\n}", "func (api *API) setupRoutes() error {\n\tvar (\n\t\tconnLimit int\n\t\terr error\n\t)\n\tif api.cfg.API.Connection.Limit == \"\" {\n\t\tconnLimit = 50\n\t} else {\n\t\t// setup the connection limit\n\t\tconnLimit, err = strconv.Atoi(api.cfg.API.Connection.Limit)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// ensure we have valid cors configuration, otherwise default to allow all\n\tvar allowedOrigins []string\n\tif len(api.cfg.API.Connection.CORS.AllowedOrigins) > 0 {\n\t\tallowedOrigins = api.cfg.API.Connection.CORS.AllowedOrigins\n\t}\n\t// set up defaults\n\tapi.r.Use(\n\t\t// allows for automatic xss removal\n\t\t// greater than what can be configured with HTTP Headers\n\t\txssMdlwr.RemoveXss(),\n\t\t// rate limiting\n\t\tlimit.MaxAllowed(connLimit),\n\t\t// security middleware\n\t\tmiddleware.NewSecWare(dev),\n\t\t// cors middleware\n\t\tmiddleware.CORSMiddleware(dev, allowedOrigins),\n\t\t// request id middleware\n\t\tmiddleware.RequestID(),\n\t\t// stats middleware\n\t\tstats.RequestStats())\n\n\t// set up middleware\n\tginjwt := middleware.JwtConfigGenerate(api.cfg.JWT.Key, api.cfg.JWT.Realm, api.dbm.DB, api.l)\n\tauthware := []gin.HandlerFunc{ginjwt.MiddlewareFunc()}\n\n\t// V2 API\n\tv2 := api.r.Group(\"/v2\")\n\n\t// system checks used to verify the integrity of our services\n\tsystemChecks := v2.Group(\"/systems\")\n\t{\n\t\tsystemChecks.GET(\"/check\", api.SystemsCheck)\n\t}\n\n\t// authless account recovery routes\n\tforgot := v2.Group(\"/forgot\")\n\t{\n\t\tforgot.POST(\"/username\", api.forgotUserName)\n\t\tforgot.POST(\"/password\", api.resetPassword)\n\t}\n\n\t// authentication\n\tauth := v2.Group(\"/auth\")\n\t{\n\t\tauth.POST(\"/register\", api.registerUserAccount)\n\t\tauth.POST(\"/login\", ginjwt.LoginHandler)\n\t\tauth.GET(\"/refresh\", ginjwt.RefreshHandler)\n\t}\n\n\t// statistics\n\tstatistics := v2.Group(\"/statistics\").Use(authware...)\n\t{\n\t\tstatistics.GET(\"/stats\", api.getStats)\n\t}\n\n\t// lens search engine\n\tlens := v2.Group(\"/lens\")\n\t{\n\t\tlens.POST(\"/index\", api.submitIndexRequest)\n\t\t// only allow registered users to search\n\t\tlens.POST(\"/search\", api.submitSearchRequest)\n\t}\n\n\t// payments\n\tpayments := v2.Group(\"/payments\", authware...)\n\t{\n\t\tdash := payments.Group(\"/dash\")\n\t\t{\n\t\t\tdash.POST(\"/create\", api.CreateDashPayment)\n\t\t}\n\t\teth := payments.Group(\"/eth\")\n\t\t{\n\t\t\teth.POST(\"/request\", api.RequestSignedPaymentMessage)\n\t\t\teth.POST(\"/confirm\", api.ConfirmETHPayment)\n\t\t}\n\t\tbch := payments.Group(\"/bch\")\n\t\t{\n\t\t\tbch.POST(\"/create\", api.createBchPayment)\n\t\t\tbch.POST(\"/confirm\", api.confirmBchPayment)\n\t\t}\n\t\tstripe := payments.Group(\"/stripe\")\n\t\t{\n\t\t\tstripe.POST(\"/charge\", api.stripeCharge)\n\t\t}\n\t\tpayments.GET(\"/status/:number\", api.getPaymentStatus)\n\t}\n\n\t// accounts\n\taccount := v2.Group(\"/account\")\n\t{\n\t\ttoken := account.Group(\"/token\", authware...)\n\t\t{\n\t\t\ttoken.GET(\"/username\", api.getUserFromToken)\n\t\t}\n\t\tpassword := account.Group(\"/password\", authware...)\n\t\t{\n\t\t\tpassword.POST(\"/change\", api.changeAccountPassword)\n\t\t}\n\t\tkey := account.Group(\"/key\", authware...)\n\t\t{\n\t\t\tkey.GET(\"/export/:name\", api.exportKey)\n\t\t\tipfs := key.Group(\"/ipfs\")\n\t\t\t{\n\t\t\t\tipfs.GET(\"/get\", api.getIPFSKeyNamesForAuthUser)\n\t\t\t\tipfs.POST(\"/new\", api.createIPFSKey)\n\t\t\t}\n\t\t}\n\t\tcredits := account.Group(\"/credits\", authware...)\n\t\t{\n\t\t\tcredits.GET(\"/available\", api.getCredits)\n\t\t}\n\t\temail := account.Group(\"/email\")\n\t\t{\n\t\t\t// auth-less account email routes\n\t\t\ttoken := email.Group(\"/verify\")\n\t\t\t{\n\t\t\t\ttoken.GET(\"/:user/:token\", api.verifyEmailAddress)\n\t\t\t}\n\t\t\t// authenticatoin email routes\n\t\t\tauth := email.Use(authware...)\n\t\t\t{\n\t\t\t\tauth.POST(\"/forgot\", api.forgotEmail)\n\t\t\t}\n\t\t}\n\t\tauth := account.Use(authware...)\n\t\t{\n\t\t\t// used to upgrade account to light tier\n\t\t\tauth.POST(\"/upgrade\", api.upgradeAccount)\n\t\t\tauth.GET(\"/usage\", api.usageData)\n\t\t}\n\t}\n\n\t// ipfs routes\n\tipfs := v2.Group(\"/ipfs\", authware...)\n\t{\n\t\t// public ipfs routes\n\t\tpublic := ipfs.Group(\"/public\")\n\t\t{\n\t\t\t// pinning routes\n\t\t\tpin := public.Group(\"/pin\")\n\t\t\t{\n\t\t\t\tpin.POST(\"/:hash\", api.pinHashLocally)\n\t\t\t\tpin.POST(\"/:hash/extend\", api.extendPin)\n\t\t\t}\n\t\t\t// file upload routes\n\t\t\tfile := public.Group(\"/file\")\n\t\t\t{\n\t\t\t\tfile.POST(\"/add\", api.addFile)\n\t\t\t\tfile.POST(\"/add/directory\", api.uploadDirectory)\n\t\t\t}\n\t\t\t// pubsub routes\n\t\t\tpubsub := public.Group(\"/pubsub\")\n\t\t\t{\n\t\t\t\tpubsub.POST(\"/publish/:topic\", api.ipfsPubSubPublish)\n\t\t\t}\n\t\t\t// general routes\n\t\t\tpublic.GET(\"/stat/:hash\", api.getObjectStatForIpfs)\n\t\t\tpublic.GET(\"/dag/:hash\", api.getDagObject)\n\t\t}\n\n\t\t// private ipfs routes\n\t\tprivate := ipfs.Group(\"/private\")\n\t\t{\n\t\t\t// network management routes\n\t\t\tprivate.GET(\"/networks\", api.getAuthorizedPrivateNetworks)\n\t\t\tnetwork := private.Group(\"/network\")\n\t\t\t{\n\t\t\t\tusers := network.Group(\"/users\")\n\t\t\t\t{\n\t\t\t\t\tusers.DELETE(\"/remove\", api.removeUsersFromNetwork)\n\t\t\t\t\tusers.POST(\"/add\", api.addUsersToNetwork)\n\t\t\t\t}\n\t\t\t\towners := network.Group(\"/owners\")\n\t\t\t\t{\n\t\t\t\t\towners.POST(\"/add\", api.addOwnersToNetwork)\n\t\t\t\t}\n\t\t\t\tnetwork.GET(\"/:name\", api.getIPFSPrivateNetworkByName)\n\t\t\t\tnetwork.POST(\"/new\", api.createIPFSNetwork)\n\t\t\t\tnetwork.POST(\"/stop\", api.stopIPFSPrivateNetwork)\n\t\t\t\tnetwork.POST(\"/start\", api.startIPFSPrivateNetwork)\n\t\t\t\tnetwork.DELETE(\"/remove\", api.removeIPFSPrivateNetwork)\n\t\t\t}\n\t\t\t// pinning routes\n\t\t\tpin := private.Group(\"/pin\")\n\t\t\t{\n\t\t\t\tpin.POST(\"/:hash\", api.pinToHostedIPFSNetwork)\n\t\t\t\tpin.GET(\"/check/:hash/:networkName\", api.checkLocalNodeForPinForHostedIPFSNetwork)\n\t\t\t}\n\t\t\t// file upload routes\n\t\t\tfile := private.Group(\"/file\")\n\t\t\t{\n\t\t\t\tfile.POST(\"/add\", api.addFileToHostedIPFSNetwork)\n\t\t\t}\n\t\t\t// pubsub routes\n\t\t\tpubsub := private.Group(\"/pubsub\")\n\t\t\t{\n\t\t\t\tpubsub.POST(\"/publish/:topic\", api.ipfsPubSubPublishToHostedIPFSNetwork)\n\t\t\t}\n\t\t\t// object stat route\n\t\t\tprivate.GET(\"/stat/:hash/:networkName\", api.getObjectStatForIpfsForHostedIPFSNetwork)\n\t\t\t// general routes\n\t\t\tprivate.GET(\"/dag/:hash/:networkName\", api.getDagObjectForHostedIPFSNetwork)\n\t\t\tprivate.GET(\"/uploads/:networkName\", api.getUploadsByNetworkName)\n\t\t}\n\t\t// utility routes\n\t\tutils := ipfs.Group(\"/utils\")\n\t\t{\n\t\t\t// generic download\n\t\t\tutils.POST(\"/download/:hash\", api.downloadContentHash)\n\t\t\tlaser := utils.Group(\"/laser\")\n\t\t\t{\n\t\t\t\tlaser.POST(\"/beam\", api.beamContent)\n\t\t\t}\n\t\t}\n\t}\n\n\t// ipns\n\tipns := v2.Group(\"/ipns\", authware...)\n\t{\n\t\t// public ipns routes\n\t\tpublic := ipns.Group(\"/public\")\n\t\t{\n\t\t\tpublic.POST(\"/publish/details\", api.publishToIPNSDetails)\n\t\t\t// used to handle pinning of IPNS records on public ipfs\n\t\t\t// this involves first resolving the record, parsing it\n\t\t\t// and extracting the hash to pin\n\t\t\tpublic.POST(\"/pin\", api.pinIPNSHash)\n\t\t}\n\t\t// general routes\n\t\tipns.GET(\"/records\", api.getIPNSRecordsPublishedByUser)\n\t}\n\n\t// database\n\tdatabase := v2.Group(\"/database\", authware...)\n\t{\n\t\tdatabase.GET(\"/uploads\", api.getUploadsForUser)\n\t\tdatabase.GET(\"/uploads/encrypted\", api.getEncryptedUploadsForUser)\n\t}\n\n\t// frontend\n\tfrontend := v2.Group(\"/frontend\", authware...)\n\t{\n\t\tcost := frontend.Group(\"/cost\")\n\t\t{\n\t\t\tcalculate := cost.Group(\"/calculate\")\n\t\t\t{\n\t\t\t\tcalculate.GET(\"/:hash/:hold_time\", api.calculatePinCost)\n\t\t\t\tcalculate.POST(\"/file\", api.calculateFileCost)\n\t\t\t}\n\t\t}\n\t}\n\n\tapi.l.Info(\"Routes initialized\")\n\treturn nil\n}", "func RegisterRoutes(ctx context.CLIContext, r *mux.Router, ns string) {\n\tr.HandleFunc(fmt.Sprintf(\"/%s/deployments\", ns), listDeploymentsHandler(ctx, ns)).Methods(\"GET\")\n}" ]
[ "0.7264951", "0.6624757", "0.6317219", "0.6261901", "0.6214964", "0.6207461", "0.6187202", "0.6167769", "0.6119995", "0.609236", "0.60369056", "0.6035869", "0.5980018", "0.5899392", "0.5896274", "0.58896464", "0.5813988", "0.58109516", "0.57868725", "0.57825184", "0.5767284", "0.5755505", "0.57154113", "0.57106364", "0.57096434", "0.5697105", "0.5689954", "0.5643674", "0.56257874", "0.5596347", "0.5571055", "0.5568594", "0.5558431", "0.5545199", "0.55399096", "0.5534649", "0.5532074", "0.5528412", "0.55149335", "0.5514477", "0.55141383", "0.5490771", "0.5484089", "0.5483263", "0.5466949", "0.54650855", "0.54642814", "0.5462831", "0.5459954", "0.5457927", "0.5450295", "0.5445245", "0.5431872", "0.543142", "0.54314005", "0.54265845", "0.5402655", "0.5395214", "0.5395137", "0.53943074", "0.5377715", "0.53734994", "0.5373187", "0.5371504", "0.5364035", "0.53590924", "0.5355056", "0.53464514", "0.53439236", "0.53374416", "0.53319764", "0.5318992", "0.5316731", "0.5311", "0.5306847", "0.5303762", "0.5303514", "0.52918804", "0.52872527", "0.5285903", "0.52850425", "0.52816427", "0.5275069", "0.52737004", "0.52730614", "0.52708983", "0.5269642", "0.5268981", "0.52685326", "0.5264814", "0.5253966", "0.52428496", "0.52413166", "0.52400434", "0.5237634", "0.52373165", "0.5237129", "0.5231471", "0.52295434", "0.52275753" ]
0.8854116
0
FindGit returns the path to the Git binary found in the corresponding CIPD package. Calling this function from any Go package will automatically establish a Bazel dependency on the corresponding CIPD package, which Bazel will download as needed.
func FindGit() (string, error) { if !bazel.InBazelTest() { return exec.LookPath("git") } if runtime.GOOS == "windows" { return filepath.Join(bazel.RunfilesDir(), "external", "git_amd64_windows", "bin", "git.exe"), nil } else if runtime.GOOS == "linux" { return filepath.Join(bazel.RunfilesDir(), "external", "git_amd64_linux", "bin", "git"), nil } return "", skerr.Fmt("unsupported runtime.GOOS: %q", runtime.GOOS) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func FindGit(ctx context.Context) (string, int, int, error) {\n\tmtx.Lock()\n\tdefer mtx.Unlock()\n\tif git == \"\" {\n\t\tgitPath, err := osexec.LookPath(\"git\")\n\t\tif err != nil {\n\t\t\treturn \"\", 0, 0, skerr.Wrapf(err, \"Failed to find git\")\n\t\t}\n\t\tmaj, min, err := Version(ctx, gitPath)\n\t\tif err != nil {\n\t\t\treturn \"\", 0, 0, skerr.Wrapf(err, \"Failed to obtain git version\")\n\t\t}\n\t\tsklog.Infof(\"Git is %s; version %d.%d\", gitPath, maj, min)\n\t\tisFromCIPD := IsFromCIPD(gitPath)\n\t\tisFromCIPDVal := 0\n\t\tif isFromCIPD {\n\t\t\tisFromCIPDVal = 1\n\t\t}\n\t\tmetrics2.GetInt64Metric(\"git_from_cipd\").Update(int64(isFromCIPDVal))\n\t\tgit = gitPath\n\t\tgitVersionMajor = maj\n\t\tgitVersionMinor = min\n\t}\n\treturn git, gitVersionMajor, gitVersionMinor, nil\n}", "func MocksForFindGit(ctx context.Context, cmd *exec.Command) error {\n\tif strings.Contains(cmd.Name, \"git\") && len(cmd.Args) == 1 && cmd.Args[0] == \"--version\" {\n\t\t_, err := cmd.CombinedOutput.Write([]byte(\"git version 99.99.1\"))\n\t\treturn err\n\t}\n\treturn nil\n}", "func FindGitDir() (string, error) {\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn findGitDirIn(wd, 0)\n}", "func _detectRemoteURL_GoGit(path string) (string, error) {\n\tgitRepo, err := git.PlainOpen(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tremote, err := gitRepo.Remote(\"origin\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn remote.Config().URLs[0], nil\n}", "func FindGitConfig(dir string) (string, error) {\n\tvar err error\n\n\tif dir, err = findGitDir(dir); err != nil {\n\t\treturn \"\", err\n\t}\n\tif dir, err = getGitCommonDir(dir); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(dir, \"config\"), nil\n}", "func FindGitRef(ctx context.Context, file string) (string, error) {\n\tlogger := common.Logger(ctx)\n\n\tlogger.Debugf(\"Loading revision from git directory\")\n\t_, ref, err := FindGitRevision(ctx, file)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tlogger.Debugf(\"HEAD points to '%s'\", ref)\n\n\t// Prefer the git library to iterate over the references and find a matching tag or branch.\n\tvar refTag = \"\"\n\tvar refBranch = \"\"\n\trepo, err := git.PlainOpenWithOptions(\n\t\tfile,\n\t\t&git.PlainOpenOptions{\n\t\t\tDetectDotGit: true,\n\t\t\tEnableDotGitCommonDir: true,\n\t\t},\n\t)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\titer, err := repo.References()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// find the reference that matches the revision's has\n\terr = iter.ForEach(func(r *plumbing.Reference) error {\n\t\t/* tags and branches will have the same hash\n\t\t * when a user checks out a tag, it is not mentioned explicitly\n\t\t * in the go-git package, we must identify the revision\n\t\t * then check if any tag matches that revision,\n\t\t * if so then we checked out a tag\n\t\t * else we look for branches and if matches,\n\t\t * it means we checked out a branch\n\t\t *\n\t\t * If a branches matches first we must continue and check all tags (all references)\n\t\t * in case we match with a tag later in the interation\n\t\t */\n\t\tif r.Hash().String() == ref {\n\t\t\tif r.Name().IsTag() {\n\t\t\t\trefTag = r.Name().String()\n\t\t\t}\n\t\t\tif r.Name().IsBranch() {\n\t\t\t\trefBranch = r.Name().String()\n\t\t\t}\n\t\t}\n\n\t\t// we found what we where looking for\n\t\tif refTag != \"\" && refBranch != \"\" {\n\t\t\treturn storer.ErrStop\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// order matters here see above comment.\n\tif refTag != \"\" {\n\t\treturn refTag, nil\n\t}\n\tif refBranch != \"\" {\n\t\treturn refBranch, nil\n\t}\n\n\treturn \"\", fmt.Errorf(\"failed to identify reference (tag/branch) for the checked-out revision '%s'\", ref)\n}", "func gitPath() (string, error) {\n\tgitOnce.Do(func() {\n\t\tpath, err := exec.LookPath(\"git\")\n\t\tif err != nil {\n\t\t\tgitOnce.err = err\n\t\t\treturn\n\t\t}\n\t\tif runtime.GOOS == \"plan9\" {\n\t\t\tgitOnce.err = errors.New(\"plan9 git does not support the full git command line\")\n\t\t}\n\t\tgitOnce.path = path\n\t})\n\n\treturn gitOnce.path, gitOnce.err\n}", "func (ss *Sources) gitFetch(spec v1.SourceSpec) (string, error) {\n\tp := ss.repoPath(spec)\n\t_, err := os.Stat(p)\n\tif os.IsNotExist(err) {\n\t\t// Clone new repo.\n\t\td, _ := filepath.Split(p)\n\t\terr = os.MkdirAll(d, 0750)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\t_, _, err = exe.Run(ss.Log, &exe.Opt{Dir: d}, \"\", \"git\", \"clone\", urlWithToken(spec.URL, spec.Token))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\t_, _, err = exe.Run(ss.Log, &exe.Opt{Dir: p}, \"\", \"git\", \"checkout\", spec.Ref)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tss.Log.Info(\"GIT-clone\", \"url\", spec.URL, \"ref\", spec.Ref)\n\t} else {\n\t\t// Pull existing repo content.\n\t\t_, _, err = exe.Run(ss.Log, &exe.Opt{Dir: p}, \"\", \"git\", \"pull\", \"origin\", spec.Ref)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tss.Log.V(2).Info(\"GIT-pull\", \"url\", spec.URL, \"ref\", spec.Ref)\n\t}\n\n\t// Get hash.\n\th, _, err := exe.Run(ss.Log, &exe.Opt{Dir: p}, \"\", \"git\", \"rev-parse\", spec.Ref)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\th = strings.TrimRight(h, \"\\n\\r\")\n\tif len(h) == 0 {\n\t\treturn \"\", fmt.Errorf(\"expected git hash\")\n\t}\n\n\treturn h, nil\n}", "func (r *Repo) Git(cmd string, args ...string) (res *exec.Cmd, out, err *bytes.Buffer) {\n\tvar path string\n\tif r.WorkDir == \"\" {\n\t\tpath = r.GitDir\n\t} else {\n\t\tpath = r.WorkDir\n\t}\n\tres, out, err = Git(cmd, args...)\n\tres.Dir = path\n\treturn\n}", "func EnsureGitIsFromCIPD(ctx context.Context) error {\n\tgit, _, _, err := FindGit(ctx)\n\tif err != nil {\n\t\treturn skerr.Wrap(err)\n\t}\n\tif !IsFromCIPD(git) {\n\t\treturn skerr.Fmt(\"Git does not appear to be obtained via CIPD: %s\", git)\n\t}\n\treturn nil\n}", "func (o IopingSpecVolumeVolumeSourceOutput) GitRepo() IopingSpecVolumeVolumeSourceGitRepoPtrOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSource) *IopingSpecVolumeVolumeSourceGitRepo { return v.GitRepo }).(IopingSpecVolumeVolumeSourceGitRepoPtrOutput)\n}", "func (git *Git) Run() error {\n\tcmd := exec.Command(\"git\", \"clone\", \"--no-checkout\", git.URL, git.SourcePath)\n\n\t_, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"git clone --no-checkout %s %s. %s\", git.URL, git.SourcePath, err)\n\t}\n\n\tcmd = exec.Command(\"git\", \"remote\", \"add\", \"composer\", git.URL)\n\tcmd.Dir = git.SourcePath\n\n\t_, err = cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"git remote add composer %s. %s\", git.URL, err)\n\t}\n\n\tcmd = exec.Command(\"git\", \"fecth\", \"composer\")\n\tcmd.Dir = git.SourcePath\n\tcmd.CombinedOutput()\n\n\tcmd = exec.Command(\"git\", \"checkout\", \"-b\", git.Version, \"composer/\"+git.Version)\n\tcmd.Dir = git.SourcePath\n\tcmd.CombinedOutput()\n\n\tcmd = exec.Command(\"git\", \"reset\", \"--hard\", git.Source[\"reference\"])\n\tcmd.Dir = git.SourcePath\n\tcmd.CombinedOutput()\n\n\t_, err = os.Stat(git.SourcePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgit.PathExist = true\n\treturn nil\n}", "func (o FioSpecVolumeVolumeSourceOutput) GitRepo() FioSpecVolumeVolumeSourceGitRepoPtrOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSource) *FioSpecVolumeVolumeSourceGitRepo { return v.GitRepo }).(FioSpecVolumeVolumeSourceGitRepoPtrOutput)\n}", "func (c cBuild) getGitCommit() string {\n\tif gproc.SearchBinary(\"git\") == \"\" {\n\t\treturn \"\"\n\t}\n\tvar (\n\t\tcmd = `git log -1 --format=\"%cd %H\" --date=format:\"%Y-%m-%d %H:%M:%S\"`\n\t\ts, _ = gproc.ShellExec(cmd)\n\t)\n\tmlog.Debug(cmd)\n\tif s != \"\" {\n\t\tif !gstr.Contains(s, \"fatal\") {\n\t\t\treturn gstr.Trim(s)\n\t\t}\n\t}\n\treturn \"\"\n}", "func findGitRoot(dir string) string {\n\torig := dir\n\tfor dir != \"\" && dir != \".\" && dir != \"/\" {\n\t\t_, err := os.Stat(filepath.Join(dir, \".git\"))\n\t\tif err == nil {\n\t\t\t// Found dir/.git, return dir.\n\t\t\treturn dir\n\t\t} else if !os.IsNotExist(err) {\n\t\t\t// Error finding .git, return original input.\n\t\t\treturn orig\n\t\t}\n\t\tdir, _ = filepath.Split(dir)\n\t\tdir = strings.TrimSuffix(dir, \"/\")\n\t}\n\treturn orig\n}", "func FindGithubRepo(ctx context.Context, file, githubInstance, remoteName string) (string, error) {\n\tif remoteName == \"\" {\n\t\tremoteName = \"origin\"\n\t}\n\n\turl, err := findGitRemoteURL(ctx, file, remoteName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t_, slug, err := findGitSlug(url, githubInstance)\n\treturn slug, err\n}", "func findBinary(name string) (string, error) {\n\tos.Setenv(\"PATH\", SafeDockerSearchPath)\n\treturn exec.LookPath(name)\n}", "func (o FioSpecVolumeVolumeSourcePtrOutput) GitRepo() FioSpecVolumeVolumeSourceGitRepoPtrOutput {\n\treturn o.ApplyT(func(v *FioSpecVolumeVolumeSource) *FioSpecVolumeVolumeSourceGitRepo {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.GitRepo\n\t}).(FioSpecVolumeVolumeSourceGitRepoPtrOutput)\n}", "func (o GroupInitContainerVolumeOutput) GitRepo() GroupInitContainerVolumeGitRepoPtrOutput {\n\treturn o.ApplyT(func(v GroupInitContainerVolume) *GroupInitContainerVolumeGitRepo { return v.GitRepo }).(GroupInitContainerVolumeGitRepoPtrOutput)\n}", "func FindGitRevision(ctx context.Context, file string) (shortSha string, sha string, err error) {\n\tlogger := common.Logger(ctx)\n\n\tgitDir, err := git.PlainOpenWithOptions(\n\t\tfile,\n\t\t&git.PlainOpenOptions{\n\t\t\tDetectDotGit: true,\n\t\t\tEnableDotGitCommonDir: true,\n\t\t},\n\t)\n\n\tif err != nil {\n\t\tlogger.WithError(err).Error(\"path\", file, \"not located inside a git repository\")\n\t\treturn \"\", \"\", err\n\t}\n\n\thead, err := gitDir.Reference(plumbing.HEAD, true)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\tif head.Hash().IsZero() {\n\t\treturn \"\", \"\", fmt.Errorf(\"HEAD sha1 could not be resolved\")\n\t}\n\n\thash := head.Hash().String()\n\n\tlogger.Debugf(\"Found revision: %s\", hash)\n\treturn hash[:7], strings.TrimSpace(hash), nil\n}", "func HasGitBinary() bool {\n\t_, err := exec.LookPath(\"git\")\n\treturn err == nil\n}", "func (o IopingSpecVolumeVolumeSourcePtrOutput) GitRepo() IopingSpecVolumeVolumeSourceGitRepoPtrOutput {\n\treturn o.ApplyT(func(v *IopingSpecVolumeVolumeSource) *IopingSpecVolumeVolumeSourceGitRepo {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.GitRepo\n\t}).(IopingSpecVolumeVolumeSourceGitRepoPtrOutput)\n}", "func FindGitByUserId(uid int32) (*Git, error) {\n\tvar git Git\n\terr := DB.Find(&git).Where(\"userid = ?\", uid).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &git, err\n}", "func GetGitRepositoryDefaultBranch(url string) (string, error) {\n\terr := C.git_libgit2_init()\n\tif err < 0 {\n\t\treturn \"\", errors.New(\"failed to initialize libgit2\")\n\t}\n\tvar odb *C.git_odb\n\terr = C.git_odb_new(&odb)\n\tif err != 0 {\n\t\treturn \"\", errors.New(\"failed to create git_odb\")\n\t}\n\tvar repo *C.git_repository\n\terr = C.git_repository_wrap_odb(&repo, odb)\n\tif err != 0 {\n\t\treturn \"\", errors.New(\"failed to wrap odb into repository\")\n\t}\n\tvar remote *C.git_remote\n\terr = C.git_remote_create_anonymous(&remote, repo, C.CString(url))\n\tif err != 0 {\n\t\treturn \"\", errors.New(\"failed to create anonymous remote\")\n\t}\n\terr = C.git_remote_connect(remote, C.GIT_DIRECTION_FETCH, nil, nil, nil)\n\tif err != 0 {\n\t\treturn \"\", errors.New(\"failed to connect to remote (fetch)\")\n\t}\n\tvar remote_heads **C.git_remote_head\n\tvar remote_heads_size C.ulong\n\terr = C.git_remote_ls(&remote_heads, &remote_heads_size, remote)\n\tif err != 0 {\n\t\treturn \"\", errors.New(\"failed to list remote heads\")\n\t}\n\tvar remote_heads2 []*C.git_remote_head\n\tsh := (*reflect.SliceHeader)(unsafe.Pointer(&remote_heads2))\n\tsh.Data = uintptr(unsafe.Pointer(remote_heads))\n\tsh.Len = int(remote_heads_size)\n\tsh.Cap = int(remote_heads_size)\n\tfound := \"\"\n\tfor _, remote_head := range remote_heads2 {\n\t\tif remote_head.symref_target != nil {\n\t\t\t// s := C.GoString(C.git_oid_tostr_s(&remote_head.oid))\n\t\t\th := C.GoString(remote_head.name)\n\t\t\tif h != \"HEAD\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsr := C.GoString(remote_head.symref_target)\n\t\t\tsr = strings.TrimPrefix(sr, \"refs/heads/\")\n\t\t\tlog.Printf(\"[%s] Found default branch name = %s\\n\", h, sr)\n\t\t\tfound = sr\n\t\t}\n\t}\n\tC.git_remote_free(remote)\n\tC.git_repository_free(repo)\n\tC.git_odb_free(odb)\n\tC.git_libgit2_shutdown()\n\n\treturn found, nil\n}", "func (r *Repository) GetGitRepo() string {\n\tif r.BuildSource != nil {\n\t\tsurl, _ := r.BuildSource.GetSourceUrl()\n\t\tif surl != nil {\n\t\t\treturn surl.String()\n\t\t}\n\t}\n\tvalidLinks := r.GetGitRepoLinks()\n\tif validLinks == nil {\n\t\treturn \"\"\n\t}\n\turlx := getMostCommonUrl(validLinks, 5)\n\treturn urlx\n}", "func IsGitRepository(path string) bool {\n\tvar out bytes.Buffer\n\tcmd := exec.Command(\"git\", \"-C\", options.Dir, \"rev-parse\", \"--is-inside-work-tree\")\n\tcmd.Stdout = &out\n\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Println(\"ERROR\", err)\n\t\treturn false\n\t}\n\n\tvar val bool\n\t_, err = fmt.Sscanf(out.String(), \"%t\", &val)\n\tif err != nil {\n\t\tlog.Println(\"ERROR\", err)\n\t\treturn false\n\t}\n\n\treturn val\n}", "func discoverRemoteGitURL() (string, error) {\n\t_, gitConfig, err := findGitConfigDir()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"there was a problem obtaining the remote Git URL: %w\", err)\n\t}\n\n\tremoteGitURL, err := discoverRemoteGitURLFromGitConfig(gitConfig)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"there was a problem obtaining the remote Git URL: %w\", err)\n\t}\n\n\treturn remoteGitURL, nil\n}", "func gitPath(path string) string {\n\troot := repoRoot()\n\t// git 2.13.0 changed the behavior of --git-path from printing\n\t// a path relative to the repo root to printing a path\n\t// relative to the working directory (issue #19477). Normalize\n\t// both behaviors by running the command from the repo root.\n\tp, err := trimErr(cmdOutputErr(\"git\", \"-C\", root, \"rev-parse\", \"--git-path\", path))\n\tif err != nil {\n\t\t// When --git-path is not available, assume the common case.\n\t\tp = filepath.Join(\".git\", path)\n\t}\n\tif !filepath.IsAbs(p) {\n\t\tp = filepath.Join(root, p)\n\t}\n\treturn p\n}", "func (g *GitLocal) FindGitConfigDir(dir string) (string, string, error) {\n\treturn g.GitCLI.FindGitConfigDir(dir)\n}", "func findGitDir(dir string) (string, error) {\n\tvar err error\n\n\tdir, err = absPath(dir)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor {\n\t\t// Check if is in a bare repo\n\t\tif isGitDir(dir) {\n\t\t\treturn dir, nil\n\t\t}\n\n\t\t// Check .git\n\t\tgitdir := filepath.Join(dir, \".git\")\n\t\tfi, err := os.Stat(gitdir)\n\t\tif err != nil {\n\t\t\t// Test parent dir\n\t\t\toldDir := dir\n\t\t\tdir = filepath.Dir(dir)\n\t\t\tif oldDir == dir {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcontinue\n\t\t} else if fi.IsDir() {\n\t\t\tif isGitDir(gitdir) {\n\t\t\t\treturn gitdir, nil\n\t\t\t}\n\t\t\treturn \"\", fmt.Errorf(\"corrupt git dir: %s\", gitdir)\n\t\t} else {\n\t\t\tf, err := os.Open(gitdir)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", fmt.Errorf(\"cannot open gitdir file '%s'\", gitdir)\n\t\t\t}\n\t\t\tdefer f.Close()\n\t\t\treader := bufio.NewReader(f)\n\t\t\tline, err := reader.ReadString('\\n')\n\t\t\tif strings.HasPrefix(line, \"gitdir:\") {\n\t\t\t\trealgit := strings.TrimSpace(strings.TrimPrefix(line, \"gitdir:\"))\n\t\t\t\tif !filepath.IsAbs(realgit) {\n\t\t\t\t\trealgit, err = absJoin(filepath.Dir(gitdir), realgit)\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\tif isGitDir(realgit) {\n\t\t\t\t\treturn realgit, nil\n\t\t\t\t}\n\t\t\t\treturn \"\", fmt.Errorf(\"gitdir '%s' points to corrupt git repo: %s\", gitdir, realgit)\n\t\t\t}\n\t\t\treturn \"\", fmt.Errorf(\"bad gitdir file '%s'\", gitdir)\n\t\t}\n\t}\n\treturn \"\", ErrNotInGitDir\n}", "func Find() (string, error) {\n\tp, err := os.Getwd()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Cannot get working dir: %v\", err)\n\t}\n\n\treturn findRecursiveGoMod(p)\n}", "func (o *RunOptions) findRequirementsAndGitURL() (*config.RequirementsConfig, string, error) {\n\tif o.JXFactory == nil {\n\t\to.JXFactory = jxfactory.NewFactory()\n\t}\n\n\tvar requirements *config.RequirementsConfig\n\tgitURL := \"\"\n\n\tjxClient, ns, err := o.JXFactory.CreateJXClient()\n\tif err != nil {\n\t\treturn requirements, gitURL, err\n\t}\n\tdevEnv, err := kube.GetDevEnvironment(jxClient, ns)\n\tif err != nil && !apierrors.IsNotFound(err) {\n\t\treturn requirements, gitURL, err\n\t}\n\tif devEnv != nil {\n\t\tgitURL = devEnv.Spec.Source.URL\n\t\trequirements, err = config.GetRequirementsConfigFromTeamSettings(&devEnv.Spec.TeamSettings)\n\t\tif err != nil {\n\t\t\tlog.Logger().Debugf(\"failed to load requirements from team settings %s\", err.Error())\n\t\t}\n\t}\n\tif o.GitURL != \"\" {\n\t\tgitURL = o.GitURL\n\n\t\tif requirements == nil {\n\t\t\trequirements, err = reqhelpers.GetRequirementsFromGit(gitURL)\n\t\t\tif err != nil {\n\t\t\t\treturn requirements, gitURL, errors.Wrapf(err, \"failed to get requirements from git URL %s\", gitURL)\n\t\t\t}\n\t\t}\n\t}\n\n\tif requirements == nil {\n\t\trequirements, _, err = config.LoadRequirementsConfig(o.Dir)\n\t\tif err != nil {\n\t\t\treturn requirements, gitURL, err\n\t\t}\n\t}\n\n\tif gitURL == \"\" {\n\t\t// lets try find the git URL from\n\t\tgitURL, err = o.findGitURLFromDir()\n\t\tif err != nil {\n\t\t\treturn requirements, gitURL, errors.Wrapf(err, \"your cluster has not been booted before and you are not inside a git clone of your dev environment repository so you need to pass in the URL of the git repository as --git-url\")\n\t\t}\n\t}\n\treturn requirements, gitURL, nil\n}", "func (b *taskBuilder) usesGit() {\n\tb.cache(CACHES_GIT...)\n\tif b.matchOs(\"Win\") || b.matchExtraConfig(\"Win\") {\n\t\tb.cipd(specs.CIPD_PKGS_GIT_WINDOWS_AMD64...)\n\t} else if b.matchOs(\"Mac\") || b.matchExtraConfig(\"Mac\") {\n\t\tb.cipd(specs.CIPD_PKGS_GIT_MAC_AMD64...)\n\t} else {\n\t\tb.cipd(specs.CIPD_PKGS_GIT_LINUX_AMD64...)\n\t}\n}", "func (o GroupContainerVolumeOutput) GitRepo() GroupContainerVolumeGitRepoPtrOutput {\n\treturn o.ApplyT(func(v GroupContainerVolume) *GroupContainerVolumeGitRepo { return v.GitRepo }).(GroupContainerVolumeGitRepoPtrOutput)\n}", "func (f *RepoFinder) Find() error {\n\tif _, err := Exists(f.root); err != nil {\n\t\treturn err\n\t}\n\n\twalkOpts := &godirwalk.Options{\n\t\tErrorCallback: f.errorCb,\n\t\tCallback: f.walkCb,\n\t\t// Use Unsorted to improve speed because repos will be processed by goroutines in a random order anyway.\n\t\tUnsorted: true,\n\t}\n\n\terr := godirwalk.Walk(f.root, walkOpts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(f.repos) == 0 {\n\t\treturn fmt.Errorf(\"no git repos found in root path %s\", f.root)\n\t}\n\n\treturn nil\n}", "func IsGitFile(path string) (string, string) {\n\turi := strings.Split(path, \"/\")\n\tif len(uri) < 8 {\n\t\treturn \"\", \"\"\n\t}\n\trepository := fmt.Sprintf(\"https://%s/%s/%s\", uri[0], uri[1], uri[2])\n\tfile := strings.Join(uri[5:], \"/\")\n\tif strings.HasPrefix(uri[0], \"http\") {\n\t\trepository = fmt.Sprintf(\"%s//%s/%s/%s\", uri[0], uri[2], uri[3], uri[4])\n\t\tfile = strings.Join(uri[7:], \"/\")\n\t}\n\tif !IsGit(repository) {\n\t\treturn \"\", \"\"\n\t}\n\treturn repository, file\n}", "func execGitCommand(ctx context.Context, store store.Store, repositoryID int, args ...string) (string, error) {\n\trepo, err := repositoryIDToRepo(ctx, store, repositoryID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcmd := gitserver.DefaultClient.Command(\"git\", args...)\n\tcmd.Repo = repo\n\tout, err := cmd.CombinedOutput(ctx)\n\treturn string(bytes.TrimSpace(out)), errors.Wrap(err, \"gitserver.Command\")\n}", "func GetGitHome() (string, error) {\n\tgoctlH, err := GetGoctlHome()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn filepath.Join(goctlH, gitDir), nil\n}", "func (r BuildInfoResolver) GitCommit() *string {\n\tif c := r.bi.GitCommit; c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func FindRootRepoPath() (string, error) {\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"Error getting pwd: \", err)\n\t\tos.Exit(1)\n\t}\n\n\tparts := strings.SplitAfter(pwd, string(os.PathSeparator))\n\tfor i, _ := range parts {\n\t\ttestPath := path.Join(parts[:i+1]...)\n\t\tif IsRepo(testPath) {\n\t\t\treturn testPath, nil\n\t\t}\n\t}\n\n\t// Return pwd in case we're cloning into pwd.\n\treturn pwd, fmt.Errorf(\"No .git found in %s or any parent dir.\", pwd)\n}", "func IsGit(path string) bool {\n\tif strings.HasSuffix(path, \".git\") || strings.HasPrefix(path, \"git@\") {\n\t\treturn true\n\t}\n\turl, err := url.Parse(path)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif url.Scheme == \"\" {\n\t\turl.Scheme = \"https\"\n\t}\n\tresp, err := http.Head(url.String() + \".git\")\n\tif err != nil {\n\t\treturn false\n\t}\n\tfor _, status := range []int{200, 301, 302, 401} {\n\t\tif resp.StatusCode == status {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func resolveGitPath(base, path string) string {\n\tif len(path) == 0 {\n\t\treturn base\n\t}\n\tif filepath.IsAbs(path) {\n\t\treturn path\n\t}\n\t// Note that git on Windows uses slashes exclusively. And it's okay\n\t// because Windows actually accepts both directory separators. More\n\t// importantly, however, parts of the git segment depend on those\n\t// slashes.\n\tif path[0] == '/' {\n\t\t// path is a disk-relative path.\n\t\treturn filepath.VolumeName(base) + path\n\t}\n\treturn filepath.ToSlash(filepath.Join(base, path))\n}", "func main() {\n\trepoPath := filepath.Join(os.Getenv(\"GOPATH\"), \"src/github.com/libgit2/git2go\")\n\tgitRepo, err := git.OpenRepository(repoPath)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcommitOid, err := gitRepo.Head()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tblob, _ := gitRepo.LookupBlob(commitOid.Target())\n\tlog.Println(blob)\n\t// commit, err := gitRepo.LookupCommit(commitOid)\n\tcommit, err := gitRepo.LookupCommit(commitOid.Target())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcommitTree, err := commit.Tree()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\toptions, err := git.DefaultDiffOptions()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\toptions.IdAbbrev = 40\n\toptions.InterhunkLines = 0\n\toptions.Flags = git.DiffIncludeUntracked\n\tvar parentTree *git.Tree\n\tif commit.ParentCount() > 0 {\n\t\tparentTree, err = commit.Parent(0).Tree()\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\tgitDiff, err := gitRepo.DiffTreeToTree(parentTree, commitTree, &options)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfindOpts, err := git.DefaultDiffFindOptions()\n\tfindOpts.Flags = git.DiffFindBreakRewrites\n\terr = gitDiff.FindSimilar(&findOpts)\n\n\t// Show all file patch diffs in a commit.\n\tfiles := make([]string, 0)\n\thunks := make([]git.DiffHunk, 0)\n\tlines := make([]git.DiffLine, 0)\n\tpatches := make([]string, 0)\n\terr = gitDiff.ForEach(func(file git.DiffDelta, progress float64) (git.DiffForEachHunkCallback, error) {\n\t\tpatch, err := gitDiff.Patch(len(patches))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer patch.Free()\n\t\tpatchStr, err := patch.String()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpatches = append(patches, patchStr)\n\n\t\tfiles = append(files, file.OldFile.Path)\n\t\treturn func(hunk git.DiffHunk) (git.DiffForEachLineCallback, error) {\n\t\t\thunks = append(hunks, hunk)\n\t\t\treturn func(line git.DiffLine) error {\n\t\t\t\tlines = append(lines, line)\n\t\t\t\treturn nil\n\t\t\t}, nil\n\t\t}, nil\n\t}, git.DiffDetailLines)\n\n\tlog.Println(\"files: \", files, \"\\n\")\n\tlog.Println(\"hunks: \", hunks, \"\\n\")\n\tlog.Println(\"lines: \", lines, \"\\n\")\n\tlog.Println(\"patches: \", patches, \"\\n\")\n}", "func (r *Repository) GetGitURL() string {\n\tif r == nil || r.GitURL == nil {\n\t\treturn \"\"\n\t}\n\treturn *r.GitURL\n}", "func (a *JXAdapter) findGitTokenForServer(serverURL string, owner string) (string, string, error) {\n\tco := a.NewCommonOptions()\n\tauthSvc, err := co.GitLocalAuthConfigService()\n\ttoken := \"\"\n\tkind := \"\"\n\tif err != nil {\n\t\treturn token, kind, errors.Wrapf(err, \"failed to load local git auth\")\n\t}\n\tcfg, err := authSvc.LoadConfig()\n\tif err != nil {\n\t\treturn token, kind, errors.Wrapf(err, \"failed to load local git auth config\")\n\t}\n\tif cfg == nil {\n\t\tcfg = &auth.AuthConfig{}\n\t}\n\tserver := cfg.GetOrCreateServer(serverURL)\n\tkind = server.Kind\n\tif kind == \"\" {\n\t\tkind = gits.SaasGitKind(serverURL)\n\t}\n\n\tuserAuth, err := cfg.PickServerUserAuth(server, \"Git user name:\", a.BatchMode, owner, co.GetIOFileHandles())\n\tif err != nil {\n\t\treturn token, kind, err\n\t}\n\n\tif userAuth == nil || userAuth.IsInvalid() {\n\t\treturn token, kind, errors.Wrapf(err, \"no valid token setup for git server %s\", serverURL)\n\t}\n\ttoken = userAuth.ApiToken\n\tif token == \"\" {\n\t\ttoken = userAuth.BearerToken\n\t}\n\treturn token, kind, nil\n}", "func (o *RunOptions) Git() gits.Gitter {\n\tif o.Gitter == nil {\n\t\to.Gitter = gits.NewGitCLI()\n\t}\n\treturn o.Gitter\n}", "func (r *RepositoryLicense) GetGitURL() string {\n\tif r == nil || r.GitURL == nil {\n\t\treturn \"\"\n\t}\n\treturn *r.GitURL\n}", "func RetrieveGitRepositories(rootpath string) ([]string, error) {\n\tvar gitPaths []string\n\terr := filepath.Walk(rootpath, func(pathdir string, fileInfo os.FileInfo, err error) error {\n\t\tif fileInfo.IsDir() && filepath.Base(pathdir) == consts.GitFileName {\n\t\t\tfileDir := filepath.Dir(pathdir)\n\t\t\ttraces.DebugTracer.Printf(\"Just found in hard drive %s\\n\", fileDir)\n\t\t\tgitPaths = append(gitPaths, fileDir)\n\t\t}\n\t\treturn nil\n\t})\n\treturn gitPaths, err\n}", "func gitGetGitHubURL() (string, string, error) {\n\n\ttry := func(remote string) (string, error) {\n\t\tcmd := exec.Command(\"git\", \"config\", \"--get\", fmt.Sprintf(\"remote.%s.url\", remote))\n\t\toutput, err := cmd.CombinedOutput()\n\t\tlg.dbg(\"git config --get remote.%s.url:\\n%s---\", remote, string(output))\n\t\tif err != nil {\n\t\t\tif len(output) == 0 {\n\t\t\t\t// Probably no remote\n\t\t\t\t// FIXME Add check to see if we're in a git repository\n\t\t\t\treturn \"\", nil\n\t\t\t}\n\t\t\treturn \"\", fmt.Errorf(\"git: %v: %s\", err, firstLine(output))\n\t\t}\n\t\treturn string(bytes.TrimSpace(output)), nil\n\t}\n\n\tfor _, remote := range []string{\"origin\", \"github\"} {\n\t\tremote, err := try(remote)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", err\n\t\t}\n\t\tif match := matchGitHubURL.FindStringSubmatch(remote); match != nil {\n\t\t\treturn match[1], match[2], nil\n\t\t}\n\t}\n\treturn \"\", \"\", nil\n}", "func GetDotGitPath(path string) (result string, err error) {\n\tdir, err := filepath.Abs(path)\n\tfiles, err := ioutil.ReadDir(dir)\n\tif err != nil {\n\t\tdir = filepath.Dir(path)\n\t\treturn GetDotGitPath(dir)\n\t}\n\n\tfor _, file := range files {\n\t\tif file.IsDir() && file.Name() == \".git\" {\n\t\t\treturn dir, err\n\t\t}\n\t}\n\n\tif dir != \"/\" {\n\t\tdir = filepath.Dir(dir)\n\t\treturn GetDotGitPath(dir)\n\t}\n\treturn result, err\n}", "func Sync(workdir string) (string, error) {\n\t// Clone the repo if necessary.\n\tco, err := git.NewCheckout(common.REPO_DEPOT_TOOLS, workdir)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Avoid doing any syncing if we already have the desired revision.\n\thash, err := co.RevParse(\"HEAD\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif hash == DEPOT_TOOLS_VERSION {\n\t\treturn co.Dir(), nil\n\t}\n\n\t// Sync the checkout into the desired state.\n\tif err := co.Fetch(); err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to fetch repo in %s: %s\", co.Dir(), err)\n\t}\n\tif err := co.Cleanup(); err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to cleanup repo in %s: %s\", co.Dir(), err)\n\t}\n\tif _, err := co.Git(\"reset\", \"--hard\", DEPOT_TOOLS_VERSION); err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to reset repo in %s: %s\", co.Dir(), err)\n\t}\n\thash, err = co.RevParse(\"HEAD\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif hash != DEPOT_TOOLS_VERSION {\n\t\treturn \"\", fmt.Errorf(\"Got incorrect depot_tools revision: %s\", hash)\n\t}\n\treturn co.Dir(), nil\n}", "func (p *PushEventRepository) GetGitURL() string {\n\tif p == nil || p.GitURL == nil {\n\t\treturn \"\"\n\t}\n\treturn *p.GitURL\n}", "func Git(cmd string, args ...string) (res *exec.Cmd, stdout, stderr *bytes.Buffer) {\n\tcmdArgs := make([]string, 1)\n\tcmdArgs[0] = cmd\n\tcmdArgs = append(cmdArgs, args...)\n\tres = exec.Command(gitCmd, cmdArgs...)\n\tstdout, stderr = new(bytes.Buffer), new(bytes.Buffer)\n\tres.Stdout, res.Stderr = stdout, stderr\n\treturn\n}", "func detectVCS(path string) (string, error) {\n\t// check tar archive case\n\tif strings.HasSuffix(path, \".tar\") {\n\t\tarchiveFile, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tdefer archiveFile.Close()\n\n\t\t// only the relative path shall be stored in the archive\n\t\tpath = filepath.Base(strings.TrimSuffix(path, \".tar\"))\n\n\t\ttr := tar.NewReader(archiveFile)\n\n\t\tfor {\n\t\t\thdr, err := tr.Next()\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\tmode := hdr.FileInfo().Mode()\n\t\t\tif mode&os.ModeDir != 0 {\n\t\t\t\t// remove trailing /, if any\n\t\t\t\tdir := strings.TrimSuffix(hdr.Name, \"/\")\n\t\t\t\tswitch dir {\n\t\t\t\t// is it a git repository?\n\t\t\t\t// (only the archive root's .git directory is valid for the check)\n\t\t\t\tcase filepath.Join(path, \".git\"):\n\t\t\t\t\treturn Git, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// is it a git repository?\n\t\tif _, err := os.Stat(filepath.Join(path, \".git\")); err == nil {\n\t\t\treturn Git, nil\n\t\t}\n\t}\n\n\treturn \"\", errors.New(\"VCS type not found\")\n}", "func TestGitCommandCheckout(t *testing.T) {\n\ttype scenario struct {\n\t\ttestName string\n\t\tcommand func(string, ...string) *exec.Cmd\n\t\ttest func(error)\n\t\tforce bool\n\t}\n\n\tscenarios := []scenario{\n\t\t{\n\t\t\t\"Checkout\",\n\t\t\tfunc(cmd string, args ...string) *exec.Cmd {\n\t\t\t\tassert.EqualValues(t, \"git\", cmd)\n\t\t\t\tassert.EqualValues(t, []string{\"checkout\", \"test\"}, args)\n\n\t\t\t\treturn secureexec.Command(\"echo\")\n\t\t\t},\n\t\t\tfunc(err error) {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t},\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"Checkout forced\",\n\t\t\tfunc(cmd string, args ...string) *exec.Cmd {\n\t\t\t\tassert.EqualValues(t, \"git\", cmd)\n\t\t\t\tassert.EqualValues(t, []string{\"checkout\", \"--force\", \"test\"}, args)\n\n\t\t\t\treturn secureexec.Command(\"echo\")\n\t\t\t},\n\t\t\tfunc(err error) {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t},\n\t\t\ttrue,\n\t\t},\n\t}\n\n\tfor _, s := range scenarios {\n\t\tt.Run(s.testName, func(t *testing.T) {\n\t\t\tgitCmd := NewDummyGitCommand()\n\t\t\tgitCmd.OSCommand.Command = s.command\n\t\t\ts.test(gitCmd.Checkout(\"test\", CheckoutOptions{Force: s.force}))\n\t\t})\n\t}\n}", "func getRepoDOI(c *Context) string {\n\trepo := c.Repo.Repository\n\tvar doiFork *db.Repository\n\tif repo.Owner.Name == \"doi\" {\n\t\tdoiFork = repo\n\t} else {\n\t\tif forks, err := repo.GetForks(); err == nil {\n\t\t\tfor _, fork := range forks {\n\t\t\t\tif fork.MustOwner().Name == \"doi\" {\n\t\t\t\t\tdoiFork = fork\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Error(2, \"failed to get forks for repository %q (%d): %v\", repo.FullName(), repo.ID, err)\n\t\t\treturn \"\"\n\t\t}\n\t}\n\n\tif doiFork == nil {\n\t\t// not owned or forked by DOI, so not registered\n\t\treturn \"\"\n\t}\n\n\t// check the DOI fork for a tag that matches our DOI prefix\n\t// if multiple exit, get the latest one\n\tdoiBase := conf.DOI.Base\n\n\tdoiForkGit, err := git.Open(doiFork.RepoPath())\n\tif err != nil {\n\t\tlog.Error(2, \"failed to open git repository at %q (%d): %v\", doiFork.RepoPath(), doiFork.ID, err)\n\t\treturn \"\"\n\t}\n\tif tags, err := doiForkGit.Tags(); err == nil {\n\t\tvar latestTime int64\n\t\tlatestTag := \"\"\n\t\tfor _, tagName := range tags {\n\t\t\tif strings.Contains(tagName, doiBase) {\n\t\t\t\ttag, err := doiForkGit.Tag(tagName)\n\t\t\t\tif err != nil {\n\t\t\t\t\t// log the error and continue to the next tag\n\t\t\t\t\tlog.Error(2, \"failed to get information for tag %q for repository at %q: %v\", tagName, doiForkGit.Path(), err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tcommit, err := tag.Commit()\n\t\t\t\tif err != nil {\n\t\t\t\t\t// log the error and continue to the next tag\n\t\t\t\t\tlog.Error(2, \"failed to get commit for tag %q for repository at %q: %v\", tagName, doiForkGit.Path(), err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tcommitTime := commit.Committer.When.Unix()\n\t\t\t\tif commitTime > latestTime {\n\t\t\t\t\tlatestTag = tagName\n\t\t\t\t\tlatestTime = commitTime\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn latestTag\n\t} else {\n\t\t// this shouldn't happen even if there are no tags\n\t\t// log the error, but fall back to the old method anyway\n\t\tlog.Error(2, \"failed to get tags for repository at %q: %v\", doiForkGit.Path(), err)\n\t}\n\n\t// Has DOI fork but isn't tagged: return old style has-based DOI\n\trepoPath := repo.FullName()\n\t// get base repo name if it's a DOI fork\n\tif c.Repo.Repository.IsFork && c.Repo.Owner.Name == \"doi\" {\n\t\trepoPath = c.Repo.Repository.BaseRepo.FullName()\n\t}\n\tuuid := libgin.RepoPathToUUID(repoPath)\n\treturn doiBase + uuid[:6]\n}", "func TestGitCommandGetBranchGraph(t *testing.T) {\n\tgitCmd := NewDummyGitCommand()\n\tgitCmd.OSCommand.Command = func(cmd string, args ...string) *exec.Cmd {\n\t\tassert.EqualValues(t, \"git\", cmd)\n\t\tassert.EqualValues(t, []string{\"log\", \"--graph\", \"--color=always\", \"--abbrev-commit\", \"--decorate\", \"--date=relative\", \"--pretty=medium\", \"test\", \"--\"}, args)\n\t\treturn secureexec.Command(\"echo\")\n\t}\n\t_, err := gitCmd.GetBranchGraph(\"test\")\n\tassert.NoError(t, err)\n}", "func ImageTagForGitRepo(repoDir string, tag string) (tagOrCommitHash string, err error) {\n\tgit := \"git\"\n\tif !CommandExists(git) {\n\t\terr = fmt.Errorf(\"command not exists: %s\", git)\n\t\treturn\n\t}\n\n\tif !GitRepoExists(repoDir) {\n\t\terr = fmt.Errorf(\"git repo not exists: %s\", repoDir)\n\t\treturn\n\t}\n\n\tif tag != \"\" && GitTagExists(repoDir, tag) {\n\t\ttagOrCommitHash = tag\n\t\treturn\n\t}\n\n\ttagOrCommitHash = LatestGitCommitHash(repoDir, true)\n\tif tagOrCommitHash == \"\" {\n\t\terr = fmt.Errorf(\"failed to get latest commit hash\")\n\t\treturn\n\t}\n\treturn\n}", "func GitRepo(ctx context.Context, repo *types.Repo) (gitserver.Repo, error) {\n\tif gitserverRepo := quickGitserverRepo(repo.Name); gitserverRepo != nil {\n\t\treturn *gitserverRepo, nil\n\t}\n\n\tresult, err := repoupdater.DefaultClient.RepoLookup(ctx, protocol.RepoLookupArgs{\n\t\tRepo: repo.Name,\n\t\tExternalRepo: repo.ExternalRepo,\n\t})\n\tif err != nil {\n\t\treturn gitserver.Repo{Name: repo.Name}, err\n\t}\n\tif result.Repo == nil {\n\t\treturn gitserver.Repo{Name: repo.Name}, repoupdater.ErrNotFound\n\t}\n\treturn gitserver.Repo{Name: result.Repo.Name, URL: result.Repo.VCS.URL}, nil\n}", "func followGitSubmodule(fs fs.FileSystem, gitPath string) (string, error) {\n\tf, err := os.Open(gitPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer f.Close()\n\n\tsc := bufio.NewScanner(f)\n\tif sc.Scan() {\n\t\ts := sc.Text()\n\n\t\tif strings.HasPrefix(s, \"gitdir: \") {\n\t\t\tnewGitPath := s[8:]\n\n\t\t\tif !filepath.IsAbs(newGitPath) {\n\t\t\t\tnewGitPath = filepath.Join(filepath.Dir(gitPath), newGitPath)\n\t\t\t}\n\n\t\t\tfi, err := fs.Stat(newGitPath)\n\t\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\tif os.IsNotExist(err) || !fi.IsDir() {\n\t\t\t\treturn \"\", fmt.Errorf(\"gitdir link in .git file %q is invalid\", gitPath)\n\t\t\t}\n\t\t\treturn newGitPath, nil\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"unable to parse .git file %q\", gitPath)\n}", "func Git(argv []string, cmdr cmd.Commander) error {\n\tusage := executable.Render(`\nValid commands for git:\n\ngit:remote Adds git remote of application to repository\ngit:remove Removes git remote of application from repository\n\nUse '{{.Name}} help [command]' to learn more.\n`)\n\n\tswitch argv[0] {\n\tcase \"git:remote\":\n\t\treturn gitRemote(argv, cmdr)\n\tcase \"git:remove\":\n\t\treturn gitRemove(argv, cmdr)\n\tcase \"git\":\n\t\tfmt.Print(usage)\n\t\treturn nil\n\tdefault:\n\t\tPrintUsage(cmdr)\n\t\treturn nil\n\t}\n}", "func _detectRemoteURL_LocalGit(path string) (string, error) {\n\tcmd := exec.Command(\"git\", \"config\", \"--get\", \"remote.origin.url\")\n\toutput, err := cmd.Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(bytes.TrimSpace(output)), nil\n}", "func (c *Config) GitInit() {\n\tfor _, service := range c.Services {\n\t\tif service.Name != \"BDD\" {\n\t\t\tfor k := range service.Values {\n\t\t\t\tdir := filepath.Join(c.ProjectName, service.Values[k])\n\t\t\t\tif _, err := os.Stat(dir + \"/.git\"); !os.IsNotExist(err) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\trepo, err := git.PlainInit(dir, false)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(err)\n\t\t\t\t}\n\n\t\t\t\tvalue := \"\"\n\t\t\t\tprompt := &survey.Select{\n\t\t\t\t\tMessage: \"Il y a-t-il un repo GitLab pour le \" + service.Name + \"/\" + service.Values[k] + \" ?\",\n\t\t\t\t\tOptions: []string{\"Oui\", \"Non\"},\n\t\t\t\t}\n\t\t\t\tsurvey.AskOne(prompt, &value)\n\n\t\t\t\tif value == \"Oui\" {\n\t\t\t\t\tvar urlGitlab string\n\t\t\t\t\tprompt := &survey.Input{\n\t\t\t\t\t\tMessage: \"Entrer l'URL http GitLab\",\n\t\t\t\t\t}\n\t\t\t\t\tsurvey.AskOne(prompt, &urlGitlab)\n\n\t\t\t\t\t_, err = repo.CreateRemote(&config.RemoteConfig{\n\t\t\t\t\t\tName: \"origin\",\n\t\t\t\t\t\tURLs: []string{urlGitlab},\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (Golang) Checkout(gopath string, meta Metadata, branch string) (err error) {\n\terr = os.Chdir(gopath)\n\tif err != nil {\n\t\terr = errors.Wrapf(err, \"failed to cwd to %s\", gopath)\n\t\treturn err\n\t}\n\n\t// install the code via go get after all, we don't really want to play if it's not in a repo.\n\tgobinary := \"go\"\n\tgocommand, err := exec.LookPath(gobinary)\n\tif err != nil {\n\t\terr = errors.Wrapf(err, \"failed to find go binary: %s\", gobinary)\n\t\treturn err\n\t}\n\n\trunenv := append(os.Environ(), fmt.Sprintf(\"GOPATH=%s\", gopath))\n\trunenv = append(runenv, \"GO111MODULE=off\")\n\n\tvar cmd *exec.Cmd\n\n\tif meta.InsecureGet {\n\t\tcmd = exec.Command(gocommand, \"get\", \"-v\", \"-insecure\", meta.Package)\n\t} else {\n\t\tcmd = exec.Command(gocommand, \"get\", \"-v\", \"-d\", fmt.Sprintf(\"%s/...\", meta.Package))\n\t}\n\n\tlogrus.Debugf(\"Running %s with GOPATH=%s\", cmd.Args, gopath)\n\n\tcmd.Env = runenv\n\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\n\terr = cmd.Run()\n\n\tif err == nil {\n\t\tlogrus.Debugf(\"Checkout of %s complete\", meta.Package)\n\t}\n\n\tgit, err := exec.LookPath(\"git\")\n\tif err != nil {\n\t\terr := errors.Wrap(err, \"Failed to find git executable in path\")\n\t\treturn err\n\t}\n\n\tcodepath := filepath.Join(gopath, \"src\", meta.Package)\n\n\terr = os.Chdir(codepath)\n\tif err != nil {\n\t\terr = errors.Wrapf(err, \"changing working dir to %q\", codepath)\n\t\treturn err\n\t}\n\n\tif branch != \"\" {\n\t\tlogrus.Debugf(\"Checking out branch: %s\", branch)\n\n\t\tcmd := exec.Command(git, \"checkout\", branch)\n\n\t\terr = cmd.Run()\n\t\tif err == nil {\n\t\t\tlogrus.Debugf(\"Checkout of branch: %s complete.\", branch)\n\t\t}\n\t}\n\n\treturn err\n}", "func (c *TestContext) FindRepoRoot() string {\n\tgoMod := c.findRepoFile(\"go.mod\")\n\treturn filepath.Dir(goMod)\n}", "func (repo *TestRepo) GitCommand(t *testing.T, args ...string) *exec.Cmd {\n\tt.Helper()\n\n\tgitArgs := []string{\"-C\", repo.Path}\n\tgitArgs = append(gitArgs, args...)\n\n\t//nolint:gosec // The args all come from the test code.\n\tcmd := exec.Command(\"git\", gitArgs...)\n\tcmd.Env = CleanGitEnv()\n\treturn cmd\n}", "func (r *RepositoryContent) GetGitURL() string {\n\tif r == nil || r.GitURL == nil {\n\t\treturn \"\"\n\t}\n\treturn *r.GitURL\n}", "func GetGitInfoFromDirectory(dir string, gitter Gitter) (string, string, error) {\n\t_, gitConfig, err := gitter.FindGitConfigDir(dir)\n\tif err != nil {\n\t\treturn \"\", \"\", errors.Wrapf(err, \"there was a problem obtaining the git config dir of directory %s\", dir)\n\t}\n\tremoteGitURL, err := gitter.DiscoverRemoteGitURL(gitConfig)\n\tif err != nil {\n\t\treturn \"\", \"\", errors.Wrapf(err, \"there was a problem obtaining the remote Git URL of directory %s\", dir)\n\t}\n\tcurrentBranch, err := gitter.Branch(dir)\n\tif err != nil {\n\t\treturn \"\", \"\", errors.Wrapf(err, \"there was a problem obtaining the current branch on directory %s\", dir)\n\t}\n\tg, err := ParseGitURL(remoteGitURL)\n\tif err != nil {\n\t\treturn \"\", \"\", errors.Wrapf(err, \"there was a problem parsing the Git URL %s to HTTPS\", remoteGitURL)\n\t}\n\n\treturn g.HttpsURL(), currentBranch, nil\n}", "func GetGitTag(dir string) (string, error) {\n\treturn runGit(dir, \"describe\", \"--tags\", \"--dirty\", \"--always\")\n}", "func (h *stiGit) Checkout(repo, ref string) error {\n\topts := cmd.CommandOpts{\n\t\tStdout: os.Stdout,\n\t\tStderr: os.Stderr,\n\t\tDir: repo,\n\t}\n\tif log.Is(1) {\n\t\treturn h.RunWithOptions(opts, \"git\", \"checkout\", \"--quiet\", ref)\n\t}\n\treturn h.RunWithOptions(opts, \"git\", \"checkout\", ref)\n}", "func findPathToSSHTools(ctx context.Context, sh *shell.Shell) (string, error) {\n\tsshKeyscan, err := sh.AbsolutePath(\"ssh-keyscan\")\n\tif err == nil {\n\t\treturn filepath.Dir(sshKeyscan), nil\n\t}\n\n\tif runtime.GOOS == \"windows\" {\n\t\texecPath, _ := sh.RunAndCapture(ctx, \"git\", \"--exec-path\")\n\t\tif len(execPath) > 0 {\n\t\t\tfor _, path := range []string{\n\t\t\t\tfilepath.Join(execPath, \"..\", \"..\", \"..\", \"usr\", \"bin\", \"ssh-keygen.exe\"),\n\t\t\t\tfilepath.Join(execPath, \"..\", \"..\", \"bin\", \"ssh-keygen.exe\"),\n\t\t\t} {\n\t\t\t\tif _, err := os.Stat(path); err == nil {\n\t\t\t\t\treturn filepath.Dir(path), nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"Unable to find ssh-keyscan: %v\", err)\n}", "func gitPathDir() string {\n\tgcd := trim(cmdOutput(\"git\", \"rev-parse\", \"--git-path\", \".\"))\n\tresult, err := filepath.Abs(gcd)\n\tif err != nil {\n\t\tdief(\"%v\", err)\n\t}\n\treturn result\n}", "func getGitLabConnection(args protocol.RepoLookupArgs) (*gitlabConnection, error) {\n\tgitlabConnections := gitlabConnections.Get().([]*gitlabConnection)\n\tif args.ExternalRepo != nil && args.ExternalRepo.ServiceType == gitlab.ServiceType {\n\t\t// Look up by external repository spec.\n\t\tfor _, conn := range gitlabConnections {\n\t\t\tif args.ExternalRepo.ServiceID == conn.baseURL.String() {\n\t\t\t\treturn conn, nil\n\t\t\t}\n\t\t}\n\t\treturn nil, errors.Wrap(gitlab.ErrNotFound, fmt.Sprintf(\"no configured GitLab connection with URL: %q\", args.ExternalRepo.ServiceID))\n\t}\n\n\tif args.Repo != \"\" {\n\t\t// Look up by repository name.\n\t\trepo := strings.ToLower(string(args.Repo))\n\t\tfor _, conn := range gitlabConnections {\n\t\t\tif strings.HasPrefix(repo, conn.baseURL.Hostname()+\"/\") {\n\t\t\t\treturn conn, nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil, nil\n}", "func GetGitLabRepository(ctx context.Context, args protocol.RepoLookupArgs) (repo *protocol.RepoInfo, authoritative bool, err error) {\n\tif GetGitLabRepositoryMock != nil {\n\t\treturn GetGitLabRepositoryMock(args)\n\t}\n\n\tghrepoToRepoInfo := func(proj *gitlab.Project, conn *gitlabConnection) *protocol.RepoInfo {\n\t\treturn &protocol.RepoInfo{\n\t\t\tName: gitlabProjectToRepoPath(conn, proj),\n\t\t\tExternalRepo: gitlab.ExternalRepoSpec(proj, *conn.baseURL),\n\t\t\tDescription: proj.Description,\n\t\t\tFork: proj.ForkedFromProject != nil,\n\t\t\tArchived: proj.Archived,\n\t\t\tVCS: protocol.VCSInfo{\n\t\t\t\tURL: conn.authenticatedRemoteURL(proj),\n\t\t\t},\n\t\t\tLinks: &protocol.RepoLinks{\n\t\t\t\tRoot: proj.WebURL,\n\t\t\t\tTree: proj.WebURL + \"/tree/{rev}/{path}\",\n\t\t\t\tBlob: proj.WebURL + \"/blob/{rev}/{path}\",\n\t\t\t\tCommit: proj.WebURL + \"/commit/{commit}\",\n\t\t\t},\n\t\t}\n\t}\n\n\tconn, err := getGitLabConnection(args)\n\tif err != nil {\n\t\treturn nil, true, err // refers to a GitLab repo but the host is not configured\n\t}\n\tif conn == nil {\n\t\treturn nil, false, nil // refers to a non-GitLab repo\n\t}\n\n\tif args.ExternalRepo != nil && args.ExternalRepo.ServiceType == gitlab.ServiceType {\n\t\t// Look up by external repository spec.\n\t\tid, err := strconv.Atoi(args.ExternalRepo.ID)\n\t\tif err != nil {\n\t\t\treturn nil, true, err\n\t\t}\n\t\tproj, err := conn.client.GetProject(ctx, gitlab.GetProjectOp{ID: id})\n\t\tif proj != nil {\n\t\t\trepo = ghrepoToRepoInfo(proj, conn)\n\t\t}\n\t\treturn repo, true, err\n\t}\n\n\tif args.Repo != \"\" {\n\t\t// Look up by repository name.\n\t\tpathWithNamespace := strings.TrimPrefix(strings.ToLower(string(args.Repo)), conn.baseURL.Hostname()+\"/\")\n\t\tproj, err := conn.client.GetProject(ctx, gitlab.GetProjectOp{PathWithNamespace: pathWithNamespace})\n\t\tif proj != nil {\n\t\t\trepo = ghrepoToRepoInfo(proj, conn)\n\t\t}\n\t\treturn repo, true, err\n\t}\n\n\treturn nil, true, fmt.Errorf(\"unable to look up GitLab repository (%+v)\", args)\n}", "func CreateGitRepo(options *git.CloneOptions, revision models.GitRevision, isSync bool) uint64 {\n\tif options == nil {\n\t\treturn 0\n\t}\n\tlog.Printf(\"clone git repo with params %+v...\\n\", options)\n\t// request new context with updating status, so that the context wouldn't be gced\n\tctx, id := requestNewContextWithID(TypeGit, StatusUpdating)\n\t// TODO: trace clone/pull/checkout progress\n\tif isSync {\n\t\tif !createGitRepo(ctx, options, revision) {\n\t\t\t// create failed\n\t\t\treturn 0\n\t\t}\n\t} else {\n\t\tgo createGitRepo(ctx, options, revision)\n\t}\n\treturn id\n}", "func discoverRemoteGitURLFromGitConfig(gitConf string) (string, error) {\n\tcfg, err := parseGitConfig(gitConf)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to unmarshal %s due to %s\", gitConf, err)\n\t}\n\n\tremotes := cfg.Remotes\n\n\tif len(remotes) == 0 {\n\t\treturn \"\", nil\n\t}\n\n\trURL := getRemoteURL(cfg, \"origin\")\n\n\tif rURL == \"\" {\n\t\trURL = getRemoteURL(cfg, \"upstream\")\n\t}\n\n\treturn rURL, nil\n}", "func (h *stiGit) GetInfo(repo string) *SourceInfo {\n\tgit := func(arg ...string) string {\n\t\tcommand := exec.Command(\"git\", arg...)\n\t\tcommand.Dir = repo\n\t\tout, err := command.CombinedOutput()\n\t\tif err != nil {\n\t\t\tlog.V(1).Infof(\"Error executing 'git %#v': %s (%v)\", arg, out, err)\n\t\t\treturn \"\"\n\t\t}\n\t\treturn strings.TrimSpace(string(out))\n\t}\n\treturn &SourceInfo{\n\t\tLocation: git(\"config\", \"--get\", \"remote.origin.url\"),\n\t\tRef: git(\"rev-parse\", \"--abbrev-ref\", \"HEAD\"),\n\t\tCommitID: git(\"rev-parse\", \"--verify\", \"HEAD\"),\n\t\tAuthorName: git(\"--no-pager\", \"show\", \"-s\", \"--format=%an\", \"HEAD\"),\n\t\tAuthorEmail: git(\"--no-pager\", \"show\", \"-s\", \"--format=%ae\", \"HEAD\"),\n\t\tCommitterName: git(\"--no-pager\", \"show\", \"-s\", \"--format=%cn\", \"HEAD\"),\n\t\tCommitterEmail: git(\"--no-pager\", \"show\", \"-s\", \"--format=%ce\", \"HEAD\"),\n\t\tDate: git(\"--no-pager\", \"show\", \"-s\", \"--format=%ad\", \"HEAD\"),\n\t\tMessage: git(\"--no-pager\", \"show\", \"-s\", \"--format=%<(80,trunc)%s\", \"HEAD\"),\n\t}\n}", "func matchGithubRepo(root string) (RemoteRepo, error) {\n\tif strings.HasSuffix(root, \".git\") {\n\t\treturn nil, errors.New(\"path must not include .git suffix\")\n\t}\n\treturn &baseRepo{\"http://\" + root + \".git\", root, vcsMap[\"git\"]}, nil\n}", "func GetGitDirectory() string {\n\tcurrentDirectory, _ := os.Getwd()\n\tvar projectDirectory = \"\"\n\tdirectoryParts := strings.Split(currentDirectory, string(os.PathSeparator))\n\n\tfor projectDirectory == \"\" {\n\t\tif _, err := os.Stat(filepath.Join(currentDirectory, \"/.git\")); err == nil {\n\t\t\treturn currentDirectory\n\t\t}\n\n\t\tif directoryParts[0]+\"\\\\\" == currentDirectory || currentDirectory == \"/\" {\n\t\t\treturn \"\"\n\t\t}\n\n\t\tcurrentDirectory = filepath.Dir(currentDirectory)\n\t}\n\n\treturn \"\"\n}", "func (project *Project) HasGitBinInPath() bool {\n\treturn strings.Contains(os.Getenv(\"PATH\"), filepath.Join(project.location, \".git\", \"bin\"))\n}", "func (imageName *ImageName) GetRepo(option FormatOption) string {\n\tresult := imageName.Repo\n\n\tif imageName.Namespace != \"\" {\n\t\tresult = fmt.Sprintf(\"%s/%s\", imageName.Namespace, result)\n\t}\n\n\tif option.Has(ExplicitNamespace) {\n\t\tresult = fmt.Sprintf(\"%s/%s\", \"library\", result)\n\t}\n\n\treturn result\n}", "func (c *TestContext) FindBinDir() string {\n\treturn c.findRepoFile(\"bin\")\n}", "func GetGitAuth() (transport.AuthMethod, error) {\n\tconf, err := config.ReadConfigs()\n\tif err != nil {\n\t\tloggers.LoggerAuth.ErrorC(logging.ErrorDetails{\n\t\t\tMessage: fmt.Sprintf(\"Error while reading configs: %s\", err.Error()),\n\t\t\tSeverity: logging.BLOCKER,\n\t\t\tErrorCode: 3000,\n\t\t})\n\t\treturn nil, err\n\t}\n\n\tusername := conf.Adapter.SourceControl.Repository.Username\n\tsshKeyFile := conf.Adapter.SourceControl.Repository.SSHKeyFile\n\tif username == \"\" && sshKeyFile == \"\" {\n\t\treturn &http.BasicAuth{}, nil\n\t} else if username != \"\" {\n\t\taccessToken := conf.Adapter.SourceControl.Repository.AccessToken\n\t\treturn &http.BasicAuth{\n\t\t\tUsername: username,\n\t\t\tPassword: accessToken,\n\t\t}, nil\n\t} else if sshKeyFile != \"\" {\n\t\tsshKey, err := ioutil.ReadFile(sshKeyFile)\n\t\tif err != nil {\n\t\t\tloggers.LoggerAuth.ErrorC(logging.ErrorDetails{\n\t\t\t\tMessage: fmt.Sprintf(\"Error reading ssh key file: %s\", err.Error()),\n\t\t\t\tSeverity: logging.CRITICAL,\n\t\t\t\tErrorCode: 3001,\n\t\t\t})\n\t\t\treturn nil, err\n\t\t}\n\n\t\tpublicKey, err := ssh.NewPublicKeys(ssh.DefaultUsername, sshKey, \"\")\n\t\tif err != nil {\n\t\t\tloggers.LoggerAuth.ErrorC(logging.ErrorDetails{\n\t\t\t\tMessage: fmt.Sprintf(\"Error creating ssh public key: %s\", err.Error()),\n\t\t\t\tSeverity: logging.CRITICAL,\n\t\t\t\tErrorCode: 3002,\n\t\t\t})\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn publicKey, nil\n\t}\n\treturn nil, errors.New(\"No username or ssh key file provided\")\n}", "func (r *RepoFinder) Find() ([]string, error) {\n\tif _, err := Exists(r.root); err != nil {\n\t\treturn nil, err\n\t}\n\n\twalkOpts := &godirwalk.Options{\n\t\tErrorCallback: r.errorCb,\n\t\tCallback: r.walkCb,\n\t\t// Use Unsorted to improve speed because repos will be processed by goroutines in a random order anyway.\n\t\tUnsorted: true,\n\t}\n\n\terr := godirwalk.Walk(r.root, walkOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(r.repos) == 0 {\n\t\treturn nil, fmt.Errorf(\"no git repos found in root path %s\", r.root)\n\t}\n\n\treturn r.repos, nil\n}", "func (v Repository) GitCommonDir() string {\n\treturn v.gitCommonDir\n}", "func parseGitCommand(sshOriginalCommand string) (command string, repopath string, err error) {\n\tr, err := regexp.Compile(`git-([a-z-]+) '/?([\\w-+@][\\w-+.@]*/)?([\\w-]+)\\.git'`)\n\tif err != nil {\n\t\treturn \"\", \"\", errors.New(\"parseGitCommand(): could not compile regex\")\n\t}\n\n\tm := r.FindStringSubmatch(sshOriginalCommand)\n\tif len(m) != 4 {\n\t\treturn \"\", \"\", errors.New(\"parseGitCommand(): Invalid GIT command\")\n\t}\n\n\treturn m[1], m[2] + m[3], nil\n}", "func GetRemoteRepo(\n\tctx context.Context,\n\tcss ChangesetSource,\n\ttargetRepo *types.Repo,\n\tch *btypes.Changeset,\n\tspec *btypes.ChangesetSpec,\n) (*types.Repo, error) {\n\t// If the changeset spec doesn't expect a fork _and_ we're not updating a\n\t// changeset that was previously created using a fork, then we don't need to\n\t// even check if the changeset source is forkable, let alone set up the\n\t// remote repo: we can just return the target repo and be done with it.\n\tif ch.ExternalForkNamespace == \"\" && (spec == nil || !spec.IsFork()) {\n\t\treturn targetRepo, nil\n\t}\n\n\tfss, ok := css.(ForkableChangesetSource)\n\tif !ok {\n\t\treturn nil, ErrChangesetSourceCannotFork\n\t}\n\n\tvar repo *types.Repo\n\tvar err error\n\n\t// ExternalForkNamespace and ExternalForkName will only be set once a changeset has\n\t// been published.\n\tif ch.ExternalForkNamespace != \"\" {\n\t\t// If we're updating an existing changeset, we should push/modify the same fork it\n\t\t// was created on, even if the user credential would now fork into a different\n\t\t// namespace.\n\t\trepo, err = fss.GetFork(ctx, targetRepo, &ch.ExternalForkNamespace, &ch.ExternalForkName)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"getting fork for changeset\")\n\t\t}\n\t\treturn repo, nil\n\t}\n\n\t// If we're creating a new changeset, we should fork into the namespace specified by\n\t// the changeset spec, if any.\n\tnamespace := spec.GetForkNamespace()\n\trepo, err = fss.GetFork(ctx, targetRepo, namespace, nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"getting fork for changeset spec\")\n\t}\n\treturn repo, nil\n}", "func getRemoteBuildDataFS(repo, commitID string) (rwvfs.FileSystem, string, sourcegraph.RepoRevSpec, error) {\n\tif repo == \"\" {\n\t\terr := errors.New(\"getRemoteBuildDataFS: repo cannot be empty\")\n\t\treturn nil, \"\", sourcegraph.RepoRevSpec{}, err\n\t}\n\tcl := NewAPIClientWithAuthIfPresent()\n\trrepo, _, err := cl.Repos.Get(sourcegraph.RepoSpec{URI: repo}, nil)\n\tif err != nil {\n\t\treturn nil, \"\", sourcegraph.RepoRevSpec{}, err\n\t}\n\n\trepoRevSpec := sourcegraph.RepoRevSpec{RepoSpec: rrepo.RepoSpec(), Rev: commitID, CommitID: commitID}\n\tfs, err := cl.BuildData.FileSystem(repoRevSpec)\n\treturn fs, fmt.Sprintf(\"remote repository (URI %s, commit %s)\", rrepo.URI, commitID), repoRevSpec, err\n}", "func FindInGoSearchPath(pkg string) string {\n\treturn FindInSearchPath(FullGoSearchPath(), pkg)\n}", "func (mf *modFile) find(mx *mg.Ctx, bctx *build.Context, importPath string, mp *ModPath) (pp *PkgPath, err error) {\n\tdefer func() {\n\t\tif pp != nil {\n\t\t\tpp.Mod = &ModPath{Dir: mf.Dir, Parent: mp}\n\t\t}\n\t}()\n\n\tmd, err := mf.require(importPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlsPkg := func(pfx, sfx string) *PkgPath {\n\t\tdir := filepath.Join(pfx, filepath.FromSlash(sfx))\n\t\tok := mx.VFS.Poke(dir).Ls().Some(goutil.PkgNdFilter)\n\t\tif ok {\n\t\t\treturn &PkgPath{Dir: dir, ImportPath: importPath}\n\t\t}\n\t\treturn nil\n\t}\n\n\t// if we're importing a self/sub-module or local replacement package don't search anywhere else\n\tif md.Dir != \"\" {\n\t\tif p := lsPkg(md.Dir, md.SubPkg); p != nil {\n\t\t\treturn p, nil\n\t\t}\n\t\treturn nil, fmt.Errorf(\"cannot find local/replacement package `%s` in `%s`\", importPath, md.Dir)\n\t}\n\n\t// local vendor first to support un-imaginable use-cases like editing third-party packages.\n\t// we don't care about BS like `-mod=vendor`\n\tsearchLocalVendor := func() *PkgPath {\n\t\treturn lsPkg(filepath.Join(mf.Dir, \"vendor\"), importPath)\n\t}\n\tmpath, err := module.EncodePath(md.ModPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgrSrc := mx.VFS.Poke(bctx.GOROOT).Poke(\"src\")\n\troots := map[string]bool{grSrc.Path(): true}\n\tsearchPkgMod := func() *PkgPath {\n\t\tgopath := mgutil.PathList(bctx.GOPATH)\n\t\tpkgMod := filepath.FromSlash(\"pkg/mod/\" + mpath + \"@\" + md.Version)\n\t\tfor _, gp := range gopath {\n\t\t\troots[mx.VFS.Poke(gp).Poke(\"src\").Path()] = true\n\t\t\tif p := lsPkg(filepath.Join(gp, pkgMod), md.SubPkg); p != nil {\n\t\t\t\treturn p\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\t// check all the parent vendor dirs. we check mf.Dir separately\n\tsearchOtherVendors := func() *PkgPath {\n\t\tfor sd := mx.VFS.Poke(mf.Dir).Parent(); !sd.IsRoot(); sd = sd.Parent() {\n\t\t\tdir := sd.Path()\n\t\t\tif roots[dir] {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif p := lsPkg(filepath.Join(dir, \"vendor\"), importPath); p != nil {\n\t\t\t\treturn p\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\t// check GOROOT/vendor to support the `std` module\n\tsearchGrVendor := func() *PkgPath {\n\t\treturn lsPkg(filepath.Join(bctx.GOROOT, \"src\", \"vendor\"), importPath)\n\t}\n\tsearch := []func() *PkgPath{\n\t\tsearchLocalVendor,\n\t\tsearchPkgMod,\n\t\tsearchOtherVendors,\n\t\tsearchGrVendor,\n\t}\n\tif !strings.Contains(strings.SplitN(importPath, \"/\", 2)[0], \".\") {\n\t\t// apparently import paths without dots are reserved for the stdlib\n\t\t// checking first also avoids the many misses for each stdlib pkg\n\t\tsearch = []func() *PkgPath{\n\t\t\tsearchGrVendor,\n\t\t\tsearchLocalVendor,\n\t\t\tsearchPkgMod,\n\t\t\tsearchOtherVendors,\n\t\t}\n\t}\n\tfor _, f := range search {\n\t\tif p := f(); p != nil {\n\t\t\treturn p, nil\n\t\t}\n\t}\n\tif md.oldPath != \"\" {\n\t\treturn nil, fmt.Errorf(\"cannot find `%s` replacement `%s` using `%s`\", importPath, md.ModPath, mf.Path)\n\t}\n\treturn nil, fmt.Errorf(\"cannot find `%s` using `%s`\", importPath, mf.Path)\n}", "func IsGit(dir string) bool {\n\tfiles, err := ioutil.ReadDir(dir)\n\tif err != nil {\n\t\tlog.Printf(\"read [%s] error, err = %s\\n\", dir, err)\n\t}\n\tfor _, file := range files {\n\t\tif file.IsDir() && file.Name() == \".git\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (gitCommand *GitCommand) Run(wait bool) (io.ReadCloser, error) {\n\tcmd := exec.Command(\"git\", gitCommand.Args...)\n\tstdout, err := cmd.StdoutPipe()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif gitCommand.ProcInput != nil {\n\t\tcmd.Stdin = gitCommand.ProcInput\n\t}\n\n\tif err := cmd.Start(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif wait {\n\t\terr = cmd.Wait()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn stdout, nil\n}", "func (g *getter) getRemoteRepository(remote RemoteRepository, branch string) error {\n\tremoteURL := remote.URL()\n\tlocal, err := LocalRepositoryFromURL(remoteURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar (\n\t\tfpath = local.FullPath\n\t\tnewPath = false\n\t)\n\n\t_, err = os.Stat(fpath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tnewPath = true\n\t\t\terr = nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tswitch {\n\tcase newPath:\n\t\tif remoteURL.Scheme == \"codecommit\" {\n\t\t\tlogger.Log(\"clone\", fmt.Sprintf(\"%s -> %s\", remoteURL.Opaque, fpath))\n\t\t} else {\n\t\t\tlogger.Log(\"clone\", fmt.Sprintf(\"%s -> %s\", remoteURL, fpath))\n\t\t}\n\t\tvar (\n\t\t\tlocalRepoRoot = fpath\n\t\t\trepoURL = remoteURL\n\t\t)\n\t\tvcs, ok := vcsRegistry[g.vcs]\n\t\tif !ok {\n\t\t\tvcs, repoURL, err = remote.VCS()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif l := detectLocalRepoRoot(remoteURL.Path, repoURL.Path); l != \"\" {\n\t\t\tlocalRepoRoot = filepath.Join(local.RootPath, remoteURL.Hostname(), l)\n\t\t}\n\n\t\tif remoteURL.Scheme == \"codecommit\" {\n\t\t\trepoURL, _ = url.Parse(remoteURL.Opaque)\n\t\t}\n\t\tif getRepoLock(localRepoRoot) {\n\t\t\treturn vcs.Clone(&vcsGetOption{\n\t\t\t\turl: repoURL,\n\t\t\t\tdir: localRepoRoot,\n\t\t\t\tshallow: g.shallow,\n\t\t\t\tsilent: g.silent,\n\t\t\t\tbranch: branch,\n\t\t\t\trecursive: g.recursive,\n\t\t\t\tbare: g.bare,\n\t\t\t})\n\t\t}\n\t\treturn nil\n\tcase g.update:\n\t\tlogger.Log(\"update\", fpath)\n\t\tvcs, localRepoRoot := local.VCS()\n\t\tif vcs == nil {\n\t\t\treturn fmt.Errorf(\"failed to detect VCS for %q\", fpath)\n\t\t}\n\t\tif getRepoLock(localRepoRoot) {\n\t\t\treturn vcs.Update(&vcsGetOption{\n\t\t\t\tdir: localRepoRoot,\n\t\t\t\tsilent: g.silent,\n\t\t\t\trecursive: g.recursive,\n\t\t\t})\n\t\t}\n\t\treturn nil\n\t}\n\tlogger.Log(\"exists\", fpath)\n\treturn nil\n}", "func (p project) gitClone() error {\n\tif p.SkipClone {\n\t\treturn nil\n\t}\n\tcmd := fmt.Sprintf(\"git clone -b %s %s %s\", p.Branch, p.Repo, localRepos+p.Name)\n\treturn doExec(cmd, \"\")\n}", "func parseGitPath(path string) string {\n\tif strings.HasPrefix(path, \"github.com\") {\n\t\treturn fmt.Sprintf(\"https://%s.git\", path)\n\t}\n\treturn path\n}", "func (c *Commander) gitInit() error {\n\tc.cmd = exec.Command(\"git\", \"init\")\n\tc.cmd.Stdin, c.cmd.Stdout, c.cmd.Stderr = os.Stdin, os.Stdout, os.Stderr\n\tif err := c.cmd.Run(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.addRemote(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func initGitRepo (dir string) (error) {\n\t// TODO revise so that we can specify the cwd for the command\n\t_, err := exec.Command(\"git\", \"init\").Output()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func GetGitRepository() (*git.Repository, error) {\n\tvar repo *git.Repository\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn repo, err\n\t}\n\n\trepo, err = git.PlainOpenWithOptions(cwd, &git.PlainOpenOptions{DetectDotGit: true})\n\tif err != nil {\n\t\treturn repo, err\n\t}\n\n\tif repo == nil {\n\t\tfmt.Println()\n\t\treturn repo, errors.New(\"Could not open repository. Please execute this command from within a git repository. \" + cwd)\n\t}\n\n\treturn repo, nil\n}", "func (j *DSGit) GetGitOps(ctx *Ctx, thrN int) (ch chan error, err error) {\n\tworker := func(c chan error, url string) (e error) {\n\t\tdefer func() {\n\t\t\tif c != nil {\n\t\t\t\tc <- e\n\t\t\t}\n\t\t}()\n\t\tvar (\n\t\t\tsout string\n\t\t\tserr string\n\t\t)\n\t\tcmdLine := []string{GitOpsCommand, url}\n\t\tvar env map[string]string\n\t\tif GitOpsNoCleanup {\n\t\t\tenv = map[string]string{\"SKIP_CLEANUP\": \"1\"}\n\t\t}\n\t\tsout, serr, e = ExecCommand(ctx, cmdLine, \"\", env)\n\t\tif e != nil {\n\t\t\tif GitOpsFailureFatal {\n\t\t\t\tPrintf(\"error executing %v: %v\\n%s\\n%s\\n\", cmdLine, e, sout, serr)\n\t\t\t} else {\n\t\t\t\tPrintf(\"WARNING: error executing %v: %v\\n%s\\n%s\\n\", cmdLine, e, sout, serr)\n\t\t\t\te = nil\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\ttype resultType struct {\n\t\t\tLoc int `json:\"loc\"`\n\t\t\tPls []RawPLS `json:\"pls\"`\n\t\t}\n\t\tvar data resultType\n\t\te = jsoniter.Unmarshal([]byte(sout), &data)\n\t\tif e != nil {\n\t\t\tif GitOpsFailureFatal {\n\t\t\t\tPrintf(\"error unmarshaling from %v\\n\", sout)\n\t\t\t} else {\n\t\t\t\tPrintf(\"WARNING: error unmarshaling from %v\\n\", sout)\n\t\t\t\te = nil\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tj.Loc = data.Loc\n\t\tfor _, f := range data.Pls {\n\t\t\tfiles, _ := strconv.Atoi(f.Files)\n\t\t\tblank, _ := strconv.Atoi(f.Blank)\n\t\t\tcomment, _ := strconv.Atoi(f.Comment)\n\t\t\tcode, _ := strconv.Atoi(f.Code)\n\t\t\tj.Pls = append(\n\t\t\t\tj.Pls,\n\t\t\t\tPLS{\n\t\t\t\t\tLanguage: f.Language,\n\t\t\t\t\tFiles: files,\n\t\t\t\t\tBlank: blank,\n\t\t\t\t\tComment: comment,\n\t\t\t\t\tCode: code,\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\treturn\n\t}\n\tif thrN <= 1 {\n\t\treturn nil, worker(nil, j.URL)\n\t}\n\tch = make(chan error)\n\tgo func() { _ = worker(ch, j.URL) }()\n\treturn ch, nil\n}", "func FindRepository(dir string) (*Repository, error) {\n\tvar (\n\t\tgitDir string\n\t\tcommonDir string\n\t\tworkDir string\n\t\tgitConfig GitConfig\n\t\terr error\n\t)\n\n\tgitDir, err = findGitDir(dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcommonDir, err = getGitCommonDir(gitDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgitConfig, err = LoadFileWithDefault(filepath.Join(commonDir, \"config\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !gitConfig.GetBool(\"core.bare\", false) {\n\t\tworkDir, _ = getWorkTree(gitDir)\n\t}\n\treturn &Repository{\n\t\tgitDir: gitDir,\n\t\tgitCommonDir: commonDir,\n\t\tworkDir: workDir,\n\t\tgitConfig: gitConfig,\n\t}, nil\n}" ]
[ "0.71428835", "0.5951756", "0.5907509", "0.5815976", "0.57849896", "0.55697924", "0.5395625", "0.5387797", "0.5077059", "0.5065078", "0.50566435", "0.50306296", "0.5012529", "0.500437", "0.49829805", "0.49811447", "0.498114", "0.495789", "0.49487612", "0.49331194", "0.49304852", "0.4926294", "0.49110234", "0.48842457", "0.48669156", "0.4864684", "0.4855003", "0.485294", "0.48287892", "0.48278144", "0.4825075", "0.47944954", "0.4781697", "0.47761694", "0.4768999", "0.47608948", "0.4757966", "0.4756579", "0.4749748", "0.47445214", "0.4741892", "0.47039238", "0.46889022", "0.46690693", "0.4656064", "0.46296814", "0.4606452", "0.45969397", "0.4567228", "0.45636588", "0.4560296", "0.45588255", "0.4557322", "0.4548741", "0.45469645", "0.45449755", "0.45448166", "0.45357648", "0.45162934", "0.451311", "0.4510415", "0.45084634", "0.45046327", "0.45021194", "0.44993147", "0.44911727", "0.44765857", "0.44517654", "0.44412315", "0.44329247", "0.4430301", "0.4420891", "0.4419708", "0.44121218", "0.44114438", "0.4411192", "0.43974158", "0.43804923", "0.43803537", "0.43764186", "0.43753594", "0.43681696", "0.43586853", "0.43519175", "0.43482298", "0.43454826", "0.43450984", "0.43357974", "0.4334071", "0.43331632", "0.4324043", "0.4322268", "0.432222", "0.43178037", "0.4312245", "0.43059152", "0.42970923", "0.42870304", "0.42865703", "0.42855495" ]
0.7978072
0
Perform various management operations on Submarine Pod and Submarine clusters to approximate the desired state
func (c *Controller) clusterAction(admin submarine.AdminInterface, cluster *rapi.SubmarineCluster, infos *submarine.ClusterInfos) (bool, error) { glog.Info("clusterAction()") var err error /* run sanity check if needed needSanity, err := sanitycheck.RunSanityChecks(admin, &c.config.submarine, c.podControl, cluster, infos, true) if err != nil { glog.Errorf("[clusterAction] cluster %s/%s, an error occurs during sanitycheck: %v ", cluster.Namespace, cluster.Name, err) return false, err } if needSanity { glog.V(3).Infof("[clusterAction] run sanitycheck cluster: %s/%s", cluster.Namespace, cluster.Name) return sanitycheck.RunSanityChecks(admin, &c.config.submarine, c.podControl, cluster, infos, false) }*/ // Start more pods in needed if needMorePods(cluster) { if setScalingCondition(&cluster.Status, true) { if cluster, err = c.updateHandler(cluster); err != nil { return false, err } } pod, err2 := c.podControl.CreatePod(cluster) if err2 != nil { glog.Errorf("[clusterAction] unable to create a pod associated to the SubmarineCluster: %s/%s, err: %v", cluster.Namespace, cluster.Name, err2) return false, err2 } glog.V(3).Infof("[clusterAction]create a Pod %s/%s", pod.Namespace, pod.Name) return true, nil } if setScalingCondition(&cluster.Status, false) { if cluster, err = c.updateHandler(cluster); err != nil { return false, err } } // Reconfigure the Cluster if needed hasChanged, err := c.applyConfiguration(admin, cluster) if err != nil { glog.Errorf("[clusterAction] cluster %s/%s, an error occurs: %v ", cluster.Namespace, cluster.Name, err) return false, err } if hasChanged { glog.V(6).Infof("[clusterAction] cluster has changed cluster: %s/%s", cluster.Namespace, cluster.Name) return true, nil } glog.Infof("[clusterAction] cluster hasn't changed cluster: %s/%s", cluster.Namespace, cluster.Name) return false, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (d *DBGenerator) setSubclusterDetail(ctx context.Context) error {\n\tq := Queries[SubclusterQueryKey]\n\trows, err := d.Conn.QueryContext(ctx, q)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed running '%s': %w\", q, err)\n\t}\n\tdefer rows.Close()\n\n\t// Map to have fast lookup of subcluster name to index in the\n\t// d.Objs.Vdb.Spec.Subclusters array\n\tsubclusterInxMap := map[string]int{}\n\n\tfor rows.Next() {\n\t\tif rows.Err() != nil {\n\t\t\treturn fmt.Errorf(\"failed running '%s': %w\", q, rows.Err())\n\t\t}\n\t\tvar name string\n\t\tvar isPrimary bool\n\t\tif err := rows.Scan(&name, &isPrimary); err != nil {\n\t\t\treturn fmt.Errorf(\"failed running '%s': %w\", q, err)\n\t\t}\n\n\t\tif !vapi.IsValidSubclusterName(name) {\n\t\t\treturn fmt.Errorf(\"subcluster names are included in the name of statefulsets, but the name \"+\n\t\t\t\t\"'%s' cannot be used as it will violate Kubernetes naming. Please rename the subcluster and \"+\n\t\t\t\t\"retry this command again\", name)\n\t\t}\n\n\t\tinx, ok := subclusterInxMap[name]\n\t\tif !ok {\n\t\t\tinx = len(d.Objs.Vdb.Spec.Subclusters)\n\t\t\t// Add an empty subcluster. We increment the count a few lines down.\n\t\t\td.Objs.Vdb.Spec.Subclusters = append(d.Objs.Vdb.Spec.Subclusters,\n\t\t\t\tvapi.Subcluster{Name: name, Size: 0, IsPrimary: isPrimary})\n\t\t\tsubclusterInxMap[name] = inx\n\t\t}\n\t\td.Objs.Vdb.Spec.Subclusters[inx].Size++\n\n\t\t// Maintain the ReviveOrder. Update the count of the prior unless the\n\t\t// previous node was for a different subcluster.\n\t\trevSz := len(d.Objs.Vdb.Spec.ReviveOrder)\n\t\tif revSz == 0 || d.Objs.Vdb.Spec.ReviveOrder[revSz-1].SubclusterIndex != inx {\n\t\t\td.Objs.Vdb.Spec.ReviveOrder = append(d.Objs.Vdb.Spec.ReviveOrder, vapi.SubclusterPodCount{SubclusterIndex: inx, PodCount: 1})\n\t\t} else {\n\t\t\td.Objs.Vdb.Spec.ReviveOrder[revSz-1].PodCount++\n\t\t}\n\t}\n\n\tif len(subclusterInxMap) == 0 {\n\t\treturn errors.New(\"not subclusters found\")\n\t}\n\treturn nil\n}", "func (s *StatusReconciler) calculateSubclusterStatus(ctx context.Context, sc *vapi.Subcluster, curStat *vapi.SubclusterStatus) error {\n\tcurStat.Name = sc.Name\n\n\tif err := s.resizeSubclusterStatus(ctx, sc, curStat); err != nil {\n\t\treturn err\n\t}\n\n\tfor podIndex := int32(0); podIndex < int32(len(curStat.Detail)); podIndex++ {\n\t\tpodName := names.GenPodName(s.Vdb, sc, podIndex)\n\t\tpf, ok := s.PFacts.Detail[podName]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tcurStat.Detail[podIndex].UpNode = pf.upNode\n\t\t// We can only reliably update the status for running pods. Skip those\n\t\t// that we couldn't figure out to preserve their state.\n\t\tif !pf.isInstalled.IsNone() {\n\t\t\tcurStat.Detail[podIndex].Installed = pf.isInstalled.IsTrue()\n\t\t}\n\t\t// Similar comment about db existence and vertica node name. Skip pods\n\t\t// that we couldn't figure out the state for.\n\t\tif !pf.dbExists.IsNone() {\n\t\t\tcurStat.Detail[podIndex].AddedToDB = pf.dbExists.IsTrue()\n\t\t\tcurStat.Detail[podIndex].VNodeName = pf.vnodeName\n\t\t}\n\t}\n\t// Refresh the counts\n\tcurStat.InstallCount = 0\n\tcurStat.AddedToDBCount = 0\n\tcurStat.UpNodeCount = 0\n\tfor _, v := range curStat.Detail {\n\t\tif v.Installed {\n\t\t\tcurStat.InstallCount++\n\t\t}\n\t\tif v.AddedToDB {\n\t\t\tcurStat.AddedToDBCount++\n\t\t}\n\t\tif v.UpNode {\n\t\t\tcurStat.UpNodeCount++\n\t\t}\n\t}\n\treturn nil\n}", "func (s *StatusReconciler) Reconcile(ctx context.Context, req *ctrl.Request) (ctrl.Result, error) {\n\t// We base our status on the pod facts, so ensure our facts are up to date.\n\tif err := s.PFacts.Collect(ctx, s.Vdb); err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t// Use all subclusters, even ones that are scheduled for removal. We keep\n\t// reporting status on the deleted ones until the statefulsets are gone.\n\tfinder := MakeSubclusterFinder(s.Client, s.Vdb)\n\tsubclusters, err := finder.FindSubclusters(ctx, FindAll)\n\tif err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\n\trefreshStatus := func(vdbChg *vapi.VerticaDB) error {\n\t\tvdbChg.Status.Subclusters = []vapi.SubclusterStatus{}\n\t\tfor i := range subclusters {\n\t\t\tif i == len(vdbChg.Status.Subclusters) {\n\t\t\t\tvdbChg.Status.Subclusters = append(vdbChg.Status.Subclusters, vapi.SubclusterStatus{})\n\t\t\t}\n\t\t\tif err := s.calculateSubclusterStatus(ctx, subclusters[i], &vdbChg.Status.Subclusters[i]); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to calculate subcluster status %s %w\", subclusters[i].Name, err)\n\t\t\t}\n\t\t}\n\t\ts.calculateClusterStatus(&vdbChg.Status)\n\t\treturn nil\n\t}\n\n\tif err := status.Update(ctx, s.Client, s.Vdb, refreshStatus); err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\treturn ctrl.Result{}, nil\n}", "func main() {\n\tdefer log.Flush()\n\terr := logger.InitLogger()\n\tif err != nil {\n\t\tfmt.Printf(\"Could not initialize logger: %+v\", err)\n\t}\n\n\tif err = cmd.RootCmd.Execute(); err != nil {\n\t\tlog.Criticalf(\"Error getting command line arguments: %+v\", err)\n\t\tos.Exit(errorCode)\n\t}\n\n\tawsSession, err := wrappers.NewAWSSession()\n\tif err != nil {\n\t\tlog.Criticalf(err.Error())\n\t\tos.Exit(errorCode)\n\t}\n\n\tcanary, err := tests.NewCanary(awsSession, cmd.ClusterStateServiceEndpoint)\n\tif err != nil {\n\t\tlog.Criticalf(err.Error())\n\t\tos.Exit(errorCode)\n\t}\n\n\tcanaryRunner, err := tests.NewCanaryRunner(awsSession)\n\tif err != nil {\n\t\tlog.Criticalf(err.Error())\n\t\tos.Exit(errorCode)\n\t}\n\n\tcanaryRunner.Run(canary.GetInstance, canary.GetInstanceMetric)\n\tcanaryRunner.Run(canary.ListInstances, canary.ListInstancesMetric)\n\tcanaryRunner.Run(canary.GetTask, canary.GetTaskMetric)\n\tcanaryRunner.Run(canary.ListTasks, canary.ListTasksMetric)\n}", "func (c *Controller) applyConfiguration(admin submarine.AdminInterface, cluster *rapi.SubmarineCluster) (bool, error) {\n\tglog.Info(\"applyConfiguration START\")\n\tdefer glog.Info(\"applyConfiguration STOP\")\n\n\tasChanged := false\n\n\t// expected replication factor and number of master nodes\n\tcReplicaFactor := *cluster.Spec.ReplicationFactor\n\tcNbMaster := *cluster.Spec.NumberOfMaster\n\t// Adapt, convert CR to structure in submarine package\n\trCluster, nodes, err := newSubmarineCluster(admin, cluster)\n\tif err != nil {\n\t\tglog.Errorf(\"Unable to create the SubmarineCluster view, error:%v\", err)\n\t\treturn false, err\n\t}\n\t// PodTemplate changes require rolling updates\n\tif needRollingUpdate(cluster) {\n\t\tif setRollingUpdateCondition(&cluster.Status, true) {\n\t\t\tif cluster, err = c.updateHandler(cluster); err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\n\t\tglog.Info(\"applyConfiguration needRollingUpdate\")\n\t\treturn c.manageRollingUpdate(admin, cluster, rCluster, nodes)\n\t}\n\tif setRollingUpdateCondition(&cluster.Status, false) {\n\t\tif cluster, err = c.updateHandler(cluster); err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\t// if the number of Pods is greater than expected\n\tif needLessPods(cluster) {\n\t\tif setRebalancingCondition(&cluster.Status, true) {\n\t\t\tif cluster, err = c.updateHandler(cluster); err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\t\tglog.Info(\"applyConfiguration needLessPods\")\n\t\t// Configure Submarine cluster\n\t\treturn c.managePodScaleDown(admin, cluster, rCluster, nodes)\n\t}\n\t// If it is not a rolling update, modify the Condition\n\tif setRebalancingCondition(&cluster.Status, false) {\n\t\tif cluster, err = c.updateHandler(cluster); err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\tclusterStatus := &cluster.Status.Cluster\n\tif (clusterStatus.NbPods - clusterStatus.NbSubmarineRunning) != 0 {\n\t\tglog.V(3).Infof(\"All pods not ready wait to be ready, nbPods: %d, nbPodsReady: %d\", clusterStatus.NbPods, clusterStatus.NbSubmarineRunning)\n\t\treturn false, err\n\t}\n\n\t// First, we define the new masters\n\t// Select the desired number of Masters and assign Hashslots to each Master. The Master will be distributed to different K8S nodes as much as possible\n\t// Set the cluster status to Calculating Rebalancing\n\tnewMasters, curMasters, allMaster, err := clustering.DispatchMasters(rCluster, nodes, cNbMaster, admin)\n\tif err != nil {\n\t\tglog.Errorf(\"Cannot dispatch slots to masters: %v\", err)\n\t\trCluster.Status = rapi.ClusterStatusError\n\t\treturn false, err\n\t}\n\t// If the number of new and old masters is not the same\n\tif len(newMasters) != len(curMasters) {\n\t\tasChanged = true\n\t}\n\n\t// Second select Node that is already a slave\n\tcurrentSlaveNodes := nodes.FilterByFunc(submarine.IsSlave)\n\n\t//New slaves are slaves which is currently a master with no slots\n\tnewSlave := nodes.FilterByFunc(func(nodeA *submarine.Node) bool {\n\t\tfor _, nodeB := range newMasters {\n\t\t\tif nodeA.ID == nodeB.ID {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tfor _, nodeB := range currentSlaveNodes {\n\t\t\tif nodeA.ID == nodeB.ID {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n\n\t// Depending on whether we scale up or down, we will dispatch slaves before/after the dispatch of slots\n\tif cNbMaster < int32(len(curMasters)) {\n\t\t// this happens usually after a scale down of the cluster\n\t\t// we should dispatch slots before dispatching slaves\n\t\tif err := clustering.DispatchSlotToNewMasters(rCluster, admin, newMasters, curMasters, allMaster); err != nil {\n\t\t\tglog.Error(\"Unable to dispatch slot on new master, err:\", err)\n\t\t\treturn false, err\n\t\t}\n\n\t\t// assign master/slave roles\n\t\tnewSubmarineSlavesByMaster, bestEffort := clustering.PlaceSlaves(rCluster, newMasters, currentSlaveNodes, newSlave, cReplicaFactor)\n\t\tif bestEffort {\n\t\t\trCluster.NodesPlacement = rapi.NodesPlacementInfoBestEffort\n\t\t}\n\n\t\tif err := clustering.AttachingSlavesToMaster(rCluster, admin, newSubmarineSlavesByMaster); err != nil {\n\t\t\tglog.Error(\"Unable to dispatch slave on new master, err:\", err)\n\t\t\treturn false, err\n\t\t}\n\t} else {\n\t\t// We are scaling up the nbmaster or the nbmaster doesn't change.\n\t\t// assign master/slave roles\n\t\tnewSubmarineSlavesByMaster, bestEffort := clustering.PlaceSlaves(rCluster, newMasters, currentSlaveNodes, newSlave, cReplicaFactor)\n\t\tif bestEffort {\n\t\t\trCluster.NodesPlacement = rapi.NodesPlacementInfoBestEffort\n\t\t}\n\n\t\tif err := clustering.AttachingSlavesToMaster(rCluster, admin, newSubmarineSlavesByMaster); err != nil {\n\t\t\tglog.Error(\"Unable to dispatch slave on new master, err:\", err)\n\t\t\treturn false, err\n\t\t}\n\n\t\tif err := clustering.DispatchSlotToNewMasters(rCluster, admin, newMasters, curMasters, allMaster); err != nil {\n\t\t\tglog.Error(\"Unable to dispatch slot on new master, err:\", err)\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\tglog.V(4).Infof(\"new nodes status: \\n %v\", nodes)\n\n\t// Set the cluster status\n\trCluster.Status = rapi.ClusterStatusOK\n\t// wait a bit for the cluster to propagate configuration to reduce warning logs because of temporary inconsistency\n\ttime.Sleep(1 * time.Second)\n\treturn asChanged, nil\n}", "func (c *Cluster) reconcileSize() error {\n\t// Grab an up-to-date list of pods that are currently running.\n\t// Pending pods may be ignored safely as we have previously made sure no pods are in pending state.\n\tpods, _, _, err := c.pollPods()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Grab the current and desired size of the NATS cluster.\n\tcurrentSize := len(pods)\n\tdesiredSize := c.cluster.Spec.Size\n\n\tif currentSize > desiredSize {\n\t\t// Report that we are scaling the cluster down.\n\t\tc.cluster.Status.AppendScalingDownCondition(currentSize, desiredSize)\n\t\t// Remove extra pods as required in order to meet the desired size.\n\t\t// As we remove each pod, we must update the config secret so that routes are re-computed.\n\t\tfor idx := currentSize - 1; idx >= desiredSize; idx-- {\n\t\t\tif err := c.tryGracefulPodDeletion(pods[idx]); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := c.updateConfigSecret(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tif currentSize < desiredSize {\n\t\t// Report that we are scaling the cluster up.\n\t\tc.cluster.Status.AppendScalingUpCondition(currentSize, desiredSize)\n\t\t// Create pods as required in order to meet the desired size.\n\t\t// As we create each pod, we must update the config secret so that routes are re-computed.\n\t\tfor idx := currentSize; idx < desiredSize; idx++ {\n\t\t\tif _, err := c.createPod(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := c.updateConfigSecret(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// Update the reported size before returning.\n\tc.cluster.Status.SetSize(desiredSize)\n\treturn nil\n}", "func CluterInfo(c *status.Cluster) error {\n\t// commands are executed on the bootstrap control-plane\n\tcp1 := c.BootstrapControlPlane()\n\n\tif err := cp1.Command(\n\t\t\"kubectl\", \"--kubeconfig=/etc/kubernetes/admin.conf\", \"get\", \"nodes\", \"-o=wide\",\n\t).RunWithEcho(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := cp1.Command(\n\t\t\"kubectl\", \"--kubeconfig=/etc/kubernetes/admin.conf\", \"get\", \"pods\", \"--all-namespaces\", \"-o=wide\",\n\t).RunWithEcho(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := cp1.Command(\n\t\t\"kubectl\", \"--kubeconfig=/etc/kubernetes/admin.conf\", \"get\", \"pods\", \"--all-namespaces\",\n\t\t\"-o=jsonpath={range .items[*]}{\\\"\\\\n\\\"}{.metadata.name}{\\\" << \\\"}{range .spec.containers[*]}{.image}{\\\", \\\"}{end}{end}\",\n\t).RunWithEcho(); err != nil {\n\t\treturn err\n\t}\n\tfmt.Println()\n\n\tif c.ExternalEtcd() == nil {\n\t\t// NB. before v1.13 local etcd is listening on localhost only; after v1.13\n\t\t// local etcd is listening on localhost and on the advertise address; we are\n\t\t// using localhost to accommodate both the use cases\n\n\t\tetcdArgs := []string{\n\t\t\t\"--kubeconfig=/etc/kubernetes/admin.conf\", \"exec\", \"-n=kube-system\", fmt.Sprintf(\"etcd-%s\", c.BootstrapControlPlane().Name()),\n\t\t\t\"--\",\n\t\t}\n\n\t\tvar lines []string\n\t\tvar err error\n\n\t\t// Get the version of etcdctl from the etcd binary\n\t\t// Retry the version command for a while to avoid \"exec\" flakes\n\t\tversionArgs := append(etcdArgs, \"etcd\", \"--version\")\n\t\tversionArgs = append([]string{\"--request-timeout=2\"}, versionArgs...) // Ensure shorter timeout\n\t\tfor i := 0; i < 10; i++ {\n\t\t\tlines, err = cp1.Command(\"kubectl\", versionArgs...).RunAndCapture()\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcp1.Infof(\"Could not execute 'etcd --version' inside %q (attempt %d/%d): %v\\n\", cp1.Name(), i+1, 10,\n\t\t\t\terrors.Wrap(err, strings.Join(lines, \"\\n\")))\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tetcdctlVersion, err := parseEtcdctlVersion(lines)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcp1.Infof(\"Using etcdctl version: %s\\n\", etcdctlVersion)\n\t\tetcdArgs = append(etcdArgs, \"etcdctl\", \"--endpoints=https://127.0.0.1:2379\")\n\n\t\t// Append version specific etcdctl certificate flags\n\t\tif err := appendEtcdctlCertArgs(etcdctlVersion, &etcdArgs); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tetcdArgs = append(etcdArgs, \"member\", \"list\")\n\n\t\tif err := cp1.Command(\n\t\t\t\"kubectl\", etcdArgs...,\n\t\t).RunWithEcho(); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tfmt.Println(\"using external etcd\")\n\t}\n\n\treturn nil\n}", "func (s *StatusReconciler) calculateClusterStatus(stat *vapi.VerticaDBStatus) {\n\tstat.SubclusterCount = 0\n\tstat.InstallCount = 0\n\tstat.AddedToDBCount = 0\n\tstat.UpNodeCount = 0\n\tfor _, sc := range stat.Subclusters {\n\t\tstat.SubclusterCount++\n\t\tstat.InstallCount += sc.InstallCount\n\t\tstat.AddedToDBCount += sc.AddedToDBCount\n\t\tstat.UpNodeCount += sc.UpNodeCount\n\t}\n}", "func (r *ReconcileKubemanager) Reconcile(request reconcile.Request) (reconcile.Result, error) {\n\tvar err error\n\treqLogger := log.WithValues(\"Request.Namespace\", request.Namespace, \"Request.Name\", request.Name)\n\treqLogger.Info(\"Reconciling Kubemanager\")\n\tinstanceType := \"kubemanager\"\n\tinstance := &v1alpha1.Kubemanager{}\n\tcassandraInstance := v1alpha1.Cassandra{}\n\tzookeeperInstance := v1alpha1.Zookeeper{}\n\trabbitmqInstance := v1alpha1.Rabbitmq{}\n\tconfigInstance := v1alpha1.Config{}\n\n\terr = r.Client.Get(context.TODO(), request.NamespacedName, instance)\n\tif err != nil && errors.IsNotFound(err) {\n\t\treturn reconcile.Result{}, nil\n\t}\n\n\tcassandraActive := cassandraInstance.IsActive(instance.Spec.ServiceConfiguration.CassandraInstance,\n\t\trequest.Namespace, r.Client)\n\tzookeeperActive := zookeeperInstance.IsActive(instance.Spec.ServiceConfiguration.ZookeeperInstance,\n\t\trequest.Namespace, r.Client)\n\trabbitmqActive := rabbitmqInstance.IsActive(instance.Labels[\"contrail_cluster\"],\n\t\trequest.Namespace, r.Client)\n\tconfigActive := configInstance.IsActive(instance.Labels[\"contrail_cluster\"],\n\t\trequest.Namespace, r.Client)\n\tif !configActive || !cassandraActive || !rabbitmqActive || !zookeeperActive {\n\t\treturn reconcile.Result{}, nil\n\t}\n\n\tmanagerInstance, err := instance.OwnedByManager(r.Client, request)\n\tif err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\tif managerInstance != nil {\n\t\tif managerInstance.Spec.Services.Kubemanagers != nil {\n\t\t\tfor _, kubemanagerManagerInstance := range managerInstance.Spec.Services.Kubemanagers {\n\t\t\t\tif kubemanagerManagerInstance.Name == request.Name {\n\t\t\t\t\tinstance.Spec.CommonConfiguration = utils.MergeCommonConfiguration(\n\t\t\t\t\t\tmanagerInstance.Spec.CommonConfiguration,\n\t\t\t\t\t\tkubemanagerManagerInstance.Spec.CommonConfiguration)\n\t\t\t\t\terr = r.Client.Update(context.TODO(), instance)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn reconcile.Result{}, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tconfigMap, err := instance.CreateConfigMap(request.Name+\"-\"+instanceType+\"-configmap\",\n\t\tr.Client,\n\t\tr.Scheme,\n\t\trequest)\n\tif err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\n\tintendedDeployment, err := instance.PrepareIntendedDeployment(GetDeployment(),\n\t\t&instance.Spec.CommonConfiguration,\n\t\trequest,\n\t\tr.Scheme)\n\tif err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\n\tinstance.AddVolumesToIntendedDeployments(intendedDeployment,\n\t\tmap[string]string{configMap.Name: request.Name + \"-\" + instanceType + \"-volume\"})\n\n\tvar serviceAccountName string\n\tif instance.Spec.ServiceConfiguration.ServiceAccount != \"\" {\n\t\tserviceAccountName = instance.Spec.ServiceConfiguration.ServiceAccount\n\t} else {\n\t\tserviceAccountName = \"contrail-service-account\"\n\t}\n\n\tvar clusterRoleName string\n\tif instance.Spec.ServiceConfiguration.ClusterRole != \"\" {\n\t\tclusterRoleName = instance.Spec.ServiceConfiguration.ClusterRole\n\t} else {\n\t\tclusterRoleName = \"contrail-cluster-role\"\n\t}\n\n\tvar clusterRoleBindingName string\n\tif instance.Spec.ServiceConfiguration.ClusterRoleBinding != \"\" {\n\t\tclusterRoleBindingName = instance.Spec.ServiceConfiguration.ClusterRoleBinding\n\t} else {\n\t\tclusterRoleBindingName = \"contrail-cluster-role-binding\"\n\t}\n\n\texistingServiceAccount := &corev1.ServiceAccount{}\n\terr = r.Client.Get(context.TODO(), types.NamespacedName{Name: serviceAccountName, Namespace: instance.Namespace}, existingServiceAccount)\n\tif err != nil && errors.IsNotFound(err) {\n\t\tserviceAccount := &corev1.ServiceAccount{\n\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\tKind: \"ServiceAccount\",\n\t\t\t},\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: serviceAccountName,\n\t\t\t\tNamespace: instance.Namespace,\n\t\t\t},\n\t\t}\n\t\tcontrollerutil.SetControllerReference(instance, serviceAccount, r.Scheme)\n\t\terr = r.Client.Create(context.TODO(), serviceAccount)\n\t\tif err != nil {\n\t\t\treturn reconcile.Result{}, err\n\t\t}\n\t}\n\n\texistingClusterRole := &rbacv1.ClusterRole{}\n\terr = r.Client.Get(context.TODO(), types.NamespacedName{Name: clusterRoleName}, existingClusterRole)\n\tif err != nil && errors.IsNotFound(err) {\n\t\tclusterRole := &rbacv1.ClusterRole{\n\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\tAPIVersion: \"rbac/v1\",\n\t\t\t\tKind: \"ClusterRole\",\n\t\t\t},\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: clusterRoleName,\n\t\t\t\tNamespace: instance.Namespace,\n\t\t\t},\n\t\t\tRules: []rbacv1.PolicyRule{{\n\t\t\t\tVerbs: []string{\n\t\t\t\t\t\"*\",\n\t\t\t\t},\n\t\t\t\tAPIGroups: []string{\n\t\t\t\t\t\"*\",\n\t\t\t\t},\n\t\t\t\tResources: []string{\n\t\t\t\t\t\"*\",\n\t\t\t\t},\n\t\t\t}},\n\t\t}\n\t\tcontrollerutil.SetControllerReference(instance, clusterRole, r.Scheme)\n\t\terr = r.Client.Create(context.TODO(), clusterRole)\n\t\tif err != nil {\n\t\t\treturn reconcile.Result{}, err\n\t\t}\n\t}\n\n\texistingClusterRoleBinding := &rbacv1.ClusterRoleBinding{}\n\terr = r.Client.Get(context.TODO(), types.NamespacedName{Name: clusterRoleBindingName}, existingClusterRoleBinding)\n\tif err != nil && errors.IsNotFound(err) {\n\t\tclusterRoleBinding := &rbacv1.ClusterRoleBinding{\n\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\tAPIVersion: \"rbac/v1\",\n\t\t\t\tKind: \"ClusterRoleBinding\",\n\t\t\t},\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: clusterRoleBindingName,\n\t\t\t\tNamespace: instance.Namespace,\n\t\t\t},\n\t\t\tSubjects: []rbacv1.Subject{{\n\t\t\t\tKind: \"ServiceAccount\",\n\t\t\t\tName: serviceAccountName,\n\t\t\t\tNamespace: instance.Namespace,\n\t\t\t}},\n\t\t\tRoleRef: rbacv1.RoleRef{\n\t\t\t\tAPIGroup: \"rbac.authorization.k8s.io\",\n\t\t\t\tKind: \"ClusterRole\",\n\t\t\t\tName: clusterRoleName,\n\t\t\t},\n\t\t}\n\t\tcontrollerutil.SetControllerReference(instance, clusterRoleBinding, r.Scheme)\n\t\terr = r.Client.Create(context.TODO(), clusterRoleBinding)\n\t\tif err != nil {\n\t\t\treturn reconcile.Result{}, err\n\t\t}\n\t}\n\tintendedDeployment.Spec.Template.Spec.ServiceAccountName = serviceAccountName\n\tfor idx, container := range intendedDeployment.Spec.Template.Spec.Containers {\n\t\tif container.Name == \"kubemanager\" {\n\t\t\tcommand := []string{\"bash\", \"-c\",\n\t\t\t\t\"/usr/bin/python /usr/bin/contrail-kube-manager -c /etc/mycontrail/kubemanager.${POD_IP}\"}\n\t\t\t//command = []string{\"sh\", \"-c\", \"while true; do echo hello; sleep 10;done\"}\n\t\t\t(&intendedDeployment.Spec.Template.Spec.Containers[idx]).Command = command\n\n\t\t\tvolumeMountList := []corev1.VolumeMount{}\n\t\t\tif len((&intendedDeployment.Spec.Template.Spec.Containers[idx]).VolumeMounts) > 0 {\n\t\t\t\tvolumeMountList = (&intendedDeployment.Spec.Template.Spec.Containers[idx]).VolumeMounts\n\t\t\t}\n\t\t\tvolumeMount := corev1.VolumeMount{\n\t\t\t\tName: request.Name + \"-\" + instanceType + \"-volume\",\n\t\t\t\tMountPath: \"/etc/mycontrail\",\n\t\t\t}\n\t\t\tvolumeMountList = append(volumeMountList, volumeMount)\n\t\t\t(&intendedDeployment.Spec.Template.Spec.Containers[idx]).VolumeMounts = volumeMountList\n\t\t\t(&intendedDeployment.Spec.Template.Spec.Containers[idx]).Image = instance.Spec.ServiceConfiguration.Images[container.Name]\n\t\t}\n\t}\n\n\tfor idx, container := range intendedDeployment.Spec.Template.Spec.InitContainers {\n\t\tfor containerName, image := range instance.Spec.ServiceConfiguration.Images {\n\t\t\tif containerName == container.Name {\n\t\t\t\t(&intendedDeployment.Spec.Template.Spec.InitContainers[idx]).Image = image\n\t\t\t}\n\t\t}\n\t}\n\n\terr = instance.CompareIntendedWithCurrentDeployment(intendedDeployment,\n\t\t&instance.Spec.CommonConfiguration,\n\t\trequest,\n\t\tr.Scheme,\n\t\tr.Client,\n\t\tfalse)\n\tif err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\n\tpodIPList, podIPMap, err := instance.PodIPListAndIPMap(request, r.Client)\n\tif err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\tif len(podIPList.Items) > 0 {\n\t\terr = instance.InstanceConfiguration(request,\n\t\t\tpodIPList,\n\t\t\tr.Client)\n\t\tif err != nil {\n\t\t\treturn reconcile.Result{}, err\n\t\t}\n\n\t\terr = instance.SetPodsToReady(podIPList, r.Client)\n\t\tif err != nil {\n\t\t\treturn reconcile.Result{}, err\n\t\t}\n\n\t\terr = instance.ManageNodeStatus(podIPMap, r.Client)\n\t\tif err != nil {\n\t\t\treturn reconcile.Result{}, err\n\t\t}\n\t}\n\n\terr = instance.SetInstanceActive(r.Client, &instance.Status, intendedDeployment, request)\n\tif err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\n\treturn reconcile.Result{}, nil\n}", "func TestTwoApiServerCluster(t *testing.T) {\n\tserviceGroup1Id := \"1\"\n\tserviceGroup2Id := \"2\"\n\tmasterCount := 3\n\n\tt.Log(\"1. set up api server 1 with serviceGroup1Id\")\n\tprefix, configFilename1 := createSingleApiServerPartitionFile(t, \"A\", \"m\")\n\tdefer deleteSinglePartitionConfigFile(t, configFilename1)\n\n\tmasterConfig1 := framework.NewIntegrationServerWithPartitionConfig(prefix, configFilename1, masterAddr1, serviceGroup1Id)\n\tmasterConfig1.ExtraConfig.MasterCount = masterCount\n\t_, _, closeFn1 := framework.RunAMaster(masterConfig1)\n\n\tt.Log(\"2. set up api server 2 with serviceGroup2Id\")\n\tmasterConfig2 := framework.NewIntegrationServerWithPartitionConfig(prefix, configFilename1, masterAddr2, serviceGroup2Id)\n\tmasterConfig2.ExtraConfig.MasterCount = masterCount\n\t_, _, closeFn2 := framework.RunAMaster(masterConfig2)\n\tdefer closeFn2()\n\n\tt.Log(\"3. set up api server 3 with serviceGroup1Id\")\n\tmasterAddr3 := \"172.10.10.1\"\n\tmasterConfig3 := framework.NewIntegrationServerWithPartitionConfig(prefix, configFilename1, masterAddr3, serviceGroup1Id)\n\tmasterConfig3.ExtraConfig.MasterCount = masterCount\n\t_, _, closeFn3 := framework.RunAMaster(masterConfig3)\n\n\tt.Log(\"4. set up api server 4 with serviceGroup2Id\")\n\tmasterAddr4 := \"100.1.1.10\"\n\tmasterConfig4 := framework.NewIntegrationServerWithPartitionConfig(prefix, configFilename1, masterAddr4, serviceGroup2Id)\n\tmasterConfig4.ExtraConfig.MasterCount = masterCount\n\t_, _, closeFn4 := framework.RunAMaster(masterConfig4)\n\tdefer closeFn4()\n\n\tt.Log(\"5. set up api server with serviceGroup2Id\")\n\tmasterAddr5 := \"100.1.1.9\"\n\tmasterConfig5 := framework.NewIntegrationServerWithPartitionConfig(prefix, configFilename1, masterAddr5, serviceGroup2Id)\n\tmasterConfig5.ExtraConfig.MasterCount = masterCount\n\t_, _, closeFn5 := framework.RunAMaster(masterConfig5)\n\n\ttime.Sleep(5 * time.Second)\n\n\tt.Log(\"5.1 check master lease in storage\")\n\tendpointClient := clientv1core.NewForConfigOrDie(masterConfig1.GenericConfig.LoopbackClientConfig)\n\te, err := endpointClient.Endpoints(v1.NamespaceDefault).Get(kubernetesServiceName, metav1.GetOptions{})\n\tassert.Nil(t, err)\n\tassert.NotNil(t, e)\n\tt.Logf(\"endpoints [%+v]\", e.Subsets)\n\tassert.Equal(t, 2, len(e.Subsets))\n\tassert.Equal(t, serviceGroup1Id, e.Subsets[0].ServiceGroupId)\n\tassert.Equal(t, serviceGroup2Id, e.Subsets[1].ServiceGroupId)\n\n\tassert.Equal(t, 2, len(e.Subsets[0].Addresses))\n\tassert.Equal(t, masterAddr3, e.Subsets[0].Addresses[0].IP)\n\tassert.Equal(t, masterAddr1, e.Subsets[0].Addresses[1].IP)\n\n\tassert.Equal(t, 3, len(e.Subsets[1].Addresses))\n\tassert.Equal(t, masterAddr4, e.Subsets[1].Addresses[0].IP)\n\tassert.Equal(t, masterAddr5, e.Subsets[1].Addresses[1].IP)\n\tassert.Equal(t, masterAddr2, e.Subsets[1].Addresses[2].IP)\n\n\tt.Logf(\"6. master 5 died\")\n\tcloseFn5()\n\n\t// master lease expires in 10 seconds\n\ttime.Sleep(11 * time.Second)\n\n\te, err = endpointClient.Endpoints(v1.NamespaceDefault).Get(kubernetesServiceName, metav1.GetOptions{})\n\tassert.Nil(t, err)\n\tassert.NotNil(t, e)\n\tassert.Equal(t, 2, len(e.Subsets))\n\tassert.Equal(t, serviceGroup1Id, e.Subsets[0].ServiceGroupId)\n\tassert.Equal(t, serviceGroup2Id, e.Subsets[1].ServiceGroupId)\n\n\tassert.Equal(t, 2, len(e.Subsets[0].Addresses))\n\tassert.Equal(t, masterAddr3, e.Subsets[0].Addresses[0].IP)\n\tassert.Equal(t, masterAddr1, e.Subsets[0].Addresses[1].IP)\n\n\tassert.Equal(t, 2, len(e.Subsets[1].Addresses))\n\tassert.Equal(t, masterAddr4, e.Subsets[1].Addresses[0].IP)\n\tassert.Equal(t, masterAddr2, e.Subsets[1].Addresses[1].IP)\n\n\tt.Log(\"7. master 1 and 3 died - simulate all server in one service group died\")\n\tcloseFn1()\n\tcloseFn3()\n\ttime.Sleep(11 * time.Second)\n\te, err = endpointClient.Endpoints(v1.NamespaceDefault).Get(kubernetesServiceName, metav1.GetOptions{})\n\tassert.Nil(t, err)\n\tassert.NotNil(t, e)\n\tassert.Equal(t, 1, len(e.Subsets))\n\tassert.Equal(t, serviceGroup2Id, e.Subsets[0].ServiceGroupId)\n\n\tassert.Equal(t, 2, len(e.Subsets[0].Addresses))\n\tassert.Equal(t, masterAddr4, e.Subsets[0].Addresses[0].IP)\n\tassert.Equal(t, masterAddr2, e.Subsets[0].Addresses[1].IP)\n}", "func verifyVolumeMetadataOnStatefulsets(client clientset.Interface, ctx context.Context, namespace string,\n\tstatefulset *appsv1.StatefulSet, replicas int32, allowedTopologyHAMap map[string][]string,\n\tcategories []string, storagePolicyName string, nodeList *v1.NodeList, f *framework.Framework) {\n\t// Waiting for pods status to be Ready\n\tfss.WaitForStatusReadyReplicas(client, statefulset, replicas)\n\tgomega.Expect(fss.CheckMount(client, statefulset, mountPath)).NotTo(gomega.HaveOccurred())\n\tssPodsBeforeScaleDown := fss.GetPodList(client, statefulset)\n\tgomega.Expect(ssPodsBeforeScaleDown.Items).NotTo(gomega.BeEmpty(),\n\t\tfmt.Sprintf(\"Unable to get list of Pods from the Statefulset: %v\", statefulset.Name))\n\tgomega.Expect(len(ssPodsBeforeScaleDown.Items) == int(replicas)).To(gomega.BeTrue(),\n\t\t\"Number of Pods in the statefulset should match with number of replicas\")\n\n\tginkgo.By(\"Verify GV PV and SV PV has has required PV node affinity details\")\n\tginkgo.By(\"Verify SV PVC has TKG HA annotations set\")\n\t// Get the list of Volumes attached to Pods before scale down\n\tfor _, sspod := range ssPodsBeforeScaleDown.Items {\n\t\tpod, err := client.CoreV1().Pods(namespace).Get(ctx, sspod.Name, metav1.GetOptions{})\n\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\tfor _, volumespec := range sspod.Spec.Volumes {\n\t\t\tif volumespec.PersistentVolumeClaim != nil {\n\t\t\t\tpvcName := volumespec.PersistentVolumeClaim.ClaimName\n\t\t\t\tpv := getPvFromClaim(client, statefulset.Namespace, pvcName)\n\t\t\t\tpvclaim, err := client.CoreV1().PersistentVolumeClaims(namespace).Get(ctx,\n\t\t\t\t\tpvcName, metav1.GetOptions{})\n\t\t\t\tgomega.Expect(pvclaim).NotTo(gomega.BeNil())\n\t\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t\t\tvolHandle := getVolumeIDFromSupervisorCluster(pv.Spec.CSI.VolumeHandle)\n\t\t\t\tgomega.Expect(volHandle).NotTo(gomega.BeEmpty())\n\t\t\t\tsvcPVCName := pv.Spec.CSI.VolumeHandle\n\n\t\t\t\tsvcPVC := getPVCFromSupervisorCluster(svcPVCName)\n\t\t\t\tgomega.Expect(*svcPVC.Spec.StorageClassName == storagePolicyName).To(\n\t\t\t\t\tgomega.BeTrue(), \"SV Pvc storageclass does not match with SV storageclass\")\n\t\t\t\tframework.Logf(\"GC PVC's storageclass matches SVC PVC's storageclass\")\n\n\t\t\t\tverifyAnnotationsAndNodeAffinity(allowedTopologyHAMap, categories, pod,\n\t\t\t\t\tnodeList, svcPVC, pv, svcPVCName)\n\n\t\t\t\t// Verify the attached volume match the one in CNS cache\n\t\t\t\terr = waitAndVerifyCnsVolumeMetadata4GCVol(volHandle, svcPVCName, pvclaim,\n\t\t\t\t\tpv, pod)\n\t\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t\t}\n\t\t}\n\t}\n\n\treplicas = 5\n\tframework.Logf(fmt.Sprintf(\"Scaling up statefulset: %v to number of Replica: %v\",\n\t\tstatefulset.Name, replicas))\n\t_, scaleupErr := fss.Scale(client, statefulset, replicas)\n\tgomega.Expect(scaleupErr).NotTo(gomega.HaveOccurred())\n\n\tfss.WaitForStatusReplicas(client, statefulset, replicas)\n\tfss.WaitForStatusReadyReplicas(client, statefulset, replicas)\n\tssPodsAfterScaleUp := fss.GetPodList(client, statefulset)\n\tgomega.Expect(ssPodsAfterScaleUp.Items).NotTo(gomega.BeEmpty(),\n\t\tfmt.Sprintf(\"Unable to get list of Pods from the Statefulset: %v\", statefulset.Name))\n\tgomega.Expect(len(ssPodsAfterScaleUp.Items) == int(replicas)).To(gomega.BeTrue(),\n\t\t\"Number of Pods in the statefulset %s, %v, should match with number of replicas %v\",\n\t\tstatefulset.Name, ssPodsAfterScaleUp.Size(), replicas,\n\t)\n\n\t// Get the list of Volumes attached to Pods before scale down\n\tfor _, sspod := range ssPodsBeforeScaleDown.Items {\n\t\tpod, err := client.CoreV1().Pods(namespace).Get(ctx, sspod.Name, metav1.GetOptions{})\n\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\tfor _, volumespec := range sspod.Spec.Volumes {\n\t\t\tif volumespec.PersistentVolumeClaim != nil {\n\t\t\t\tpvcName := volumespec.PersistentVolumeClaim.ClaimName\n\t\t\t\tpv := getPvFromClaim(client, statefulset.Namespace, pvcName)\n\t\t\t\tpvclaim, err := client.CoreV1().PersistentVolumeClaims(namespace).Get(ctx,\n\t\t\t\t\tpvcName, metav1.GetOptions{})\n\t\t\t\tgomega.Expect(pvclaim).NotTo(gomega.BeNil())\n\t\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\n\t\t\t\tvolHandle := getVolumeIDFromSupervisorCluster(pv.Spec.CSI.VolumeHandle)\n\t\t\t\tgomega.Expect(volHandle).NotTo(gomega.BeEmpty())\n\t\t\t\tsvcPVCName := pv.Spec.CSI.VolumeHandle\n\t\t\t\tsvcPVC := getPVCFromSupervisorCluster(svcPVCName)\n\n\t\t\t\tverifyAnnotationsAndNodeAffinity(allowedTopologyHAMap, categories, pod,\n\t\t\t\t\tnodeList, svcPVC, pv, svcPVCName)\n\n\t\t\t\tframework.Logf(fmt.Sprintf(\"Verify volume: %s is attached to the node: %s\",\n\t\t\t\t\tpv.Spec.CSI.VolumeHandle, sspod.Spec.NodeName))\n\t\t\t\tvar vmUUID string\n\t\t\t\tctx, cancel := context.WithCancel(context.Background())\n\t\t\t\tdefer cancel()\n\t\t\t\tvmUUID, err = getVMUUIDFromNodeName(pod.Spec.NodeName)\n\t\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t\t\tverifyCRDInSupervisorWithWait(ctx, f, pod.Spec.NodeName+\"-\"+svcPVCName,\n\t\t\t\t\tcrdCNSNodeVMAttachment, crdVersion, crdGroup, true)\n\n\t\t\t\tisDiskAttached, err := e2eVSphere.isVolumeAttachedToVM(client, volHandle, vmUUID)\n\t\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t\t\tgomega.Expect(isDiskAttached).To(gomega.BeTrue(), \"Disk is not attached to the node\")\n\t\t\t\tframework.Logf(\"After scale up, verify the attached volumes match those in CNS Cache\")\n\t\t\t\terr = waitAndVerifyCnsVolumeMetadata4GCVol(volHandle, svcPVCName, pvclaim,\n\t\t\t\t\tpv, pod)\n\t\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t\t}\n\t\t}\n\t}\n\n}", "func (r *RqliteClusterReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {\n\t_ = context.Background()\n\tlog := r.Log.WithValues(\"Reconcile RqliteCluster \", req.Name, \" in namespace \", req.NamespacedName)\n\n\tlog.V(1).Info(\"Get Object Info\")\n\t//objectInfo := new(rqlitev1.RqliteCluster{})\n\tobjectInfo := &rqlitev1.RqliteCluster{}\n\terr := r.Get(context.TODO(), req.NamespacedName, objectInfo)\n\n\tif err != nil {\n\t\tlog.Error(err, \"Error during r.Get\")\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn reconcile.Result{}, nil\n\t\t}\n\t\treturn reconcile.Result{}, err\n\t}\n\tlog.Info(\"Dump Object Info\", \"ClusterName\", objectInfo.Spec.Name, \"ClusterSize\", objectInfo.Spec.ClusterSize)\n\n\tlog.V(1).Info(\"Update Object Status\")\n\tlog.V(1).Info(\"Get Object Current Status\", \"NAme\", objectInfo.Spec.Name, \"Status\", objectInfo.Status.CurrentStatus)\n\tif objectInfo.Status.CurrentStatus == \"\" {\n\t\tlog.V(1).Info(\"Creating new RqliteCluster)\n\t\tpod := newRqliteCluster(objectInfo)\n\t\tobjectInfo.Status.CurrentStatus = \"OK\"\n\t}\n\n\tlog.V(1).Info(\"Set Object Target Status : \", \"Name\", objectInfo.Spec.Name, \"Status \", objectInfo.Status.CurrentStatus)\n\n\terr = r.Status().Update(context.TODO(), objectInfo)\n\tif err != nil {\n\t\tlog.Error(err, \"Error during r.Status\")\n\t\treturn reconcile.Result{}, err\n\t}\n\t//if anything else happens\n\treturn ctrl.Result{}, nil\n}", "func PollManagementClusterStatusOnANode(ctx context.Context, clusterOperWaitGroup *sync.WaitGroup, intendedCluster *operation.ConfigCluster,\n\tmctNode *operation.ClusterMemberNode, clusterConfigErrors chan OperationError) {\n\n\tdefer clusterOperWaitGroup.Done()\n\n\tlog := appcontext.Logger(ctx).WithFields(nlog.Fields{\n\t\t\"App\": \"dcfabric\",\n\t\t\"Fabric\": intendedCluster.FabricName,\n\t\t\"Operation\": \"Poll Management Cluster Status\",\n\t\t\"Switch\": mctNode.NodeMgmtIP,\n\t})\n\n\t/*Netconf client*/\n\tadapter := ad.GetAdapter(mctNode.NodeModel)\n\tclient := &client.NetconfClient{Host: mctNode.NodeMgmtIP, User: mctNode.NodeMgmtUserName, Password: mctNode.NodeMgmtPassword}\n\tclient.Login()\n\tdefer client.Close()\n\n\tintendedClusterMembers := intendedCluster.ClusterMemberNodes\n\n\tOperation := \"Poll for management cluster status\"\n\tif len(intendedClusterMembers) > 2 {\n\t\tclusterConfigErrors <- OperationError{Operation: Operation, Error: errors.New(\"Management cluster is supported for a maximum of 2 nodes\"), Host: mctNode.NodeMgmtIP}\n\t\treturn\n\t}\n\n\ttimeout := time.After(time.Duration(MgmtClusterStatePollingTimeOutInSec) * (time.Second))\n\ttick := time.Tick(time.Duration(MgmtClusterStatePollingIntervalInSec) * (time.Second))\n\n\tfor {\n\t\tselect {\n\t\tcase <-timeout:\n\t\t\tclusterConfigErrors <- OperationError{Operation: Operation, Error: errors.New(\"Management Cluster is not operational. Polling timed out\"), Host: mctNode.NodeMgmtIP}\n\t\t\treturn\n\t\tcase <-tick:\n\t\t\tfmt.Println(\"Management cluster status polled at\", time.Now())\n\n\t\t\toutput, operationalClusterMembers, principalNode, err := adapter.GetManagementClusterStatus(client)\n\t\t\tlog.Infof(\"Principal Node IP obtained on <%s> is <%s>\", mctNode.NodeMgmtIP, principalNode)\n\t\t\toperationalClusterMemberCount, err := strconv.Atoi(operationalClusterMembers.TotalMemberNodeCount)\n\n\t\t\tif err != nil {\n\t\t\t\tclusterConfigErrors <- OperationError{Operation: Operation, Error: err, Host: mctNode.NodeMgmtIP}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif operationalClusterMemberCount == len(intendedClusterMembers) {\n\t\t\t\tvar i = 0\n\t\t\t\tvar j = 0\n\t\t\t\tvar found = false\n\t\t\t\tfor i = 0; i < operationalClusterMemberCount; i++ {\n\t\t\t\t\tfound = false\n\t\t\t\t\toperationalClusterMember := operationalClusterMembers.MemberNodes[i]\n\t\t\t\t\tfor j = 0; j < operationalClusterMemberCount; j++ {\n\t\t\t\t\t\tvar ipClusterMember = intendedClusterMembers[j]\n\t\t\t\t\t\tif operationalClusterMember.NodeMgmtIP == ipClusterMember.NodeMgmtIP {\n\t\t\t\t\t\t\tfound = true\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif found == false {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif found == true {\n\t\t\t\t\tfmt.Println(\"Management Cluster is operational, hence exiting the poll on \", mctNode.NodeMgmtIP)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlog.Info(\"Raw o/p of show-cluster-management\", output)\n\t\t\t//fmt.Println(\"operationalClusterMembers\", operationalClusterMembers)\n\t\t}\n\t}\n}", "func TestNoTopo(t *testing.T) {\n\tkdlog.InitLogs()\n\n\tkubePod := &kubev1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"Pod0\",\n\t\t\tAnnotations: map[string]string{\n\t\t\t\t\"ABCD\": \"EFGH\",\n\t\t\t},\n\t\t},\n\t\tSpec: kubev1.PodSpec{\n\t\t\tContainers: []kubev1.Container{\n\t\t\t\t{\n\t\t\t\t\tName: \"Cont0\",\n\t\t\t\t\tResources: kubev1.ResourceRequirements{\n\t\t\t\t\t\tRequests: kubev1.ResourceList{\n\t\t\t\t\t\t\tkubev1.ResourceName(gpuplugintypes.ResourceGPU): *resource.NewQuantity(4, resource.DecimalSI),\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\tnodeInfo0 := &kubev1.Node{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"Node0\",\n\t\t},\n\t\tStatus: kubev1.NodeStatus{\n\t\t\tCapacity: kubev1.ResourceList{\n\t\t\t\tkubev1.ResourceName(gpuplugintypes.ResourceGPU): *resource.NewQuantity(4, resource.DecimalSI),\n\t\t\t},\n\t\t\tAllocatable: kubev1.ResourceList{\n\t\t\t\tkubev1.ResourceName(gpuplugintypes.ResourceGPU): *resource.NewQuantity(4, resource.DecimalSI),\n\t\t\t},\n\t\t},\n\t}\n\tnodeInfo1 := &kubev1.Node{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"Node1\",\n\t\t},\n\t\tStatus: kubev1.NodeStatus{\n\t\t\tCapacity: kubev1.ResourceList{\n\t\t\t\tkubev1.ResourceName(gpuplugintypes.ResourceGPU): *resource.NewQuantity(8, resource.DecimalSI),\n\t\t\t},\n\t\t\tAllocatable: kubev1.ResourceList{\n\t\t\t\tkubev1.ResourceName(gpuplugintypes.ResourceGPU): *resource.NewQuantity(8, resource.DecimalSI),\n\t\t\t},\n\t\t},\n\t}\n\tnodeInfo2 := &kubev1.Node{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"Node2\",\n\t\t},\n\t\tStatus: kubev1.NodeStatus{\n\t\t\tCapacity: kubev1.ResourceList{\n\t\t\t\tkubev1.ResourceName(gpuplugintypes.ResourceGPU): *resource.NewQuantity(0, resource.DecimalSI),\n\t\t\t},\n\t\t\tAllocatable: kubev1.ResourceList{\n\t\t\t\tkubev1.ResourceName(gpuplugintypes.ResourceGPU): *resource.NewQuantity(0, resource.DecimalSI),\n\t\t\t},\n\t\t},\n\t}\n\tnodeInfo3 := &kubev1.Node{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"Node3\",\n\t\t},\n\t\tStatus: kubev1.NodeStatus{},\n\t}\n\tnodeInfo4 := &kubev1.Node{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"Node4\",\n\t\t},\n\t\tStatus: kubev1.NodeStatus{\n\t\t\tCapacity: kubev1.ResourceList{\n\t\t\t\tkubev1.ResourceName(gpuplugintypes.ResourceGPU): *resource.NewQuantity(8, resource.DecimalSI),\n\t\t\t},\n\t\t\tAllocatable: kubev1.ResourceList{\n\t\t\t\tkubev1.ResourceName(gpuplugintypes.ResourceGPU): *resource.NewQuantity(8, resource.DecimalSI),\n\t\t\t},\n\t\t},\n\t}\n\n\tds := DeviceScheduler\n\tds.RemoveAll()\n\tdev := &gpuschedulerplugin.NvidiaGPUScheduler{}\n\tds.AddDevice(dev)\n\n\tn0, _ := kubeinterface.KubeNodeToNodeInfo(nodeInfo0, nil)\n\tn1, _ := kubeinterface.KubeNodeToNodeInfo(nodeInfo1, nil)\n\tn2, _ := kubeinterface.KubeNodeToNodeInfo(nodeInfo2, nil)\n\tn3, _ := kubeinterface.KubeNodeToNodeInfo(nodeInfo3, nil)\n\tn4, _ := kubeinterface.KubeNodeToNodeInfo(nodeInfo4, nil)\n\tds.AddNode(nodeInfo0.ObjectMeta.Name, n0)\n\tds.AddNode(nodeInfo1.ObjectMeta.Name, n1)\n\tds.AddNode(nodeInfo2.ObjectMeta.Name, n2)\n\tds.AddNode(nodeInfo3.ObjectMeta.Name, n3)\n\tfmt.Printf(\"NodeLocationMap:\\n%+v\\n\", gpuschedulerplugin.NodeLocationMap)\n\tfmt.Printf(\"NodeCacheMap:\\n%+v\\n\", gpuschedulerplugin.NodeCacheMap)\n\tds.AddNode(nodeInfo4.ObjectMeta.Name, n4)\n\tfmt.Printf(\"NodeLocationMap:\\n%+v\\n\", gpuschedulerplugin.NodeLocationMap)\n\tfmt.Printf(\"NodeCacheMap:\\n%+v\\n\", gpuschedulerplugin.NodeCacheMap)\n\tfmt.Printf(\"Node: %+v\\n\", n0)\n\tfmt.Printf(\"Node: %+v\\n\", n1)\n\tmodReq := gpuschedulerplugin.TranslateGPUResources(n0.KubeAlloc[gpuplugintypes.ResourceGPU], types.ResourceList{\n\t\ttypes.DeviceGroupPrefix + \"/gpugrp1/A/gpugrp0/B/gpu/GPU0/cards\": int64(1),\n\t}, n0.Allocatable)\n\tif !reflect.DeepEqual(modReq, n0.Allocatable) {\n\t\tt.Errorf(\"Alloc not same, expect: %v, have: %v\", n0.Allocatable, modReq)\n\t}\n\tn0.Allocatable = modReq\n\t//fmt.Printf(\"Node: %+v\\n\", n0)\n\n\tp0, _ := kubeinterface.KubePodInfoToPodInfo(kubePod, false)\n\tfmt.Printf(\"Pod: %+v\\n\", p0)\n\n\tfits, failures, score := ds.PodFitsResources(p0, n0, false)\n\tfmt.Printf(\"Fit: %v Failures: %v Score: %v\\n\", fits, failures, score)\n\n\tfits, failures, score = ds.PodFitsResources(p0, n1, false)\n\tfmt.Printf(\"Fit: %v Failures: %v Score: %v\\n\", fits, failures, score)\n\n\tfits, failures, score = ds.PodFitsResources(p0, n2, false)\n\tfmt.Printf(\"Fit: %v Failures: %v Score: %v\\n\", fits, failures, score)\n\n\tfits, failures, score = ds.PodFitsResources(p0, n3, false)\n\tfmt.Printf(\"Fit: %v Failures: %v Score: %v\\n\", fits, failures, score)\n\n\tfmt.Printf(\"Scores: %+v\\n\", ds.score)\n\n\tpri0 := ds.PodPriority(p0, n0)\n\tfmt.Printf(\"PodPriority0: %v\\n\", pri0)\n\n\tpri1 := ds.PodPriority(p0, n1)\n\tfmt.Printf(\"PodPriority1: %v\\n\", pri1)\n\n\tds.RemoveNode(\"Node1\")\n\tfmt.Printf(\"NodeLocationMap:\\n%+v\\n\", gpuschedulerplugin.NodeLocationMap)\n\tfmt.Printf(\"NodeCacheMap:\\n%+v\\n\", gpuschedulerplugin.NodeCacheMap)\n\tds.RemoveNode(\"Node4\")\n\tfmt.Printf(\"NodeLocationMap:\\n%+v\\n\", gpuschedulerplugin.NodeLocationMap)\n\tfmt.Printf(\"NodeCacheMap:\\n%+v\\n\", gpuschedulerplugin.NodeCacheMap)\n\n\tkdlog.FlushLogs()\n}", "func cassandraClusterScaleDownSimpleTest(t *testing.T, f *framework.Framework, ctx *framework.TestCtx) {\n\tt.Logf(\"0. Init Operator\")\n\n\tnamespace, err := ctx.GetNamespace()\n\tif err != nil {\n\t\tt.Fatalf(\"could not get namespace: %v\", err)\n\t}\n\n\t/*----\n\t */\n\tt.Logf(\"1. We Create the Cluster (1dc/1rack/2node\")\n\n\tcc := mye2eutil.HelperInitCluster(t, f, ctx, \"cassandracluster-1DC.yaml\", namespace)\n\tcc.Namespace = namespace\n\tcc.Spec.Topology.DC[0].NodesPerRacks = func(i int32) *int32 { return &i }(2)\n\n\tt.Logf(\"Create CassandraCluster cassandracluster-1DC.yaml in namespace %s\", namespace)\n\terr = f.Client.Create(goctx.TODO(), cc, &framework.CleanupOptions{TestContext: ctx,\n\t\tTimeout: mye2eutil.CleanupTimeout,\n\t\tRetryInterval: mye2eutil.CleanupRetryInterval})\n\tif err != nil && !apierrors.IsAlreadyExists(err) {\n\t\tt.Logf(\"Error Creating cassandracluster: %v\", err)\n\t\tt.Fatal(err)\n\t}\n\t// wait for statefulset dc1-rack1 2 nodes\n\terr = mye2eutil.WaitForStatefulset(t, f.KubeClient, namespace, \"cassandra-e2e-dc1-rack1\", 2,\n\t\tmye2eutil.RetryInterval,\n\t\tmye2eutil.Timeout)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = mye2eutil.WaitForStatusDone(t, f, namespace, \"cassandra-e2e\", mye2eutil.RetryInterval, mye2eutil.Timeout)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t//Get Updated cc\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\", Namespace: namespace}, cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t//locale dc-rack state is OK\n\tassert.Equal(t, api.ClusterPhaseInitial.Name, cc.Status.CassandraRackStatus[\"dc1-rack1\"].CassandraLastAction.Name)\n\tassert.Equal(t, api.StatusDone, cc.Status.CassandraRackStatus[\"dc1-rack1\"].CassandraLastAction.Status)\n\tassert.Equal(t, api.ClusterPhaseInitial.Name, cc.Status.LastClusterAction)\n\tassert.Equal(t, api.StatusDone, cc.Status.LastClusterActionStatus)\n\n\t/*----\n\t */\n\tt.Logf(\"3. We Request a ScaleDown to 1\")\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\", Namespace: namespace}, cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcc.Spec.Topology.DC[0].NodesPerRacks = func(i int32) *int32 { return &i }(1)\n\terr = f.Client.Update(goctx.TODO(), cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// wait for statefulset dc1-rack1\n\terr = mye2eutil.WaitForStatefulset(t, f.KubeClient, namespace, \"cassandra-e2e-dc1-rack1\", 1,\n\t\tmye2eutil.RetryInterval,\n\t\tmye2eutil.Timeout)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = mye2eutil.WaitForStatusDone(t, f, namespace, \"cassandra-e2e\", mye2eutil.RetryInterval, mye2eutil.Timeout)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tt.Log(\"Get Updated cc\")\n\tcc = &api.CassandraCluster{}\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\", Namespace: namespace}, cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t//Because AutoUpdateSeedList is false we stay on ScaleUp=Done status\n\tassert.Equal(t, api.ActionScaleDown.Name, cc.Status.CassandraRackStatus[\"dc1-rack1\"].CassandraLastAction.Name)\n\tassert.Equal(t, api.StatusDone, cc.Status.CassandraRackStatus[\"dc1-rack1\"].CassandraLastAction.Status)\n\t//Check Global state\n\tassert.Equal(t, api.ActionScaleDown.Name, cc.Status.LastClusterAction)\n\tassert.Equal(t, api.StatusDone, cc.Status.LastClusterActionStatus)\n}", "func TestCluster_ResizeStates(t *testing.T) {\n\n\tt.Run(\"Single node, no data\", func(t *testing.T) {\n\t\ttc := NewClusterCluster(1)\n\n\t\t// Open TestCluster.\n\t\tif err := tc.Open(); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tnode := tc.Clusters[0]\n\n\t\t// Ensure that node comes up in state NORMAL.\n\t\tif node.State() != ClusterStateNormal {\n\t\t\tt.Errorf(\"expected state: %v, but got: %v\", ClusterStateNormal, node.State())\n\t\t}\n\n\t\texpectedTop := &Topology{\n\t\t\tnodeIDs: []string{node.Node.ID},\n\t\t}\n\n\t\t// Verify topology file.\n\t\tif !reflect.DeepEqual(node.Topology.nodeIDs, expectedTop.nodeIDs) {\n\t\t\tt.Errorf(\"expected topology: %v, but got: %v\", expectedTop.nodeIDs, node.Topology.nodeIDs)\n\t\t}\n\n\t\t// Close TestCluster.\n\t\tif err := tc.Close(); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t})\n\n\tt.Run(\"Single node, in topology\", func(t *testing.T) {\n\t\ttc := NewClusterCluster(0)\n\t\ttc.addNode()\n\n\t\tnode := tc.Clusters[0]\n\n\t\t// write topology to data file\n\t\ttop := &Topology{\n\t\t\tnodeIDs: []string{node.Node.ID},\n\t\t}\n\t\ttc.WriteTopology(node.Path, top)\n\n\t\t// Open TestCluster.\n\t\tif err := tc.Open(); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\t// Ensure that node comes up in state NORMAL.\n\t\tif node.State() != ClusterStateNormal {\n\t\t\tt.Errorf(\"expected state: %v, but got: %v\", ClusterStateNormal, node.State())\n\t\t}\n\n\t\t// Close TestCluster.\n\t\tif err := tc.Close(); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t})\n\n\tt.Run(\"Single node, not in topology\", func(t *testing.T) {\n\t\ttc := NewClusterCluster(0)\n\t\ttc.addNode()\n\n\t\tnode := tc.Clusters[0]\n\n\t\t// write topology to data file\n\t\ttop := &Topology{\n\t\t\tnodeIDs: []string{\"some-other-host\"},\n\t\t}\n\t\ttc.WriteTopology(node.Path, top)\n\n\t\t// Open TestCluster.\n\t\texpected := \"coordinator node0 is not in topology: [some-other-host]\"\n\t\terr := tc.Open()\n\t\tif err == nil || errors.Cause(err).Error() != expected {\n\t\t\tt.Errorf(\"did not receive expected error, got: %s\", errors.Cause(err).Error())\n\t\t}\n\n\t\t// Close TestCluster.\n\t\tif err := tc.Close(); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t})\n\n\tt.Run(\"Multiple nodes, no data\", func(t *testing.T) {\n\t\ttc := NewClusterCluster(0)\n\t\ttc.addNode()\n\n\t\t// Open TestCluster.\n\t\tif err := tc.Open(); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\ttc.addNode()\n\n\t\tnode0 := tc.Clusters[0]\n\t\tnode1 := tc.Clusters[1]\n\n\t\t// Ensure that nodes comes up in state NORMAL.\n\t\tif node0.State() != ClusterStateNormal {\n\t\t\tt.Errorf(\"expected node0 state: %v, but got: %v\", ClusterStateNormal, node0.State())\n\t\t} else if node1.State() != ClusterStateNormal {\n\t\t\tt.Errorf(\"expected node1 state: %v, but got: %v\", ClusterStateNormal, node1.State())\n\t\t}\n\n\t\texpectedTop := &Topology{\n\t\t\tnodeIDs: []string{node0.Node.ID, node1.Node.ID},\n\t\t}\n\n\t\t// Verify topology file.\n\t\tif !reflect.DeepEqual(node0.Topology.nodeIDs, expectedTop.nodeIDs) {\n\t\t\tt.Errorf(\"expected node0 topology: %v, but got: %v\", expectedTop.nodeIDs, node0.Topology.nodeIDs)\n\t\t} else if !reflect.DeepEqual(node1.Topology.nodeIDs, expectedTop.nodeIDs) {\n\t\t\tt.Errorf(\"expected node1 topology: %v, but got: %v\", expectedTop.nodeIDs, node1.Topology.nodeIDs)\n\t\t}\n\n\t\t// Close TestCluster.\n\t\tif err := tc.Close(); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t})\n\n\tt.Run(\"Multiple nodes, in/not in topology\", func(t *testing.T) {\n\t\ttc := NewClusterCluster(0)\n\t\ttc.addNode()\n\t\tnode0 := tc.Clusters[0]\n\n\t\t// write topology to data file\n\t\ttop := &Topology{\n\t\t\tnodeIDs: []string{\"node0\", \"node2\"},\n\t\t}\n\t\ttc.WriteTopology(node0.Path, top)\n\n\t\t// Open TestCluster.\n\t\tif err := tc.Open(); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\t// Ensure that node is in state STARTING before the other node joins.\n\t\tif node0.State() != ClusterStateStarting {\n\t\t\tt.Errorf(\"expected node0 state: %v, but got: %v\", ClusterStateStarting, node0.State())\n\t\t}\n\n\t\t// Expect an error by adding a node not in the topology.\n\t\texpectedError := \"host is not in topology: node1\"\n\t\terr := tc.addNode()\n\t\tif err == nil || err.Error() != expectedError {\n\t\t\tt.Errorf(\"did not receive expected error: %s\", expectedError)\n\t\t}\n\n\t\ttc.addNode()\n\t\tnode2 := tc.Clusters[2]\n\n\t\t// Ensure that node comes up in state NORMAL.\n\t\tif node0.State() != ClusterStateNormal {\n\t\t\tt.Errorf(\"expected node0 state: %v, but got: %v\", ClusterStateNormal, node0.State())\n\t\t} else if node2.State() != ClusterStateNormal {\n\t\t\tt.Errorf(\"expected node1 state: %v, but got: %v\", ClusterStateNormal, node2.State())\n\t\t}\n\n\t\t// Close TestCluster.\n\t\tif err := tc.Close(); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t})\n\n\tt.Run(\"Multiple nodes, with data\", func(t *testing.T) {\n\t\ttc := NewClusterCluster(0)\n\t\ttc.addNode()\n\t\tnode0 := tc.Clusters[0]\n\n\t\t// Open TestCluster.\n\t\tif err := tc.Open(); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\t// Add Bit Data to node0.\n\t\tif err := tc.CreateField(\"i\", \"f\", OptFieldTypeDefault()); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\ttc.SetBit(\"i\", \"f\", 1, 101, nil)\n\t\ttc.SetBit(\"i\", \"f\", 1, 1300000, nil)\n\n\t\t// Before starting the resize, get the CheckSum to use for\n\t\t// comparison later.\n\t\tnode0Field := node0.holder.Field(\"i\", \"f\")\n\t\tnode0View := node0Field.view(\"standard\")\n\t\tnode0Fragment := node0View.Fragment(1)\n\t\tnode0Checksum := node0Fragment.Checksum()\n\n\t\t// addNode needs to block until the resize process has completed.\n\t\ttc.addNode()\n\t\tnode1 := tc.Clusters[1]\n\n\t\t// Ensure that nodes come up in state NORMAL.\n\t\tif node0.State() != ClusterStateNormal {\n\t\t\tt.Errorf(\"expected node0 state: %v, but got: %v\", ClusterStateNormal, node0.State())\n\t\t} else if node1.State() != ClusterStateNormal {\n\t\t\tt.Errorf(\"expected node1 state: %v, but got: %v\", ClusterStateNormal, node1.State())\n\t\t}\n\n\t\texpectedTop := &Topology{\n\t\t\tnodeIDs: []string{node0.Node.ID, node1.Node.ID},\n\t\t}\n\n\t\t// Verify topology file.\n\t\tif !reflect.DeepEqual(node0.Topology.nodeIDs, expectedTop.nodeIDs) {\n\t\t\tt.Errorf(\"expected node0 topology: %v, but got: %v\", expectedTop.nodeIDs, node0.Topology.nodeIDs)\n\t\t} else if !reflect.DeepEqual(node1.Topology.nodeIDs, expectedTop.nodeIDs) {\n\t\t\tt.Errorf(\"expected node1 topology: %v, but got: %v\", expectedTop.nodeIDs, node1.Topology.nodeIDs)\n\t\t}\n\n\t\t// Bits\n\t\t// Verify that node-1 contains the fragment (i/f/standard/1) transferred from node-0.\n\t\tnode1Field := node1.holder.Field(\"i\", \"f\")\n\t\tnode1View := node1Field.view(\"standard\")\n\t\tnode1Fragment := node1View.Fragment(1)\n\n\t\t// Ensure checksums are the same.\n\t\tif chksum := node1Fragment.Checksum(); !bytes.Equal(chksum, node0Checksum) {\n\t\t\tt.Fatalf(\"expected standard view checksum to match: %x - %x\", chksum, node0Checksum)\n\t\t}\n\n\t\t// Close TestCluster.\n\t\tif err := tc.Close(); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t})\n}", "func (a *Actuator) Reconcile(cluster *clusterv1.Cluster) error {\n\tlog := a.log.WithValues(\"cluster-name\", cluster.Name, \"cluster-namespace\", cluster.Namespace)\n\tlog.Info(\"Reconciling Cluster\")\n\n\tscope, err := scope.NewClusterScope(scope.ClusterScopeParams{\n\t\tCluster: cluster,\n\t\tLogger: a.log,\n\t})\n\tif err != nil {\n\t\treturn errors.Errorf(\"failed to create scope: %+v\", err)\n\t}\n\n\tdefer scope.Close()\n\n\tec2svc := ec2.NewService(scope)\n\telbsvc := elb.NewService(scope)\n\tcertSvc := certificates.NewService(scope)\n\n\t// Store cert material in spec.\n\tif err := certSvc.ReconcileCertificates(); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to reconcile certificates for cluster %q\", cluster.Name)\n\t}\n\n\tif err := ec2svc.ReconcileNetwork(); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to reconcile network for cluster %q\", cluster.Name)\n\t}\n\n\tif err := ec2svc.ReconcileBastion(); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to reconcile bastion host for cluster %q\", cluster.Name)\n\t}\n\n\tif err := elbsvc.ReconcileLoadbalancers(); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to reconcile load balancers for cluster %q\", cluster.Name)\n\t}\n\n\tif cluster.Annotations == nil {\n\t\tcluster.Annotations = make(map[string]string)\n\t}\n\tcluster.Annotations[v1alpha2.AnnotationClusterInfrastructureReady] = v1alpha2.ValueReady\n\n\t// Store KubeConfig for Cluster API NodeRef controller to use.\n\tkubeConfigSecretName := remote.KubeConfigSecretName(cluster.Name)\n\tsecretClient := a.coreClient.Secrets(cluster.Namespace)\n\tif _, err := secretClient.Get(kubeConfigSecretName, metav1.GetOptions{}); err != nil && apierrors.IsNotFound(err) {\n\t\tkubeConfig, err := a.Deployer.GetKubeConfig(cluster, nil)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to get kubeconfig for cluster %q\", cluster.Name)\n\t\t}\n\n\t\tkubeConfigSecret := &apiv1.Secret{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: kubeConfigSecretName,\n\t\t\t},\n\t\t\tStringData: map[string]string{\n\t\t\t\t\"value\": kubeConfig,\n\t\t\t},\n\t\t}\n\n\t\tif _, err := secretClient.Create(kubeConfigSecret); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to create kubeconfig secret for cluster %q\", cluster.Name)\n\t\t}\n\t} else if err != nil {\n\t\treturn errors.Wrapf(err, \"failed to get kubeconfig secret for cluster %q\", cluster.Name)\n\t}\n\n\t// If the control plane is ready, try to delete the control plane configmap lock, if it exists, and return.\n\tif cluster.Annotations[v1alpha2.AnnotationControlPlaneReady] == v1alpha2.ValueReady {\n\t\tconfigMapName := scope.ControlPlaneConfigMapName()\n\t\tlog.Info(\"Checking for existence of control plane configmap lock\", \"configmap-name\", configMapName)\n\n\t\t_, err := a.coreClient.ConfigMaps(cluster.Namespace).Get(configMapName, metav1.GetOptions{})\n\t\tswitch {\n\t\tcase apierrors.IsNotFound(err):\n\t\t\t// It doesn't exist - no-op\n\t\tcase err != nil:\n\t\t\treturn errors.Wrapf(err, \"Error retrieving control plane configmap lock %q\", configMapName)\n\t\tdefault:\n\t\t\tif err := a.coreClient.ConfigMaps(cluster.Namespace).Delete(configMapName, nil); err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"Error deleting control plane configmap lock %q\", configMapName)\n\t\t\t}\n\t\t}\n\n\t\t// Nothing more to reconcile - return early.\n\t\treturn nil\n\t}\n\n\tlog.Info(\"Cluster does not have ready annotation - checking for ready control plane machines\")\n\n\tmachineList := &clusterv1.MachineList{}\n\tif err := a.List(context.Background(), machineList, scope.ListOptionsLabelSelector()); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to retrieve machines in cluster %q\", cluster.Name)\n\t}\n\n\tcontrolPlaneMachines := util.GetControlPlaneMachinesFromList(machineList)\n\n\tmachineReady := false\n\tfor _, machine := range controlPlaneMachines {\n\t\tif machine.Status.NodeRef != nil {\n\t\t\tmachineReady = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !machineReady {\n\t\tlog.Info(\"No control plane machines are ready - requeuing cluster\")\n\t\treturn &controllerError.RequeueAfterError{RequeueAfter: waitForControlPlaneMachineDuration}\n\t}\n\n\tlog.Info(\"Setting cluster ready annotation\")\n\tcluster.Annotations[v1alpha2.AnnotationControlPlaneReady] = v1alpha2.ValueReady\n\n\treturn nil\n}", "func (c *HyperpilotOperator) Run(stopCh chan struct{}) error {\n\t// Lifecycle:\n\tc.state = operatorInitializing\n\n\t// 1. Register informers\n\tc.podInformer = InitPodInformer(c.kclient, c)\n\tc.nodeInformer = InitNodeInformer(c.kclient, c)\n\tc.rsInformer = InitReplicaSetInformer(c.kclient, c)\n\n\tgo c.podInformer.indexInformer.Run(stopCh)\n\tgo c.nodeInformer.indexInformer.Run(stopCh)\n\tgo c.rsInformer.indexInformer.Run(stopCh)\n\n\t// 2. Initialize clusterState state use KubeAPI get pods, .......\n\n\terr := c.clusterState.PopulateNodeInfo(c.kclient)\n\tif err != nil {\n\t\treturn errors.New(\"Unable to list nodes from kubernetes: \" + err.Error())\n\t}\n\n\terr = c.clusterState.PopulatePods(c.kclient)\n\tif err != nil {\n\t\treturn errors.New(\"Unable to list pods from kubernetes\")\n\t}\n\n\terr = c.clusterState.PopulateReplicaSet(c.kclient)\n\tif err != nil {\n\t\treturn errors.New(\"Unable to list ReplicaSet from kubernetes\")\n\t}\n\n\t// 3. Initialize controllers\n\tc.state = operatorInitializingControllers\n\n\tcontrollerWg := &sync.WaitGroup{}\n\tfor _, controller := range c.controllers {\n\t\tcontrollerWg.Add(1)\n\t\t// pass controller variable to launch() to avoid reference to the same object.\n\t\tgo c.launch(controller, controllerWg, stopCh)\n\t}\n\n\tcontrollerWg.Wait()\n\t// Use wait group to wait for all controller init to finish\n\n\t// 3. Forward events to controllers\n\tc.state = operatorRunning\n\n\tc.podInformer.onOperatorReady()\n\tc.nodeInformer.onOperatorReady()\n\tc.rsInformer.onOperatorReady()\n\n\terr = c.InitApiServer()\n\tif err != nil {\n\t\treturn errors.New(\"Unable to start API server: \" + err.Error())\n\t}\n\n\t// Wait till we receive a stop signal\n\t<-stopCh\n\n\treturn nil\n}", "func TestCheckNonAllowedChangesScaleDown(t *testing.T) {\n\tassert := assert.New(t)\n\n\trcc, cc := HelperInitCluster(t, \"cassandracluster-3DC.yaml\")\n\tstatus := cc.Status.DeepCopy()\n\trcc.updateCassandraStatus(cc, status)\n\n\t//Create the Pods wanted by the statefulset dc2-rack1 (1 node)\n\tpod := &v1.Pod{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"Pod\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"cassandra-demo-dc2-rack1-0\",\n\t\t\tNamespace: \"ns\",\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"app\": \"cassandracluster\",\n\t\t\t\t\"cassandracluster\": \"cassandra-demo\",\n\t\t\t\t\"cassandraclusters.db.orange.com.dc\": \"dc2\",\n\t\t\t\t\"cassandraclusters.db.orange.com.rack\": \"rack1\",\n\t\t\t\t\"cluster\": \"k8s.pic\",\n\t\t\t\t\"dc-rack\": \"dc2-rack1\",\n\t\t\t},\n\t\t},\n\t}\n\tpod.Status.Phase = v1.PodRunning\n\tpod.Spec.Hostname = \"cassandra-demo2-dc2-rack1-0\"\n\tpod.Spec.Subdomain = \"cassandra-demo2-dc2-rack1\"\n\thostName := k8s.PodHostname(*pod)\n\trcc.CreatePod(pod)\n\n\t//Mock Jolokia Call to NonLocalKeyspacesInDC\n\thttpmock.Activate()\n\tdefer httpmock.DeactivateAndReset()\n\tkeyspacesDescribed := []string{}\n\n\thttpmock.RegisterResponder(\"POST\", JolokiaURL(hostName, jolokiaPort),\n\t\tfunc(req *http.Request) (*http.Response, error) {\n\t\t\tvar execrequestdata execRequestData\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&execrequestdata); err != nil {\n\t\t\t\tt.Error(\"Can't decode request received\")\n\t\t\t}\n\t\t\tif execrequestdata.Attribute == \"Keyspaces\" {\n\t\t\t\treturn httpmock.NewStringResponse(200, keyspaceListString()), nil\n\t\t\t}\n\t\t\tkeyspace, ok := execrequestdata.Arguments[0].(string)\n\n\t\t\tif !ok {\n\t\t\t\tt.Error(\"Keyspace can't be nil\")\n\t\t\t}\n\n\t\t\tkeyspacesDescribed = append(keyspacesDescribed, keyspace)\n\n\t\t\tresponse := `{\"request\": {\"mbean\": \"org.apache.cassandra.db:type=StorageService\",\n\t\t\t\t\t\t \"arguments\": [\"%s\"],\n\t\t\t\t\t\t \"type\": \"exec\",\n\t\t\t\t\t\t \"operation\": \"describeRingJMX\"},\n\t\t\t\t \"timestamp\": 1541908753,\n\t\t\t\t \"status\": 200,`\n\n\t\t\t// For keyspace demo1 and demo2 we return token ranges with some of them assigned to nodes on dc2\n\t\t\tif keyspace[:4] == \"demo\" {\n\t\t\t\tresponse += `\"value\":\n\t\t\t\t\t [\"TokenRange(start_token:4572538884437204647, end_token:4764428918503636065, endpoints:[10.244.3.8], rpc_endpoints:[10.244.3.8], endpoint_details:[EndpointDetails(host:10.244.3.8, datacenter:dc1, rack:rack1)])\",\n\t\t\t\t\t\t\"TokenRange(start_token:-8547872176065322335, end_token:-8182289314504856691, endpoints:[10.244.2.5], rpc_endpoints:[10.244.2.5], endpoint_details:[EndpointDetails(host:10.244.2.5, datacenter:dc1, rack:rack1)])\",\n\t\t\t\t\t\t\"TokenRange(start_token:-2246208089217404881, end_token:-2021878843377619999, endpoints:[10.244.2.5], rpc_endpoints:[10.244.2.5], endpoint_details:[EndpointDetails(host:10.244.2.5, datacenter:dc2, rack:rack1)])\",\n\t\t\t\t\t\t\"TokenRange(start_token:-1308323778199165410, end_token:-1269907200339273513, endpoints:[10.244.2.6], rpc_endpoints:[10.244.2.6], endpoint_details:[EndpointDetails(host:10.244.2.6, datacenter:dc1, rack:rack1)])\",\n\t\t\t\t\t\t\"TokenRange(start_token:8544184416734424972, end_token:8568577617447026631, endpoints:[10.244.2.6], rpc_endpoints:[10.244.2.6], endpoint_details:[EndpointDetails(host:10.244.2.6, datacenter:dc2, rack:rack1)])\",\n\t\t\t\t\t\t\"TokenRange(start_token:2799723085723957315, end_token:3289697029162626204, endpoints:[10.244.3.7], rpc_endpoints:[10.244.3.7], endpoint_details:[EndpointDetails(host:10.244.3.7, datacenter:dc1, rack:rack1)])\"]}`\n\t\t\t\treturn httpmock.NewStringResponse(200, fmt.Sprintf(response, keyspace)), nil\n\t\t\t}\n\t\t\treturn httpmock.NewStringResponse(200, fmt.Sprintf(response+`\"value\": []}`, keyspace)), nil\n\t\t},\n\t)\n\n\t// ask scale down to 0\n\tvar nb int32\n\tcc.Spec.Topology.DC[1].NodesPerRacks = &nb\n\n\tres := rcc.CheckNonAllowedChanges(cc, status)\n\trcc.updateCassandraStatus(cc, status)\n\t//Change not allowed because DC still has nodes\n\tassert.Equal(true, res)\n\n\t//We have restore nodesperrack\n\tassert.Equal(int32(1), *cc.Spec.Topology.DC[1].NodesPerRacks)\n\n\t//Changes replicated keyspaces (remove demo1 and demo2 which still have replicated datas\n\t//allKeyspaces is a global test variable\n\tallKeyspaces = []string{\"system\", \"system_auth\", \"system_schema\", \"something\", \"else\"}\n\tcc.Spec.Topology.DC[1].NodesPerRacks = &nb\n\n\tres = rcc.CheckNonAllowedChanges(cc, status)\n\n\t//Change allowed because there is no more keyspace with replicated datas\n\tassert.Equal(false, res)\n\n\t//Nodes Per Rack is still 0\n\tassert.Equal(int32(0), *cc.Spec.Topology.DC[1].NodesPerRacks)\n}", "func RunStatus(cmd *cobra.Command, args []string) {\n\tc := LoadOperatorConf(cmd)\n\tLoadAdmissionConf(c)\n\tutil.KubeCheck(c.NS)\n\tif util.KubeCheck(c.SA) && util.KubeCheck(c.SAEndpoint) {\n\t\t// in OLM deployment the roles and bindings have generated names\n\t\t// so we list and lookup bindings to our service account to discover the actual names\n\t\tDetectRole(c)\n\t\tDetectClusterRole(c)\n\t}\n\tutil.KubeCheck(c.Role)\n\tutil.KubeCheck(c.RoleBinding)\n\tutil.KubeCheck(c.RoleEndpoint)\n\tutil.KubeCheck(c.RoleBindingEndpoint)\n\tutil.KubeCheck(c.ClusterRole)\n\tutil.KubeCheck(c.ClusterRoleBinding)\n\tutil.KubeCheckOptional(c.WebhookConfiguration)\n\tutil.KubeCheckOptional(c.WebhookSecret)\n\tutil.KubeCheckOptional(c.WebhookService)\n\tnoDeploy, _ := cmd.Flags().GetBool(\"no-deploy\")\n\tif !noDeploy {\n\t\tutil.KubeCheck(c.Deployment)\n\t}\n}", "func main() {\n\t// var metricsAddr string\n\t// var enableLeaderElection bool\n\t// var probeAddr string\n\t// flag.StringVar(&metricsAddr, \"metrics-bind-address\", \":8080\", \"The address the metric endpoint binds to.\")\n\t// flag.StringVar(&probeAddr, \"health-probe-bind-address\", \":8081\", \"The address the probe endpoint binds to.\")\n\t// flag.BoolVar(&enableLeaderElection, \"leader-elect\", false,\n\t// \t\"Enable leader election for controller manager. \"+\n\t// \t\t\"Enabling this will ensure there is only one active controller manager.\")\n\n\tctrl.SetLogger(zap.New())\n\n\t// mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{\n\t// \tScheme: scheme,\n\t// \tMetricsBindAddress: metricsAddr,\n\t// \tPort: 9443,\n\t// \tHealthProbeBindAddress: probeAddr,\n\t// \tLeaderElection: enableLeaderElection,\n\t// \tLeaderElectionID: \"e04e27b0.redhat.io\",\n\t// })\n\t// if err != nil {\n\t// \tsetupLog.Error(err, \"unable to start manager\")\n\t// \tos.Exit(1)\n\t// }\n\n\t//+kubebuilder:scaffold:builder\n\n\tbaselog := ctrl.Log.WithName(\"apiserver\")\n\n\tcmd, err := builder.APIServer.\n\t\tWithResourceAndHandler(&redhatcopv1alpha1.SecretEngine{}, vaultstorage.NewVaultMountStorageProvider(baselog)).\n\t\tWithResourceAndHandler(&redhatcopv1alpha1.PolicyBinding{}, vaultstorage.NewVaultRoleResourceProvider(baselog)).\n\t\tWithResourceAndHandler(&redhatcopv1alpha1.Policy{}, vaultstorage.NewVaultPolicyResourceProvider(baselog)).\n\t\tWithLocalDebugExtension().\n\t\tWithoutEtcd().\n\t\t//WithOpenAPIDefinitions(\"vault.redhatcop.redhat.io\", \"v1alpha1\", redhatcopv1alpha1.GetOpenAPIDefinitions).\n\t\tBuild()\n\n\tif err != nil {\n\t\tsetupLog.Error(err, \"unable to set up apiserver\")\n\t\tos.Exit(1)\n\t}\n\n\tcmd.Flags().AddFlag(&pflag.Flag{\n\t\tName: vaultstorage.KubeAuthPathFlagName,\n\t\tUsage: \"this is the path where the kubernetes authentication method was mounted\",\n\t\tDefValue: \"auth/kubernetes\",\n\t})\n\tviper.BindPFlag(vaultstorage.KubeAuthPathFlagName, cmd.PersistentFlags().Lookup(vaultstorage.KubeAuthPathFlagName))\n\terr = cmd.Execute()\n\tif err != nil {\n\t\tsetupLog.Error(err, \"unable to start apiserver\")\n\t\tos.Exit(1)\n\t}\n\t// if err := mgr.AddHealthzCheck(\"healthz\", healthz.Ping); err != nil {\n\t// \tsetupLog.Error(err, \"unable to set up health check\")\n\t// \tos.Exit(1)\n\t// }\n\t// if err := mgr.AddReadyzCheck(\"readyz\", healthz.Ping); err != nil {\n\t// \tsetupLog.Error(err, \"unable to set up ready check\")\n\t// \tos.Exit(1)\n\t// }\n\n\t// setupLog.Info(\"starting manager\")\n\t// if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {\n\t// \tsetupLog.Error(err, \"problem running manager\")\n\t// \tos.Exit(1)\n\t// }\n}", "func TestClusterCreate(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tmachineSets []clustopv1alpha1.ClusterMachineSet\n\t}{\n\t\t{\n\t\t\tname: \"no compute machine sets\",\n\t\t\tmachineSets: []clustopv1alpha1.ClusterMachineSet{\n\t\t\t\t{\n\t\t\t\t\tShortName: \"master\",\n\t\t\t\t\tMachineSetConfig: clustopv1alpha1.MachineSetConfig{\n\t\t\t\t\t\tSize: 3,\n\t\t\t\t\t\tNodeType: clustopv1alpha1.NodeTypeMaster,\n\t\t\t\t\t\tInfra: true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"single compute machine sets\",\n\t\t\tmachineSets: []clustopv1alpha1.ClusterMachineSet{\n\t\t\t\t{\n\t\t\t\t\tShortName: \"master\",\n\t\t\t\t\tMachineSetConfig: clustopv1alpha1.MachineSetConfig{\n\t\t\t\t\t\tSize: 3,\n\t\t\t\t\t\tNodeType: clustopv1alpha1.NodeTypeMaster,\n\t\t\t\t\t\tInfra: true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tShortName: \"first\",\n\t\t\t\t\tMachineSetConfig: clustopv1alpha1.MachineSetConfig{\n\t\t\t\t\t\tSize: 5,\n\t\t\t\t\t\tNodeType: clustopv1alpha1.NodeTypeCompute,\n\t\t\t\t\t\tInfra: false,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"multiple compute machine sets\",\n\t\t\tmachineSets: []clustopv1alpha1.ClusterMachineSet{\n\t\t\t\t{\n\t\t\t\t\tShortName: \"master\",\n\t\t\t\t\tMachineSetConfig: clustopv1alpha1.MachineSetConfig{\n\t\t\t\t\t\tSize: 3,\n\t\t\t\t\t\tNodeType: clustopv1alpha1.NodeTypeMaster,\n\t\t\t\t\t\tInfra: true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tShortName: \"first\",\n\t\t\t\t\tMachineSetConfig: clustopv1alpha1.MachineSetConfig{\n\t\t\t\t\t\tSize: 5,\n\t\t\t\t\t\tNodeType: clustopv1alpha1.NodeTypeCompute,\n\t\t\t\t\t\tInfra: false,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tShortName: \"second\",\n\t\t\t\t\tMachineSetConfig: clustopv1alpha1.MachineSetConfig{\n\t\t\t\t\t\tSize: 6,\n\t\t\t\t\t\tNodeType: clustopv1alpha1.NodeTypeCompute,\n\t\t\t\t\t\tInfra: false,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tShortName: \"3rd\",\n\t\t\t\t\tMachineSetConfig: clustopv1alpha1.MachineSetConfig{\n\t\t\t\t\t\tSize: 3,\n\t\t\t\t\t\tNodeType: clustopv1alpha1.NodeTypeCompute,\n\t\t\t\t\t\tInfra: false,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tkubeClient, _, clustopClient, capiClient, _, tearDown := startServerAndControllers(t)\n\t\t\tdefer tearDown()\n\n\t\t\tclusterVersion := &clustopv1alpha1.ClusterVersion{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tNamespace: testNamespace,\n\t\t\t\t\tName: testClusterVersionName,\n\t\t\t\t},\n\t\t\t\tSpec: clustopv1alpha1.ClusterVersionSpec{\n\t\t\t\t\tImageFormat: \"openshift/origin-${component}:${version}\",\n\t\t\t\t\tVMImages: clustopv1alpha1.VMImages{\n\t\t\t\t\t\tAWSImages: &clustopv1alpha1.AWSVMImages{\n\t\t\t\t\t\t\tRegionAMIs: []clustopv1alpha1.AWSRegionAMIs{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tRegion: \"us-east-1\",\n\t\t\t\t\t\t\t\t\tAMI: \"computeAMI_ID\",\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\tDeploymentType: clustopv1alpha1.ClusterDeploymentTypeOrigin,\n\t\t\t\t\tVersion: \"v3.7.0\",\n\t\t\t\t\tOpenshiftAnsibleImage: func(s string) *string { return &s }(\"test-ansible-image\"),\n\t\t\t\t\tOpenshiftAnsibleImagePullPolicy: func(p kapi.PullPolicy) *kapi.PullPolicy { return &p }(kapi.PullNever),\n\t\t\t\t},\n\t\t\t}\n\t\t\tclustopClient.ClusteroperatorV1alpha1().ClusterVersions(testNamespace).Create(clusterVersion)\n\n\t\t\tclusterDeploymentSpec := &clustopv1alpha1.ClusterDeploymentSpec{\n\t\t\t\tClusterID: testClusterName + \"-abcde\",\n\t\t\t\tClusterVersionRef: clustopv1alpha1.ClusterVersionReference{\n\t\t\t\t\tNamespace: clusterVersion.Namespace,\n\t\t\t\t\tName: clusterVersion.Name,\n\t\t\t\t},\n\t\t\t\tHardware: clustopv1alpha1.ClusterHardwareSpec{\n\t\t\t\t\tAWS: &clustopv1alpha1.AWSClusterSpec{\n\t\t\t\t\t\tRegion: \"us-east-1\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tDefaultHardwareSpec: &clustopv1alpha1.MachineSetHardwareSpec{\n\t\t\t\t\tAWS: &clustopv1alpha1.MachineSetAWSHardwareSpec{\n\t\t\t\t\t\tInstanceType: \"instance-type\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tMachineSets: tc.machineSets,\n\t\t\t}\n\t\t\tcluster := &capiv1alpha1.Cluster{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tNamespace: testNamespace,\n\t\t\t\t\tName: testClusterName,\n\t\t\t\t},\n\t\t\t\tSpec: capiv1alpha1.ClusterSpec{\n\t\t\t\t\tClusterNetwork: capiv1alpha1.ClusterNetworkingConfig{\n\t\t\t\t\t\tServices: capiv1alpha1.NetworkRanges{\n\t\t\t\t\t\t\tCIDRBlocks: []string{\"255.255.255.255\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tPods: capiv1alpha1.NetworkRanges{\n\t\t\t\t\t\t\tCIDRBlocks: []string{\"255.255.255.255\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tServiceDomain: \"service-domain\",\n\t\t\t\t\t},\n\t\t\t\t\tProviderConfig: capiv1alpha1.ProviderConfig{\n\t\t\t\t\t\tValue: clusterAPIProviderConfigFromClusterSpec(clusterDeploymentSpec),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tcluster, err := capiClient.ClusterV1alpha1().Clusters(testNamespace).Create(cluster)\n\t\t\tif !assert.NoError(t, err, \"could not create the cluster\") {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tmachineSets := make([]*capiv1alpha1.MachineSet, len(tc.machineSets))\n\t\t\tvar masterMachineSet *capiv1alpha1.MachineSet\n\n\t\t\tfor i, clustopClusterMS := range tc.machineSets {\n\n\t\t\t\trole := capicommon.NodeRole\n\t\t\t\tif clustopClusterMS.NodeType == clustopv1alpha1.NodeTypeMaster {\n\t\t\t\t\trole = capicommon.MasterRole\n\t\t\t\t}\n\n\t\t\t\tmachineSet := testMachineSet(\n\t\t\t\t\tfmt.Sprintf(\"%s-%s\", cluster.Name, clustopClusterMS.ShortName),\n\t\t\t\t\tint32(clustopClusterMS.Size),\n\t\t\t\t\t[]capicommon.MachineRole{role},\n\t\t\t\t\tclustopClusterMS.Infra)\n\n\t\t\t\tif machineSet.Labels == nil {\n\t\t\t\t\tmachineSet.Labels = map[string]string{}\n\t\t\t\t}\n\t\t\t\tmachineSet.Labels[\"clusteroperator.openshift.io/cluster\"] = cluster.Name\n\t\t\t\tms, err := capiClient.ClusterV1alpha1().MachineSets(testNamespace).Create(machineSet)\n\t\t\t\tif !assert.NoError(t, err, \"could not create machineset %v\", machineSet.Name) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tmachineSets[i] = ms\n\n\t\t\t\tif clustopClusterMS.NodeType == clustopv1alpha1.NodeTypeMaster {\n\t\t\t\t\tif masterMachineSet != nil {\n\t\t\t\t\t\tt.Fatalf(\"multiple master machinesets: %s and %s\", masterMachineSet.Name, ms.Name)\n\t\t\t\t\t}\n\t\t\t\t\tmasterMachineSet = ms\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif masterMachineSet == nil {\n\t\t\t\tt.Fatalf(\"no master machineset\")\n\t\t\t}\n\n\t\t\tif err := waitForClusterToExist(capiClient, testNamespace, testClusterName); err != nil {\n\t\t\t\tt.Fatalf(\"error waiting for Cluster to exist: %v\", err)\n\t\t\t}\n\n\t\t\tfor _, ms := range machineSets {\n\t\t\t\tif err := waitForMachineSetToExist(capiClient, testNamespace, ms.Name); err != nil {\n\t\t\t\t\tt.Fatalf(\"error waiting for MachineSet %v to exist: %v\", ms.Name, err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !completeInfraProvision(t, kubeClient, capiClient, cluster) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif !completeControlPlaneInstall(t, kubeClient, capiClient, cluster) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif !completeComponentsInstall(t, kubeClient, capiClient, cluster) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif !completeNodeConfigInstall(t, kubeClient, capiClient, cluster) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif !completeDeployClusterAPIInstall(t, kubeClient, capiClient, cluster) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif err := capiClient.ClusterV1alpha1().Clusters(cluster.Namespace).Delete(cluster.Name, &metav1.DeleteOptions{}); err != nil {\n\t\t\t\tt.Fatalf(\"could not delete cluster: %v\", err)\n\t\t\t}\n\n\t\t\tif !completeInfraDeprovision(t, kubeClient, capiClient, cluster) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif err := waitForClusterToNotExist(capiClient, cluster.Namespace, cluster.Name); err != nil {\n\t\t\t\tt.Fatalf(\"cluster not removed: %v\", err)\n\t\t\t}\n\t\t})\n\t}\n}", "func main() {\n\n //bring up the services\n\tmasterSrvAddr := master.StartMasterSrv(9090) //9090\n\tworkerSrvAddr1 := worker.StartWorkerSrv(9091); //9091 ,9092, 9093\n\tworkerSrvAddr2 := worker.StartWorkerSrv(9092);\n\tworker.StartWorkerCli(masterSrvAddr, []string{workerSrvAddr1,workerSrvAddr2});\n\tmaster.StartMasterCli();\n\n\t//distributed map-reduce flow\n\tmapOutput,err := master.DoOperation([]string{\"/Users/k0c00nc/go/src/MapReduce/res/input.txt\", \"/Users/k0c00nc/go/src/distributedDb\" +\n\t\t\"/res/input1.txt\"},\"Map\")\n\tif err !=nil{\n\t\tfmt.Printf(\"map phase failed with err %s \", err.Error())\n\t}\n\n\tlocalAggregation,err :=master.DoOperation(mapOutput,\"LocalAggregation\")\n\tif err !=nil{\n\t\tfmt.Printf(\"localAggregation phase failed with err %s \", err.Error())\n\t}\n\n\tshuffing,err :=master.DoOperation(localAggregation,\"Shuffing\")\n\tif err !=nil{\n\t\tfmt.Printf(\"shuffing phase failed with err %s \", err.Error())\n\t}\n\n\treduce,err :=master.DoOperation(shuffing,\"Reduce\")\n\tif err !=nil{\n\t\tfmt.Printf(\"reduce phase failed with err %s \", err.Error())\n\t}\n\n fmt.Println(\"MR output are in file\", reduce[0])\n\n}", "func verifyStsVolumeMetadata(client clientset.Interface, ctx context.Context, namespace string,\n\tstatefulset *appsv1.StatefulSet, replicas int32, allowedTopologyHAMap map[string][]string,\n\tcategories []string, storagePolicyName string, nodeList *v1.NodeList, f *framework.Framework) {\n\t// Waiting for pods status to be Ready\n\tfss.WaitForStatusReadyReplicas(client, statefulset, replicas)\n\tgomega.Expect(fss.CheckMount(client, statefulset, mountPath)).NotTo(gomega.HaveOccurred())\n\tssPodsBeforeScaleDown := fss.GetPodList(client, statefulset)\n\tgomega.Expect(ssPodsBeforeScaleDown.Items).NotTo(gomega.BeEmpty(),\n\t\tfmt.Sprintf(\"Unable to get list of Pods from the Statefulset: %v\", statefulset.Name))\n\tgomega.Expect(len(ssPodsBeforeScaleDown.Items) == int(replicas)).To(gomega.BeTrue(),\n\t\t\"Number of Pods in the statefulset should match with number of replicas\")\n\n\tginkgo.By(\"Verify GV PV and SV PV has has required PV node affinity details\")\n\tginkgo.By(\"Verify SV PVC has TKG HA annotations set\")\n\t// Get the list of Volumes attached to Pods before scale down\n\tfor _, sspod := range ssPodsBeforeScaleDown.Items {\n\t\tpod, err := client.CoreV1().Pods(namespace).Get(ctx, sspod.Name, metav1.GetOptions{})\n\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\tfor _, volumespec := range sspod.Spec.Volumes {\n\t\t\tif volumespec.PersistentVolumeClaim != nil {\n\t\t\t\tpvcName := volumespec.PersistentVolumeClaim.ClaimName\n\t\t\t\tpv := getPvFromClaim(client, statefulset.Namespace, pvcName)\n\t\t\t\tpvclaim, err := client.CoreV1().PersistentVolumeClaims(namespace).Get(ctx,\n\t\t\t\t\tpvcName, metav1.GetOptions{})\n\t\t\t\tgomega.Expect(pvclaim).NotTo(gomega.BeNil())\n\t\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t\t\tvolHandle := getVolumeIDFromSupervisorCluster(pv.Spec.CSI.VolumeHandle)\n\t\t\t\tgomega.Expect(volHandle).NotTo(gomega.BeEmpty())\n\t\t\t\tsvcPVCName := pv.Spec.CSI.VolumeHandle\n\n\t\t\t\tsvcPVC := getPVCFromSupervisorCluster(svcPVCName)\n\t\t\t\tgomega.Expect(*svcPVC.Spec.StorageClassName == storagePolicyName).To(\n\t\t\t\t\tgomega.BeTrue(), \"SV Pvc storageclass does not match with SV storageclass\")\n\t\t\t\tframework.Logf(\"GC PVC's storageclass matches SVC PVC's storageclass\")\n\n\t\t\t\tverifyAnnotationsAndNodeAffinity(allowedTopologyHAMap, categories, pod,\n\t\t\t\t\tnodeList, svcPVC, pv, svcPVCName)\n\n\t\t\t\t// Verify the attached volume match the one in CNS cache\n\t\t\t\terr = waitAndVerifyCnsVolumeMetadata4GCVol(volHandle, svcPVCName, pvclaim,\n\t\t\t\t\tpv, pod)\n\t\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\n\t\t\t\tframework.Logf(fmt.Sprintf(\"Verify volume: %s is attached to the node: %s\",\n\t\t\t\t\tpv.Spec.CSI.VolumeHandle, sspod.Spec.NodeName))\n\t\t\t\tvar vmUUID string\n\t\t\t\tctx, cancel := context.WithCancel(context.Background())\n\t\t\t\tdefer cancel()\n\t\t\t\tvmUUID, err = getVMUUIDFromNodeName(pod.Spec.NodeName)\n\t\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t\t\tverifyCRDInSupervisorWithWait(ctx, f, pod.Spec.NodeName+\"-\"+svcPVCName,\n\t\t\t\t\tcrdCNSNodeVMAttachment, crdVersion, crdGroup, true)\n\n\t\t\t\tisDiskAttached, err := e2eVSphere.isVolumeAttachedToVM(client, volHandle, vmUUID)\n\t\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t\t\tgomega.Expect(isDiskAttached).To(gomega.BeTrue(), \"Disk is not attached to the node\")\n\t\t\t\tframework.Logf(\"verify the attached volumes match those in CNS Cache\")\n\t\t\t\terr = waitAndVerifyCnsVolumeMetadata4GCVol(volHandle, svcPVCName, pvclaim,\n\t\t\t\t\tpv, pod)\n\t\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t\t}\n\t\t}\n\t}\n\n}", "func testDependentServiceChanges(t *testing.T) {\n\ttc, err := NewTestContext()\n\trequire.NoError(t, err)\n\terr = tc.waitForConfiguredWindowsNodes(gc.numberOfMachineNodes, false, false)\n\trequire.NoError(t, err, \"timed out waiting for Windows Machine nodes\")\n\terr = tc.waitForConfiguredWindowsNodes(gc.numberOfBYOHNodes, false, true)\n\trequire.NoError(t, err, \"timed out waiting for BYOH Windows nodes\")\n\tnodes := append(gc.machineNodes, gc.byohNodes...)\n\n\tqueryCommand := \"Get-WmiObject win32_service | Where-Object {$_.Name -eq \\\\\\\"hybrid-overlay-node\\\\\\\"} \" +\n\t\t\"|select -ExpandProperty PathName\"\n\tfor _, node := range nodes {\n\t\tt.Run(node.GetName(), func(t *testing.T) {\n\t\t\t// Get initial configuration of hybrid-overlay-node, this service is used as kube-proxy is dependent on it\n\t\t\taddr, err := controllers.GetAddress(node.Status.Addresses)\n\t\t\trequire.NoError(t, err, \"error getting node address\")\n\t\t\tout, err := tc.runPowerShellSSHJob(\"hybrid-overlay-query\", queryCommand, addr)\n\t\t\trequire.NoError(t, err, \"error querying hybrid-overlay service\")\n\t\t\t// The binPath/pathName will be the final line of the pod logs\n\t\t\toriginalPath := finalLine(out)\n\n\t\t\t// Change hybrid-overlay-node configuration\n\t\t\tnewPath, err := changeHybridOverlayCommandVerbosity(originalPath)\n\t\t\trequire.NoError(t, err, \"error constructing new hybrid-overlay command\")\n\t\t\tchangeCommand := fmt.Sprintf(\"sc.exe config hybrid-overlay-node binPath=\\\\\\\"%s\\\\\\\"\", newPath)\n\t\t\tout, err = tc.runPowerShellSSHJob(\"hybrid-overlay-change\", changeCommand, addr)\n\t\t\trequire.NoError(t, err, \"error changing hybrid-overlay command\")\n\n\t\t\t// Wait until hybrid-overlay-node is returned to correct config\n\t\t\terr = wait.Poll(retry.Interval, retry.Timeout, func() (bool, error) {\n\t\t\t\tout, err = tc.runPowerShellSSHJob(\"hybrid-overlay-query2\", queryCommand, addr)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t\tcurrentPath := finalLine(out)\n\t\t\t\tif currentPath != originalPath {\n\t\t\t\t\tlog.Printf(\"waiting for hybrid-overlay service config to be reconciled, current value: %s\",\n\t\t\t\t\t\tcurrentPath)\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\trequire.NoError(t, err)\n\t\t})\n\t}\n}", "func (c *Cluster) aggregateClusterView() {\n\tfor {\n\t\tselect {\n\t\tcase event := <-c.ingressEvents:\n\t\t\tif event.Created {\n\t\t\t\tc.currentClusterState.Ingresses = append(c.currentClusterState.Ingresses, event.Ingress)\n\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\"cluster\": c.config.Name,\n\t\t\t\t\t\"ingress\": event.Ingress.Name,\n\t\t\t\t}).Info(\"Detected new ingress.\")\n\t\t\t} else {\n\t\t\t\tfor i, ingress := range c.currentClusterState.Ingresses {\n\t\t\t\t\tif ingress.Name == event.Ingress.Name {\n\t\t\t\t\t\tc.currentClusterState.Ingresses[i] = c.currentClusterState.Ingresses[len(c.currentClusterState.Ingresses)-1]\n\t\t\t\t\t\tc.currentClusterState.Ingresses = c.currentClusterState.Ingresses[:len(c.currentClusterState.Ingresses)-1]\n\t\t\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\t\t\"cluster\": c.config.Name,\n\t\t\t\t\t\t\t\"ingress\": event.Ingress.Name,\n\t\t\t\t\t\t}).Info(\"Removed old ingress.\")\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\tc.clusterStateChannel <- c.currentClusterState\n\t\tcase event := <-c.backendEvents:\n\t\t\tif event.Created {\n\t\t\t\tc.currentClusterState.Backends = append(c.currentClusterState.Backends, event.Backend)\n\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\"cluster\": c.config.Name,\n\t\t\t\t\t\"backend\": event.Backend.Name,\n\t\t\t\t\t\"ip\": event.Backend.IP,\n\t\t\t\t}).Info(\"Detected new backend pod.\")\n\t\t\t} else {\n\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\"cluster\": c.config.Name,\n\t\t\t\t\t\"backend\": event.Backend.Name,\n\t\t\t\t\t\"ip\": event.Backend.IP,\n\t\t\t\t}).Debug(\"Detected backend pod removal, searching...\")\n\t\t\t\tfor i, backend := range c.currentClusterState.Backends {\n\t\t\t\t\tif backend.Name == event.Backend.Name {\n\t\t\t\t\t\tc.currentClusterState.Backends[i] = c.currentClusterState.Backends[len(c.currentClusterState.Backends)-1]\n\t\t\t\t\t\tc.currentClusterState.Backends = c.currentClusterState.Backends[:len(c.currentClusterState.Backends)-1]\n\t\t\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\t\t\"cluster\": c.config.Name,\n\t\t\t\t\t\t\t\"backend\": event.Backend.Name,\n\t\t\t\t\t\t\t\"ip\": event.Backend.IP,\n\t\t\t\t\t\t}).Info(\"Removed old backend pod.\")\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\tc.clusterStateChannel <- c.currentClusterState\n\t\tcase _ = <-c.aggregatorStopChannel:\n\t\t\treturn\n\t\tcase _ = <-c.clearChannel:\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"cluster\": c.config.Name,\n\t\t\t}).Debug(\"Clearing full cluster state...\")\n\t\t\tc.currentClusterState.Backends = nil\n\t\t\tc.currentClusterState.Ingresses = nil\n\t\t\tc.clusterStateChannel <- c.currentClusterState\n\t\t}\n\t}\n}", "func (c *Controller) onUpdate(oldObj, newObj interface{}) {\n\toldcluster := oldObj.(*crv1.Pgcluster)\n\tnewcluster := newObj.(*crv1.Pgcluster)\n\n\tlog.Debugf(\"pgcluster onUpdate for cluster %s (namespace %s)\", newcluster.ObjectMeta.Namespace,\n\t\tnewcluster.ObjectMeta.Name)\n\n\t// if the status of the pgcluster shows that it has been bootstrapped, then proceed with\n\t// creating the cluster (i.e. the cluster deployment, services, etc.)\n\tif newcluster.Status.State == crv1.PgclusterStateBootstrapped {\n\t\tclusteroperator.AddClusterBase(c.Client, newcluster, newcluster.GetNamespace())\n\t\treturn\n\t}\n\n\t// if the 'shutdown' parameter in the pgcluster update shows that the cluster should be either\n\t// shutdown or started but its current status does not properly reflect that it is, then\n\t// proceed with the logic needed to either shutdown or start the cluster\n\tif newcluster.Spec.Shutdown && newcluster.Status.State != crv1.PgclusterStateShutdown {\n\t\tclusteroperator.ShutdownCluster(c.Client, *newcluster)\n\t} else if !newcluster.Spec.Shutdown &&\n\t\tnewcluster.Status.State == crv1.PgclusterStateShutdown {\n\t\tclusteroperator.StartupCluster(c.Client, *newcluster)\n\t}\n\n\t// check to see if the \"autofail\" label on the pgcluster CR has been changed from either true to false, or from\n\t// false to true. If it has been changed to false, autofail will then be disabled in the pg cluster. If has\n\t// been changed to true, autofail will then be enabled in the pg cluster\n\tif newcluster.ObjectMeta.Labels[config.LABEL_AUTOFAIL] != \"\" {\n\t\tautofailEnabledOld, err := strconv.ParseBool(oldcluster.ObjectMeta.Labels[config.LABEL_AUTOFAIL])\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t\tautofailEnabledNew, err := strconv.ParseBool(newcluster.ObjectMeta.Labels[config.LABEL_AUTOFAIL])\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t\tif autofailEnabledNew != autofailEnabledOld {\n\t\t\tutil.ToggleAutoFailover(c.Client, autofailEnabledNew,\n\t\t\t\tnewcluster.ObjectMeta.Labels[config.LABEL_PGHA_SCOPE],\n\t\t\t\tnewcluster.ObjectMeta.Namespace)\n\t\t}\n\n\t}\n\n\t// handle standby being enabled and disabled for the cluster\n\tif oldcluster.Spec.Standby && !newcluster.Spec.Standby {\n\t\tif err := clusteroperator.DisableStandby(c.Client, *newcluster); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t} else if !oldcluster.Spec.Standby && newcluster.Spec.Standby {\n\t\tif err := clusteroperator.EnableStandby(c.Client, *newcluster); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// see if any of the resource values have changed, and if so, update them\n\tif !reflect.DeepEqual(oldcluster.Spec.Resources, newcluster.Spec.Resources) ||\n\t\t!reflect.DeepEqual(oldcluster.Spec.Limits, newcluster.Spec.Limits) {\n\t\tif err := clusteroperator.UpdateResources(c.Client, c.Client.Config, newcluster); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// see if any of the pgBackRest repository resource values have changed, and\n\t// if so, update them\n\tif !reflect.DeepEqual(oldcluster.Spec.BackrestResources, newcluster.Spec.BackrestResources) ||\n\t\t!reflect.DeepEqual(oldcluster.Spec.BackrestLimits, newcluster.Spec.BackrestLimits) {\n\t\tif err := backrestoperator.UpdateResources(c.Client, newcluster); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// see if any of the pgBouncer values have changed, and if so, update the\n\t// pgBouncer deployment\n\tif !reflect.DeepEqual(oldcluster.Spec.PgBouncer, newcluster.Spec.PgBouncer) {\n\t\tif err := updatePgBouncer(c, oldcluster, newcluster); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// if we are not in a standby state, check to see if the tablespaces have\n\t// differed, and if so, add the additional volumes to the primary and replicas\n\tif !reflect.DeepEqual(oldcluster.Spec.TablespaceMounts, newcluster.Spec.TablespaceMounts) {\n\t\tif err := updateTablespaces(c, oldcluster, newcluster); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (r *MultiClusterObservabilityReconciler) SetupWithManager(mgr ctrl.Manager) error {\n\t// Create a new controller\n\tc, err := controller.New(\"multiclustermonitoring-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpred := predicate.Funcs{\n\t\tCreateFunc: func(e event.CreateEvent) bool {\n\t\t\t//set request name to be used in placementrule controller\n\t\t\tconfig.SetMonitoringCRName(e.Object.GetName())\n\t\t\treturn true\n\t\t},\n\t\tUpdateFunc: func(e event.UpdateEvent) bool {\n\t\t\treturn e.ObjectOld.GetGeneration() != e.ObjectNew.GetGeneration()\n\t\t},\n\t\tDeleteFunc: func(e event.DeleteEvent) bool {\n\t\t\treturn !e.DeleteStateUnknown\n\t\t},\n\t}\n\t// Watch for changes to primary resource MultiClusterObservability\n\terr = c.Watch(&source.Kind{Type: &mcov1beta1.MultiClusterObservability{}}, &handler.EnqueueRequestForObject{}, pred)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to secondary resource Deployment and requeue the owner MultiClusterObservability\n\terr = c.Watch(&source.Kind{Type: &appsv1.Deployment{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &mcov1beta1.MultiClusterObservability{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to secondary resource statefulSet and requeue the owner MultiClusterObservability\n\terr = c.Watch(&source.Kind{Type: &appsv1.StatefulSet{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &mcov1beta1.MultiClusterObservability{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to secondary resource ConfigMap and requeue the owner MultiClusterObservability\n\terr = c.Watch(&source.Kind{Type: &corev1.ConfigMap{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &mcov1beta1.MultiClusterObservability{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to secondary resource Secret and requeue the owner MultiClusterObservability\n\terr = c.Watch(&source.Kind{Type: &corev1.Secret{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &mcov1beta1.MultiClusterObservability{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to secondary resource Service and requeue the owner MultiClusterObservability\n\terr = c.Watch(&source.Kind{Type: &corev1.Service{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &mcov1beta1.MultiClusterObservability{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to secondary Observatorium CR and requeue the owner MultiClusterObservability\n\terr = c.Watch(&source.Kind{Type: &observatoriumv1alpha1.Observatorium{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &mcov1beta1.MultiClusterObservability{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpred = predicate.Funcs{\n\t\tCreateFunc: func(e event.CreateEvent) bool {\n\t\t\tif e.Object.GetName() == config.AlertRuleCustomConfigMapName &&\n\t\t\t\te.Object.GetNamespace() == config.GetDefaultNamespace() {\n\t\t\t\tconfig.SetCustomRuleConfigMap(true)\n\t\t\t\treturn true\n\t\t\t}\n\t\t\treturn false\n\t\t},\n\t\tUpdateFunc: func(e event.UpdateEvent) bool {\n\t\t\t// Find a way to restart the alertmanager to take the update\n\t\t\t// if e.ObjectNew.GetName() == config.AlertRuleCustomConfigMapName &&\n\t\t\t// \te.ObjectNew.GetNamespace() == config.GetDefaultNamespace() {\n\t\t\t// \tconfig.SetCustomRuleConfigMap(true)\n\t\t\t// \treturn e.ObjectOld.GetResourceVersion() != e.ObjectNew.GetResourceVersion()\n\t\t\t// }\n\t\t\treturn false\n\t\t},\n\t\tDeleteFunc: func(e event.DeleteEvent) bool {\n\t\t\tif e.Object.GetName() == config.AlertRuleCustomConfigMapName &&\n\t\t\t\te.Object.GetNamespace() == config.GetDefaultNamespace() {\n\t\t\t\tconfig.SetCustomRuleConfigMap(false)\n\t\t\t\treturn true\n\t\t\t}\n\t\t\treturn false\n\t\t},\n\t}\n\t// Watch the configmap\n\terr = c.Watch(&source.Kind{Type: &corev1.ConfigMap{}}, &handler.EnqueueRequestForObject{}, pred)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpred = predicate.Funcs{\n\t\tCreateFunc: func(e event.CreateEvent) bool {\n\t\t\treturn false\n\t\t},\n\t\tUpdateFunc: func(e event.UpdateEvent) bool {\n\t\t\treturn false\n\t\t},\n\t\tDeleteFunc: func(e event.DeleteEvent) bool {\n\t\t\tif e.Object.GetName() == config.AlertmanagerConfigName &&\n\t\t\t\te.Object.GetNamespace() == config.GetDefaultNamespace() {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\treturn false\n\t\t},\n\t}\n\t// Watch the Secret\n\terr = c.Watch(&source.Kind{Type: &corev1.Secret{}}, &handler.EnqueueRequestForObject{}, pred)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\tFor(&mcov1beta1.MultiClusterObservability{}).\n\t\tComplete(r)\n}", "func cmdAdd(args *skel.CmdArgs) error {\n\tipamConf, confVersion, err := allocator.LoadIPAMConfig(args.StdinData, args.Args)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresult := &current.Result{}\n\n\ttlsInfo := &transport.TLSInfo{\n\t\tCertFile: ipamConf.CertFile,\n\t\tKeyFile: ipamConf.KeyFile,\n\t\tTrustedCAFile: ipamConf.TrustedCAFile,\n\t}\n\ttlsConfig, _ := tlsInfo.ClientConfig()\n\n\tstore, err := etcd.New(ipamConf.Name, strings.Split(ipamConf.Endpoints, \",\"), tlsConfig)\n\tdefer store.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Get annotations of the pod, such as ipAddrs and current user.\n\n\t// 1. Get conf for k8s client and create a k8s_client\n\tk8sClient, err := k8s.NewK8sClient(ipamConf.Kubernetes, ipamConf.Policy)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// 2. Get K8S_POD_NAME and K8S_POD_NAMESPACE.\n\tk8sArgs := k8s.K8sArgs{}\n\tif err := types.LoadArgs(args.Args, &k8sArgs); err != nil {\n\t\treturn err\n\t}\n\n\t// 3. Get annotations from k8s_client via K8S_POD_NAME and K8S_POD_NAMESPACE.\n\tlabel, annot, err := k8s.GetK8sPodInfo(k8sClient, string(k8sArgs.K8S_POD_NAME), string(k8sArgs.K8S_POD_NAMESPACE))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error while read annotaions for pod\" + err.Error())\n\t}\n\n\tuserDefinedSubnet := annot[\"cni.daocloud.io/subnet\"]\n\tuserDefinedRoutes := annot[\"cni.daocloud.io/routes\"]\n\tuserDefinedGateway := annot[\"cni.daocloud.io/gateway\"]\n\n\t// app := label[\"io.daocloud.dce.app\"]\n\tapp := label[\"dce.daocloud.io/app\"]\n\tif app == \"\" {\n\t\tapp = \"unknown\"\n\t}\n\tservice, err := k8s.ResourceControllerName(k8sClient, string(k8sArgs.K8S_POD_NAME), string(k8sArgs.K8S_POD_NAMESPACE))\n\n\tif service == \"\" {\n\t\tservice = \"unknown\"\n\t}\n\n\tif userDefinedSubnet == \"\" {\n\t\treturn fmt.Errorf(\"No ip found for pod \" + string(k8sArgs.K8S_POD_NAME))\n\t}\n\n\t_, subnet, err := net.ParseCIDR(userDefinedSubnet)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif userDefinedGateway != \"\" {\n\t\tgw := types.Route{\n\t\t\tDst: net.IPNet{\n\t\t\t\tIP: net.IPv4zero,\n\t\t\t\tMask: net.IPv4Mask(0, 0, 0, 0),\n\t\t\t},\n\t\t\tGW: net.ParseIP(userDefinedGateway),\n\t\t}\n\t\tresult.Routes = append(result.Routes, &gw)\n\t}\n\n\tif userDefinedRoutes != \"\" {\n\t\troutes := strings.Split(userDefinedRoutes, \";\")\n\t\tfor _, r := range routes {\n\t\t\t_, dst, _ := net.ParseCIDR(strings.Split(r, \",\")[0])\n\t\t\tgateway := strings.Split(r, \",\")[1]\n\n\t\t\tgw := types.Route{\n\t\t\t\tDst: *dst,\n\t\t\t\tGW: net.ParseIP(gateway),\n\t\t\t}\n\t\t\tresult.Routes = append(result.Routes, &gw)\n\t\t}\n\t}\n\t// result.Routes = append(result.Routes, ipamConf.Routes...)\n\n\tif ipamConf.Service_IPNet != \"\" {\n\t\t_, service_net, err := net.ParseCIDR(ipamConf.Service_IPNet)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Invalid service cluster ip range: \" + ipamConf.Service_IPNet)\n\t\t}\n\t\tfor _, node_ip := range ipamConf.Node_IPs {\n\t\t\tif subnet.Contains(net.ParseIP(node_ip)) {\n\t\t\t\tsn := types.Route{\n\t\t\t\t\tDst: *service_net,\n\t\t\t\t\tGW: net.ParseIP(node_ip),\n\t\t\t\t}\n\t\t\t\tresult.Routes = append(result.Routes, &sn)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// If none of node_ip in subnet, nothing to do.\n\t\t}\n\t}\n\n\tuserDefinedNameserver := annot[\"cni.daocloud.io/nameserver\"]\n\tuserDefinedDomain := annot[\"cni.daocloud.io/domain\"]\n\tuserDefinedSearch := annot[\"cni.daocloud.io/search\"]\n\tuserDefinedOptions := annot[\"cni.daocloud.io/options\"]\n\tdns, err := generateDNS(userDefinedNameserver, userDefinedDomain, userDefinedSearch, userDefinedOptions)\n\tresult.DNS = *dns\n\n\talloc := allocator.NewAnchorAllocator(subnet, store, string(k8sArgs.K8S_POD_NAME), string(k8sArgs.K8S_POD_NAMESPACE), app, service)\n\n\tipConf, err := alloc.Get(args.ContainerID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Below here, if error, we should call store.Release(args.ContainerID) to release the IP written to database.\n\tif userDefinedGateway == \"\" {\n\t\tgw := types.Route{\n\t\t\tDst: net.IPNet{\n\t\t\t\tIP: net.IPv4zero,\n\t\t\t\tMask: net.IPv4Mask(0, 0, 0, 0),\n\t\t\t},\n\t\t\tGW: ipConf.Gateway,\n\t\t}\n\t\tresult.Routes = append(result.Routes, &gw)\n\t}\n\tresult.IPs = append(result.IPs, ipConf)\n\n\treturn types.PrintResult(result, confVersion)\n}", "func (s) TestSwitchClusterNodeBetweenLeafAndAggregated(t *testing.T) {\n\t// Getting the test to the point where there's a root cluster which is a eds\n\t// leaf.\n\tch, fakeClient := setupTests()\n\tch.updateRootCluster(edsService2)\n\tctx, ctxCancel := context.WithTimeout(context.Background(), defaultTestTimeout)\n\tdefer ctxCancel()\n\t_, err := fakeClient.WaitForWatchCluster(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"xdsClient.WatchCDS failed with error: %v\", err)\n\t}\n\tfakeClient.InvokeWatchClusterCallback(xdsresource.ClusterUpdate{\n\t\tClusterType: xdsresource.ClusterTypeEDS,\n\t\tClusterName: edsService2,\n\t}, nil)\n\tselect {\n\tcase <-ch.updateChannel:\n\tcase <-ctx.Done():\n\t\tt.Fatal(\"Timed out waiting for update from update channel.\")\n\t}\n\t// Switch the cluster to an aggregate cluster, this should cause two new\n\t// child watches to be created.\n\tfakeClient.InvokeWatchClusterCallback(xdsresource.ClusterUpdate{\n\t\tClusterType: xdsresource.ClusterTypeAggregate,\n\t\tClusterName: edsService2,\n\t\tPrioritizedClusterNames: []string{edsService, logicalDNSService},\n\t}, nil)\n\n\t// xds client should be called to start a watch for one of the child\n\t// clusters of the aggregate. The order of the children in the update\n\t// written to the buffer to send to CDS matters, however there is no\n\t// guarantee on the order it will start the watches of the children.\n\tgotCluster, err := fakeClient.WaitForWatchCluster(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"xdsClient.WatchCDS failed with error: %v\", err)\n\t}\n\tif gotCluster != edsService {\n\t\tif gotCluster != logicalDNSService {\n\t\t\tt.Fatalf(\"xdsClient.WatchCDS called for cluster: %v, want: %v\", gotCluster, edsService)\n\t\t}\n\t}\n\n\t// xds client should then be called to start a watch for the second child\n\t// cluster.\n\tgotCluster, err = fakeClient.WaitForWatchCluster(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"xdsClient.WatchCDS failed with error: %v\", err)\n\t}\n\tif gotCluster != edsService {\n\t\tif gotCluster != logicalDNSService {\n\t\t\tt.Fatalf(\"xdsClient.WatchCDS called for cluster: %v, want: %v\", gotCluster, logicalDNSService)\n\t\t}\n\t}\n\n\t// After starting a watch for the second child cluster, there should be no\n\t// more watches started on the xds client.\n\tshouldNotHappenCtx, shouldNotHappenCtxCancel := context.WithTimeout(context.Background(), defaultTestShortTimeout)\n\tdefer shouldNotHappenCtxCancel()\n\tgotCluster, err = fakeClient.WaitForWatchCluster(shouldNotHappenCtx)\n\tif err == nil {\n\t\tt.Fatalf(\"xdsClient.WatchCDS called for cluster: %v, no more watches should be started.\", gotCluster)\n\t}\n\n\t// The handleResp() call on the root aggregate cluster should not ping the\n\t// cluster handler to try and construct an update, as the handleResp()\n\t// callback knows that when a child is created, it cannot possibly build a\n\t// successful update yet. Thus, there should be nothing in the update\n\t// channel.\n\n\tshouldNotHappenCtx, shouldNotHappenCtxCancel = context.WithTimeout(context.Background(), defaultTestShortTimeout)\n\tdefer shouldNotHappenCtxCancel()\n\n\tselect {\n\tcase <-ch.updateChannel:\n\t\tt.Fatal(\"Cluster Handler wrote an update to updateChannel when it shouldn't have, as each node in the full cluster tree has not yet received an update\")\n\tcase <-shouldNotHappenCtx.Done():\n\t}\n\n\t// Switch the cluster back to an EDS Cluster. This should cause the two\n\t// children to be deleted.\n\tfakeClient.InvokeWatchClusterCallback(xdsresource.ClusterUpdate{\n\t\tClusterType: xdsresource.ClusterTypeEDS,\n\t\tClusterName: edsService2,\n\t}, nil)\n\n\t// Should delete the two children (no guarantee of ordering deleted, which\n\t// is ok), then successfully write an update to the update buffer as the\n\t// full cluster tree has received updates.\n\tclusterNameDeleted, err := fakeClient.WaitForCancelClusterWatch(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"xdsClient.CancelCDS failed with error: %v\", err)\n\t}\n\t// No guarantee of ordering, so one of the children should be deleted first.\n\tif clusterNameDeleted != edsService {\n\t\tif clusterNameDeleted != logicalDNSService {\n\t\t\tt.Fatalf(\"xdsClient.CancelCDS called for cluster %v, want either: %v or: %v\", clusterNameDeleted, edsService, logicalDNSService)\n\t\t}\n\t}\n\t// Then the other child should be deleted.\n\tclusterNameDeleted, err = fakeClient.WaitForCancelClusterWatch(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"xdsClient.CancelCDS failed with error: %v\", err)\n\t}\n\tif clusterNameDeleted != edsService {\n\t\tif clusterNameDeleted != logicalDNSService {\n\t\t\tt.Fatalf(\"xdsClient.CancelCDS called for cluster %v, want either: %v or: %v\", clusterNameDeleted, edsService, logicalDNSService)\n\t\t}\n\t}\n\n\t// After cancelling a watch for the second child cluster, there should be no\n\t// more watches cancelled on the xds client.\n\tshouldNotHappenCtx, shouldNotHappenCtxCancel = context.WithTimeout(context.Background(), defaultTestShortTimeout)\n\tdefer shouldNotHappenCtxCancel()\n\tgotCluster, err = fakeClient.WaitForCancelClusterWatch(shouldNotHappenCtx)\n\tif err == nil {\n\t\tt.Fatalf(\"xdsClient.WatchCDS called for cluster: %v, no more watches should be cancelled.\", gotCluster)\n\t}\n\n\t// Then an update should successfully be written to the update buffer.\n\tselect {\n\tcase chu := <-ch.updateChannel:\n\t\tif diff := cmp.Diff(chu.updates, []xdsresource.ClusterUpdate{{\n\t\t\tClusterType: xdsresource.ClusterTypeEDS,\n\t\t\tClusterName: edsService2,\n\t\t}}); diff != \"\" {\n\t\t\tt.Fatalf(\"got unexpected cluster update, diff (-got, +want): %v\", diff)\n\t\t}\n\tcase <-ctx.Done():\n\t\tt.Fatal(\"Timed out waiting for update from update channel.\")\n\t}\n}", "func (c *Controller) processClusterScaleUp(ecs *ecsv1.KubernetesCluster) error {\n\t// diff work nodes\n\tvar oldSpec ecsv1.KubernetesClusterSpec\n\toldSpecStr := ecs.Annotations[enum.Spec]\n\terr := json.Unmarshal([]byte(oldSpecStr), &oldSpec)\n\tif err != nil {\n\t\tglog.Errorf(\"get old spec failed with:%v\", err)\n\t\treturn err\n\t}\n\tnodeList := diffNodeList(oldSpec.Cluster.NodeList, ecs.Spec.Cluster.NodeList, ecs.Annotations[enum.Operation])\n\n\tdeployMode := ecs.Spec.Cluster.DeployMode\n\tswitch deployMode {\n\tcase ecsv1.BinaryDeployMode:\n\t\terr = c.sshInstaller.ClusterScaleUp(ecs, nodeList)\n\tcase ecsv1.ContainerDeployMode:\n\t\terr = c.grpcInstaller.ClusterScaleUp(ecs, nodeList)\n\t}\n\n\tif err != nil {\n\t\tglog.Errorf(\"scaleup cluster %s failed with %v\", ecs.Name, err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (o *ClusterUninstaller) Run() (*types.ClusterQuota, error) {\n\tctx := context.Background()\n\tssn, err := gcpconfig.GetSession(ctx)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get session\")\n\t}\n\n\toptions := []option.ClientOption{\n\t\toption.WithCredentials(ssn.Credentials),\n\t\toption.WithUserAgent(fmt.Sprintf(\"OpenShift/4.x Destroyer/%s\", version.Raw)),\n\t}\n\n\to.computeSvc, err = compute.NewService(ctx, options...)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create compute service\")\n\t}\n\n\tcctx, cancel := context.WithTimeout(ctx, longTimeout)\n\tdefer cancel()\n\n\to.cpusByMachineType = map[string]int64{}\n\treq := o.computeSvc.MachineTypes.AggregatedList(o.ProjectID).Fields(\"items/*/machineTypes(name,guestCpus),nextPageToken\")\n\tif err := req.Pages(cctx, func(list *compute.MachineTypeAggregatedList) error {\n\t\tfor _, scopedList := range list.Items {\n\t\t\tfor _, item := range scopedList.MachineTypes {\n\t\t\t\to.cpusByMachineType[item.Name] = item.GuestCpus\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to cache machine types\")\n\t}\n\n\to.iamSvc, err = iam.NewService(ctx, options...)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create iam service\")\n\t}\n\n\to.dnsSvc, err = dns.NewService(ctx, options...)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create dns service\")\n\t}\n\n\to.storageSvc, err = storage.NewService(ctx, options...)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create storage service\")\n\t}\n\n\to.rmSvc, err = resourcemanager.NewService(ctx, options...)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create resourcemanager service\")\n\t}\n\n\terr = wait.PollImmediateInfinite(\n\t\ttime.Second*10,\n\t\to.destroyCluster,\n\t)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to destroy cluster\")\n\t}\n\n\tquota := gcptypes.Quota(o.pendingItemTracker.removedQuota)\n\treturn &types.ClusterQuota{GCP: &quota}, nil\n}", "func manageVolumes(glusterClusterAddr string) error {\n\n\trwolog.Debug(\"Performing peer probe with serf query to the leader \", glusterClusterAddr)\n\n\tglusterConnectedToPeerVal, err := helpers.SerfQuery(\"gluster\", \"peer probe \"+glusterClusterAddr)\n\tif strings.Contains(string(glusterConnectedToPeerVal), \"having volumes\") {\n\t\trwolog.Debug(\"Already part of some other gluster, peer probe failed. need to purge old state\")\n\t\t// For extra clean up, so not checking error\n\t\tpurgeOldStateOfGluster()\n\t\t// Lets wait\n\t\ttime.Sleep(2 * time.Second)\n\n\t}\n\n\tif err != nil {\n\t\trwolog.Error(\"Error while doing peer probe with serf query \", err.Error())\n\t\treturn err\n\t}\n\n\t// For slow machines: Gluster will take some time to update peer list. sleep for 15 seconds to give gluster to update its information.\n\ttime.Sleep(15 * time.Second)\n\tif strings.Contains(string(glusterConnectedToPeerVal), \"success\") {\n\t\terr = addBricks(glusterVolumeName, glusterClusterAddr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\n\t\trwolog.Debug(\"Unable to probe peer from the leader. Will set up serf tags to retry.\", glusterClusterAddr)\n\t\tserfTagGlusterRetry = serfTagGlusterRetry + 1\n\n\t\terr = helpers.SetGlusterRetryTag(strconv.Itoa(serfTagGlusterRetry))\n\t\tif err != nil {\n\t\t\trwolog.Error(\"Error while setting up serf tags for retry\")\n\t\t\treturn err\n\t\t}\n\t\ttime.Sleep(2 * time.Second)\n\t\treturn fmt.Errorf(\"unable to probe peer from the leader, will set up serf tags to retry\", glusterClusterAddr)\n\t}\n\treturn nil\n}", "func (cli *CLI) SystemStatus() {\n\ts := system.New(types.NamespacedName{Namespace: cli.Namespace, Name: cli.SystemName}, cli.Client, scheme.Scheme, nil)\n\ts.Load()\n\n\t// TEMPORARY ? check PVCs here because we couldn't own them in openshift\n\t// See https://github.com/noobaa/noobaa-operator/issues/12\n\tfor i := range s.CoreApp.Spec.VolumeClaimTemplates {\n\t\tt := &s.CoreApp.Spec.VolumeClaimTemplates[i]\n\t\tpvc := &corev1.PersistentVolumeClaim{\n\t\t\tTypeMeta: metav1.TypeMeta{Kind: \"PersistentVolumeClaim\"},\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: t.Name + \"-\" + cli.SystemName + \"-core-0\",\n\t\t\t\tNamespace: cli.Namespace,\n\t\t\t},\n\t\t}\n\t\tutil.KubeCheck(cli.Client, pvc)\n\t}\n\n\t// sys := cli.LoadSystemDefaults()\n\t// util.KubeCheck(cli.Client, sys)\n\tif s.NooBaa.Status.Phase == nbv1.SystemPhaseReady {\n\t\tcli.Log.Printf(\"✅ System Phase is \\\"%s\\\"\\n\", s.NooBaa.Status.Phase)\n\t\tsecretRef := s.NooBaa.Status.Accounts.Admin.SecretRef\n\t\tsecret := &corev1.Secret{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: secretRef.Name,\n\t\t\t\tNamespace: secretRef.Namespace,\n\t\t\t},\n\t\t}\n\t\tutil.KubeCheck(cli.Client, secret)\n\n\t\tcli.Log.Println(\"\")\n\t\tcli.Log.Println(\"#------------------#\")\n\t\tcli.Log.Println(\"#- Mgmt Addresses -#\")\n\t\tcli.Log.Println(\"#------------------#\")\n\t\tcli.Log.Println(\"\")\n\n\t\tcli.Log.Println(\"ExternalDNS :\", s.NooBaa.Status.Services.ServiceMgmt.ExternalDNS)\n\t\tcli.Log.Println(\"ExternalIP :\", s.NooBaa.Status.Services.ServiceMgmt.ExternalIP)\n\t\tcli.Log.Println(\"NodePorts :\", s.NooBaa.Status.Services.ServiceMgmt.NodePorts)\n\t\tcli.Log.Println(\"InternalDNS :\", s.NooBaa.Status.Services.ServiceMgmt.InternalDNS)\n\t\tcli.Log.Println(\"InternalIP :\", s.NooBaa.Status.Services.ServiceMgmt.InternalIP)\n\t\tcli.Log.Println(\"PodPorts :\", s.NooBaa.Status.Services.ServiceMgmt.PodPorts)\n\n\t\tcli.Log.Println(\"\")\n\t\tcli.Log.Println(\"#----------------#\")\n\t\tcli.Log.Println(\"#- S3 Addresses -#\")\n\t\tcli.Log.Println(\"#----------------#\")\n\t\tcli.Log.Println(\"\")\n\n\t\tcli.Log.Println(\"ExternalDNS :\", s.NooBaa.Status.Services.ServiceS3.ExternalDNS)\n\t\tcli.Log.Println(\"ExternalIP :\", s.NooBaa.Status.Services.ServiceS3.ExternalIP)\n\t\tcli.Log.Println(\"NodePorts :\", s.NooBaa.Status.Services.ServiceS3.NodePorts)\n\t\tcli.Log.Println(\"InternalDNS :\", s.NooBaa.Status.Services.ServiceS3.InternalDNS)\n\t\tcli.Log.Println(\"InternalIP :\", s.NooBaa.Status.Services.ServiceS3.InternalIP)\n\t\tcli.Log.Println(\"PodPorts :\", s.NooBaa.Status.Services.ServiceS3.PodPorts)\n\n\t\tcli.Log.Println(\"\")\n\t\tcli.Log.Println(\"#---------------#\")\n\t\tcli.Log.Println(\"#- Credentials -#\")\n\t\tcli.Log.Println(\"#---------------#\")\n\t\tcli.Log.Println(\"\")\n\t\tfor key, value := range secret.Data {\n\t\t\tcli.Log.Printf(\"%s: %s\\n\", key, string(value))\n\t\t}\n\t\tcli.Log.Println(\"\")\n\t} else {\n\t\tcli.Log.Printf(\"❌ System Phase is \\\"%s\\\"\\n\", s.NooBaa.Status.Phase)\n\n\t}\n}", "func cassandraClusterScaleDownDC2Test(t *testing.T, f *framework.Framework, ctx *framework.TestCtx) {\n\tt.Logf(\"0. Init Operator\")\n\n\tnamespace, err := ctx.GetNamespace()\n\tif err != nil {\n\t\tt.Fatalf(\"could not get namespace: %v\", err)\n\t}\n\n\t/*----\n\t */\n\tt.Logf(\"1. We Create the Cluster (2dc/1rack/1node\")\n\n\tcc := mye2eutil.HelperInitCluster(t, f, ctx, \"cassandracluster-2DC.yaml\", namespace)\n\tcc.Namespace = namespace\n\tt.Logf(\"Create CassandraCluster cassandracluster-2DC.yaml in namespace %s\", namespace)\n\t// use TestCtx's create helper to create the object and add a cleanup function for the new object\n\terr = f.Client.Create(goctx.TODO(), cc, &framework.CleanupOptions{TestContext: ctx,\n\t\tTimeout: mye2eutil.CleanupTimeout,\n\t\tRetryInterval: mye2eutil.CleanupRetryInterval})\n\tif err != nil && !apierrors.IsAlreadyExists(err) {\n\t\tt.Logf(\"Error Creating cassandracluster: %v\", err)\n\t\tt.Fatal(err)\n\t}\n\t// wait for statefulset dc1-rack1\n\terr = mye2eutil.WaitForStatefulset(t, f.KubeClient, namespace, \"cassandra-e2e-dc1-rack1\", 1,\n\t\tmye2eutil.RetryInterval,\n\t\tmye2eutil.Timeout)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// wait for statefulset dc1-rack1\n\terr = mye2eutil.WaitForStatefulset(t, f.KubeClient, namespace, \"cassandra-e2e-dc2-rack1\", 1,\n\t\tmye2eutil.RetryInterval,\n\t\tmye2eutil.Timeout)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = mye2eutil.WaitForStatusDone(t, f, namespace, \"cassandra-e2e\", mye2eutil.RetryInterval, mye2eutil.Timeout)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t//Get Updated cc\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\", Namespace: namespace}, cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t//locale dc-rack state is OK\n\tassert.Equal(t, api.ClusterPhaseInitial.Name, cc.Status.CassandraRackStatus[\"dc1-rack1\"].CassandraLastAction.Name)\n\tassert.Equal(t, api.StatusDone, cc.Status.CassandraRackStatus[\"dc1-rack1\"].CassandraLastAction.Status)\n\tassert.Equal(t, api.ClusterPhaseInitial.Name, cc.Status.LastClusterAction)\n\tassert.Equal(t, api.StatusDone, cc.Status.LastClusterActionStatus)\n\n\t//Check that numTokens are 256 (default) for dc1 and 32 (as specified in the crd) for dc2\n\tgrepNumTokens := \"grep num_tokens: /etc/cassandra/cassandra.yaml\"\n\tres, _, _ := mye2eutil.ExecPodFromName(t, f, namespace, \"cassandra-e2e-dc1-rack1-0\", grepNumTokens)\n\tassert.Equal(t, \"num_tokens: 256\", res)\n\tres, _, _ = mye2eutil.ExecPodFromName(t, f, namespace, \"cassandra-e2e-dc2-rack1-0\", grepNumTokens)\n\tassert.Equal(t, \"num_tokens: 32\", res)\n\t/*----\n\t */\n\tconst Strategy1DC = \"cqlsh -u cassandra -p cassandra -e \\\"ALTER KEYSPACE %s WITH REPLICATION = {'class\" +\n\t\t\"' : 'NetworkTopologyStrategy', 'dc1' : 1};\\\"\"\n\tconst Strategy2DC = \"cqlsh -u cassandra -p cassandra -e \\\"ALTER KEYSPACE %s WITH REPLICATION = {'class\" +\n\t\t\"' : 'NetworkTopologyStrategy', 'dc1' : 1, 'dc2' : 1};\\\"\"\n\tkeyspaces := []string{\n\t\t\"system_auth\",\n\t\t\"system_distributed\",\n\t\t\"system_traces\",\n\t}\n\tpod := &v1.Pod{TypeMeta: metav1.TypeMeta{Kind: \"Pod\", APIVersion: \"v1\"}}\n\n\tt.Log(\"We Change Replication Topology to 2 DC \")\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e-dc1-rack1-0\", Namespace: namespace}, pod)\n\tfor i := range keyspaces {\n\t\tcmd := fmt.Sprintf(Strategy2DC, keyspaces[i])\n\t\t_, _, err = mye2eutil.ExecPod(t, f, cc.Namespace, pod, []string{\"bash\", \"-c\", cmd})\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Error exec change keyspace %s = %v\", keyspaces[i], err)\n\t\t}\n\t}\n\ttime.Sleep(2 * time.Second)\n\n\tt.Logf(\"2. Ask Scale Down to 0 but this will be refused\")\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\", Namespace: namespace}, cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcc.Spec.Topology.DC[1].NodesPerRacks = func(i int32) *int32 { return &i }(0)\n\terr = f.Client.Update(goctx.TODO(), cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\ttime.Sleep(30 * time.Second)\n\n\t//Check Result\n\tt.Log(\"Get Updated cc\")\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\", Namespace: namespace}, cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t//Operator has restore old CRD\n\tassert.Equal(t, api.ActionCorrectCRDConfig.Name, cc.Status.LastClusterAction)\n\tassert.Equal(t, api.StatusDone, cc.Status.LastClusterActionStatus)\n\n\t/*----\n\t */\n\tt.Logf(\"3. We Remove the replication to the dc2\")\n\t//pod := &v1.Pod{TypeMeta: metav1.TypeMeta{Kind: \"Pod\", APIVersion: \"v1\"}}\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e-dc1-rack1-0\", Namespace: namespace}, pod)\n\n\tfor i := range keyspaces {\n\t\tcmd := fmt.Sprintf(Strategy1DC, keyspaces[i])\n\t\t_, _, err = mye2eutil.ExecPod(t, f, cc.Namespace, pod, []string{\"bash\", \"-c\", cmd})\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Error exec change keyspace %s{%s} = %v\", keyspaces[i], cmd, err)\n\t\t}\n\t}\n\ttime.Sleep(2 * time.Second)\n\n\t/*----\n\t */\n\tt.Logf(\"4. We Request a ScaleDown to 0 prior to remove a DC\")\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\", Namespace: namespace}, cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcc.Spec.Topology.DC[1].NodesPerRacks = func(i int32) *int32 { return &i }(0)\n\terr = f.Client.Update(goctx.TODO(), cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// wait for statefulset dc1-rack1\n\terr = mye2eutil.WaitForStatefulset(t, f.KubeClient, namespace, \"cassandra-e2e-dc2-rack1\", 0,\n\t\tmye2eutil.RetryInterval,\n\t\tmye2eutil.Timeout)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = mye2eutil.WaitForStatusDone(t, f, namespace, \"cassandra-e2e\", mye2eutil.RetryInterval, mye2eutil.Timeout)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tt.Log(\"Get Updated cc\")\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\", Namespace: namespace}, cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t//Because AutoUpdateSeedList is false we stay on ScaleUp=Done status\n\tassert.Equal(t, api.ActionScaleDown.Name, cc.Status.CassandraRackStatus[\"dc2-rack1\"].CassandraLastAction.Name)\n\tassert.Equal(t, api.StatusDone, cc.Status.CassandraRackStatus[\"dc2-rack1\"].CassandraLastAction.Status)\n\n\tstatefulset, err := f.KubeClient.AppsV1().StatefulSets(namespace).Get(\"cassandra-e2e-dc2-rack1\",\n\t\tmetav1.GetOptions{})\n\tassert.Equal(t, int32(0), statefulset.Status.CurrentReplicas)\n\n\t/*----\n\t */\n\tt.Logf(\"5. We Remove the DC\")\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\", Namespace: namespace}, cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcc.Spec.Topology.DC.Remove(1)\n\terr = f.Client.Update(goctx.TODO(), cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\ttime.Sleep(30 * time.Second)\n\n\tt.Log(\"Check Statefulset is deleted\")\n\tstatefulset, err = f.KubeClient.AppsV1().StatefulSets(namespace).Get(\"cassandra-e2e-dc2-rack1\",\n\t\tmetav1.GetOptions{})\n\t//assert.Equal(t, true, apierrors.IsNotFound(err))\n\n\tt.Log(\"Check Service is deleted\")\n\tsvc := &v1.Pod{TypeMeta: metav1.TypeMeta{Kind: \"Service\", APIVersion: \"v1\"}}\n\tnames := []string{\n\t\t\"cassandra-e2e-dc2\",\n\t}\n\tfor i := range names {\n\t\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: names[i], Namespace: namespace}, svc)\n\t\tassert.Equal(t, true, apierrors.IsNotFound(err))\n\t}\n\n\tt.Log(\"Get Updated cc\")\n\tcc = &api.CassandraCluster{}\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\", Namespace: namespace}, cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tt.Logf(\"Actual status is %s\", cc.Status.LastClusterAction)\n\t//We have only 1 dcRack in status\n\tassert.Equal(t, 1, len(cc.Status.CassandraRackStatus))\n\tassert.Equal(t, api.ActionDeleteDC.Name, cc.Status.LastClusterAction)\n\tassert.Equal(t, api.StatusDone, cc.Status.LastClusterActionStatus)\n}", "func (e *AlluxioEngine) setupMasterInernal() (desiredNum uint32, err error) {\n\n\tvar (\n\t\tchartName = utils.GetChartsDirectory() + \"/\" + common.ALLUXIO_CHART\n\t\tnamespace = common.ALLUXIO_NAMESPACE\n\t\tname = e.Config.Name\n\t\tconfigMapName = name + \"-\" + e.Type() + \"-values\"\n\t\tvalueFileName = \"\"\n\t)\n\n\t// 1.generate alluxio value struct\n\talluxioValue, err := e.generateAlluxioValue()\n\tif err != nil {\n\t\treturn desiredNum, err\n\t}\n\n\tdesiredNum = uint32(alluxioValue.ReplicaCount)\n\n\tfound, err := kubeclient.IsConfigMapExist(e.Client, configMapName, namespace)\n\tif err != nil {\n\t\treturn\n\t}\n\tif found {\n\t\tvalueFileName, err = kubectl.SaveConfigMapToFile(configMapName, \"data\", namespace)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t} else {\n\t\t// 2.generate value file\n\t\tvalueFile, err := ioutil.TempFile(os.TempDir(), fmt.Sprintf(\"%s-%s-values.yaml\", name, e.Type()))\n\t\tif err != nil {\n\t\t\te.Log.Error(err, \"failed to create tmp file\", \"valueFile\", valueFile.Name())\n\t\t\treturn desiredNum, err\n\t\t}\n\n\t\tvalueFileName = valueFile.Name()\n\t\te.Log.V(1).Info(\"Save the values file\", \"valueFile\", valueFileName)\n\n\t\t// 2. dump the object into the template file\n\t\terr = utils.ToYaml(alluxioValue, valueFile)\n\t\tif err != nil {\n\t\t\treturn desiredNum, err\n\t\t}\n\n\t\terr = kubectl.CreateConfigMapFromFile(configMapName, \"data\", valueFile.Name(), namespace)\n\t\tif err != nil {\n\t\t\treturn desiredNum, err\n\t\t}\n\t}\n\n\tfound, err = helm.CheckRelease(name, namespace)\n\tif err != nil {\n\t\treturn desiredNum, err\n\t}\n\n\tif found {\n\t\treturn desiredNum, nil\n\t}\n\n\terr = helm.InstallRelease(name, namespace, valueFileName, chartName)\n\n\treturn desiredNum, err\n}", "func (g *Generator) Update(current *cke.Cluster) (*cke.Cluster, error) {\n\tg.clearIntermediateData()\n\n\tcurrentCPs := cke.ControlPlanes(current.Nodes)\n\tcurrentWorkers := cke.Workers(current.Nodes)\n\n\top, err := g.removeNonExistentNode(currentCPs, currentWorkers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif op != nil {\n\t\treturn g.fill(op)\n\t}\n\n\top, err = g.increaseControlPlane()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif op != nil {\n\t\treturn g.fill(op)\n\t}\n\n\top, err = g.decreaseControlPlane()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif op != nil {\n\t\treturn g.fill(op)\n\t}\n\n\top, err = g.replaceControlPlane()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif op != nil {\n\t\treturn g.fill(op)\n\t}\n\n\top, err = g.increaseWorker()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif op != nil {\n\t\treturn g.fill(op)\n\t}\n\n\top, err = g.decreaseWorker()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif op != nil {\n\t\treturn g.fill(op)\n\t}\n\n\top, err = g.taintNodes(currentCPs, currentWorkers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif op != nil {\n\t\treturn g.fill(op)\n\t}\n\n\treturn nil, nil\n}", "func GetStatus(\n\tprincipal savedstate.Principal,\n\titself string,\n\ttmpDir string,\n\ttimeout time.Duration,\n\tlogger *structlog.Logger,\n) (statusType, statusType) {\n\tstatus := getStatus(principal.ID)\n\tif status < StatusUpdated || status == StatusReady {\n\t\treturn StatusReady, status\n\t}\n\n\tclusterName := principal.Sess.Name + \".\" + principal.Sess.Domain\n\tif strings.HasSuffix(clusterName, \".\") {\n\t\tclusterName = clusterName[:len(clusterName)-1]\n\t}\n\tapiHost := \"api.\" + clusterName\n\n\tres, err := net.LookupHost(apiHost)\n\tif err != nil {\n\t\tlogger.Debug(\"Kubernetes API host has not domain resolve\", \"Host\", apiHost)\n\t\treturn StatusReady, status\n\t}\n\tlogger.Debug(\"Kubernetes API host resolved to\", res)\n\n\thomeDir := filepath.Join(tmpDir, principal.ID)\n\n\t// Validate //////////////////////////////////////////////////////////////\n\tcmdParams := []string{\n\t\t\"--kopsValidate\",\n\t\tfmt.Sprintf(\"--name=%v\", clusterName),\n\t\tfmt.Sprintf(\"--state=s3://%v\", principal.Sess.Bucket),\n\t\tfmt.Sprintf(\"--timeout=%v\", timeout),\n\t}\n\n\tlogger.Debug(\"Calling Kops validate\", \"params\", cmdParams)\n\n\tcmd := exec.Command(itself, cmdParams...) // #nosec\n\tcmd.Env = []string{\n\t\tfmt.Sprintf(\"HOME=%v\", homeDir),\n\t\t// ToDo: replace with file in $HOME\n\t\tfmt.Sprintf(\"AWS_ACCESS_KEY=%v\", principal.Sess.AccessKey),\n\t\tfmt.Sprintf(\"AWS_SECRET_KEY=%v\", principal.Sess.SecretKey),\n\t}\n\n\tcmdOut, err := cmd.CombinedOutput()\n\n\tif err != nil {\n\t\tlogger.PrintErr(\"Kops validate failed\", \"err\", err, \"out\", string(cmdOut))\n\t\treturn StatusReady, status\n\t}\n\n\tlogger.Debug(\"Kops validate done\", \"out\", string(cmdOut))\n\n\tif !readyRegexp.Match(cmdOut) {\n\t\tlogger.Debug(\"Cluster is not ready yet\", \"total\", StatusReady, \"current\", status)\n\t\treturn StatusReady, status\n\t}\n\n\tsetStatus(principal.ID, StatusReady)\n\n\tlogger.Info(\"Cluster ready\")\n\n\treturn StatusReady, StatusReady\n}", "func (m *podManager) setup(req *cniserver.PodRequest) (cnitypes.Result, *runningPod, error) {\n\tdefer metrics.PodOperationsLatency.WithLabelValues(metrics.PodOperationSetup).Observe(metrics.SinceInMicroseconds(time.Now()))\n\tvar v1Pod *corev1.Pod\n\tvar err error\n\t// Release any IPAM allocations if the setup failed\n\tvar success bool\n\tdefer func() {\n\t\tif !success {\n\t\t\tm.ipamDel(req.SandboxID)\n\t\t}\n\t}()\n\tpKey := getPodKey(req.PodNamespace, req.PodName)\n\tif v1Pod, success = m.reattachPods[pKey]; !success {\n\t\tif v1Pod, err = m.kClient.CoreV1().Pods(req.PodNamespace).Get(context.TODO(), req.PodName, metav1.GetOptions{}); err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\tvar ipamResult cnitypes.Result\n\tpodIP := net.ParseIP(req.AssignedIP)\n\tif podIP == nil {\n\t\tipamResult, podIP, err = m.ipamAdd(req.Netns, req.SandboxID)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to run IPAM for %v: %v\", req.SandboxID, err)\n\t\t}\n\t\tif err := maybeAddMacvlan(v1Pod, req.Netns); err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\tvnid, err := m.policy.GetVNID(req.PodNamespace)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tofport, err := m.ovs.SetUpPod(req.SandboxID, req.HostVeth, podIP, vnid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif err := setupPodBandwidth(m.ovs, v1Pod, req.HostVeth, req.SandboxID); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tm.policy.EnsureVNIDRules(vnid)\n\n\tif err := m.policy.SetUpPod(v1Pod, podIP.String()); err != nil {\n\t\tklog.Errorf(\"network policy cannot be applied to pod %s (%v)\", req.PodName, err)\n\t}\n\tsuccess = true\n\tklog.Infof(\"CNI_ADD %s/%s got IP %s, ofport %d\", req.PodNamespace, req.PodName, podIP, ofport)\n\treturn ipamResult, &runningPod{vnid: vnid, ofport: ofport}, nil\n}", "func main() {\n\tctlConf := parseEnvFlags()\n\tlogger.WithField(\"version\", pkg.Version).\n\t\tWithField(\"ctlConf\", ctlConf).Info(\"starting gameServer operator...\")\n\n\tif err := ctlConf.validate(); err != nil {\n\t\tlogger.WithError(err).Fatal(\"Could not create controller from environment or flags\")\n\t}\n\n\tclientConf, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tlogger.WithError(err).Fatal(\"Could not create in cluster config\")\n\t}\n\n\tkubeClient, err := kubernetes.NewForConfig(clientConf)\n\tif err != nil {\n\t\tlogger.WithError(err).Fatal(\"Could not create the kubernetes clientset\")\n\t}\n\n\textClient, err := extclientset.NewForConfig(clientConf)\n\tif err != nil {\n\t\tlogger.WithError(err).Fatal(\"Could not create the api extension clientset\")\n\t}\n\n\tagonesClient, err := versioned.NewForConfig(clientConf)\n\tif err != nil {\n\t\tlogger.WithError(err).Fatal(\"Could not create the agones api clientset\")\n\t}\n\n\thealth := healthcheck.NewHandler()\n\twh := webhooks.NewWebHook(ctlConf.CertFile, ctlConf.KeyFile)\n\tagonesInformerFactory := externalversions.NewSharedInformerFactory(agonesClient, defaultResync)\n\tkubeInformationFactory := informers.NewSharedInformerFactory(kubeClient, defaultResync)\n\n\tallocationMutex := &sync.Mutex{}\n\n\tgsController := gameservers.NewController(wh, health, allocationMutex,\n\t\tctlConf.MinPort, ctlConf.MaxPort, ctlConf.SidecarImage, ctlConf.AlwaysPullSidecar,\n\t\tctlConf.SidecarCPURequest, ctlConf.SidecarCPULimit,\n\t\tkubeClient, kubeInformationFactory, extClient, agonesClient, agonesInformerFactory)\n\tgsSetController := gameserversets.NewController(wh, health, allocationMutex,\n\t\tkubeClient, extClient, agonesClient, agonesInformerFactory)\n\tfleetController := fleets.NewController(wh, health, kubeClient, extClient, agonesClient, agonesInformerFactory)\n\tfaController := fleetallocation.NewController(wh, allocationMutex,\n\t\tkubeClient, extClient, agonesClient, agonesInformerFactory)\n\tfasController := fleetautoscalers.NewController(wh, health,\n\t\tkubeClient, extClient, agonesClient, agonesInformerFactory)\n\n\tstop := signals.NewStopChannel()\n\n\tkubeInformationFactory.Start(stop)\n\tagonesInformerFactory.Start(stop)\n\n\trs := []runner{\n\t\twh, gsController, gsSetController, fleetController, faController, fasController, healthServer{handler: health},\n\t}\n\tfor _, r := range rs {\n\t\tgo func(rr runner) {\n\t\t\tif runErr := rr.Run(workers, stop); runErr != nil {\n\t\t\t\tlogger.WithError(runErr).Fatalf(\"could not start runner: %s\", reflect.TypeOf(rr))\n\t\t\t}\n\t\t}(r)\n\t}\n\n\t<-stop\n\tlogger.Info(\"Shut down agones controllers\")\n}", "func verifyVolumeProvisioningWithServiceDown(serviceName string, namespace string, client clientset.Interface,\n\tstoragePolicyName string, allowedTopologyHAMap map[string][]string, categories []string, isServiceStopped bool,\n\tf *framework.Framework) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tginkgo.By(\"CNS_TEST: Running for GC setup\")\n\tnodeList, err := fnodes.GetReadySchedulableNodes(client)\n\tframework.ExpectNoError(err, \"Unable to find ready and schedulable Node\")\n\tif !(len(nodeList.Items) > 0) {\n\t\tframework.Failf(\"Unable to find ready and schedulable Node\")\n\t}\n\n\tginkgo.By(fmt.Sprintf(\"Stopping %v on the vCenter host\", serviceName))\n\tvcAddress := e2eVSphere.Config.Global.VCenterHostname + \":\" + sshdPort\n\terr = invokeVCenterServiceControl(stopOperation, serviceName, vcAddress)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tisServiceStopped = true\n\terr = waitVCenterServiceToBeInState(serviceName, vcAddress, svcStoppedMessage)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\n\tdefer func() {\n\t\tif isServiceStopped {\n\t\t\tginkgo.By(fmt.Sprintf(\"Starting %v on the vCenter host\", serviceName))\n\t\t\terr = invokeVCenterServiceControl(startOperation, serviceName, vcAddress)\n\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t\terr = waitVCenterServiceToBeInState(serviceName, vcAddress, svcRunningMessage)\n\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t\tbootstrap()\n\t\t\tisServiceStopped = false\n\t\t}\n\t}()\n\n\tginkgo.By(\"Create statefulset with default pod management policy with replica 3\")\n\tcreateResourceQuota(client, namespace, rqLimit, storagePolicyName)\n\tstorageclass, err := client.StorageV1().StorageClasses().Get(ctx, storagePolicyName, metav1.GetOptions{})\n\tif !apierrors.IsNotFound(err) {\n\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t}\n\n\t// Creating StatefulSet service\n\tginkgo.By(\"Creating service\")\n\tservice := CreateService(namespace, client)\n\tdefer func() {\n\t\tdeleteService(namespace, client, service)\n\t}()\n\n\tstatefulset := GetStatefulSetFromManifest(namespace)\n\tginkgo.By(\"Creating statefulset\")\n\tstatefulset.Spec.VolumeClaimTemplates[len(statefulset.Spec.VolumeClaimTemplates)-1].\n\t\tSpec.StorageClassName = &storageclass.Name\n\t*statefulset.Spec.Replicas = 3\n\t_, err = client.AppsV1().StatefulSets(namespace).Create(ctx, statefulset, metav1.CreateOptions{})\n\tframework.ExpectNoError(err)\n\treplicas := *(statefulset.Spec.Replicas)\n\n\tdefer func() {\n\t\tscaleDownNDeleteStsDeploymentsInNamespace(ctx, client, namespace)\n\t\tpvcs, err := client.CoreV1().PersistentVolumeClaims(namespace).List(ctx, metav1.ListOptions{})\n\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\tfor _, claim := range pvcs.Items {\n\t\t\tpv := getPvFromClaim(client, namespace, claim.Name)\n\t\t\terr := fpv.DeletePersistentVolumeClaim(client, claim.Name, namespace)\n\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t\tginkgo.By(\"Verify it's PV and corresponding volumes are deleted from CNS\")\n\t\t\terr = fpv.WaitForPersistentVolumeDeleted(client, pv.Name, poll,\n\t\t\t\tpollTimeout)\n\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t\tvolumeHandle := pv.Spec.CSI.VolumeHandle\n\t\t\terr = e2eVSphere.waitForCNSVolumeToBeDeleted(volumeHandle)\n\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred(),\n\t\t\t\tfmt.Sprintf(\"Volume: %s should not be present in the CNS after it is deleted from \"+\n\t\t\t\t\t\"kubernetes\", volumeHandle))\n\t\t}\n\t}()\n\n\tginkgo.By(fmt.Sprintf(\"PVC and POD creations should be in pending state since %s is down\", serviceName))\n\tpvcs, err := client.CoreV1().PersistentVolumeClaims(namespace).List(ctx, metav1.ListOptions{})\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tfor _, pvc := range pvcs.Items {\n\t\terr = fpv.WaitForPersistentVolumeClaimPhase(v1.ClaimPending, client,\n\t\t\tpvc.Namespace, pvc.Name, framework.Poll, time.Minute)\n\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to find the volume in pending state with err: %v\", err))\n\t}\n\n\tpods := fss.GetPodList(client, statefulset)\n\tfor _, pod := range pods.Items {\n\t\tif pod.Status.Phase != v1.PodPending {\n\t\t\tframework.Failf(\"Expected pod to be in: %s state but is in: %s state\", v1.PodPending,\n\t\t\t\tpod.Status.Phase)\n\t\t}\n\t}\n\n\tginkgo.By(fmt.Sprintf(\"Starting %v on the vCenter host\", serviceName))\n\terr = invokeVCenterServiceControl(startOperation, serviceName, vcAddress)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tisServiceStopped = false\n\terr = waitVCenterServiceToBeInState(serviceName, vcAddress, svcRunningMessage)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\n\tbootstrap()\n\n\tverifyVolumeMetadataOnStatefulsets(client, ctx, namespace, statefulset, replicas,\n\t\tallowedTopologyHAMap, categories, storagePolicyName, nodeList, f)\n\n}", "func (fe *FeServiceImpl) applyDelta(ctx context.Context, latestState map[uint64]api.BiosphereState, targetState *ControllerCommand) {\n\tchunkInstances, err := fe.GetChunkServerInstances(ctx)\n\tif err != nil {\n\t\tlog.Printf(\"Error while fetching instance list %v\", err)\n\t\treturn\n\t}\n\tif targetState != nil && len(chunkInstances) == 0 {\n\t\tlog.Printf(\"Allocating 1 node\")\n\t\tlatestState[targetState.bsId] = api.BiosphereState_T_RUN\n\t\tclientCompute, err := fe.AuthCompute(ctx)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error in allocation: %v\", err)\n\t\t\treturn\n\t\t}\n\t\tfe.prepare(clientCompute)\n\t} else if targetState != nil && len(chunkInstances) > 0 {\n\t\tfor _, instance := range chunkInstances {\n\t\t\tip := instance.NetworkInterfaces[0].NetworkIP\n\t\t\tconn, err := grpc.Dial(fmt.Sprintf(\"%s:9000\", ip),\n\t\t\t\tgrpc.WithInsecure(), grpc.WithBlock(), grpc.WithTimeout(100*time.Millisecond))\n\t\t\tif err != nil {\n\t\t\t\t// Server not ready yet. This is expected, so don't do anything and just wait for next cycle.\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer conn.Close()\n\t\t\tchunkService := api.NewChunkServiceClient(conn)\n\t\t\t_, err = chunkService.Status(ctx, &api.StatusQ{})\n\t\t\tif err != nil {\n\t\t\t\t// Server not ready yet. This is expected, so don't do anything and just wait for next cycle.\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfe.applyChunkDelta(ctx, ip, chunkService, latestState, targetState)\n\t\t}\n\t} else if targetState == nil && len(chunkInstances) > 0 {\n\t\tlog.Printf(\"Deallocating %d nodes\", len(chunkInstances))\n\t\tclientCompute, err := fe.AuthCompute(ctx)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error in compute auth: %v\", err)\n\t\t\treturn\n\t\t}\n\t\tnames := make([]string, len(chunkInstances))\n\t\tfor ix, chunkInstance := range chunkInstances {\n\t\t\tnames[ix] = chunkInstance.Name\n\t\t}\n\t\tfe.deleteInstances(clientCompute, names)\n\t}\n}", "func (reconciler *ClusterReconciler) reconcile() (ctrl.Result, error) {\n\tvar err error\n\n\t// Child resources of the cluster CR will be automatically reclaimed by K8S.\n\tif reconciler.observed.cluster == nil {\n\t\treconciler.log.Info(\"The cluster has been deleted, no action to take\")\n\t\treturn ctrl.Result{}, nil\n\t}\n\n\terr = reconciler.reconcileConfigMap()\n\tif err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\n\terr = reconciler.reconcileJobManagerDeployment()\n\tif err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\n\terr = reconciler.reconcileJobManagerService()\n\tif err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\n\terr = reconciler.reconcileJobManagerIngress()\n\tif err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\n\terr = reconciler.reconcileTaskManagerDeployment()\n\tif err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\n\tresult, err := reconciler.reconcileJob()\n\n\treturn result, nil\n}", "func (o *Options) Run(ctx context.Context) error {\n\tctx, cancel := context.WithTimeout(ctx, o.Timeout)\n\tdefer cancel()\n\n\t// Create and initialize cluster 1.\n\tcluster1 := inband.NewCluster(o.LocalFactory, o.RemoteFactory)\n\tif err := cluster1.Init(ctx); err != nil {\n\t\treturn err\n\t}\n\n\t// Create and initialize cluster 2.\n\tcluster2 := inband.NewCluster(o.RemoteFactory, o.LocalFactory)\n\tif err := cluster2.Init(ctx); err != nil {\n\t\treturn err\n\t}\n\n\t// Check whether a ForeignCluster resource already exists in cluster 1 for cluster 2, and perform sanity checks.\n\tif err := cluster1.CheckForeignCluster(ctx, cluster2.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Check whether a ForeignCluster resource already exists in cluster 2 for cluster 1, and perform sanity checks.\n\tif err := cluster2.CheckForeignCluster(ctx, cluster1.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// SetUp tenant namespace for cluster 2 in cluster 1.\n\tif err := cluster1.SetUpTenantNamespace(ctx, cluster2.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\tcluster2.SetRemTenantNS(cluster1.GetLocTenantNS())\n\n\t// SetUp tenant namespace for cluster in cluster 2.\n\tif err := cluster2.SetUpTenantNamespace(ctx, cluster1.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\tcluster1.SetRemTenantNS(cluster2.GetLocTenantNS())\n\n\t// Configure network configuration for cluster 1.\n\tif err := cluster1.ExchangeNetworkCfg(ctx, cluster2.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Configure network configuration for cluster 2.\n\tif err := cluster2.ExchangeNetworkCfg(ctx, cluster1.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Port-forwarding ipam service for cluster 1.\n\tif err := cluster1.PortForwardIPAM(ctx); err != nil {\n\t\treturn err\n\t}\n\tdefer cluster1.StopPortForwardIPAM()\n\n\t// Port-forwarding ipam service for cluster 2.\n\tif err := cluster2.PortForwardIPAM(ctx); err != nil {\n\t\treturn err\n\t}\n\tdefer cluster2.StopPortForwardIPAM()\n\n\t// Creating IPAM client for cluster 1.\n\tipamClient1, err := cluster1.NewIPAMClient(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Creating IPAM client for cluster 2.\n\tipamClient2, err := cluster2.NewIPAMClient(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Mapping proxy's ip in cluster1 for cluster2.\n\tif err := cluster1.MapProxyIPForCluster(ctx, ipamClient1, cluster2.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Mapping proxy's ip in cluster2 for cluster2\n\tif err := cluster2.MapProxyIPForCluster(ctx, ipamClient2, cluster1.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Mapping auth's ip in cluster1 for cluster2.\n\tif err := cluster1.MapAuthIPForCluster(ctx, ipamClient1, cluster2.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Mapping auth's ip in cluster2 for cluster1\n\tif err := cluster2.MapAuthIPForCluster(ctx, ipamClient2, cluster1.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Creating foreign cluster in cluster1 for cluster 2.\n\tif err := cluster1.EnforceForeignCluster(ctx, cluster2.GetClusterID(), cluster2.GetAuthToken(),\n\t\tcluster2.GetAuthURL(), cluster2.GetProxyURL()); err != nil {\n\t\treturn err\n\t}\n\n\t// Creating foreign cluster in cluster2 for cluster 1.\n\tif err := cluster2.EnforceForeignCluster(ctx, cluster1.GetClusterID(), cluster1.GetAuthToken(),\n\t\tcluster1.GetAuthURL(), cluster1.GetProxyURL()); err != nil {\n\t\treturn err\n\t}\n\n\t// Setting the foreign cluster outgoing flag in cluster 1 for cluster 2\n\t// This operation is performed after that both foreign clusters have already been successfully created, to prevent a\n\t// possible race condition in which the resource request originated by the local foreign cluster is replicated to and\n\t// reconciled in the remote cluster before we create the corresponding foreign cluster. This would cause an incorrect\n\t// foreign cluster (i.e., of type OutOfBand) to be automatically created, leading to a broken peering.\n\tif err := cluster1.EnforceOutgoingPeeringFlag(ctx, cluster2.GetClusterID(), true); err != nil {\n\t\treturn err\n\t}\n\n\t// Setting the foreign cluster outgoing flag in cluster 2 for cluster 1\n\tif err := cluster2.EnforceOutgoingPeeringFlag(ctx, cluster1.GetClusterID(), o.Bidirectional); err != nil {\n\t\treturn err\n\t}\n\n\t// Waiting for VPN connection to be established in cluster 1.\n\tif err := cluster1.Waiter.ForNetwork(ctx, cluster2.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Waiting for VPN connection to be established in cluster 2.\n\tif err := cluster2.Waiter.ForNetwork(ctx, cluster1.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Waiting for authentication to complete in cluster 1.\n\tif err := cluster1.Waiter.ForAuth(ctx, cluster2.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Waiting for authentication to complete in cluster 2.\n\tif err := cluster2.Waiter.ForAuth(ctx, cluster1.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Waiting for outgoing peering to complete in cluster 1.\n\tif err := cluster1.Waiter.ForOutgoingPeering(ctx, cluster2.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Waiting for virtual node to be created in cluster 1.\n\tif err := cluster1.Waiter.ForNode(ctx, cluster2.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\tif !o.Bidirectional {\n\t\treturn nil\n\t}\n\n\t// Waiting for outgoing peering to complete in cluster 2.\n\tif err := cluster2.Waiter.ForOutgoingPeering(ctx, cluster1.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Waiting for virtual node to be created in cluster 2.\n\treturn cluster2.Waiter.ForNode(ctx, cluster1.GetClusterID())\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 add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"rethinkdbcluster-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource RethinkDBCluster\n\terr = c.Watch(&source.Kind{Type: &rethinkdbv1alpha1.RethinkDBCluster{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to secondary resource ConfigMap and requeue the owner RethinkDBCluster\n\terr = c.Watch(&source.Kind{Type: &corev1.ConfigMap{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &rethinkdbv1alpha1.RethinkDBCluster{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to secondary resource PersistentVolumeClaims and requeue the owner RethinkDBCluster\n\terr = c.Watch(&source.Kind{Type: &corev1.PersistentVolumeClaim{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &rethinkdbv1alpha1.RethinkDBCluster{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to secondary resource Pods and requeue the owner RethinkDBCluster\n\terr = c.Watch(&source.Kind{Type: &corev1.Pod{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &rethinkdbv1alpha1.RethinkDBCluster{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to secondary resource Secret and requeue the owner RethinkDBCluster\n\terr = c.Watch(&source.Kind{Type: &corev1.Secret{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &rethinkdbv1alpha1.RethinkDBCluster{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to secondary resource Service and requeue the owner RethinkDBCluster\n\terr = c.Watch(&source.Kind{Type: &corev1.Service{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &rethinkdbv1alpha1.RethinkDBCluster{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func calculateStatus(allRSs []*apps.ReplicaSet, newRS *apps.ReplicaSet, deployment *apps.Deployment) apps.DeploymentStatus {\n\tavailableReplicas := deploymentutil.GetAvailableReplicaCountForReplicaSets(allRSs)\n\ttotalReplicas := deploymentutil.GetReplicaCountForReplicaSets(allRSs)\n\tunavailableReplicas := totalReplicas - availableReplicas\n\t// If unavailableReplicas is negative, then that means the Deployment has more available replicas running than\n\t// desired, e.g. whenever it scales down. In such a case we should simply default unavailableReplicas to zero.\n\tif unavailableReplicas < 0 {\n\t\tunavailableReplicas = 0\n\t}\n\n\tstatus := apps.DeploymentStatus{\n\t\t// TODO: Ensure that if we start retrying status updates, we won't pick up a new Generation value.\n\t\tObservedGeneration: deployment.Generation,\n\t\tReplicas: deploymentutil.GetActualReplicaCountForReplicaSets(allRSs),\n\t\tUpdatedReplicas: deploymentutil.GetActualReplicaCountForReplicaSets([]*apps.ReplicaSet{newRS}),\n\t\tReadyReplicas: deploymentutil.GetReadyReplicaCountForReplicaSets(allRSs),\n\t\tAvailableReplicas: availableReplicas,\n\t\tUnavailableReplicas: unavailableReplicas,\n\t\tCollisionCount: deployment.Status.CollisionCount,\n\t}\n\n\t// Copy conditions one by one so we won't mutate the original object.\n\tconditions := deployment.Status.Conditions\n\tfor i := range conditions {\n\t\tstatus.Conditions = append(status.Conditions, conditions[i])\n\t}\n\n\tif availableReplicas >= *(deployment.Spec.Replicas)-deploymentutil.MaxUnavailable(*deployment) {\n\t\tminAvailability := deploymentutil.NewDeploymentCondition(apps.DeploymentAvailable, v1.ConditionTrue, deploymentutil.MinimumReplicasAvailable, \"Deployment has minimum availability.\")\n\t\tdeploymentutil.SetDeploymentCondition(&status, *minAvailability)\n\t} else {\n\t\tnoMinAvailability := deploymentutil.NewDeploymentCondition(apps.DeploymentAvailable, v1.ConditionFalse, deploymentutil.MinimumReplicasUnavailable, \"Deployment does not have minimum availability.\")\n\t\tdeploymentutil.SetDeploymentCondition(&status, *noMinAvailability)\n\t}\n\n\treturn status\n}", "func (p *Planner) categorizeNodes(podDestinations map[string]bool, scaleDownCandidates []*apiv1.Node) {\n\tunremovableTimeout := p.latestUpdate.Add(p.context.AutoscalingOptions.UnremovableNodeRecheckTimeout)\n\tunremovableCount := 0\n\tvar removableList []simulator.NodeToBeRemoved\n\tp.unremovableNodes.Update(p.context.ClusterSnapshot.NodeInfos(), p.latestUpdate)\n\tcurrentlyUnneededNodeNames, utilizationMap, ineligible := p.eligibilityChecker.FilterOutUnremovable(p.context, scaleDownCandidates, p.latestUpdate, p.unremovableNodes)\n\tfor _, n := range ineligible {\n\t\tp.unremovableNodes.Add(n)\n\t}\n\tp.nodeUtilizationMap = utilizationMap\n\ttimer := time.NewTimer(p.context.ScaleDownSimulationTimeout)\n\n\tfor i, node := range currentlyUnneededNodeNames {\n\t\tif timedOut(timer) {\n\t\t\tklog.Warningf(\"%d out of %d nodes skipped in scale down simulation due to timeout.\", len(currentlyUnneededNodeNames)-i, len(currentlyUnneededNodeNames))\n\t\t\tbreak\n\t\t}\n\t\tif len(removableList) >= p.unneededNodesLimit() {\n\t\t\tklog.V(4).Infof(\"%d out of %d nodes skipped in scale down simulation: there are already %d unneeded nodes so no point in looking for more.\", len(currentlyUnneededNodeNames)-i, len(currentlyUnneededNodeNames), len(removableList))\n\t\t\tbreak\n\t\t}\n\t\tremovable, unremovable := p.rs.SimulateNodeRemoval(node, podDestinations, p.latestUpdate, p.context.RemainingPdbTracker.GetPdbs())\n\t\tif removable != nil {\n\t\t\t_, inParallel, _ := p.context.RemainingPdbTracker.CanRemovePods(removable.PodsToReschedule)\n\t\t\tif !inParallel {\n\t\t\t\tremovable.IsRisky = true\n\t\t\t}\n\t\t\tdelete(podDestinations, removable.Node.Name)\n\t\t\tp.context.RemainingPdbTracker.RemovePods(removable.PodsToReschedule)\n\t\t\tremovableList = append(removableList, *removable)\n\t\t}\n\t\tif unremovable != nil {\n\t\t\tunremovableCount += 1\n\t\t\tp.unremovableNodes.AddTimeout(unremovable, unremovableTimeout)\n\t\t}\n\t}\n\tp.unneededNodes.Update(removableList, p.latestUpdate)\n\tif unremovableCount > 0 {\n\t\tklog.V(1).Infof(\"%v nodes found to be unremovable in simulation, will re-check them at %v\", unremovableCount, unremovableTimeout)\n\t}\n}", "func Run(s *state.State, nodes corev1.NodeList) error {\n\tvar errs []error\n\n\t// Verify that list of nodes match with the provided manifest\n\ts.Logger.Infoln(\"Verifying that nodes in the cluster match nodes defined in the manifest...\")\n\tif err := verifyMatchNodes(s.Cluster.ControlPlane.Hosts, nodes, s.Logger, s.Verbose); err != nil {\n\t\ts.Logger.Errorln(\"Unable to match all control plane nodes in the cluster and all nodes defined in the manifest.\")\n\t\terrs = append(errs, err...)\n\t}\n\n\t// Verify that all nodes in the cluster are ready\n\ts.Logger.Infoln(\"Verifying that all nodes in the cluster are ready...\")\n\tif err := verifyNodesReady(nodes, s.Logger, s.Verbose); err != nil {\n\t\ts.Logger.Errorln(\"Unable to match all control plane nodes in the cluster and all nodes defined in the manifest.\")\n\t\terrs = append(errs, err...)\n\t}\n\n\t// Verify that upgrade is not in progress\n\ts.Logger.Infoln(\"Verifying that there is no upgrade in progress...\")\n\tif err := verifyNoUpgradeLabels(nodes, s.Logger, s.Verbose); err != nil {\n\t\ts.Logger.Errorf(\"Unable to verify that there is no upgrade in progress.\")\n\t\terrs = append(errs, err...)\n\t}\n\n\treturn utilerrors.NewAggregate(errs)\n}", "func (r *FoundationDBClusterReconciler) Reconcile(ctx context.Context, request ctrl.Request) (ctrl.Result, error) {\n\tcluster := &fdbtypes.FoundationDBCluster{}\n\n\terr := r.Get(ctx, request.NamespacedName, cluster)\n\tif err != nil {\n\t\tif k8serrors.IsNotFound(err) {\n\t\t\treturn ctrl.Result{}, nil\n\n\t\t}\n\t\t// Error reading the object - requeue the request.\n\t\treturn ctrl.Result{}, err\n\t}\n\n\tclusterLog := log.WithValues(\"namespace\", cluster.Namespace, \"cluster\", cluster.Name)\n\n\tif cluster.Spec.Skip {\n\t\tclusterLog.Info(\"Skipping cluster with skip value true\", \"skip\", cluster.Spec.Skip)\n\t\t// Don't requeue\n\t\treturn ctrl.Result{}, nil\n\t}\n\n\terr = internal.NormalizeClusterSpec(cluster, r.DeprecationOptions)\n\tif err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\n\tadminClient, err := r.getDatabaseClientProvider().GetAdminClient(cluster, r)\n\tif err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\tdefer adminClient.Close()\n\n\tsupportedVersion, err := adminClient.VersionSupported(cluster.Spec.Version)\n\tif err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\tif !supportedVersion {\n\t\treturn ctrl.Result{}, fmt.Errorf(\"version %s is not supported\", cluster.Spec.Version)\n\t}\n\n\tsubReconcilers := []clusterSubReconciler{\n\t\tupdateStatus{},\n\t\tupdateLockConfiguration{},\n\t\tupdateConfigMap{},\n\t\tcheckClientCompatibility{},\n\t\treplaceMisconfiguredProcessGroups{},\n\t\treplaceFailedProcessGroups{},\n\t\tdeletePodsForBuggification{},\n\t\taddProcessGroups{},\n\t\taddServices{},\n\t\taddPVCs{},\n\t\taddPods{},\n\t\tgenerateInitialClusterFile{},\n\t\tupdateSidecarVersions{},\n\t\tupdatePodConfig{},\n\t\tupdateLabels{},\n\t\tupdateDatabaseConfiguration{},\n\t\tchooseRemovals{},\n\t\texcludeInstances{},\n\t\tchangeCoordinators{},\n\t\tbounceProcesses{},\n\t\tupdatePods{},\n\t\tremoveServices{},\n\t\tremoveProcessGroups{},\n\t\tupdateStatus{},\n\t}\n\n\toriginalGeneration := cluster.ObjectMeta.Generation\n\tnormalizedSpec := cluster.Spec.DeepCopy()\n\tdelayedRequeue := false\n\n\tfor _, subReconciler := range subReconcilers {\n\t\t// We have to set the normalized spec here again otherwise any call to Update() for the status of the cluster\n\t\t// will reset all normalized fields...\n\t\tcluster.Spec = *(normalizedSpec.DeepCopy())\n\t\tclusterLog.Info(\"Attempting to run sub-reconciler\", \"subReconciler\", fmt.Sprintf(\"%T\", subReconciler))\n\n\t\trequeue := subReconciler.reconcile(r, ctx, cluster)\n\t\tif requeue == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif requeue.delayedRequeue {\n\t\t\tclusterLog.Info(\"Delaying requeue for sub-reconciler\",\n\t\t\t\t\"subReconciler\", fmt.Sprintf(\"%T\", subReconciler),\n\t\t\t\t\"message\", requeue.message)\n\t\t\tdelayedRequeue = true\n\t\t\tcontinue\n\t\t}\n\n\t\treturn processRequeue(requeue, subReconciler, cluster, r.Recorder, clusterLog)\n\t}\n\n\tif cluster.Status.Generations.Reconciled < originalGeneration || delayedRequeue {\n\t\tclusterLog.Info(\"Cluster was not fully reconciled by reconciliation process\", \"status\", cluster.Status.Generations)\n\n\t\treturn ctrl.Result{Requeue: true}, nil\n\t}\n\n\tclusterLog.Info(\"Reconciliation complete\", \"generation\", cluster.Status.Generations.Reconciled)\n\tr.Recorder.Event(cluster, corev1.EventTypeNormal, \"ReconciliationComplete\", fmt.Sprintf(\"Reconciled generation %d\", cluster.Status.Generations.Reconciled))\n\n\treturn ctrl.Result{}, nil\n}", "func (gs *GKEClient) Setup(numNodes *int64, nodeType *string, region *string, zone *string, project *string) (ClusterOperations, error) {\n\tvar err error\n\tgc := &GKECluster{\n\t\tRequest: &GKERequest{\n\t\t\tNumNodes: DefaultGKENumNodes,\n\t\t\tNodeType: DefaultGKENodeType,\n\t\t\tRegion: DefaultGKERegion,\n\t\t\tZone: DefaultGKEZone,\n\t\t\tBackupRegions: DefaultGKEBackupRegions},\n\t}\n\n\tctx := context.Background()\n\n\tc, err := google.DefaultClient(ctx, container.CloudPlatformScope)\n\tif nil != err {\n\t\treturn nil, fmt.Errorf(\"failed create google client: '%v'\", err)\n\t}\n\n\tcontainerService, err := container.New(c)\n\tif nil != err {\n\t\treturn nil, fmt.Errorf(\"failed create container service: '%v'\", err)\n\t}\n\tgc.operations = &GKESDKClient{containerService}\n\n\tif nil != project { // use provided project and create cluster\n\t\tgc.Project = project\n\t\tgc.NeedCleanup = true\n\t} else if err := gc.checkEnvironment(); nil != err {\n\t\treturn nil, fmt.Errorf(\"failed checking existing cluster: '%v'\", err)\n\t} else if nil != gc.Cluster { // return if Cluster was already set by kubeconfig\n\t\treturn gc, nil\n\t}\n\tif nil == gc.Cluster {\n\t\tif common.IsProw() {\n\t\t\tproject, err := boskos.AcquireGKEProject(nil)\n\t\t\tif nil != err {\n\t\t\t\treturn nil, fmt.Errorf(\"failed acquire boskos project: '%v'\", err)\n\t\t\t}\n\t\t\tgc.Project = &project.Name\n\t\t}\n\t\tif nil != numNodes {\n\t\t\tgc.Request.NumNodes = *numNodes\n\t\t}\n\t\tif nil != nodeType {\n\t\t\tgc.Request.NodeType = *nodeType\n\t\t}\n\t\tif nil != region {\n\t\t\tgc.Request.Region = *region\n\t\t}\n\t\tif \"\" != common.GetOSEnv(regionEnv) {\n\t\t\tgc.Request.Region = common.GetOSEnv(regionEnv)\n\t\t}\n\t\tif \"\" != common.GetOSEnv(backupRegionEnv) {\n\t\t\tgc.Request.BackupRegions = strings.Split(common.GetOSEnv(backupRegionEnv), \" \")\n\t\t}\n\t\tif nil != zone {\n\t\t\tgc.Request.Zone = *zone\n\t\t\tgc.Request.BackupRegions = make([]string, 0)\n\t\t}\n\t}\n\tif nil == gc.Project || \"\" == *gc.Project {\n\t\treturn nil, fmt.Errorf(\"gcp project must be set\")\n\t}\n\tlog.Printf(\"use project '%s' for running test\", *gc.Project)\n\treturn gc, nil\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"kubemanager-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource Kubemanager\n\terr = c.Watch(&source.Kind{Type: &v1alpha1.Kubemanager{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to PODs\n\tsrcPod := &source.Kind{Type: &corev1.Pod{}}\n\tpodHandler := resourceHandler(mgr.GetClient())\n\tpredInitStatus := utils.PodInitStatusChange(map[string]string{\"contrail_manager\": \"kubemanager\"})\n\tpredPodIPChange := utils.PodIPChange(map[string]string{\"contrail_manager\": \"kubemanager\"})\n\terr = c.Watch(srcPod, podHandler, predPodIPChange)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = c.Watch(srcPod, podHandler, predInitStatus)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrcManager := &source.Kind{Type: &v1alpha1.Manager{}}\n\tmanagerHandler := resourceHandler(mgr.GetClient())\n\tpredManagerSizeChange := utils.ManagerSizeChange(utils.KubemanagerGroupKind())\n\terr = c.Watch(srcManager, managerHandler, predManagerSizeChange)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrcCassandra := &source.Kind{Type: &v1alpha1.Cassandra{}}\n\tcassandraHandler := resourceHandler(mgr.GetClient())\n\tpredCassandraSizeChange := utils.CassandraActiveChange()\n\terr = c.Watch(srcCassandra, cassandraHandler, predCassandraSizeChange)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrcConfig := &source.Kind{Type: &v1alpha1.Config{}}\n\tconfigHandler := resourceHandler(mgr.GetClient())\n\tpredConfigSizeChange := utils.ConfigActiveChange()\n\terr = c.Watch(srcConfig, configHandler, predConfigSizeChange)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrcRabbitmq := &source.Kind{Type: &v1alpha1.Rabbitmq{}}\n\trabbitmqHandler := resourceHandler(mgr.GetClient())\n\tpredRabbitmqSizeChange := utils.RabbitmqActiveChange()\n\terr = c.Watch(srcRabbitmq, rabbitmqHandler, predRabbitmqSizeChange)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrcZookeeper := &source.Kind{Type: &v1alpha1.Zookeeper{}}\n\tzookeeperHandler := resourceHandler(mgr.GetClient())\n\tpredZookeeperSizeChange := utils.ZookeeperActiveChange()\n\terr = c.Watch(srcZookeeper, zookeeperHandler, predZookeeperSizeChange)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrcDeployment := &source.Kind{Type: &appsv1.Deployment{}}\n\tdeploymentHandler := &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &v1alpha1.Kubemanager{},\n\t}\n\tdeploymentPred := utils.DeploymentStatusChange(utils.KubemanagerGroupKind())\n\terr = c.Watch(srcDeployment, deploymentHandler, deploymentPred)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func TestMetricLongItem(t *testing.T) {\n\thelper := newHelper(t)\n\tdefer helper.Close()\n\n\thelper.preregisterAgent(t)\n\thelper.initSynchronizer(t)\n\thelper.AddTime(time.Minute)\n\n\tsrvRedis1 := discovery.Service{\n\t\tName: \"redis\",\n\t\tInstance: \"short-redis-container-name\",\n\t\tServiceType: discovery.RedisService,\n\t\t// ContainerID: \"1234\",\n\t\tActive: true,\n\t}\n\n\tsrvRedis2 := discovery.Service{\n\t\tName: \"redis\",\n\t\tInstance: \"long-redis-container-name--this-one-is-more-than-100-char-which-is-the-limit-on-bleemeo-api-0123456789abcdef\",\n\t\tServiceType: discovery.RedisService,\n\t\t// ContainerID: \"1234\",\n\t\tActive: true,\n\t}\n\n\thelper.discovery.SetResult([]discovery.Service{srvRedis1, srvRedis2}, nil)\n\n\thelper.pushPoints(t, []labels.Labels{\n\t\tmodel.AnnotationToMetaLabels(labels.FromMap(srvRedis1.LabelsOfStatus()), srvRedis1.AnnotationsOfStatus()),\n\t\tmodel.AnnotationToMetaLabels(labels.FromMap(srvRedis2.LabelsOfStatus()), srvRedis2.AnnotationsOfStatus()),\n\t})\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tmetrics := helper.MetricsFromAPI()\n\t// agent_status + the two service_status metrics\n\tif len(metrics) != 3 {\n\t\tt.Errorf(\"len(metrics) = %v, want %v\", len(metrics), 3)\n\t}\n\n\thelper.SetTimeToNextFullSync()\n\n\thelper.pushPoints(t, []labels.Labels{\n\t\tmodel.AnnotationToMetaLabels(labels.FromMap(srvRedis1.LabelsOfStatus()), srvRedis1.AnnotationsOfStatus()),\n\t\tmodel.AnnotationToMetaLabels(labels.FromMap(srvRedis2.LabelsOfStatus()), srvRedis2.AnnotationsOfStatus()),\n\t})\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\t// We do 1 request: list metrics.\n\thelper.api.AssertCallPerResource(t, mockAPIResourceMetric, 1)\n\n\tmetrics = helper.MetricsFromAPI()\n\t// No new metrics\n\tif len(metrics) != 3 {\n\t\tt.Errorf(\"len(metrics) = %v, want %v\", len(metrics), 3)\n\t}\n}", "func TestE2E(t *testing.T) {\n\tvar missingEnvs []string\n\tfor _, env := range []string{kopsEnvVarClusterName} {\n\t\tif _, ok := os.LookupEnv(env); !ok {\n\t\t\tmissingEnvs = append(missingEnvs, env)\n\t\t}\n\t}\n\tif len(missingEnvs) > 0 {\n\t\tt.Fatalf(\"missing required environment variable(s): %s\", missingEnvs)\n\t}\n\n\ts3Cl, err := createS3Client()\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create S3 client: %s\", err)\n\t}\n\n\ttests := []struct {\n\t\tdesc string\n\t\tkubeVer string\n\t}{\n\t\t{\n\t\t\tdesc: \"latest release\",\n\t\t\tkubeVer: \"1.12.0\",\n\t\t},\n\t\t{\n\t\t\tdesc: \"previous release\",\n\t\t\tkubeVer: \"1.11.2\",\n\t\t},\n\t\t{\n\t\t\tdesc: \"previous previous release\",\n\t\t\tkubeVer: \"1.10.6\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\ttt := tt\n\t\tt.Run(tt.desc, func(t *testing.T) {\n\t\t\tl := log.New(os.Stdout, fmt.Sprintf(\"[%s] \", t.Name()), 0)\n\n\t\t\tcs, cleanup, err := setupCluster(l, s3Cl, t.Name(), tt.kubeVer)\n\t\t\tdefer func() {\n\t\t\t\tl.Println(\"Cleaning up cluster\")\n\t\t\t\tif err := cleanup(); err != nil {\n\t\t\t\t\tt.Errorf(\"failed to clean up after test: %s\", err)\n\t\t\t\t}\n\t\t\t}()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"failed to set up cluster: %s\", err)\n\t\t\t}\n\n\t\t\t// Check that nodes become ready.\n\t\t\tl.Println(\"Polling for node readiness\")\n\t\t\tvar (\n\t\t\t\tgotNodes []corev1.Node\n\t\t\t\tnumReadyNodes int\n\t\t\t)\n\t\t\tstart := time.Now()\n\t\t\tif err := wait.Poll(5*time.Second, 6*time.Minute, func() (bool, error) {\n\t\t\t\tnl, err := cs.CoreV1().Nodes().List(metav1.ListOptions{LabelSelector: \"kubernetes.io/role=node\"})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\n\t\t\t\tgotNodes = nl.Items\n\t\t\t\tnumReadyNodes = 0\n\t\t\tNodes:\n\t\t\t\tfor _, node := range gotNodes {\n\t\t\t\t\t// Make sure the \"uninitialized\" node taint is missing.\n\t\t\t\t\tfor _, taint := range node.Spec.Taints {\n\t\t\t\t\t\tif taint.Key == cloudprovider.TaintExternalCloudProvider {\n\t\t\t\t\t\t\tcontinue Nodes\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Make sure the node is ready and has a DO-specific label\n\t\t\t\t\t// attached.\n\t\t\t\t\tfor _, cond := range node.Status.Conditions {\n\t\t\t\t\t\tif cond.Type == corev1.NodeReady && cond.Status == corev1.ConditionTrue {\n\t\t\t\t\t\t\tif _, ok := node.Labels[doLabel]; ok {\n\t\t\t\t\t\t\t\tnumReadyNodes++\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\tl.Printf(\"Found %d/%d ready node(s)\", numReadyNodes, numWantNodes)\n\t\t\t\treturn numReadyNodes == numWantNodes, nil\n\t\t\t}); err != nil {\n\t\t\t\tt.Fatalf(\"got %d ready node(s), want %d: %s\\nnnodes: %v\", numReadyNodes, numWantNodes, err, spew.Sdump(gotNodes))\n\t\t\t}\n\t\t\tl.Printf(\"Took %v for nodes to become ready\\n\", time.Since(start))\n\n\t\t\t// Check that load balancer is working.\n\n\t\t\t// Install example pod to load-balance to.\n\t\t\tappName := \"app\"\n\t\t\tpod := corev1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: appName,\n\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\"app\": appName,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tContainers: []corev1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"nginx\",\n\t\t\t\t\t\t\tImage: \"nginx\",\n\t\t\t\t\t\t\tPorts: []corev1.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\n\t\t\tif _, err := cs.CoreV1().Pods(corev1.NamespaceDefault).Create(context.Background(), &pod, metav1.CreateOptions{}); err != nil {\n\t\t\t\tt.Fatalf(\"failed to create example pod: %s\", err)\n\t\t\t}\n\n\t\t\t// Wait for example pod to become ready.\n\t\t\tl.Println(\"Polling for pod readiness\")\n\t\t\tstart = time.Now()\n\t\t\tvar appPod *corev1.Pod\n\t\t\tif err := wait.Poll(1*time.Second, 1*time.Minute, func() (bool, error) {\n\t\t\t\tpod, err := cs.CoreV1().Pods(corev1.NamespaceDefault).Get(appName, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\tif kerrors.IsNotFound(err) {\n\t\t\t\t\t\treturn false, nil\n\t\t\t\t\t}\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tappPod = pod\n\t\t\t\tfor _, cond := range appPod.Status.Conditions {\n\t\t\t\t\tif cond.Type == corev1.PodReady && cond.Status == corev1.ConditionTrue {\n\t\t\t\t\t\treturn true, nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn false, nil\n\t\t\t}); err != nil {\n\t\t\t\tt.Fatalf(\"failed to observe ready example pod %q in time: %s\\npod: %v\", appName, err, appPod)\n\t\t\t}\n\t\t\tl.Printf(\"Took %v for pod to become ready\\n\", time.Since(start))\n\n\t\t\t// Create service object.\n\t\t\tsvcName := \"svc\"\n\t\t\tsvc := corev1.Service{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: svcName,\n\t\t\t\t},\n\t\t\t\tSpec: corev1.ServiceSpec{\n\t\t\t\t\tSelector: map[string]string{\n\t\t\t\t\t\t\"app\": appName,\n\t\t\t\t\t},\n\t\t\t\t\tType: corev1.ServiceTypeLoadBalancer,\n\t\t\t\t\tPorts: []corev1.ServicePort{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tPort: 80,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tif _, err := cs.CoreV1().Services(corev1.NamespaceDefault).Create(context.Background(), &svc, metav1.CreateOptions{}); err != nil {\n\t\t\t\tt.Fatalf(\"failed to create service: %s\", err)\n\t\t\t}\n\t\t\t// External LBs don't seem to get deleted when the kops cluster is\n\t\t\t// removed, at least not on DO. Hence, we'll do it explicitly.\n\t\t\tvar lbAddr string\n\t\t\tdefer func() {\n\t\t\t\tl.Printf(\"Deleting service %q\\n\", svcName)\n\t\t\t\tif err := cs.CoreV1().Services(corev1.NamespaceDefault).Delete(context.Background(), svcName, &metav1.DeleteOptions{}); err != nil {\n\t\t\t\t\tt.Errorf(\"failed to delete service: %s\", err)\n\t\t\t\t}\n\t\t\t\t// If this is the last test, CCM might not be able to remove\n\t\t\t\t// the LB before the cluster gets deleted, leaving the LB\n\t\t\t\t// dangling. Therefore, we make sure to stick around until it's\n\t\t\t\t// gone for sure, which we presume is the case if requests\n\t\t\t\t// cannot be delivered anymore due to a network error.\n\n\t\t\t\t// We skip this step if the LB address was never populated,\n\t\t\t\t// however, indicating that the test never came that far.\n\t\t\t\tif lbAddr == \"\" {\n\t\t\t\t\tl.Println(\"Load balancer IP address was never assigned -- skipping check for winded down LB\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tcl := &http.Client{\n\t\t\t\t\tTimeout: 5 * time.Second,\n\t\t\t\t}\n\t\t\t\tu := fmt.Sprintf(\"http://%s:80\", lbAddr)\n\t\t\t\tvar attempts, lastStatusCode int\n\t\t\t\tif err := wait.Poll(1*time.Second, 3*time.Minute, func() (bool, error) {\n\t\t\t\t\tl.Printf(\"Sending request through winding down LB to %s\", u)\n\t\t\t\t\tattempts++\n\t\t\t\t\tresp, err := cl.Get(u)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tlastStatusCode = resp.StatusCode\n\t\t\t\t\t\tresp.Body.Close()\n\t\t\t\t\t\treturn false, nil\n\t\t\t\t\t}\n\t\t\t\t\treturn true, nil\n\t\t\t\t}); err != nil {\n\t\t\t\t\tt.Fatalf(\"continued to deliver requests over LB to example application: %s (last status code: %d / attempts: %d)\", err, lastStatusCode, attempts)\n\t\t\t\t}\n\t\t\t\tl.Printf(\"Needed %d attempt(s) to stop delivering sample request\\n\", attempts)\n\t\t\t}()\n\n\t\t\t// Wait for service IP address to be assigned.\n\t\t\tl.Println(\"Polling for service load balancer IP address assignment\")\n\t\t\tstart = time.Now()\n\t\t\tif err := wait.Poll(5*time.Second, 10*time.Minute, func() (bool, error) {\n\t\t\t\tsvc, err := cs.CoreV1().Services(corev1.NamespaceDefault).Get(context.Background(), svcName, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tif len(svc.Status.LoadBalancer.Ingress) > 0 {\n\t\t\t\t\tlbAddr = svc.Status.LoadBalancer.Ingress[0].IP\n\t\t\t\t\treturn true, nil\n\t\t\t\t}\n\n\t\t\t\treturn false, nil\n\t\t\t}); err != nil {\n\t\t\t\tt.Fatalf(\"failed to observe load balancer IP address assignment: %s\", err)\n\t\t\t}\n\t\t\tl.Printf(\"Took %v for load balancer to get its IP address assigned\\n\", time.Since(start))\n\n\t\t\t// Send request to the pod over the LB.\n\t\t\tcl := &http.Client{\n\t\t\t\tTimeout: 5 * time.Second,\n\t\t\t}\n\t\t\tu := fmt.Sprintf(\"http://%s:80\", lbAddr)\n\n\t\t\tvar attempts, lastStatusCode int\n\t\t\tif err := wait.Poll(1*time.Second, 3*time.Minute, func() (bool, error) {\n\t\t\t\tl.Printf(\"Sending request to %s\", u)\n\t\t\t\tattempts++\n\t\t\t\tresp, err := cl.Get(u)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t\tdefer resp.Body.Close()\n\n\t\t\t\tlastStatusCode = resp.StatusCode\n\t\t\t\tif resp.StatusCode != http.StatusOK {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\n\t\t\t\treturn true, nil\n\t\t\t}); err != nil {\n\t\t\t\tt.Fatalf(\"failed to send request over LB to example application: %s (last status code: %d / attempts: %d)\", err, lastStatusCode, attempts)\n\t\t\t}\n\t\t\tl.Printf(\"Needed %d attempt(s) to successfully deliver sample request\\n\", attempts)\n\t\t})\n\t}\n}", "func Discovery(ctx context.Context, c client.Client, namespace, name string, options DiscoverOptions) (*ObjectTree, error) {\n\t// Fetch the Cluster instance.\n\tcluster := &clusterv1.Cluster{}\n\tclusterKey := client.ObjectKey{\n\t\tNamespace: namespace,\n\t\tName: name,\n\t}\n\tif err := c.Get(ctx, clusterKey, cluster); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Enforce TypeMeta to make sure checks on GVK works properly.\n\tcluster.TypeMeta = metav1.TypeMeta{\n\t\tKind: \"Cluster\",\n\t\tAPIVersion: clusterv1.GroupVersion.String(),\n\t}\n\n\t// Create an object tree with the cluster as root\n\ttree := NewObjectTree(cluster, options.toObjectTreeOptions())\n\n\t// Adds cluster infra\n\tclusterInfra, err := external.Get(ctx, c, cluster.Spec.InfrastructureRef, cluster.Namespace)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"get InfraCluster reference from Cluster\")\n\t}\n\ttree.Add(cluster, clusterInfra, ObjectMetaName(\"ClusterInfrastructure\"))\n\n\tif options.ShowClusterResourceSets {\n\t\taddClusterResourceSetsToObjectTree(ctx, c, cluster, tree)\n\t}\n\n\t// Adds control plane\n\tcontrolPlane, err := external.Get(ctx, c, cluster.Spec.ControlPlaneRef, cluster.Namespace)\n\tif err == nil {\n\t\taddControlPlane(cluster, controlPlane, tree, options)\n\t}\n\n\t// Adds control plane machines.\n\tmachinesList, err := getMachinesInCluster(ctx, c, cluster.Namespace, cluster.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmachineMap := map[string]bool{}\n\taddMachineFunc := func(parent client.Object, m *clusterv1.Machine) {\n\t\t_, visible := tree.Add(parent, m)\n\t\tmachineMap[m.Name] = true\n\n\t\tif visible {\n\t\t\tif (m.Spec.InfrastructureRef != corev1.ObjectReference{}) {\n\t\t\t\tif machineInfra, err := external.Get(ctx, c, &m.Spec.InfrastructureRef, cluster.Namespace); err == nil {\n\t\t\t\t\ttree.Add(m, machineInfra, ObjectMetaName(\"MachineInfrastructure\"), NoEcho(true))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif m.Spec.Bootstrap.ConfigRef != nil {\n\t\t\t\tif machineBootstrap, err := external.Get(ctx, c, m.Spec.Bootstrap.ConfigRef, cluster.Namespace); err == nil {\n\t\t\t\t\ttree.Add(m, machineBootstrap, ObjectMetaName(\"BootstrapConfig\"), NoEcho(true))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tcontrolPlaneMachines := selectControlPlaneMachines(machinesList)\n\tif controlPlane != nil {\n\t\tfor i := range controlPlaneMachines {\n\t\t\tcp := controlPlaneMachines[i]\n\t\t\taddMachineFunc(controlPlane, cp)\n\t\t}\n\t}\n\n\tmachinePoolList, err := getMachinePoolsInCluster(ctx, c, cluster.Namespace, cluster.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tworkers := VirtualObject(cluster.Namespace, \"WorkerGroup\", \"Workers\")\n\t// Add WorkerGroup if there are MachineDeployments or MachinePools\n\tif len(machinesList.Items) != len(controlPlaneMachines) || len(machinePoolList.Items) > 0 {\n\t\ttree.Add(cluster, workers)\n\t}\n\n\tif len(machinesList.Items) != len(controlPlaneMachines) { // Add MachineDeployment objects\n\t\ttree.Add(cluster, workers)\n\t\terr = addMachineDeploymentToObjectTree(ctx, c, cluster, workers, machinesList, tree, options, addMachineFunc)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif len(machinePoolList.Items) > 0 { // Add MachinePool objects\n\t\ttree.Add(cluster, workers)\n\t\taddMachinePoolsToObjectTree(ctx, c, cluster.Namespace, workers, machinePoolList, machinesList, tree, addMachineFunc)\n\t}\n\n\t// Handles orphan machines.\n\tif len(machineMap) < len(machinesList.Items) {\n\t\tother := VirtualObject(cluster.Namespace, \"OtherGroup\", \"Other\")\n\t\ttree.Add(workers, other)\n\n\t\tfor i := range machinesList.Items {\n\t\t\tm := &machinesList.Items[i]\n\t\t\tif _, ok := machineMap[m.Name]; ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\taddMachineFunc(other, m)\n\t\t}\n\t}\n\n\treturn tree, nil\n}", "func main() {\n\tvar (\n\t\t//port = flag.Int(\"port\", 7472, \"HTTP listening port for Prometheus metrics\")\n\t\t//name = flag.String(\"name\", \"lb-ippool\", \"configmap name in default namespace\")\n\t\tpath = flag.String(\"config\", \"\", \"config file\")\n\t\tkubeconfig = flag.String(\"kubeconfig\", \"\", \"absolute path to the kubeconfig file (only needed when running outside of k8s)\")\n\t)\n\n\tflag.Parse()\n\tif len(*path) == 0 {\n\t\tklog.Fatalf(fmt.Sprintf(\"config file is required\"))\n\t}\n\n\trestConfig, err := clientcmd.BuildConfigFromFlags(\"\", *kubeconfig)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\tclientset, err := kubernetes.NewForConfig(restConfig)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\tbroadcaster := record.NewBroadcaster()\n\tbroadcaster.StartRecordingToSink(&corev1.EventSinkImpl{Interface: corev1.New(clientset.CoreV1().RESTClient()).Events(\"\")})\n\trecorder := broadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"lb-controller\"})\n\tqueue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())\n\n\t// INFO: (1) 与 router server 建立 bgp session\n\ts := getSpeaker(*path)\n\n\tsvcWatcher := cache.NewListWatchFromClient(clientset.CoreV1().RESTClient(), \"services\",\n\t\tmetav1.NamespaceAll, fields.Everything())\n\tsvcIndexer, svcInformer := cache.NewIndexerInformer(svcWatcher, &v1.Service{}, 0, cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tkey, err := cache.MetaNamespaceKeyFunc(obj)\n\t\t\tif err == nil {\n\t\t\t\tqueue.Add(svcKey(key))\n\t\t\t}\n\t\t},\n\t\tUpdateFunc: func(old interface{}, new interface{}) {\n\t\t\t//key, err := cache.MetaNamespaceKeyFunc(new)\n\t\t\t//if err == nil {\n\t\t\t//\t//queue.Add(svcKey(key))\n\t\t\t//\tklog.Infof(fmt.Sprintf(\"update %s\", key))\n\t\t\t//}\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\t//key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)\n\t\t\t//if err == nil {\n\t\t\t//\t//queue.Add(svcKey(key))\n\t\t\t//\tklog.Infof(fmt.Sprintf(\"delete %s\", key))\n\t\t\t//}\n\t\t},\n\t}, cache.Indexers{})\n\n\tepWatcher := cache.NewListWatchFromClient(clientset.CoreV1().RESTClient(), \"endpoints\",\n\t\tmetav1.NamespaceAll, fields.Everything())\n\tepIndexer, epInformer := cache.NewIndexerInformer(epWatcher, &v1.Endpoints{}, 0, cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\t//key, err := cache.MetaNamespaceKeyFunc(obj)\n\t\t\t//if err == nil {\n\t\t\t//\t//queue.Add(svcKey(key))\n\t\t\t//\tklog.Info(key)\n\t\t\t//}\n\t\t},\n\t\tUpdateFunc: func(old interface{}, new interface{}) {\n\t\t\t//key, err := cache.MetaNamespaceKeyFunc(new)\n\t\t\t//if err == nil {\n\t\t\t//\tklog.Info(key)\n\t\t\t//\t//queue.Add(svcKey(key))\n\t\t\t//}\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\t//key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)\n\t\t\t//if err == nil {\n\t\t\t//\t//queue.Add(svcKey(key))\n\t\t\t//\tklog.Info(key)\n\t\t\t//}\n\t\t},\n\t}, cache.Indexers{})\n\n\tstopCh := make(chan struct{})\n\tgo svcInformer.Run(stopCh)\n\tgo epInformer.Run(stopCh)\n\tif !cache.WaitForCacheSync(stopCh, svcInformer.HasSynced, epInformer.HasSynced) {\n\t\tklog.Fatalf(fmt.Sprintf(\"time out waiting for cache sync\"))\n\t}\n\n\tsync := func(key interface{}, queue workqueue.RateLimitingInterface) error {\n\t\tdefer queue.Done(key)\n\n\t\tswitch k := key.(type) {\n\t\tcase svcKey:\n\t\t\tsvc, exists, err := svcIndexer.GetByKey(string(k))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !exists {\n\t\t\t\treturn fmt.Errorf(\"not exist\")\n\t\t\t}\n\t\t\tendpoints, exists, err := epIndexer.GetByKey(string(k))\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"failed to get endpoints\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !exists {\n\t\t\t\treturn fmt.Errorf(\"not exist\")\n\t\t\t}\n\n\t\t\tif svc.(*v1.Service).Spec.Type != v1.ServiceTypeLoadBalancer {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\trecorder.Eventf(svc.(*v1.Service), v1.EventTypeNormal, \"SetBalancer\", \"advertise svc ip\")\n\t\t\ts.SetBalancer(string(k), svc.(*v1.Service), endpoints.(*v1.Endpoints))\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"unknown key type for %s %T\", key, key))\n\t\t}\n\t}\n\n\tfor {\n\t\tkey, quit := queue.Get()\n\t\tif quit {\n\t\t\treturn\n\t\t}\n\n\t\terr := sync(key, queue)\n\t\tif err != nil {\n\t\t\tklog.Error(err)\n\t\t} else {\n\t\t\tqueue.Forget(key)\n\t\t}\n\t}\n}", "func (r *recommender) UpdateVPAs() {\n\tcnt := metrics_recommender.NewObjectCounter()\n\tdefer cnt.Observe()\n\n\tfor _, observedVpa := range r.clusterState.ObservedVpas {\n\t\tkey := model.VpaID{\n\t\t\tNamespace: observedVpa.Namespace,\n\t\t\tVpaName: observedVpa.Name,\n\t\t}\n\n\t\tvpa, found := r.clusterState.Vpas[key]\n\t\tif !found {\n\t\t\tcontinue\n\t\t}\n\t\tresources := r.podResourceRecommender.GetRecommendedPodResources(GetContainerNameToAggregateStateMap(vpa))\n\t\thad := vpa.HasRecommendation()\n\n\t\tlistOfResourceRecommendation := logic.MapToListOfRecommendedContainerResources(resources)\n\n\t\tfor _, postProcessor := range r.recommendationPostProcessor {\n\t\t\tlistOfResourceRecommendation = postProcessor.Process(vpa, listOfResourceRecommendation, observedVpa.Spec.ResourcePolicy)\n\t\t}\n\n\t\tvpa.UpdateRecommendation(listOfResourceRecommendation)\n\t\tif vpa.HasRecommendation() && !had {\n\t\t\tmetrics_recommender.ObserveRecommendationLatency(vpa.Created)\n\t\t}\n\t\thasMatchingPods := vpa.PodCount > 0\n\t\tvpa.UpdateConditions(hasMatchingPods)\n\t\tif err := r.clusterState.RecordRecommendation(vpa, time.Now()); err != nil {\n\t\t\tklog.Warningf(\"%v\", err)\n\t\t\tif klog.V(4).Enabled() {\n\t\t\t\tklog.Infof(\"VPA dump\")\n\t\t\t\tklog.Infof(\"%+v\", vpa)\n\t\t\t\tklog.Infof(\"HasMatchingPods: %v\", hasMatchingPods)\n\t\t\t\tklog.Infof(\"PodCount: %v\", vpa.PodCount)\n\t\t\t\tpods := r.clusterState.GetMatchingPods(vpa)\n\t\t\t\tklog.Infof(\"MatchingPods: %+v\", pods)\n\t\t\t\tif len(pods) != vpa.PodCount {\n\t\t\t\t\tklog.Errorf(\"ClusterState pod count and matching pods disagree for vpa %v/%v\", vpa.ID.Namespace, vpa.ID.VpaName)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcnt.Add(vpa)\n\n\t\t_, err := vpa_utils.UpdateVpaStatusIfNeeded(\n\t\t\tr.vpaClient.VerticalPodAutoscalers(vpa.ID.Namespace), vpa.ID.VpaName, vpa.AsStatus(), &observedVpa.Status)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\n\t\t\t\t\"Cannot update VPA %v object. Reason: %+v\", vpa.ID.VpaName, err)\n\t\t}\n\t}\n}", "func newPreVoteMigrationCluster(t *testing.T) *network {\n\tn1 := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())\n\tn2 := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())\n\tn3 := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())\n\n\tn1.becomeFollower(1, None)\n\tn2.becomeFollower(1, None)\n\tn3.becomeFollower(1, None)\n\n\tn1.preVote = true\n\tn2.preVote = true\n\t// We intentionally do not enable PreVote for n3, this is done so in order\n\t// to simulate a rolling restart process where it's possible to have a mixed\n\t// version cluster with replicas with PreVote enabled, and replicas without.\n\n\tnt := newNetwork(n1, n2, n3)\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})\n\n\t// Cause a network partition to isolate n3.\n\tnt.isolate(3)\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte(\"some data\")}}})\n\tnt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})\n\tnt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})\n\n\t// check state\n\t// n1.state == StateLeader\n\t// n2.state == StateFollower\n\t// n3.state == StateCandidate\n\tif n1.state != StateLeader {\n\t\tt.Fatalf(\"node 1 state: %s, want %s\", n1.state, StateLeader)\n\t}\n\tif n2.state != StateFollower {\n\t\tt.Fatalf(\"node 2 state: %s, want %s\", n2.state, StateFollower)\n\t}\n\tif n3.state != StateCandidate {\n\t\tt.Fatalf(\"node 3 state: %s, want %s\", n3.state, StateCandidate)\n\t}\n\n\t// check term\n\t// n1.Term == 2\n\t// n2.Term == 2\n\t// n3.Term == 4\n\tif n1.Term != 2 {\n\t\tt.Fatalf(\"node 1 term: %d, want %d\", n1.Term, 2)\n\t}\n\tif n2.Term != 2 {\n\t\tt.Fatalf(\"node 2 term: %d, want %d\", n2.Term, 2)\n\t}\n\tif n3.Term != 4 {\n\t\tt.Fatalf(\"node 3 term: %d, want %d\", n3.Term, 4)\n\t}\n\n\t// Enable prevote on n3, then recover the network\n\tn3.preVote = true\n\tnt.recover()\n\n\treturn nt\n}", "func ListAllClusters(response *JsonListClustersMap) *JsonListClustersMap {\n\tvar SIDCluster int\n\tvar SName string\n\tvar SAWSAccount int64\n\tvar SAWSRegion string\n\tvar SAWSEnvironment string\n\tvar SK8sVersion string\n\n\tvar SNodeType string\n\tvar SNodeInstance string\n\tvar STotalInstances int\n\n\tvar totalInstances int\n\n\tdescription := make(DescriptionMap)\n\n\tdb, err := sql.Open(\"mysql\", UserDB+\":\"+PassDB+\"@tcp(\"+HostDB+\":\"+PortDB+\")/\"+DatabaseDB+\"?charset=utf8\")\n\tcheckErr(err)\n\n\tdefer db.Close()\n\n\trows, err := db.Query(\"SELECT id_cluster, nome, aws_account, aws_region, aws_env, k8s_version FROM clusters ORDER BY nome\")\n\tcheckErr(err)\n\n\tfor rows.Next() {\n\t\terr = rows.Scan(&SIDCluster, &SName, &SAWSAccount, &SAWSRegion, &SAWSEnvironment, &SK8sVersion)\n\t\tcheckErr(err)\n\n\t\tdescription = DescriptionMap{}\n\t\ttotalInstances = 0\n\n\t\trows1, err := db.Query(\"SELECT node_type, node_instance, total_instances FROM nodes WHERE id_cluster=?\", SIDCluster)\n\t\tcheckErr(err)\n\n\t\tfor rows1.Next() {\n\t\t\terr = rows1.Scan(&SNodeType, &SNodeInstance, &STotalInstances)\n\t\t\tcheckErr(err)\n\n\t\t\tdescription[SNodeType] = append(\n\t\t\t\tdescription[SNodeType],\n\t\t\t\tDescriptionStruct{\n\t\t\t\t\tDescription{\n\t\t\t\t\t\tType: SNodeInstance,\n\t\t\t\t\t\tTotalTypeInstances: STotalInstances,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t)\n\n\t\t\ttotalInstances = totalInstances + STotalInstances\n\t\t}\n\n\t\t*response = append(\n\t\t\t*response,\n\t\t\tjsonListClusters{\n\t\t\t\tClusterName: SName,\n\t\t\t\tAws: AWS{\n\t\t\t\t\tAccount: SAWSAccount,\n\t\t\t\t\tRegion: SAWSRegion,\n\t\t\t\t\tEnvironment: SAWSEnvironment,\n\t\t\t\t},\n\t\t\t\tK8SVersion: SK8sVersion,\n\t\t\t\tInstances: Instances{\n\t\t\t\t\tTotalInstances: totalInstances,\n\t\t\t\t\tDescription: description,\n\t\t\t\t},\n\t\t\t},\n\t\t)\n\t}\n\n\treturn response\n}", "func (r *Reconciler) update() error {\n\tif err := validateMachine(*r.machine); err != nil {\n\t\treturn fmt.Errorf(\"%v: failed validating machine provider spec: %w\", r.machine.GetName(), err)\n\t}\n\n\tif r.providerStatus.TaskRef != \"\" {\n\t\tmoTask, err := r.session.GetTask(r.Context, r.providerStatus.TaskRef)\n\t\tif err != nil {\n\t\t\tif !isRetrieveMONotFound(r.providerStatus.TaskRef, err) {\n\t\t\t\tmetrics.RegisterFailedInstanceUpdate(&metrics.MachineLabels{\n\t\t\t\t\tName: r.machine.Name,\n\t\t\t\t\tNamespace: r.machine.Namespace,\n\t\t\t\t\tReason: \"GetTask finished with error\",\n\t\t\t\t})\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif moTask != nil {\n\t\t\tif taskIsFinished, err := taskIsFinished(moTask); err != nil {\n\t\t\t\tmetrics.RegisterFailedInstanceUpdate(&metrics.MachineLabels{\n\t\t\t\t\tName: r.machine.Name,\n\t\t\t\t\tNamespace: r.machine.Namespace,\n\t\t\t\t\tReason: \"Task finished with error\",\n\t\t\t\t})\n\t\t\t\treturn fmt.Errorf(\"%v task %v finished with error: %w\", moTask.Info.DescriptionId, moTask.Reference().Value, err)\n\t\t\t} else if !taskIsFinished {\n\t\t\t\treturn fmt.Errorf(\"%v task %v has not finished\", moTask.Info.DescriptionId, moTask.Reference().Value)\n\t\t\t}\n\t\t}\n\t}\n\n\tvmRef, err := findVM(r.machineScope)\n\tif err != nil {\n\t\tmetrics.RegisterFailedInstanceUpdate(&metrics.MachineLabels{\n\t\t\tName: r.machine.Name,\n\t\t\tNamespace: r.machine.Namespace,\n\t\t\tReason: \"FindVM finished with error\",\n\t\t})\n\t\tif !isNotFound(err) {\n\t\t\treturn err\n\t\t}\n\t\treturn fmt.Errorf(\"vm not found on update: %w\", err)\n\t}\n\n\tvm := &virtualMachine{\n\t\tContext: r.machineScope.Context,\n\t\tObj: object.NewVirtualMachine(r.machineScope.session.Client.Client, vmRef),\n\t\tRef: vmRef,\n\t}\n\n\tif err := vm.reconcileTags(r.Context, r.session, r.machine); err != nil {\n\t\tmetrics.RegisterFailedInstanceUpdate(&metrics.MachineLabels{\n\t\t\tName: r.machine.Name,\n\t\t\tNamespace: r.machine.Namespace,\n\t\t\tReason: \"ReconcileTags finished with error\",\n\t\t})\n\t\treturn fmt.Errorf(\"failed to reconcile tags: %w\", err)\n\t}\n\n\tif err := r.reconcileMachineWithCloudState(vm, r.providerStatus.TaskRef); err != nil {\n\t\tmetrics.RegisterFailedInstanceUpdate(&metrics.MachineLabels{\n\t\t\tName: r.machine.Name,\n\t\t\tNamespace: r.machine.Namespace,\n\t\t\tReason: \"ReconcileWithCloudState finished with error\",\n\t\t})\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (a AddPods) Reconcile(r *FoundationDBClusterReconciler, context ctx.Context, cluster *fdbtypes.FoundationDBCluster) (bool, error) {\n\tcurrentCounts := cluster.Status.ProcessCounts.Map()\n\tdesiredCountStruct, err := cluster.GetProcessCountsWithDefaults()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdesiredCounts := desiredCountStruct.Map()\n\n\tif reflect.DeepEqual(currentCounts, desiredCounts) {\n\t\treturn true, nil\n\t}\n\n\tconfigMap, err := GetConfigMap(context, cluster, r)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\texistingConfigMap := &corev1.ConfigMap{}\n\terr = r.Get(context, types.NamespacedName{Namespace: configMap.Namespace, Name: configMap.Name}, existingConfigMap)\n\tif err != nil && k8serrors.IsNotFound(err) {\n\t\tlog.Info(\"Creating config map\", \"namespace\", configMap.Namespace, \"cluster\", cluster.Name, \"name\", configMap.Name)\n\t\terr = r.Create(context, configMap)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t} else if err != nil {\n\t\treturn false, err\n\t}\n\n\tinstances, err := r.PodLifecycleManager.GetInstances(r, cluster, context, getPodListOptions(cluster, \"\", \"\")...)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tinstancesPendingRemoval := make(map[string]bool, 0)\n\tfor _, id := range cluster.Spec.InstancesToRemove {\n\t\tinstancesPendingRemoval[id] = true\n\t}\n\n\tinstanceIDs := make(map[string]map[int]bool)\n\tfor _, instance := range instances {\n\t\tinstanceID := instance.GetInstanceID()\n\t\t_, num, err := ParseInstanceID(instanceID)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tclass := instance.GetProcessClass()\n\t\tif instanceIDs[class] == nil {\n\t\t\tinstanceIDs[class] = make(map[int]bool)\n\t\t}\n\n\t\tif instance.Pod != nil && instance.Pod.DeletionTimestamp != nil && !cluster.InstanceIsBeingRemoved(instanceID) {\n\t\t\treturn false, ReconciliationNotReadyError{message: \"Cluster has pod that is pending deletion\", retryable: true}\n\t\t}\n\n\t\tinstanceIDs[class][num] = true\n\t}\n\n\tfor _, processClass := range fdbtypes.ProcessClasses {\n\t\tdesiredCount := desiredCounts[processClass]\n\t\tif desiredCount < 0 {\n\t\t\tdesiredCount = 0\n\t\t}\n\t\tnewCount := desiredCount - currentCounts[processClass]\n\t\tif newCount > 0 {\n\t\t\tr.Recorder.Event(cluster, \"Normal\", \"AddingProcesses\", fmt.Sprintf(\"Adding %d %s processes\", newCount, processClass))\n\n\t\t\tpvcs := &corev1.PersistentVolumeClaimList{}\n\t\t\tr.List(context, pvcs, getPodListOptions(cluster, processClass, \"\")...)\n\t\t\treusablePvcs := make(map[int]bool, len(pvcs.Items))\n\n\t\t\tfor index, pvc := range pvcs.Items {\n\t\t\t\townedByCluster := false\n\t\t\t\tfor _, ownerReference := range pvc.OwnerReferences {\n\t\t\t\t\tif ownerReference.UID == cluster.UID {\n\t\t\t\t\t\townedByCluster = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif ownedByCluster && pvc.ObjectMeta.DeletionTimestamp == nil {\n\t\t\t\t\tinstanceID := GetInstanceIDFromMeta(pvc.ObjectMeta)\n\t\t\t\t\tif instancesPendingRemoval[instanceID] {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tmatchingInstances, err := r.PodLifecycleManager.GetInstances(\n\t\t\t\t\t\tr, cluster, context,\n\t\t\t\t\t\tgetPodListOptions(cluster, processClass, instanceID)...,\n\t\t\t\t\t)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn false, err\n\t\t\t\t\t}\n\t\t\t\t\tif len(matchingInstances) == 0 && !cluster.InstanceIsBeingRemoved(instanceID) {\n\t\t\t\t\t\treusablePvcs[index] = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\taddedCount := 0\n\t\t\tfor index := range reusablePvcs {\n\t\t\t\tif newCount <= 0 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tinstanceID := GetInstanceIDFromMeta(pvcs.Items[index].ObjectMeta)\n\t\t\t\t_, idNum, err := ParseInstanceID(instanceID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\n\t\t\t\tpod, err := GetPod(context, cluster, processClass, idNum, r)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tif GetInstanceIDFromMeta(pod.ObjectMeta) != instanceID {\n\t\t\t\t\treturn false, fmt.Errorf(\"Failed to create new pod to match PVC %s\", pvcs.Items[index].Name)\n\t\t\t\t}\n\n\t\t\t\terr = r.PodLifecycleManager.CreateInstance(r, context, pod)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\n\t\t\t\tif instanceIDs[processClass] == nil {\n\t\t\t\t\tinstanceIDs[processClass] = make(map[int]bool)\n\t\t\t\t}\n\t\t\t\tinstanceIDs[processClass][idNum] = true\n\n\t\t\t\taddedCount++\n\t\t\t\tnewCount--\n\t\t\t}\n\n\t\t\tidNum := 1\n\n\t\t\tif instanceIDs[processClass] == nil {\n\t\t\t\tinstanceIDs[processClass] = make(map[int]bool)\n\t\t\t}\n\n\t\t\tfor i := 0; i < newCount; i++ {\n\t\t\t\tfor idNum > 0 {\n\t\t\t\t\t_, instanceID := getInstanceID(cluster, processClass, idNum)\n\n\t\t\t\t\tif !instancesPendingRemoval[instanceID] && !instanceIDs[processClass][idNum] {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t\tidNum++\n\t\t\t\t}\n\n\t\t\t\tpvc, err := GetPvc(cluster, processClass, idNum)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\n\t\t\t\tif pvc != nil {\n\t\t\t\t\towner, err := buildOwnerReference(context, cluster.TypeMeta, cluster.ObjectMeta, r)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn false, err\n\t\t\t\t\t}\n\t\t\t\t\tpvc.ObjectMeta.OwnerReferences = owner\n\n\t\t\t\t\terr = r.Create(context, pvc)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn false, err\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tpod, err := GetPod(context, cluster, processClass, idNum, r)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\terr = r.PodLifecycleManager.CreateInstance(r, context, pod)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\n\t\t\t\taddedCount++\n\t\t\t\tidNum++\n\t\t\t}\n\t\t\tcluster.Status.ProcessCounts.IncreaseCount(processClass, addedCount)\n\t\t}\n\t}\n\n\treturn true, nil\n}", "func (s) TestSuccessCaseLeafNode(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tclusterName string\n\t\tclusterUpdate xdsresource.ClusterUpdate\n\t\tlbPolicy *xdsresource.ClusterLBPolicyRingHash\n\t}{\n\t\t{\n\t\t\tname: \"test-update-root-cluster-EDS-success\",\n\t\t\tclusterName: edsService,\n\t\t\tclusterUpdate: xdsresource.ClusterUpdate{\n\t\t\t\tClusterType: xdsresource.ClusterTypeEDS,\n\t\t\t\tClusterName: edsService,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"test-update-root-cluster-EDS-with-ring-hash\",\n\t\t\tclusterName: logicalDNSService,\n\t\t\tclusterUpdate: xdsresource.ClusterUpdate{\n\t\t\t\tClusterType: xdsresource.ClusterTypeLogicalDNS,\n\t\t\t\tClusterName: logicalDNSService,\n\t\t\t\tLBPolicy: &xdsresource.ClusterLBPolicyRingHash{MinimumRingSize: 10, MaximumRingSize: 100},\n\t\t\t},\n\t\t\tlbPolicy: &xdsresource.ClusterLBPolicyRingHash{MinimumRingSize: 10, MaximumRingSize: 100},\n\t\t},\n\t\t{\n\t\t\tname: \"test-update-root-cluster-Logical-DNS-success\",\n\t\t\tclusterName: logicalDNSService,\n\t\t\tclusterUpdate: xdsresource.ClusterUpdate{\n\t\t\t\tClusterType: xdsresource.ClusterTypeLogicalDNS,\n\t\t\t\tClusterName: logicalDNSService,\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tch, fakeClient := setupTests()\n\t\t\t// When you first update the root cluster, it should hit the code\n\t\t\t// path which will start a cluster node for that root. Updating the\n\t\t\t// root cluster logically represents a ping from a ClientConn.\n\t\t\tch.updateRootCluster(test.clusterName)\n\t\t\t// Starting a cluster node involves communicating with the\n\t\t\t// xdsClient, telling it to watch a cluster.\n\t\t\tctx, ctxCancel := context.WithTimeout(context.Background(), defaultTestTimeout)\n\t\t\tdefer ctxCancel()\n\t\t\tgotCluster, err := fakeClient.WaitForWatchCluster(ctx)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"xdsClient.WatchCDS failed with error: %v\", err)\n\t\t\t}\n\t\t\tif gotCluster != test.clusterName {\n\t\t\t\tt.Fatalf(\"xdsClient.WatchCDS called for cluster: %v, want: %v\", gotCluster, test.clusterName)\n\t\t\t}\n\t\t\t// Invoke callback with xds client with a certain clusterUpdate. Due\n\t\t\t// to this cluster update filling out the whole cluster tree, as the\n\t\t\t// cluster is of a root type (EDS or Logical DNS) and not an\n\t\t\t// aggregate cluster, this should trigger the ClusterHandler to\n\t\t\t// write to the update buffer to update the CDS policy.\n\t\t\tfakeClient.InvokeWatchClusterCallback(test.clusterUpdate, nil)\n\t\t\tselect {\n\t\t\tcase chu := <-ch.updateChannel:\n\t\t\t\tif diff := cmp.Diff(chu.updates, []xdsresource.ClusterUpdate{test.clusterUpdate}); diff != \"\" {\n\t\t\t\t\tt.Fatalf(\"got unexpected cluster update, diff (-got, +want): %v\", diff)\n\t\t\t\t}\n\t\t\t\tif diff := cmp.Diff(chu.lbPolicy, test.lbPolicy); diff != \"\" {\n\t\t\t\t\tt.Fatalf(\"got unexpected lb policy in cluster update, diff (-got, +want): %v\", diff)\n\t\t\t\t}\n\t\t\tcase <-ctx.Done():\n\t\t\t\tt.Fatal(\"Timed out waiting for update from update channel.\")\n\t\t\t}\n\t\t\t// Close the clusterHandler. This is meant to be called when the CDS\n\t\t\t// Balancer is closed, and the call should cancel the watch for this\n\t\t\t// cluster.\n\t\t\tch.close()\n\t\t\tclusterNameDeleted, err := fakeClient.WaitForCancelClusterWatch(ctx)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"xdsClient.CancelCDS failed with error: %v\", err)\n\t\t\t}\n\t\t\tif clusterNameDeleted != test.clusterName {\n\t\t\t\tt.Fatalf(\"xdsClient.CancelCDS called for cluster %v, want: %v\", clusterNameDeleted, logicalDNSService)\n\t\t\t}\n\t\t})\n\t}\n}", "func (updatePodConfig) reconcile(r *FoundationDBClusterReconciler, context ctx.Context, cluster *fdbtypes.FoundationDBCluster) *requeue {\n\tlogger := log.WithValues(\"namespace\", cluster.Namespace, \"cluster\", cluster.Name, \"reconciler\", \"updatePodConfig\")\n\tconfigMap, err := internal.GetConfigMap(cluster)\n\tif err != nil {\n\t\treturn &requeue{curError: err}\n\t}\n\n\tpods, err := r.PodLifecycleManager.GetPods(r, cluster, context, internal.GetPodListOptions(cluster, \"\", \"\")...)\n\tif err != nil {\n\t\treturn &requeue{curError: err}\n\t}\n\n\tpodMap := internal.CreatePodMap(cluster, pods)\n\n\tallSynced := true\n\thasUpdate := false\n\tvar errs []error\n\t// We try to update all instances and if we observe an error we add it to the error list.\n\tfor _, processGroup := range cluster.Status.ProcessGroups {\n\t\tcurLogger := logger.WithValues(\"processGroupID\", processGroup.ProcessGroupID)\n\n\t\tif processGroup.Remove {\n\t\t\tcurLogger.V(1).Info(\"Ignore process group marked for removal\")\n\t\t\tcontinue\n\t\t}\n\n\t\tif cluster.SkipProcessGroup(processGroup) {\n\t\t\tcurLogger.Info(\"Process group has pending Pod, will be skipped\")\n\t\t\tcontinue\n\t\t}\n\n\t\tpod, ok := podMap[processGroup.ProcessGroupID]\n\t\tif !ok || pod == nil {\n\t\t\tcurLogger.Info(\"Could not find Pod for process group\")\n\t\t\t// TODO (johscheuer): we should requeue if that happens.\n\t\t\tcontinue\n\t\t}\n\n\t\tserverPerPod, err := internal.GetStorageServersPerPodForPod(pod)\n\t\tif err != nil {\n\t\t\tcurLogger.Error(err, \"Error when receiving storage server per Pod\")\n\t\t\terrs = append(errs, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tprocessClass, err := podmanager.GetProcessClass(cluster, pod)\n\t\tif err != nil {\n\t\t\tcurLogger.Error(err, \"Error when fetching process class from Pod\")\n\t\t\terrs = append(errs, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tconfigMapHash, err := internal.GetDynamicConfHash(configMap, processClass, serverPerPod)\n\t\tif err != nil {\n\t\t\tcurLogger.Error(err, \"Error when receiving dynamic ConfigMap hash\")\n\t\t\terrs = append(errs, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif pod.ObjectMeta.Annotations[fdbtypes.LastConfigMapKey] == configMapHash {\n\t\t\tcontinue\n\t\t}\n\n\t\tsynced, err := r.updatePodDynamicConf(cluster, pod)\n\t\tif !synced {\n\t\t\tallSynced = false\n\t\t\thasUpdate = true\n\t\t\tcurLogger.Error(err, \"Update Pod ConfigMap annotation\")\n\t\t\tif internal.IsNetworkError(err) {\n\t\t\t\tprocessGroup.UpdateCondition(fdbtypes.SidecarUnreachable, true, cluster.Status.ProcessGroups, processGroup.ProcessGroupID)\n\t\t\t} else {\n\t\t\t\tprocessGroup.UpdateCondition(fdbtypes.IncorrectConfigMap, true, cluster.Status.ProcessGroups, processGroup.ProcessGroupID)\n\t\t\t}\n\n\t\t\tpod.ObjectMeta.Annotations[fdbtypes.OutdatedConfigMapKey] = time.Now().Format(time.RFC3339)\n\t\t\terr = r.PodLifecycleManager.UpdateMetadata(r, context, cluster, pod)\n\t\t\tif err != nil {\n\t\t\t\tallSynced = false\n\t\t\t\tcurLogger.Error(err, \"Update Pod ConfigMap annotation\")\n\t\t\t\terrs = append(errs, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tpod.ObjectMeta.Annotations[fdbtypes.LastConfigMapKey] = configMapHash\n\t\tdelete(pod.ObjectMeta.Annotations, fdbtypes.OutdatedConfigMapKey)\n\t\terr = r.PodLifecycleManager.UpdateMetadata(r, context, cluster, pod)\n\t\tif err != nil {\n\t\t\tallSynced = false\n\t\t\tcurLogger.Error(err, \"Update Pod metadata\")\n\t\t\terrs = append(errs, err)\n\t\t}\n\n\t\thasUpdate = true\n\t\tprocessGroup.UpdateCondition(fdbtypes.SidecarUnreachable, false, cluster.Status.ProcessGroups, processGroup.ProcessGroupID)\n\t}\n\n\tif hasUpdate {\n\t\terr = r.Status().Update(context, cluster)\n\t\tif err != nil {\n\t\t\treturn &requeue{curError: err}\n\t\t}\n\t}\n\n\t// If any error has happened requeue.\n\t// We don't provide an error here since we log all errors above.\n\tif len(errs) > 0 {\n\t\treturn &requeue{message: \"errors occurred during update pod config reconcile\"}\n\t}\n\n\t// If we return an error we don't requeue\n\t// So we just return that we can't continue but don't have an error\n\tif !allSynced {\n\t\treturn &requeue{message: \"Waiting for Pod to receive ConfigMap update\", delay: podSchedulingDelayDuration}\n\t}\n\n\treturn nil\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"aerospikecluster-controller\", mgr, controller.Options{Reconciler: r, MaxConcurrentReconciles: maxConcurrentReconciles})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource AerospikeCluster\n\terr = c.Watch(\n\t\t&source.Kind{Type: &aerospikev1alpha1.AerospikeCluster{}},\n\t\t&handler.EnqueueRequestForObject{},\n\t\t// Skip where cluster object generation is not changed\n\t\tpredicate.GenerationChangedPredicate{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// TODO: Do we need to monitor this? Statefulset is updated many times in reconcile and this add new entry in\n\t// update queue. If user will change only cr then we may not need to monitor statefulset.\n\t// Think all possible situation\n\n\t// Watch for changes to secondary resource StatefulSet and requeue the owner AerospikeCluster\n\terr = c.Watch(\n\t\t&source.Kind{Type: &appsv1.StatefulSet{}},\n\t\t&handler.EnqueueRequestForOwner{\n\t\t\tIsController: true,\n\t\t\tOwnerType: &aerospikev1alpha1.AerospikeCluster{},\n\t\t}, predicate.Funcs{\n\t\t\tCreateFunc: func(e event.CreateEvent) bool {\n\t\t\t\treturn false\n\t\t\t},\n\t\t\tUpdateFunc: func(e event.UpdateEvent) bool {\n\t\t\t\treturn false\n\t\t\t},\n\t\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s) TestClusterUpdate_Success(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tclusterResource *v3clusterpb.Cluster\n\t\twantChildCfg serviceconfig.LoadBalancingConfig\n\t}{\n\t\t{\n\t\t\tname: \"happy-case-with-circuit-breakers\",\n\t\t\tclusterResource: func() *v3clusterpb.Cluster {\n\t\t\t\tc := e2e.DefaultCluster(clusterName, serviceName, e2e.SecurityLevelNone)\n\t\t\t\tc.CircuitBreakers = &v3clusterpb.CircuitBreakers{\n\t\t\t\t\tThresholds: []*v3clusterpb.CircuitBreakers_Thresholds{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tPriority: v3corepb.RoutingPriority_DEFAULT,\n\t\t\t\t\t\t\tMaxRequests: wrapperspb.UInt32(512),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tPriority: v3corepb.RoutingPriority_HIGH,\n\t\t\t\t\t\t\tMaxRequests: nil,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\treturn c\n\t\t\t}(),\n\t\t\twantChildCfg: &clusterresolver.LBConfig{\n\t\t\t\tDiscoveryMechanisms: []clusterresolver.DiscoveryMechanism{{\n\t\t\t\t\tCluster: clusterName,\n\t\t\t\t\tType: clusterresolver.DiscoveryMechanismTypeEDS,\n\t\t\t\t\tEDSServiceName: serviceName,\n\t\t\t\t\tMaxConcurrentRequests: newUint32(512),\n\t\t\t\t\tOutlierDetection: json.RawMessage(`{}`),\n\t\t\t\t}},\n\t\t\t\tXDSLBPolicy: json.RawMessage(`[{\"xds_wrr_locality_experimental\": {\"childPolicy\": [{\"round_robin\": {}}]}}]`),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"happy-case-with-ring-hash-lb-policy\",\n\t\t\tclusterResource: func() *v3clusterpb.Cluster {\n\t\t\t\tc := e2e.ClusterResourceWithOptions(e2e.ClusterOptions{\n\t\t\t\t\tClusterName: clusterName,\n\t\t\t\t\tServiceName: serviceName,\n\t\t\t\t\tSecurityLevel: e2e.SecurityLevelNone,\n\t\t\t\t\tPolicy: e2e.LoadBalancingPolicyRingHash,\n\t\t\t\t})\n\t\t\t\tc.LbConfig = &v3clusterpb.Cluster_RingHashLbConfig_{\n\t\t\t\t\tRingHashLbConfig: &v3clusterpb.Cluster_RingHashLbConfig{\n\t\t\t\t\t\tMinimumRingSize: &wrapperspb.UInt64Value{Value: 100},\n\t\t\t\t\t\tMaximumRingSize: &wrapperspb.UInt64Value{Value: 1000},\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\treturn c\n\t\t\t}(),\n\t\t\twantChildCfg: &clusterresolver.LBConfig{\n\t\t\t\tDiscoveryMechanisms: []clusterresolver.DiscoveryMechanism{{\n\t\t\t\t\tCluster: clusterName,\n\t\t\t\t\tType: clusterresolver.DiscoveryMechanismTypeEDS,\n\t\t\t\t\tEDSServiceName: serviceName,\n\t\t\t\t\tOutlierDetection: json.RawMessage(`{}`),\n\t\t\t\t}},\n\t\t\t\tXDSLBPolicy: json.RawMessage(`[{\"ring_hash_experimental\": {\"minRingSize\":100, \"maxRingSize\":1000}}]`),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"happy-case-outlier-detection-xds-defaults\", // OD proto set but no proto fields set\n\t\t\tclusterResource: func() *v3clusterpb.Cluster {\n\t\t\t\tc := e2e.ClusterResourceWithOptions(e2e.ClusterOptions{\n\t\t\t\t\tClusterName: clusterName,\n\t\t\t\t\tServiceName: serviceName,\n\t\t\t\t\tSecurityLevel: e2e.SecurityLevelNone,\n\t\t\t\t\tPolicy: e2e.LoadBalancingPolicyRingHash,\n\t\t\t\t})\n\t\t\t\tc.OutlierDetection = &v3clusterpb.OutlierDetection{}\n\t\t\t\treturn c\n\t\t\t}(),\n\t\t\twantChildCfg: &clusterresolver.LBConfig{\n\t\t\t\tDiscoveryMechanisms: []clusterresolver.DiscoveryMechanism{{\n\t\t\t\t\tCluster: clusterName,\n\t\t\t\t\tType: clusterresolver.DiscoveryMechanismTypeEDS,\n\t\t\t\t\tEDSServiceName: serviceName,\n\t\t\t\t\tOutlierDetection: json.RawMessage(`{\"successRateEjection\":{}}`),\n\t\t\t\t}},\n\t\t\t\tXDSLBPolicy: json.RawMessage(`[{\"ring_hash_experimental\": {\"minRingSize\":1024, \"maxRingSize\":8388608}}]`),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"happy-case-outlier-detection-all-fields-set\",\n\t\t\tclusterResource: func() *v3clusterpb.Cluster {\n\t\t\t\tc := e2e.ClusterResourceWithOptions(e2e.ClusterOptions{\n\t\t\t\t\tClusterName: clusterName,\n\t\t\t\t\tServiceName: serviceName,\n\t\t\t\t\tSecurityLevel: e2e.SecurityLevelNone,\n\t\t\t\t\tPolicy: e2e.LoadBalancingPolicyRingHash,\n\t\t\t\t})\n\t\t\t\tc.OutlierDetection = &v3clusterpb.OutlierDetection{\n\t\t\t\t\tInterval: durationpb.New(10 * time.Second),\n\t\t\t\t\tBaseEjectionTime: durationpb.New(30 * time.Second),\n\t\t\t\t\tMaxEjectionTime: durationpb.New(300 * time.Second),\n\t\t\t\t\tMaxEjectionPercent: wrapperspb.UInt32(10),\n\t\t\t\t\tSuccessRateStdevFactor: wrapperspb.UInt32(1900),\n\t\t\t\t\tEnforcingSuccessRate: wrapperspb.UInt32(100),\n\t\t\t\t\tSuccessRateMinimumHosts: wrapperspb.UInt32(5),\n\t\t\t\t\tSuccessRateRequestVolume: wrapperspb.UInt32(100),\n\t\t\t\t\tFailurePercentageThreshold: wrapperspb.UInt32(85),\n\t\t\t\t\tEnforcingFailurePercentage: wrapperspb.UInt32(5),\n\t\t\t\t\tFailurePercentageMinimumHosts: wrapperspb.UInt32(5),\n\t\t\t\t\tFailurePercentageRequestVolume: wrapperspb.UInt32(50),\n\t\t\t\t}\n\t\t\t\treturn c\n\t\t\t}(),\n\t\t\twantChildCfg: &clusterresolver.LBConfig{\n\t\t\t\tDiscoveryMechanisms: []clusterresolver.DiscoveryMechanism{{\n\t\t\t\t\tCluster: clusterName,\n\t\t\t\t\tType: clusterresolver.DiscoveryMechanismTypeEDS,\n\t\t\t\t\tEDSServiceName: serviceName,\n\t\t\t\t\tOutlierDetection: json.RawMessage(`{\n\t\t\t\t\t\t\"interval\": \"10s\",\n\t\t\t\t\t\t\"baseEjectionTime\": \"30s\",\n\t\t\t\t\t\t\"maxEjectionTime\": \"300s\",\n\t\t\t\t\t\t\"maxEjectionPercent\": 10,\n\t\t\t\t\t\t\"successRateEjection\": {\n\t\t\t\t\t\t\t\"stdevFactor\": 1900,\n\t\t\t\t\t\t\t\"enforcementPercentage\": 100,\n\t\t\t\t\t\t\t\"minimumHosts\": 5,\n\t\t\t\t\t\t\t\"requestVolume\": 100\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"failurePercentageEjection\": {\n\t\t\t\t\t\t\t\"threshold\": 85,\n\t\t\t\t\t\t\t\"enforcementPercentage\": 5,\n\t\t\t\t\t\t\t\"minimumHosts\": 5,\n\t\t\t\t\t\t\t\"requestVolume\": 50\n\t\t\t\t\t\t}\n\t\t\t\t\t}`),\n\t\t\t\t}},\n\t\t\t\tXDSLBPolicy: json.RawMessage(`[{\"ring_hash_experimental\": {\"minRingSize\":1024, \"maxRingSize\":8388608}}]`),\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tlbCfgCh, _, _, _ := registerWrappedClusterResolverPolicy(t)\n\t\t\tmgmtServer, nodeID, _, _, _, _, _ := setupWithManagementServer(t)\n\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)\n\t\t\tdefer cancel()\n\t\t\tif err := mgmtServer.Update(ctx, e2e.UpdateOptions{\n\t\t\t\tNodeID: nodeID,\n\t\t\t\tClusters: []*v3clusterpb.Cluster{test.clusterResource},\n\t\t\t\tSkipValidation: true,\n\t\t\t}); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tif err := compareLoadBalancingConfig(ctx, lbCfgCh, test.wantChildCfg); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t})\n\t}\n}", "func (r *ReconcileAerospikeCluster) cleanupPods(aeroCluster *aerospikev1alpha1.AerospikeCluster, podNames []string, rackState RackState) error {\n\tlogger := pkglog.New(log.Ctx{\"AerospikeCluster\": utils.ClusterNamespacedName(aeroCluster)})\n\n\tlogger.Info(\"Removing pvc for removed pods\", log.Ctx{\"pods\": podNames})\n\n\t// Delete PVCs if cascadeDelete\n\tpvcItems, err := r.getPodsPVCList(aeroCluster, podNames, rackState.Rack.ID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not find pvc for pods %v: %v\", podNames, err)\n\t}\n\tstorage := rackState.Rack.Storage\n\tif err := r.removePVCs(aeroCluster, &storage, pvcItems); err != nil {\n\t\treturn fmt.Errorf(\"Could not cleanup pod PVCs: %v\", err)\n\t}\n\n\tneedStatusCleanup := []string{}\n\n\tclusterPodList, err := r.getClusterPodList(aeroCluster)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not cleanup pod PVCs: %v\", err)\n\t}\n\n\tfor _, podName := range podNames {\n\t\t// Clear references to this pod in the running cluster.\n\t\tfor _, np := range clusterPodList.Items {\n\t\t\t// TODO: We remove node from the end. Nodes will not have seed of successive nodes\n\t\t\t// So this will be no op.\n\t\t\t// We should tip in all nodes the same seed list,\n\t\t\t// then only this will have any impact. Is it really necessary?\n\n\t\t\t// TODO: tip after scaleup and create\n\t\t\t// All nodes from other rack\n\t\t\tr.tipClearHostname(aeroCluster, &np, podName)\n\n\t\t\tr.alumniReset(aeroCluster, &np)\n\t\t}\n\n\t\tif aeroCluster.Spec.MultiPodPerHost {\n\t\t\t// Remove service for pod\n\t\t\t// TODO: make it more roboust, what if it fails\n\t\t\tif err := r.deleteServiceForPod(podName, aeroCluster.Namespace); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t_, ok := aeroCluster.Status.Pods[podName]\n\t\tif ok {\n\t\t\tneedStatusCleanup = append(needStatusCleanup, podName)\n\t\t}\n\t}\n\n\tif len(needStatusCleanup) > 0 {\n\t\tlogger.Info(\"Removing pod status for dangling pods\", log.Ctx{\"pods\": podNames})\n\n\t\tif err := r.removePodStatus(aeroCluster, needStatusCleanup); err != nil {\n\t\t\treturn fmt.Errorf(\"Could not cleanup pod status: %v\", err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *Controller) managePodScaleDown(admin submarine.AdminInterface, cluster *rapi.SubmarineCluster, rCluster *submarine.Cluster, nodes submarine.Nodes) (bool, error) {\n\treturn true, nil\n}", "func TestInterPodAffinityAnnotationsWithMultipleNodes(t *testing.T) {\n\tutilfeature.DefaultFeatureGate.Set(\"AffinityInAnnotations=true\")\n\tpodLabelA := map[string]string{\n\t\t\"foo\": \"bar\",\n\t}\n\tlabelRgChina := map[string]string{\n\t\t\"region\": \"China\",\n\t}\n\tlabelRgChinaAzAz1 := map[string]string{\n\t\t\"region\": \"China\",\n\t\t\"az\": \"az1\",\n\t}\n\tlabelRgIndia := map[string]string{\n\t\t\"region\": \"India\",\n\t}\n\ttests := []struct {\n\t\tpod *v1.Pod\n\t\tpods []*v1.Pod\n\t\tnodes []v1.Node\n\t\tfits map[string]bool\n\t\ttest string\n\t}{\n\t\t{\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\tv1.AffinityAnnotationKey: `\n\t\t\t\t\t\t{\"podAffinity\": {\n\t\t\t\t\t\t\t\"requiredDuringSchedulingIgnoredDuringExecution\": [{\n\t\t\t\t\t\t\t\t\"labelSelector\": {\n\t\t\t\t\t\t\t\t\t\"matchExpressions\": [{\n\t\t\t\t\t\t\t\t\t\t\"key\": \"foo\",\n\t\t\t\t\t\t\t\t\t\t\"operator\": \"In\",\n\t\t\t\t\t\t\t\t\t\t\"values\": [\"bar\"]\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\"topologyKey\": \"region\"\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\tpods: []*v1.Pod{\n\t\t\t\t{Spec: v1.PodSpec{NodeName: \"machine1\"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelA}},\n\t\t\t},\n\t\t\tnodes: []v1.Node{\n\t\t\t\t{ObjectMeta: metav1.ObjectMeta{Name: \"machine1\", Labels: labelRgChina}},\n\t\t\t\t{ObjectMeta: metav1.ObjectMeta{Name: \"machine2\", Labels: labelRgChinaAzAz1}},\n\t\t\t\t{ObjectMeta: metav1.ObjectMeta{Name: \"machine3\", Labels: labelRgIndia}},\n\t\t\t},\n\t\t\tfits: map[string]bool{\n\t\t\t\t\"machine1\": true,\n\t\t\t\t\"machine2\": true,\n\t\t\t\t\"machine3\": false,\n\t\t\t},\n\t\t\ttest: \"A pod can be scheduled onto all the nodes that have the same topology key & label value with one of them has an existing pod that match the affinity rules\",\n\t\t},\n\t\t{\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\tv1.AffinityAnnotationKey: `\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"nodeAffinity\": {\n\t\t\t\t\t\t\t\t\"requiredDuringSchedulingIgnoredDuringExecution\": {\n\t\t\t\t\t\t\t\t\t\"nodeSelectorTerms\": [{\n\t\t\t\t\t\t\t\t\t\t\"matchExpressions\": [{\n\t\t\t\t\t\t\t\t\t\t\t\"key\": \"hostname\",\n\t\t\t\t\t\t\t\t\t\t\t\"operator\": \"NotIn\",\n\t\t\t\t\t\t\t\t\t\t\t\"values\": [\"h1\"]\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\t\"podAffinity\": {\n\t\t\t\t\t\t\t\t\"requiredDuringSchedulingIgnoredDuringExecution\": [{\n\t\t\t\t\t\t\t\t\t\"labelSelector\": {\n\t\t\t\t\t\t\t\t\t\t\"matchExpressions\": [{\n\t\t\t\t\t\t\t\t\t\t\t\"key\": \"foo\",\n\t\t\t\t\t\t\t\t\t\t\t\"operator\": \"In\",\n\t\t\t\t\t\t\t\t\t\t\t\"values\": [\"abc\"]\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\t\"topologyKey\": \"region\"\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\tpods: []*v1.Pod{\n\t\t\t\t{Spec: v1.PodSpec{NodeName: \"nodeA\"}, ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{\"foo\": \"abc\"}}},\n\t\t\t\t{Spec: v1.PodSpec{NodeName: \"nodeB\"}, ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{\"foo\": \"def\"}}},\n\t\t\t},\n\t\t\tnodes: []v1.Node{\n\t\t\t\t{ObjectMeta: metav1.ObjectMeta{Name: \"nodeA\", Labels: map[string]string{\"region\": \"r1\", \"hostname\": \"h1\"}}},\n\t\t\t\t{ObjectMeta: metav1.ObjectMeta{Name: \"nodeB\", Labels: map[string]string{\"region\": \"r1\", \"hostname\": \"h2\"}}},\n\t\t\t},\n\t\t\tfits: map[string]bool{\n\t\t\t\t\"nodeA\": false,\n\t\t\t\t\"nodeB\": true,\n\t\t\t},\n\t\t\ttest: \"NodeA and nodeB have same topologyKey and label value. NodeA does not satisfy node affinity rule, but has an existing pod that match the inter pod affinity rule. The pod can be scheduled onto nodeB.\",\n\t\t},\n\t\t{\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\"foo\": \"bar\",\n\t\t\t\t\t},\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\tv1.AffinityAnnotationKey: `\n\t\t\t\t\t\t{\"podAffinity\": {\n\t\t\t\t\t\t\t\"requiredDuringSchedulingIgnoredDuringExecution\": [{\n\t\t\t\t\t\t\t\t\"labelSelector\": {\n\t\t\t\t\t\t\t\t\t\"matchExpressions\": [{\n\t\t\t\t\t\t\t\t\t\t\"key\": \"foo\",\n\t\t\t\t\t\t\t\t\t\t\"operator\": \"In\",\n\t\t\t\t\t\t\t\t\t\t\"values\": [\"bar\"]\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\"topologyKey\": \"zone\"\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\tpods: []*v1.Pod{},\n\t\t\tnodes: []v1.Node{\n\t\t\t\t{ObjectMeta: metav1.ObjectMeta{Name: \"nodeA\", Labels: map[string]string{\"zone\": \"az1\", \"hostname\": \"h1\"}}},\n\t\t\t\t{ObjectMeta: metav1.ObjectMeta{Name: \"nodeB\", Labels: map[string]string{\"zone\": \"az2\", \"hostname\": \"h2\"}}},\n\t\t\t},\n\t\t\tfits: map[string]bool{\n\t\t\t\t\"nodeA\": true,\n\t\t\t\t\"nodeB\": true,\n\t\t\t},\n\t\t\ttest: \"The affinity rule is to schedule all of the pods of this collection to the same zone. The first pod of the collection \" +\n\t\t\t\t\"should not be blocked from being scheduled onto any node, even there's no existing pod that match the rule anywhere.\",\n\t\t},\n\t\t{\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\tv1.AffinityAnnotationKey: `\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"podAntiAffinity\": {\n\t\t\t\t\t\t\t\t\"requiredDuringSchedulingIgnoredDuringExecution\": [{\n\t\t\t\t\t\t\t\t\t\"labelSelector\": {\n\t\t\t\t\t\t\t\t\t\t\"matchExpressions\": [{\n\t\t\t\t\t\t\t\t\t\t\t\"key\": \"foo\",\n\t\t\t\t\t\t\t\t\t\t\t\"operator\": \"In\",\n\t\t\t\t\t\t\t\t\t\t\t\"values\": [\"abc\"]\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\t\"topologyKey\": \"region\"\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\tpods: []*v1.Pod{\n\t\t\t\t{Spec: v1.PodSpec{NodeName: \"nodeA\"}, ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{\"foo\": \"abc\"}}},\n\t\t\t},\n\t\t\tnodes: []v1.Node{\n\t\t\t\t{ObjectMeta: metav1.ObjectMeta{Name: \"nodeA\", Labels: map[string]string{\"region\": \"r1\", \"hostname\": \"nodeA\"}}},\n\t\t\t\t{ObjectMeta: metav1.ObjectMeta{Name: \"nodeB\", Labels: map[string]string{\"region\": \"r1\", \"hostname\": \"nodeB\"}}},\n\t\t\t},\n\t\t\tfits: map[string]bool{\n\t\t\t\t\"nodeA\": false,\n\t\t\t\t\"nodeB\": false,\n\t\t\t},\n\t\t\ttest: \"NodeA and nodeB have same topologyKey and label value. NodeA has an existing pod that match the inter pod affinity rule. The pod can not be scheduled onto nodeA and nodeB.\",\n\t\t},\n\t\t{\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\tv1.AffinityAnnotationKey: `\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"podAntiAffinity\": {\n\t\t\t\t\t\t\t\t\"requiredDuringSchedulingIgnoredDuringExecution\": [{\n\t\t\t\t\t\t\t\t\t\"labelSelector\": {\n\t\t\t\t\t\t\t\t\t\t\"matchExpressions\": [{\n\t\t\t\t\t\t\t\t\t\t\t\"key\": \"foo\",\n\t\t\t\t\t\t\t\t\t\t\t\"operator\": \"In\",\n\t\t\t\t\t\t\t\t\t\t\t\"values\": [\"abc\"]\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\t\"topologyKey\": \"region\"\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\tpods: []*v1.Pod{\n\t\t\t\t{Spec: v1.PodSpec{NodeName: \"nodeA\"}, ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{\"foo\": \"abc\"}}},\n\t\t\t},\n\t\t\tnodes: []v1.Node{\n\t\t\t\t{ObjectMeta: metav1.ObjectMeta{Name: \"nodeA\", Labels: labelRgChina}},\n\t\t\t\t{ObjectMeta: metav1.ObjectMeta{Name: \"nodeB\", Labels: labelRgChinaAzAz1}},\n\t\t\t\t{ObjectMeta: metav1.ObjectMeta{Name: \"nodeC\", Labels: labelRgIndia}},\n\t\t\t},\n\t\t\tfits: map[string]bool{\n\t\t\t\t\"nodeA\": false,\n\t\t\t\t\"nodeB\": false,\n\t\t\t\t\"nodeC\": true,\n\t\t\t},\n\t\t\ttest: \"NodeA and nodeB have same topologyKey and label value. NodeA has an existing pod that match the inter pod affinity rule. The pod can not be scheduled onto nodeA and nodeB but can be schedulerd onto nodeC\",\n\t\t},\n\t}\n\taffinityExpectedFailureReasons := []algorithm.PredicateFailureReason{ErrPodAffinityNotMatch}\n\tselectorExpectedFailureReasons := []algorithm.PredicateFailureReason{ErrNodeSelectorNotMatch}\n\n\tfor _, test := range tests {\n\t\tnodeListInfo := FakeNodeListInfo(test.nodes)\n\t\tfor _, node := range test.nodes {\n\t\t\tvar podsOnNode []*v1.Pod\n\t\t\tfor _, pod := range test.pods {\n\t\t\t\tif pod.Spec.NodeName == node.Name {\n\t\t\t\t\tpodsOnNode = append(podsOnNode, pod)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttestFit := PodAffinityChecker{\n\t\t\t\tinfo: nodeListInfo,\n\t\t\t\tpodLister: schedulertesting.FakePodLister(test.pods),\n\t\t\t}\n\t\t\tnodeInfo := schedulercache.NewNodeInfo(podsOnNode...)\n\t\t\tnodeInfo.SetNode(&node)\n\t\t\tnodeInfoMap := map[string]*schedulercache.NodeInfo{node.Name: nodeInfo}\n\t\t\tfits, reasons, err := testFit.InterPodAffinityMatches(test.pod, PredicateMetadata(test.pod, nodeInfoMap), nodeInfo)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"%s: unexpected error %v\", test.test, err)\n\t\t\t}\n\t\t\tif !fits && !reflect.DeepEqual(reasons, affinityExpectedFailureReasons) {\n\t\t\t\tt.Errorf(\"%s: unexpected failure reasons: %v\", test.test, reasons)\n\t\t\t}\n\t\t\taffinity, err := v1helper.GetAffinityFromPodAnnotations(test.pod.ObjectMeta.Annotations)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"%s: unexpected error: %v\", test.test, err)\n\t\t\t}\n\t\t\tif affinity != nil && affinity.NodeAffinity != nil {\n\t\t\t\tnodeInfo := schedulercache.NewNodeInfo()\n\t\t\t\tnodeInfo.SetNode(&node)\n\t\t\t\tnodeInfoMap := map[string]*schedulercache.NodeInfo{node.Name: nodeInfo}\n\t\t\t\tfits2, reasons, err := PodMatchNodeSelector(test.pod, PredicateMetadata(test.pod, nodeInfoMap), nodeInfo)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(\"%s: unexpected error: %v\", test.test, err)\n\t\t\t\t}\n\t\t\t\tif !fits2 && !reflect.DeepEqual(reasons, selectorExpectedFailureReasons) {\n\t\t\t\t\tt.Errorf(\"%s: unexpected failure reasons: %v, want: %v\", test.test, reasons, selectorExpectedFailureReasons)\n\t\t\t\t}\n\t\t\t\tfits = fits && fits2\n\t\t\t}\n\n\t\t\tif fits != test.fits[node.Name] {\n\t\t\t\tt.Errorf(\"%s: expected %v for %s got %v\", test.test, test.fits[node.Name], node.Name, fits)\n\t\t\t}\n\t\t}\n\t}\n}", "func getScaleUpStatus(ctx context.Context, c clientset.Interface) (*scaleUpStatus, error) {\n\tconfigMap, err := c.CoreV1().ConfigMaps(\"kube-system\").Get(ctx, \"cluster-autoscaler-status\", metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstatus, ok := configMap.Data[\"status\"]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Status information not found in configmap\")\n\t}\n\n\ttimestamp, err := getStatusTimestamp(status)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmatcher, err := regexp.Compile(\"s*ScaleUp:\\\\s*([A-Za-z]+)\\\\s*\\\\(ready=([0-9]+)\\\\s*cloudProviderTarget=([0-9]+)\\\\s*\\\\)\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmatches := matcher.FindAllStringSubmatch(status, -1)\n\tif len(matches) < 1 {\n\t\treturn nil, fmt.Errorf(\"Failed to parse CA status configmap, raw status: %v\", status)\n\t}\n\n\tresult := scaleUpStatus{\n\t\tstatus: caNoScaleUpStatus,\n\t\tready: 0,\n\t\ttarget: 0,\n\t\ttimestamp: timestamp,\n\t}\n\tfor _, match := range matches {\n\t\tif match[1] == caOngoingScaleUpStatus {\n\t\t\tresult.status = caOngoingScaleUpStatus\n\t\t}\n\t\tnewReady, err := strconv.Atoi(match[2])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult.ready += newReady\n\t\tnewTarget, err := strconv.Atoi(match[3])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult.target += newTarget\n\t}\n\tklog.Infof(\"Cluster-Autoscaler scale-up status: %v (%v, %v)\", result.status, result.ready, result.target)\n\treturn &result, nil\n}", "func updateEmptyClusterStateMetrics() {\n\tmetrics.UpdateClusterSafeToAutoscale(false)\n\tmetrics.UpdateNodesCount(0, 0, 0, 0, 0)\n}", "func main() {\n\tdestCfg, err := config.GetConfig()\n\tdestCfg.Burst = 1000\n\tdestCfg.QPS = 1000\n\toldKubeConfigEnv := os.Getenv(\"KUBECONFIG\")\n\tos.Setenv(\"KUBECONFIG\", os.Getenv(\"HOME\")+\"/.kube/config\")\n\tsrcCfg, err := config.GetConfig()\n\tsrcCfg.Burst = 1000\n\tsrcCfg.QPS = 1000\n\tos.Setenv(\"KUBECONFIG\", oldKubeConfigEnv)\n\n\tscheme := runtime.NewScheme()\n\tif err := routev1.AddToScheme(scheme); err != nil {\n\t\tlog.Fatal(err, \"unable to add routev1 scheme\")\n\t}\n\tif err := v1.AddToScheme(scheme); err != nil {\n\t\tlog.Fatal(err, \"unable to add v1 scheme\")\n\t}\n\tif err := corev1.AddToScheme(scheme); err != nil {\n\n\t\tlog.Fatal(err, \"unable to add corev1 scheme\")\n\t}\n\n\tsrcClient, err := client.New(srcCfg, client.Options{Scheme: scheme})\n\tif err != nil {\n\t\tlog.Fatal(err, \"unable to create source client\")\n\t}\n\n\tdestClient, err := client.New(destCfg, client.Options{Scheme: scheme})\n\tif err != nil {\n\t\tlog.Fatal(err, \"unable to create destination client\")\n\t}\n\n\t// quiesce the applications if needed on the source side\n\terr = state_transfer.QuiesceApplications(srcCfg, srcNamespace)\n\tif err != nil {\n\t\tlog.Fatal(err, \"unable to quiesce application on source cluster\")\n\t}\n\n\t// set up the PVC on destination to receive the data\n\tpvc := &corev1.PersistentVolumeClaim{}\n\terr = srcClient.Get(context.TODO(), client.ObjectKey{Namespace: srcNamespace, Name: srcPVC}, pvc)\n\tif err != nil {\n\t\tlog.Fatal(err, \"unable to get source PVC\")\n\t}\n\n\tdestPVC := pvc.DeepCopy()\n\n\tdestPVC.ResourceVersion = \"\"\n\tdestPVC.Spec.VolumeName = \"\"\n\tpvc.Annotations = map[string]string{}\n\terr = destClient.Create(context.TODO(), destPVC, &client.CreateOptions{})\n\tif err != nil {\n\t\tlog.Fatal(err, \"unable to create destination PVC\")\n\t}\n\n\tpvcList, err := transfer.NewPVCPairList(\n\t\ttransfer.NewPVCPair(pvc, destPVC),\n\t)\n\tif err != nil {\n\t\tlog.Fatal(err, \"invalid pvc list\")\n\t}\n\n\tendpointPort := int32(2222)\n\t// create a route for data transfer\n\tr := route.NewEndpoint(\n\t\ttypes.NamespacedName{\n\t\t\tNamespace: pvc.Namespace,\n\t\t\tName: pvc.Name,\n\t\t}, endpointPort, route.EndpointTypePassthrough, labels.Labels)\n\te, err := endpoint.Create(r, destClient)\n\tif err != nil {\n\t\tlog.Fatal(err, \"unable to create route endpoint\")\n\t}\n\n\t_ = wait.PollUntil(time.Second*5, func() (done bool, err error) {\n\t\tready, err := e.IsHealthy(destClient)\n\t\tif err != nil {\n\t\t\tlog.Println(err, \"unable to check route health, retrying...\")\n\t\t\treturn false, nil\n\t\t}\n\t\treturn ready, nil\n\t}, make(<-chan struct{}))\n\n\t// create an stunnel transport to carry the data over the route\n\tproxyOptions := transport.ProxyOptions{\n\t\tURL: \"127.0.0.1\",\n\t\tUsername: \"foo\",\n\t\tPassword: \"bar\",\n\t}\n\ts := stunnel.NewTransport(&proxyOptions)\n\t_, err = transport.CreateServer(s, srcClient, e)\n\tif err != nil {\n\t\tlog.Fatal(err, \"error creating stunnel client\")\n\t}\n\n\t//_, err = transport.CreateClient(s, destClient, e)\n\t//if err != nil {\n\t//\tlog.Fatal(err, \"error creating stunnel server\")\n\t//}\n\n\t// Create Rclone Transfer Pod\n\tt, err := rclone.NewTransfer(s, r, srcCfg, destCfg, pvcList)\n\tif err != nil {\n\t\tlog.Fatal(err, \"errror creating rclone transfer\")\n\t}\n\n\terr = transfer.CreateServer(t)\n\tif err != nil {\n\t\tlog.Fatal(err, \"error creating rclone server\")\n\t}\n\n\t// Create Rclone Client Pod\n\terr = transfer.CreateClient(t)\n\tif err != nil {\n\t\tlog.Fatal(err, \"error creating rclone client\")\n\t}\n\n\t// TODO: check if the client is completed\n}", "func (r *Microk8sConfigReconciler) Reconcile(req ctrl.Request) (_ ctrl.Result, rerr error) {\n\tctx := context.Background()\n\tlog := r.Log.WithValues(\"microk8sconfig\", req.NamespacedName)\n\n\t// your logic here\n\tmicrok8sconfig := &bootstrapv1alpha1.Microk8sConfig{}\n\n\tif err := r.Client.Get(ctx, req.NamespacedName, microk8sconfig); err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn ctrl.Result{}, nil\n\t\t}\n\t\tlog.Error(err, \"failed to get config\")\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t// Look up the owner of this KubeConfig if there is one\n\tconfigOwner, err := bsutil.GetConfigOwner(ctx, r.Client, microk8sconfig)\n\tif apierrors.IsNotFound(err) {\n\t\t// Could not find the owner yet, this is not an error and will rereconcile when the owner gets set.\n\t\treturn ctrl.Result{}, nil\n\t}\n\tif err != nil {\n\t\tlog.Error(err, \"failed to get owner\")\n\t\treturn ctrl.Result{}, err\n\t}\n\tif configOwner == nil {\n\t\tlog.Error(err, \"failed to get config-owner\")\n\t\treturn ctrl.Result{}, nil\n\t}\n\tlog = log.WithValues(\"kind\", configOwner.GetKind(), \"version\", configOwner.GetResourceVersion(), \"name\", configOwner.GetName())\n\n\t// Initialize the patch helper\n\tpatchHelper, err := patch.NewHelper(microk8sconfig, r)\n\tif err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\n\tif configOwner.IsControlPlaneMachine() {\n\t\t_, err := r.setupControlPlaneBootstrapData(ctx, microk8sconfig)\n\t\tif err != nil {\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t\treturn ctrl.Result{}, patchHelper.Patch(ctx, microk8sconfig)\n\t} else {\n\t\t// Worker node\n\t\t_, err := r.setupWorkerBootstrapData(ctx, microk8sconfig)\n\t\tif err != nil {\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t\treturn ctrl.Result{}, patchHelper.Patch(ctx, microk8sconfig)\n\t}\n}", "func (worker *K8sControllerDiscoveryWorker) Do(cluster *repository.ClusterSummary, kubeControllers []*repository.KubeController) ([]*proto.EntityDTO, error) {\n\tnamespacesMap := worker.cluster.NamespaceMap\n\t// Map from controller UID to the corresponding kubeController\n\tkubeControllersMap := make(map[string]*repository.KubeController)\n\t// Combine the pods and allocation resources usage from different discovery workers but belonging to the same K8s controller.\n\tfor _, kubeController := range kubeControllers {\n\t\texistingKubeController, exists := kubeControllersMap[kubeController.UID]\n\t\tif !exists {\n\t\t\tkubeNamespace, exists := namespacesMap[kubeController.Namespace]\n\t\t\tif !exists {\n\t\t\t\tglog.Errorf(\"Namespace %s does not exist in cluster %s\", kubeController.Namespace, worker.cluster.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\taverageNodeCpuFrequency := kubeNamespace.AverageNodeCpuFrequency\n\t\t\tif averageNodeCpuFrequency <= 0.0 {\n\t\t\t\tglog.Errorf(\"Average node CPU frequency is not larger than zero in namespace %s. Skip KubeController %s\",\n\t\t\t\t\tkubeNamespace.Name, kubeController.GetFullName())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor resourceType, resource := range kubeController.AllocationResources {\n\t\t\t\t// For CPU resources, convert the capacity values expressed in number of cores to MHz.\n\t\t\t\t// Skip the conversion if capacity value is repository.DEFAULT_METRIC_CAPACITY_VALUE (infinity), which\n\t\t\t\t// means resource quota is not configured on the corresponding namespace.\n\t\t\t\tif metrics.IsCPUType(resourceType) && resource.Capacity != repository.DEFAULT_METRIC_CAPACITY_VALUE {\n\t\t\t\t\tnewCapacity := resource.Capacity * kubeNamespace.AverageNodeCpuFrequency\n\t\t\t\t\tglog.V(4).Infof(\"Changing capacity of %s::%s from %f cores to %f MHz\",\n\t\t\t\t\t\tkubeController.GetFullName(), resourceType, resource.Capacity, newCapacity)\n\t\t\t\t\tresource.Capacity = newCapacity\n\t\t\t\t}\n\t\t\t}\n\t\t\tkubeControllersMap[kubeController.UID] = kubeController\n\t\t} else {\n\t\t\tfor resourceType, resource := range existingKubeController.AllocationResources {\n\t\t\t\tusedValue, err := kubeController.GetResourceUsed(resourceType)\n\t\t\t\tif err != nil {\n\t\t\t\t\tglog.Error(err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// Aggregate allocation resource usage of the same kubeController discovered by different discovery worker.\n\t\t\t\t// The usage values of CPU resources have already been converted from cores to MHz based on the CPU\n\t\t\t\t// frequency of the corresponding node in controller_metrics_collector.\n\t\t\t\tresource.Used += usedValue\n\t\t\t}\n\t\t\t// Update the pod lists of the existing KubeController\n\t\t\texistingKubeController.Pods = append(existingKubeController.Pods, kubeController.Pods...)\n\t\t}\n\n\t}\n\tfor _, kubeController := range kubeControllersMap {\n\t\tglog.V(4).Infof(\"Discovered WorkloadController entity: %s\", kubeController)\n\t}\n\t// Create DTOs for each k8s WorkloadController entity\n\tworkloadControllerDTOBuilder := dtofactory.NewWorkloadControllerDTOBuilder(cluster, kubeControllersMap, worker.cluster.NamespaceUIDMap)\n\tworkloadControllerDtos, err := workloadControllerDTOBuilder.BuildDTOs()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while creating WorkloadController entityDTOs: %v\", err)\n\t}\n\treturn workloadControllerDtos, nil\n}", "func (r *MilvusClusterReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n\tif !config.IsDebug() {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tr.logger.Error(err.(error), \"reconcile panic\")\n\t\t\t}\n\t\t}()\n\t}\n\n\tmilvuscluster := &milvusiov1alpha1.MilvusCluster{}\n\tif err := r.Get(ctx, req.NamespacedName, milvuscluster); err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// The resource may have be deleted after reconcile request coming in\n\t\t\t// Reconcile is done\n\t\t\treturn ctrl.Result{}, nil\n\t\t}\n\n\t\treturn ctrl.Result{}, fmt.Errorf(\"error get milvus cluster: %w\", err)\n\t}\n\n\t// Finalize\n\tif milvuscluster.ObjectMeta.DeletionTimestamp.IsZero() {\n\t\tif !controllerutil.ContainsFinalizer(milvuscluster, MCFinalizerName) {\n\t\t\tcontrollerutil.AddFinalizer(milvuscluster, MCFinalizerName)\n\t\t\tif err := r.Update(ctx, milvuscluster); err != nil {\n\t\t\t\treturn ctrl.Result{}, err\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\tif controllerutil.ContainsFinalizer(milvuscluster, MCFinalizerName) {\n\t\t\tif err := r.Finalize(ctx, *milvuscluster); err != nil {\n\t\t\t\treturn ctrl.Result{}, err\n\t\t\t}\n\t\t\tcontrollerutil.RemoveFinalizer(milvuscluster, MCFinalizerName)\n\t\t\tif err := r.Update(ctx, milvuscluster); err != nil {\n\t\t\t\treturn ctrl.Result{}, err\n\t\t\t}\n\t\t}\n\t\t// Stop reconciliation as the item is being deleted\n\t\treturn ctrl.Result{}, nil\n\t}\n\n\t// Start reconcile\n\tr.logger.Info(\"start reconcile\")\n\told := milvuscluster.DeepCopy()\n\n\tif err := r.SetDefault(ctx, milvuscluster); err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\n\tif !IsEqual(old.Spec, milvuscluster.Spec) {\n\t\treturn ctrl.Result{}, r.Update(ctx, milvuscluster)\n\t}\n\n\tif err := r.ReconcileAll(ctx, *milvuscluster); err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\n\tif err := r.UpdateStatus(ctx, milvuscluster); err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\n\tif milvuscluster.Status.Status == v1alpha1.StatusUnHealthy {\n\t\treturn ctrl.Result{RequeueAfter: 30 * time.Second}, nil\n\t}\n\n\tif config.IsDebug() {\n\t\tdiff, err := client.MergeFrom(old).Data(milvuscluster)\n\t\tif err != nil {\n\t\t\tr.logger.Info(\"Update diff\", \"diff\", string(diff))\n\t\t}\n\t}\n\n\treturn ctrl.Result{}, nil\n}", "func (c *DroneStatus) ReallyExpensiveAssessmentOfTheSystemState() (\n\tpendingCurrent map[string]float64, runningCurrent map[string]float64, successTotal map[string]float64, killedCurrent map[string]float64, failureCurrent map[string]float64) {\n\n\t//Connection to MySQL\n\tdroneDBConn, err := lib.OpenMysqlDB(\"192.168.25.154\", 3306, \"root\", \"Mm123456\", \"drone\")\n\tif err != nil {\n\t\terr = errors.WithStack(err)\n\t\treturn\n\t}\n\tdefer droneDBConn.Close()\n\n\tvar pending_query = \"SELECT repo_slug AS repo,count(*) AS count FROM builds INNER JOIN repos ON builds.build_repo_id=repos.repo_id WHERE builds.build_status='pending' AND builds.build_created>=UNIX_TIMESTAMP (CURRENT_TIMESTAMP-INTERVAL 5 MINUTE) GROUP BY repos.repo_slug\"\n\tvar running_query = \"SELECT repo_slug AS repo,count(*) AS count FROM builds INNER JOIN repos ON builds.build_repo_id=repos.repo_id WHERE builds.build_status='running' AND builds.build_created>=UNIX_TIMESTAMP (CURRENT_TIMESTAMP-INTERVAL 5 MINUTE) GROUP BY repos.repo_slug\"\n\tvar success_query = \"SELECT repo_slug AS repo,count(*) AS count FROM builds INNER JOIN repos ON builds.build_repo_id=repos.repo_id WHERE builds.build_status='success' GROUP BY repos.repo_slug\"\n\tvar killed_query = \"SELECT repo_slug AS repo,count(*) AS count FROM builds INNER JOIN repos ON builds.build_repo_id=repos.repo_id WHERE builds.build_status='killed' AND builds.build_created>=UNIX_TIMESTAMP (CURRENT_TIMESTAMP-INTERVAL 10 MINUTE) GROUP BY repos.repo_slug\"\n\tvar failure_query = \"SELECT repo_slug AS repo,count(*) AS count FROM builds INNER JOIN repos ON builds.build_repo_id=repos.repo_id WHERE builds.build_status='failure' AND builds.build_created>=UNIX_TIMESTAMP (CURRENT_TIMESTAMP-INTERVAL 5 MINUTE) GROUP BY repos.repo_slug\"\n\tpendingResult, err := droneDBConn.Query(pending_query)\n\trunningResult, err := droneDBConn.Query(running_query)\n\tsuccessResult, err := droneDBConn.Query(success_query)\n\tkilledResult, err := droneDBConn.Query(killed_query)\n\tfailureResult, err := droneDBConn.Query(failure_query)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpendingCurrent = make(map[string]float64)\n\trunningCurrent = make(map[string]float64)\n\tsuccessTotal = make(map[string]float64)\n\tkilledCurrent = make(map[string]float64)\n\tfailureCurrent = make(map[string]float64)\n\tfor pendingResult.Next() {\n\t\tvar count float64\n\t\tvar repo string\n\t\terr = pendingResult.Scan(&repo, &count)\n\t\tpendingCurrent[repo] = count\n\t}\n\n\tfor runningResult.Next() {\n\t\tvar count float64\n\t\tvar repo string\n\t\terr = runningResult.Scan(&repo, &count)\n\t\trunningCurrent[repo] = count\n\t}\n\n\tfor successResult.Next() {\n\t\tvar count float64\n\t\tvar repo string\n\t\terr = successResult.Scan(&repo, &count)\n\t\tsuccessTotal[repo] = count\n\t}\n\n\tfor killedResult.Next() {\n\t\tvar count float64\n\t\tvar repo string\n\t\terr = killedResult.Scan(&repo, &count)\n\t\tkilledCurrent[repo] = count\n\t}\n\n\tfor failureResult.Next() {\n\t\tvar count float64\n\t\tvar repo string\n\t\terr = failureResult.Scan(&repo, &count)\n\t\tfailureCurrent[repo] = count\n\t}\n\n\t//End of Conver,\n\n\treturn\n}", "func getSelfhostingSubCommand(in io.Reader) *cobra.Command {\n\n\tcfg := &kubeadmapiv1beta1.InitConfiguration{}\n\t// Default values for the cobra help text\n\tkubeadmscheme.Scheme.Default(cfg)\n\n\tvar cfgPath, featureGatesString string\n\tforcePivot, certsInSecrets := false, false\n\tkubeConfigFile := constants.GetAdminKubeConfigPath()\n\n\t// Creates the UX Command\n\tcmd := &cobra.Command{\n\t\tUse: \"pivot\",\n\t\tAliases: []string{\"from-staticpods\"},\n\t\tShort: \"Converts a static Pod-hosted control plane into a self-hosted one\",\n\t\tLong: selfhostingLongDesc,\n\t\tExample: selfhostingExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\n\t\t\tvar err error\n\n\t\t\tif !forcePivot {\n\t\t\t\tfmt.Println(\"WARNING: self-hosted clusters are not supported by kubeadm upgrade and by other kubeadm commands!\")\n\t\t\t\tfmt.Print(\"[pivot] are you sure you want to proceed? [y/n]: \")\n\t\t\t\ts := bufio.NewScanner(in)\n\t\t\t\ts.Scan()\n\n\t\t\t\terr = s.Err()\n\t\t\t\tkubeadmutil.CheckErr(err)\n\n\t\t\t\tif strings.ToLower(s.Text()) != \"y\" {\n\t\t\t\t\tkubeadmutil.CheckErr(errors.New(\"aborted pivot operation\"))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfmt.Println(\"[pivot] pivoting cluster to self-hosted\")\n\n\t\t\tif cfg.FeatureGates, err = features.NewFeatureGate(&features.InitFeatureGates, featureGatesString); err != nil {\n\t\t\t\tkubeadmutil.CheckErr(err)\n\t\t\t}\n\n\t\t\tif err := validation.ValidateMixedArguments(cmd.Flags()); err != nil {\n\t\t\t\tkubeadmutil.CheckErr(err)\n\t\t\t}\n\n\t\t\t// Gets the Kubernetes client\n\t\t\tkubeConfigFile = cmdutil.FindExistingKubeConfig(kubeConfigFile)\n\t\t\tclient, err := kubeconfigutil.ClientSetFromFile(kubeConfigFile)\n\t\t\tkubeadmutil.CheckErr(err)\n\n\t\t\t// KubernetesVersion is not used, but we set it explicitly to avoid the lookup\n\t\t\t// of the version from the internet when executing ConfigFileAndDefaultsToInternalConfig\n\t\t\tphases.SetKubernetesVersion(cfg)\n\n\t\t\t// This call returns the ready-to-use configuration based on the configuration file that might or might not exist and the default cfg populated by flags\n\t\t\tinternalcfg, err := configutil.ConfigFileAndDefaultsToInternalConfig(cfgPath, cfg)\n\t\t\tkubeadmutil.CheckErr(err)\n\n\t\t\t// Converts the Static Pod-hosted control plane into a self-hosted one\n\t\t\twaiter := apiclient.NewKubeWaiter(client, 2*time.Minute, os.Stdout)\n\t\t\terr = selfhosting.CreateSelfHostedControlPlane(constants.GetStaticPodDirectory(), constants.KubernetesDir, internalcfg, client, waiter, false, certsInSecrets)\n\t\t\tkubeadmutil.CheckErr(err)\n\t\t},\n\t}\n\n\t// Add flags to the command\n\t// flags bound to the configuration object\n\tcmd.Flags().StringVar(&cfg.CertificatesDir, \"cert-dir\", cfg.CertificatesDir, `The path where certificates are stored`)\n\tcmd.Flags().StringVar(&cfgPath, \"config\", cfgPath, \"Path to a kubeadm config file. WARNING: Usage of a configuration file is experimental\")\n\n\tcmd.Flags().BoolVarP(\n\t\t&certsInSecrets, \"store-certs-in-secrets\", \"s\",\n\t\tfalse, \"Enable storing certs in secrets\")\n\n\tcmd.Flags().BoolVarP(\n\t\t&forcePivot, \"force\", \"f\", false,\n\t\t\"Pivot the cluster without prompting for confirmation\",\n\t)\n\n\t// flags that are not bound to the configuration object\n\t// Note: All flags that are not bound to the cfg object should be whitelisted in cmd/kubeadm/app/apis/kubeadm/validation/validation.go\n\toptions.AddKubeConfigFlag(cmd.Flags(), &kubeConfigFile)\n\n\treturn cmd\n}", "func (s *Service) Run() derrors.Error {\n\t// Create system model connection\n\tsmConn, err := grpc.Dial(s.Configuration.SystemModelAddress, grpc.WithInsecure())\n\tif err != nil {\n\t\treturn derrors.NewUnavailableError(\"cannot create connection with the system model\", err)\n\t}\n\n\t// Create Edge Inventory Proxy connection\n\teipConn, err := grpc.Dial(s.Configuration.EdgeInventoryProxyAddress, grpc.WithInsecure())\n\tif err != nil {\n\t\treturn derrors.NewUnavailableError(\"cannot create connection with the edge inventory proxy\", err)\n\t}\n\n\t// Create clients\n\tclustersClient := grpc_infrastructure_go.NewClustersClient(smConn)\n\torganizationsClient := grpc_organization_go.NewOrganizationsClient(smConn)\n\tassetsClient := grpc_inventory_go.NewAssetsClient(smConn)\n\tcontrollersClient := grpc_inventory_go.NewControllersClient(smConn)\n\teipClient := grpc_edge_inventory_proxy_go.NewEdgeControllerProxyClient(eipConn)\n\n\t// Start listening\n\tlis, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", s.Configuration.Port))\n\tif err != nil {\n\t\treturn derrors.NewUnavailableError(\"failed to listen\", err)\n\t}\n\n\t// Create managers and handler\n\tparams := &clients.AppClusterConnectParams{\n\t\tAppClusterPrefix: s.Configuration.AppClusterPrefix,\n\t\tAppClusterPort: s.Configuration.AppClusterPort,\n\t\tUseTLS: s.Configuration.UseTLS,\n\t\tCACertPath: s.Configuration.CACertPath,\n\t\tClientCertPath: s.Configuration.ClientCertPath,\n\t\tSkipServerCertValidation: s.Configuration.SkipServerCertValidation,\n\t}\n\n\t// Cluster monitoring\n\tclusterManager, derr := NewManager(&clustersClient, &organizationsClient, params)\n\tif derr != nil {\n\t\treturn derr\n\t}\n\tclusterHandler, derr := NewHandler(clusterManager, s.Configuration.CacheTTL)\n\tif derr != nil {\n\t\treturn derr\n\t}\n\n\t// Asset monitoring\n\tassetManager, derr := asset.NewManager(eipClient, assetsClient, controllersClient)\n\tif derr != nil {\n\t\treturn derr\n\t}\n\tassetHandler, derr := asset.NewHandler(assetManager)\n\n\t// Create server and register handler\n\tserver := grpc.NewServer()\n\tgrpc_monitoring_go.RegisterMonitoringManagerServer(server, clusterHandler)\n\tgrpc_monitoring_go.RegisterAssetMonitoringServer(server, assetHandler)\n\n\treflection.Register(server)\n\tlog.Info().Int(\"port\", s.Configuration.Port).Msg(\"Launching gRPC server\")\n\tif err := server.Serve(lis); err != nil {\n\t\treturn derrors.NewUnavailableError(\"failed to serve\", err)\n\t}\n\n\treturn nil\n}", "func Healthy(name string) ClusterController {\n\tco := Running(name)\n\n\tas, err := kverify.APIServerStatus(co.CP.Runner, co.CP.Hostname, co.CP.Port)\n\tif err != nil {\n\t\tout.FailureT(`Unable to get control plane status: {{.error}}`, out.V{\"error\": err})\n\t\texitTip(\"delete\", name, reason.ExSvcError)\n\t}\n\n\tif as == state.Paused {\n\t\tout.Styled(style.Shrug, `The control plane for \"{{.name}}\" is paused!`, out.V{\"name\": name})\n\t\texitTip(\"unpause\", name, reason.ExSvcConfig)\n\t}\n\n\tif as != state.Running {\n\t\tout.Styled(style.Shrug, `This control plane is not running! (state={{.state}})`, out.V{\"state\": as.String()})\n\t\tout.WarningT(`This is unusual - you may want to investigate using \"{{.command}}\"`, out.V{\"command\": ExampleCmd(name, \"logs\")})\n\t\texitTip(\"start\", name, reason.ExSvcUnavailable)\n\t}\n\treturn co\n}", "func (p *Planner) UpdateClusterState(podDestinations, scaleDownCandidates []*apiv1.Node, as scaledown.ActuationStatus, currentTime time.Time) errors.AutoscalerError {\n\tupdateInterval := currentTime.Sub(p.latestUpdate)\n\tif updateInterval < p.minUpdateInterval {\n\t\tp.minUpdateInterval = updateInterval\n\t}\n\tp.latestUpdate = currentTime\n\tp.actuationStatus = as\n\t// Avoid persisting changes done by the simulation.\n\tp.context.ClusterSnapshot.Fork()\n\tdefer p.context.ClusterSnapshot.Revert()\n\terr := p.injectRecentlyEvictedPods()\n\tif err != nil {\n\t\tklog.Warningf(\"Not all recently evicted pods could be injected\")\n\t}\n\tdeletions := asMap(merged(as.DeletionsInProgress()))\n\tpodDestinations = filterOutOngoingDeletions(podDestinations, deletions)\n\tscaleDownCandidates = filterOutOngoingDeletions(scaleDownCandidates, deletions)\n\tp.categorizeNodes(asMap(nodeNames(podDestinations)), scaleDownCandidates)\n\tp.rs.DropOldHints()\n\tp.actuationInjector.DropOldHints()\n\treturn nil\n}", "func TestTwoVpasForPod(t *testing.T) {\n\tcluster := NewClusterState()\n\tcluster.AddOrUpdateVpa(VpaID{\"vpa-1\"}, \"label-1 = value-1\")\n\tpod := addTestPod(cluster)\n\tcluster.AddOrUpdateVpa(VpaID{\"vpa-2\"}, \"label-1 in (value-1,value-2)\")\n\tassert.Equal(t, cluster.Vpas[VpaID{\"vpa-1\"}], pod.Vpa)\n\t// Delete the VPA that currently controls the Pod. Expect that it will\n\t// switch to the remaining one.\n\tassert.NoError(t, cluster.DeleteVpa(VpaID{\"vpa-1\"}))\n\tassert.Equal(t, cluster.Vpas[VpaID{\"vpa-2\"}], pod.Vpa)\n\t// Delete the other VPA. The Pod is no longer vertically-scaled by anyone.\n\tassert.NoError(t, cluster.DeleteVpa(VpaID{\"vpa-2\"}))\n\tassert.Nil(t, pod.Vpa)\n}", "func updateMachineSetStatus(ctx context.Context, log *zap.SugaredLogger, c client.Client, ms *v1alpha1.MachineSet, newStatus v1alpha1.MachineSetStatus) (*v1alpha1.MachineSet, error) {\n\t// This is the steady state. It happens when the MachineSet doesn't have any expectations, since\n\t// we do a periodic relist every 30s. If the generations differ but the replicas are\n\t// the same, a caller might've resized to the same replica count.\n\tif ms.Status.Replicas == newStatus.Replicas &&\n\t\tms.Status.FullyLabeledReplicas == newStatus.FullyLabeledReplicas &&\n\t\tms.Status.ReadyReplicas == newStatus.ReadyReplicas &&\n\t\tms.Status.AvailableReplicas == newStatus.AvailableReplicas &&\n\t\tms.Generation == ms.Status.ObservedGeneration {\n\t\treturn ms, nil\n\t}\n\n\t// Save the generation number we acted on, otherwise we might wrongfully indicate\n\t// that we've seen a spec update when we retry.\n\t// TODO: This can clobber an update if we allow multiple agents to write to the\n\t// same status.\n\tnewStatus.ObservedGeneration = ms.Generation\n\n\tvar getErr, updateErr error\n\tfor i := 0; ; i++ {\n\t\tvar replicas int32\n\t\tif ms.Spec.Replicas != nil {\n\t\t\treplicas = *ms.Spec.Replicas\n\t\t}\n\n\t\tlog.Debugw(\"Updating status\",\n\t\t\t\"specreplicas\", replicas,\n\t\t\t\"oldreplicas\", ms.Status.Replicas,\n\t\t\t\"newreplicas\", newStatus.Replicas,\n\t\t\t\"oldlabeledreplicas\", ms.Status.FullyLabeledReplicas,\n\t\t\t\"newlabeledreplicas\", newStatus.FullyLabeledReplicas,\n\t\t\t\"oldreadyreplicas\", ms.Status.ReadyReplicas,\n\t\t\t\"newreadyreplicas\", newStatus.ReadyReplicas,\n\t\t\t\"oldavailablereplicas\", ms.Status.AvailableReplicas,\n\t\t\t\"newavailablereplicas\", newStatus.AvailableReplicas,\n\t\t\t\"oldobservedgeneration\", ms.Status.ObservedGeneration,\n\t\t\t\"newobservedgeneration\", newStatus.ObservedGeneration,\n\t\t)\n\n\t\tms.Status = newStatus\n\t\tupdateErr = c.Status().Update(ctx, ms)\n\t\tif updateErr == nil {\n\t\t\treturn ms, nil\n\t\t}\n\t\t// Stop retrying if we exceed statusUpdateRetries - the machineSet will be requeued with a rate limit.\n\t\tif i >= statusUpdateRetries {\n\t\t\tbreak\n\t\t}\n\t\t// Update the MachineSet with the latest resource version for the next poll\n\t\tif getErr = c.Get(ctx, client.ObjectKey{Namespace: ms.Namespace, Name: ms.Name}, ms); getErr != nil {\n\t\t\t// If the GET fails we can't trust status.Replicas anymore. This error\n\t\t\t// is bound to be more interesting than the update failure.\n\t\t\treturn nil, getErr\n\t\t}\n\t}\n\n\treturn nil, updateErr\n}", "func (bi *BridgerInfo) mainStateMachine() {\n\tif bi.stopping && bi.stiCQD == 0 {\n\t\tbi.alldone = true\n\t\treturn\n\t}\n\n\tfor bi.stiRnq.Len() > 0 && bi.stiCQD < bi.stiMQD {\n\t\te := bi.stiRnq.Front()\n\t\treq := e.Value.(*stiReq)\n\t\tbi.stiRnq.Remove(e)\n\t\tbi.stiCQD++\n\n\t\tgo bi.ingestInstanceWorker(req.tmpDir, req.req)\n\t}\n\n\tif bi.stiCQD > 0 || bi.stiRnq.Len() > 0 {\n\t\tzlog.Info(\"BRIDGER-STATS: rnq %d active %d\\n\", bi.stiRnq.Len(), bi.stiCQD)\n\t}\n}", "func (optr *Operator) Run(workers int, stopCh <-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\tdefer optr.queue.ShutDown()\n\n\tapiClient := optr.apiExtClient.ApiextensionsV1()\n\t_, err := apiClient.CustomResourceDefinitions().Get(context.TODO(), \"controllerconfigs.machineconfiguration.openshift.io\", metav1.GetOptions{})\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\tklog.Infof(\"Couldn't find controllerconfig CRD, in cluster bringup mode\")\n\t\t\toptr.inClusterBringup = true\n\t\t} else {\n\t\t\tklog.Errorf(\"While checking for cluster bringup: %v\", err)\n\t\t}\n\t}\n\n\tif !cache.WaitForCacheSync(stopCh,\n\t\toptr.crdListerSynced,\n\t\toptr.deployListerSynced,\n\t\toptr.daemonsetListerSynced,\n\t\toptr.infraListerSynced,\n\t\toptr.mcoCmListerSynced,\n\t\toptr.clusterCmListerSynced,\n\t\toptr.serviceAccountInformerSynced,\n\t\toptr.clusterRoleInformerSynced,\n\t\toptr.maoSecretInformerSynced,\n\t\toptr.clusterRoleBindingInformerSynced,\n\t\toptr.networkListerSynced,\n\t\toptr.proxyListerSynced,\n\t\toptr.oseKubeAPIListerSynced,\n\t\toptr.nodeListerSynced,\n\t\toptr.mcpListerSynced,\n\t\toptr.mcListerSynced,\n\t\toptr.dnsListerSynced) {\n\t\tklog.Error(\"failed to sync caches\")\n\t\treturn\n\t}\n\n\t// these can only be synced after CRDs are installed\n\tif !optr.inClusterBringup {\n\t\tif !cache.WaitForCacheSync(stopCh,\n\t\t\toptr.ccListerSynced,\n\t\t) {\n\t\t\tklog.Error(\"failed to sync caches\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tklog.Info(\"Starting MachineConfigOperator\")\n\tdefer klog.Info(\"Shutting down MachineConfigOperator\")\n\n\toptr.stopCh = stopCh\n\n\tfor i := 0; i < workers; i++ {\n\t\tgo wait.Until(optr.worker, time.Second, stopCh)\n\t}\n\n\t<-stopCh\n}", "func TestNamespace1(t *testing.T) {\n\ttestName := \"TestNamespace1\"\n\tbeforeTest()\n\t// kinds to check for status\n\tvar kindsToCheckStatus = map[string]bool{\n\t\t\"Application\": 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\tnsListkAppNavConfigMap,\n\t\tCrdApplication,\n\t\tns4NoAnnoApplication,\n\t\tns1Service,\n\t\tns1Deployment,\n\t\tns2Service,\n\t\tns2Deployment,\n\t\tns3Service,\n\t\tns3Deployment,\n\t\tns4Service,\n\t\tns4Deployment,\n\t}\n\titeration0IDs, err := readResourceIDs(files)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t/* Iteration 0: no resources should have status */\n\ttestActions := newTestActions(testName, kindsToCheckStatus)\n\tvar emptyIDs = []resourceID{}\n\n\titeration0IDs[2].expectedStatus = NoStatus // ns4 Application\n\titeration0IDs[3].expectedStatus = NoStatus // ns1 Service\n\titeration0IDs[4].expectedStatus = NoStatus\n\titeration0IDs[5].expectedStatus = NoStatus // ns2 Service\n\titeration0IDs[6].expectedStatus = NoStatus\n\titeration0IDs[7].expectedStatus = NoStatus // ns3 Service\n\titeration0IDs[8].expectedStatus = NoStatus\n\titeration0IDs[9].expectedStatus = NoStatus // ns4 Service\n\titeration0IDs[10].expectedStatus = NoStatus\n\ttestActions.addIteration(iteration0IDs, emptyIDs)\n\n\t/* iteration 1: 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// run all the test actions\n\terr = testActions.transitionAll()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func (e *Exporter) ovnMetricsUpdate() {\n\tfor {\n\t\te.exportOvnStatusGauge()\n\t\te.exportOvnLogFileSizeGauge()\n\t\te.exportOvnDBFileSizeGauge()\n\t\te.exportOvnRequestErrorGauge()\n\t\te.exportOvnDBStatusGauge()\n\n\t\te.exportOvnChassisGauge()\n\t\te.exportLogicalSwitchGauge()\n\t\te.exportLogicalSwitchPortGauge()\n\n\t\te.exportOvnClusterEnableGauge()\n\t\tif isClusterEnabled {\n\t\t\te.exportOvnClusterInfoGauge()\n\t\t}\n\n\t\ttime.Sleep(time.Duration(e.pollInterval) * time.Second)\n\t}\n}", "func main() {\n\tlog.LoadConfiguration(\"log.cfg\")\n\tlog.Info(\"Start Master\")\n\n\tcfg := loadMasterConfiguration()\n\n\tlog.Info(\"Setting go cpu number to \", cfg.Constants.CpuNumber, \" success: \", runtime.GOMAXPROCS(cfg.Constants.CpuNumber))\n\n\t// Start rest api server with tcp services for inserts and selects\n\tportNum := fmt.Sprintf(\":%d\", cfg.Ports.RestApi)\n\tvar server = restApi.Server{Port: portNum}\n\tchanReq := server.StartApi()\n\n\t// Initialize node manager\n\tlog.Info(\"Initialize node manager\")\n\tgo node.NodeManager.Manage()\n\tnodeBal := node.NewLoadBalancer(node.NodeManager.GetNodes())\n\tgo nodeBal.Balance(node.NodeManager.InfoChan)\n\n\t// Initialize reduce factory\n\tlog.Info(\"Initialize reduce factory\")\n\treduce.Initialize()\n\n\t// Initialize task manager (balancer)\n\tlog.Info(\"Initialize task manager\")\n\tgo task.TaskManager.Manage()\n\ttaskBal := task.NewBalancer(cfg.Constants.WorkersCount, cfg.Constants.JobForWorkerCount, nodeBal)\n\tgo taskBal.Balance(chanReq, cfg.Balancer.Timeout)\n\n\t// Initialize node listener\n\tlog.Info(\"Initialize node listener\")\n\tservice := fmt.Sprintf(\":%d\", cfg.Ports.NodeCommunication)\n\tlog.Debug(service)\n\tlist := node.NewListener(service)\n\tgo list.WaitForNodes(task.TaskManager.GetChan)\n\tdefer list.Close() // fire netListen.Close() when program ends\n\n\t// TODO: Wait for console instructions (q - quit for example)\n\t// Wait for some input end exit (only for now)\n\t//var i int\n\t//fmt.Scanf(\"%d\", &i)\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\t<-c\n\treturn\n}", "func UpdateMetrics(result *Results) {\n\n\t// Publish system variables\n\tupTimeGauge.Set(float64(result.SysMonitorInfo.Uptime))\n\tcpuUsageGauge.Set(float64(result.SysMonitorInfo.CpuUsagePercent))\n\n\t// Memory\n\tmemUsagePercentGauge.Set(result.SysMonitorInfo.MemUsagePercent)\n\tmemTotalGauge.Set(float64(result.SysMonitorInfo.MemTotal))\n\tmemAvailableGauge.Set(float64(result.SysMonitorInfo.MemAvailable))\n\n\t// Bandwidth\n\tbandwidthUsageTotalGauge.Set(float64(result.SysMonitorInfo.BandwidthUsageTotal))\n\tbandwidthUsageSentGauge.Set(float64(result.SysMonitorInfo.BandwidthUsageSent))\n\tbandwidthUsageRecvGauge.Set(float64(result.SysMonitorInfo.BandwidthUsageRecv))\n\n\tfor _, driveUsage := range result.SysMonitorInfo.DriveUsage {\n\t\t// \"drive_path\", \"available\", \"growth_rate\", \"full_in\", \"physical_drive\"\n\n\t\tdays := strconv.FormatFloat(driveUsage.DaysTillFull, 'f', 3, 64)\n\n\t\tif math.IsInf(driveUsage.DaysTillFull, 0) {\n\t\t\tdays = \"10 years\"\n\t\t}\n\n\t\tdriveSpace.WithLabelValues(driveUsage.Path,\n\t\t\tstrconv.FormatFloat(driveUsage.PercentUsed, 'f', 3, 64),\n\t\t\tstrconv.FormatUint(driveUsage.GrowthPerDayBytes, 10),\n\t\t\tdays,\n\t\t\tdriveUsage.VolumeName).Set(driveUsage.PercentUsed)\n\t}\n\n\t// Publish endpoints being monitored\n\tfor _, uptimeResponse := range result.UptimeList {\n\n\t\tif uptimeResponse.ResponseCode == 200 {\n\t\t\tendpointAvailable.WithLabelValues(uptimeResponse.Endpoint).Set(1)\n\t\t} else {\n\t\t\tendpointAvailable.WithLabelValues(uptimeResponse.Endpoint).Set(0)\n\t\t}\n\n\t\tendpointDuration.WithLabelValues(uptimeResponse.Endpoint).Set(uptimeResponse.ResponseTime.Seconds())\n\t}\n\n\tfor _, backupInfo := range result.BackupInfoList {\n\n\t\t/*\n\t\t\tif backupInfo.WasBackedUp {\n\t\t\t\tbackupsDone.WithLabelValues(backupInfo.Folder).Set(1)\n\t\t\t} else {\n\t\t\t\tbackupsDone.WithLabelValues(backupInfo.Folder).Set(0)\n\t\t\t}\n\t\t*/\n\n\t\t// {\"backup_directory\", \"backup_in_last_24_hours\", \"last_backup_size\", \"last_backup_date\", \"last_backup_time\"})\n\n\t\t// backupsSize.WithLabelValues(backupInfo.Folder).Set(float64(backupInfo.BackupFileSize))\n\n\t\tbackupInfoGauge.WithLabelValues(backupInfo.Folder,\n\t\t\tbtoa(backupInfo.WasBackedUp),\n\t\t\titoa(backupInfo.LastBackupSize),\n\t\t\tttoa(backupInfo.LastBackupTime),\n\t\t\tbackupInfo.LastBackupFile).Set(btof(backupInfo.WasBackedUp))\n\t}\n\n\t// TODO: This loop is not needed, you can build the summary on the first loop\n\tvar too_many_lines = 500\n\tfor _, logLine := range result.LoglineList {\n\n\t\tsummary, ok := result.LogSummary[logLine.LogPath]\n\n\t\tif ok == false {\n\t\t\tsummary = LogSummary{}\n\t\t\tsummary.StatusCount = make(map[string]int64)\n\t\t\tsummary.SeverityLevelCount = make(map[string]int64)\n\t\t}\n\n\t\tsummary.StatusCount[logLine.StatusCode] = summary.StatusCount[logLine.StatusCode] + 1\n\n\t\tif len(logLine.Severity) > 0 {\n\t\t\tsummary.SeverityLevelCount[logLine.Severity] = summary.SeverityLevelCount[logLine.Severity] + 1\n\t\t}\n\n\t\tresult.LogSummary[logLine.LogPath] = summary\n\n\t\tif too_many_lines <= 0 {\n\t\t\t// Pending a better solution, let's not allow the processing\n\t\t\t// of too many lines, to not kill the server\n\t\t\tlLog.Print(\"Too many lines for a single tick to process\")\n\t\t\tbreak\n\t\t}\n\n\t}\n\n\t// Set the values for the logs. We use two labels (logpath, code)\n\tfor logFilePath, logSummary := range result.LogSummary {\n\n\t\tfor s, value := range logSummary.StatusCount {\n\t\t\tstatusCodes.WithLabelValues(logFilePath, s).Set(float64(value))\n\t\t}\n\n\t\tfor s, value := range logSummary.SeverityLevelCount {\n\t\t\tseverity.WithLabelValues(logFilePath, s).Set(float64(value))\n\t\t}\n\n\t}\n}", "func ExampleClustersClient_BeginUpdate() {\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\tclientFactory, err := armservicefabric.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpoller, err := clientFactory.NewClustersClient().BeginUpdate(ctx, \"resRg\", \"myCluster\", armservicefabric.ClusterUpdateParameters{\n\t\tProperties: &armservicefabric.ClusterPropertiesUpdateParameters{\n\t\t\tEventStoreServiceEnabled: to.Ptr(true),\n\t\t\tNodeTypes: []*armservicefabric.NodeTypeDescription{\n\t\t\t\t{\n\t\t\t\t\tName: to.Ptr(\"nt1vm\"),\n\t\t\t\t\tApplicationPorts: &armservicefabric.EndpointRangeDescription{\n\t\t\t\t\t\tEndPort: to.Ptr[int32](30000),\n\t\t\t\t\t\tStartPort: to.Ptr[int32](20000),\n\t\t\t\t\t},\n\t\t\t\t\tClientConnectionEndpointPort: to.Ptr[int32](19000),\n\t\t\t\t\tDurabilityLevel: to.Ptr(armservicefabric.DurabilityLevelBronze),\n\t\t\t\t\tEphemeralPorts: &armservicefabric.EndpointRangeDescription{\n\t\t\t\t\t\tEndPort: to.Ptr[int32](64000),\n\t\t\t\t\t\tStartPort: to.Ptr[int32](49000),\n\t\t\t\t\t},\n\t\t\t\t\tHTTPGatewayEndpointPort: to.Ptr[int32](19007),\n\t\t\t\t\tIsPrimary: to.Ptr(true),\n\t\t\t\t\tVMInstanceCount: to.Ptr[int32](5),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: to.Ptr(\"testnt1\"),\n\t\t\t\t\tApplicationPorts: &armservicefabric.EndpointRangeDescription{\n\t\t\t\t\t\tEndPort: to.Ptr[int32](2000),\n\t\t\t\t\t\tStartPort: to.Ptr[int32](1000),\n\t\t\t\t\t},\n\t\t\t\t\tClientConnectionEndpointPort: to.Ptr[int32](0),\n\t\t\t\t\tDurabilityLevel: to.Ptr(armservicefabric.DurabilityLevelBronze),\n\t\t\t\t\tEphemeralPorts: &armservicefabric.EndpointRangeDescription{\n\t\t\t\t\t\tEndPort: to.Ptr[int32](4000),\n\t\t\t\t\t\tStartPort: to.Ptr[int32](3000),\n\t\t\t\t\t},\n\t\t\t\t\tHTTPGatewayEndpointPort: to.Ptr[int32](0),\n\t\t\t\t\tIsPrimary: to.Ptr(false),\n\t\t\t\t\tVMInstanceCount: to.Ptr[int32](3),\n\t\t\t\t}},\n\t\t\tReliabilityLevel: to.Ptr(armservicefabric.ReliabilityLevelBronze),\n\t\t\tUpgradeMode: to.Ptr(armservicefabric.UpgradeModeAutomatic),\n\t\t\tUpgradePauseEndTimestampUTC: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, \"2021-06-25T22:00:00Z\"); return t }()),\n\t\t\tUpgradePauseStartTimestampUTC: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, \"2021-06-21T22:00:00Z\"); return t }()),\n\t\t\tUpgradeWave: to.Ptr(armservicefabric.ClusterUpgradeCadence(\"Wave\")),\n\t\t},\n\t\tTags: map[string]*string{\n\t\t\t\"a\": to.Ptr(\"b\"),\n\t\t},\n\t}, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\tres, err := poller.PollUntilDone(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to pull the result: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.Cluster = armservicefabric.Cluster{\n\t// \tName: to.Ptr(\"myCluster\"),\n\t// \tType: to.Ptr(\"Microsoft.ServiceFabric/clusters\"),\n\t// \tEtag: to.Ptr(\"W/\\\"636462502169240744\\\"\"),\n\t// \tID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/resRg/providers/Microsoft.ServiceFabric/clusters/myCluster\"),\n\t// \tLocation: to.Ptr(\"eastus\"),\n\t// \tTags: map[string]*string{\n\t// \t\t\"a\": to.Ptr(\"b\"),\n\t// \t},\n\t// \tProperties: &armservicefabric.ClusterProperties{\n\t// \t\tAvailableClusterVersions: []*armservicefabric.ClusterVersionDetails{\n\t// \t\t\t{\n\t// \t\t\t\tCodeVersion: to.Ptr(\"6.1.480.9494\"),\n\t// \t\t\t\tEnvironment: to.Ptr(armservicefabric.ClusterEnvironmentWindows),\n\t// \t\t\t\tSupportExpiryUTC: to.Ptr(\"2018-06-15T23:59:59.9999999\"),\n\t// \t\t}},\n\t// \t\tCertificateCommonNames: &armservicefabric.ServerCertificateCommonNames{\n\t// \t\t\tCommonNames: []*armservicefabric.ServerCertificateCommonName{\n\t// \t\t\t\t{\n\t// \t\t\t\t\tCertificateCommonName: to.Ptr(\"abc.com\"),\n\t// \t\t\t\t\tCertificateIssuerThumbprint: to.Ptr(\"12599211F8F14C90AFA9532AD79A6F2CA1C00622\"),\n\t// \t\t\t}},\n\t// \t\t\tX509StoreName: to.Ptr(armservicefabric.StoreNameMy),\n\t// \t\t},\n\t// \t\tClientCertificateCommonNames: []*armservicefabric.ClientCertificateCommonName{\n\t// \t\t},\n\t// \t\tClientCertificateThumbprints: []*armservicefabric.ClientCertificateThumbprint{\n\t// \t\t},\n\t// \t\tClusterCodeVersion: to.Ptr(\"6.1.480.9494\"),\n\t// \t\tClusterEndpoint: to.Ptr(\"https://eastus.servicefabric.azure.com\"),\n\t// \t\tClusterID: to.Ptr(\"92584666-9889-4ae8-8d02-91902923d37f\"),\n\t// \t\tClusterState: to.Ptr(armservicefabric.ClusterStateWaitingForNodes),\n\t// \t\tDiagnosticsStorageAccountConfig: &armservicefabric.DiagnosticsStorageAccountConfig{\n\t// \t\t\tBlobEndpoint: to.Ptr(\"https://diag.blob.core.windows.net/\"),\n\t// \t\t\tProtectedAccountKeyName: to.Ptr(\"StorageAccountKey1\"),\n\t// \t\t\tQueueEndpoint: to.Ptr(\"https://diag.queue.core.windows.net/\"),\n\t// \t\t\tStorageAccountName: to.Ptr(\"diag\"),\n\t// \t\t\tTableEndpoint: to.Ptr(\"https://diag.table.core.windows.net/\"),\n\t// \t\t},\n\t// \t\tEventStoreServiceEnabled: to.Ptr(true),\n\t// \t\tFabricSettings: []*armservicefabric.SettingsSectionDescription{\n\t// \t\t\t{\n\t// \t\t\t\tName: to.Ptr(\"UpgradeService\"),\n\t// \t\t\t\tParameters: []*armservicefabric.SettingsParameterDescription{\n\t// \t\t\t\t\t{\n\t// \t\t\t\t\t\tName: to.Ptr(\"AppPollIntervalInSeconds\"),\n\t// \t\t\t\t\t\tValue: to.Ptr(\"60\"),\n\t// \t\t\t\t}},\n\t// \t\t}},\n\t// \t\tManagementEndpoint: to.Ptr(\"http://myCluster.eastus.cloudapp.azure.com:19080\"),\n\t// \t\tNodeTypes: []*armservicefabric.NodeTypeDescription{\n\t// \t\t\t{\n\t// \t\t\t\tName: to.Ptr(\"nt1vm\"),\n\t// \t\t\t\tApplicationPorts: &armservicefabric.EndpointRangeDescription{\n\t// \t\t\t\t\tEndPort: to.Ptr[int32](30000),\n\t// \t\t\t\t\tStartPort: to.Ptr[int32](20000),\n\t// \t\t\t\t},\n\t// \t\t\t\tClientConnectionEndpointPort: to.Ptr[int32](19000),\n\t// \t\t\t\tDurabilityLevel: to.Ptr(armservicefabric.DurabilityLevelBronze),\n\t// \t\t\t\tEphemeralPorts: &armservicefabric.EndpointRangeDescription{\n\t// \t\t\t\t\tEndPort: to.Ptr[int32](64000),\n\t// \t\t\t\t\tStartPort: to.Ptr[int32](49000),\n\t// \t\t\t\t},\n\t// \t\t\t\tHTTPGatewayEndpointPort: to.Ptr[int32](19007),\n\t// \t\t\t\tIsPrimary: to.Ptr(true),\n\t// \t\t\t\tVMInstanceCount: to.Ptr[int32](5),\n\t// \t\t\t},\n\t// \t\t\t{\n\t// \t\t\t\tName: to.Ptr(\"testnt1\"),\n\t// \t\t\t\tApplicationPorts: &armservicefabric.EndpointRangeDescription{\n\t// \t\t\t\t\tEndPort: to.Ptr[int32](2000),\n\t// \t\t\t\t\tStartPort: to.Ptr[int32](1000),\n\t// \t\t\t\t},\n\t// \t\t\t\tClientConnectionEndpointPort: to.Ptr[int32](0),\n\t// \t\t\t\tDurabilityLevel: to.Ptr(armservicefabric.DurabilityLevelBronze),\n\t// \t\t\t\tEphemeralPorts: &armservicefabric.EndpointRangeDescription{\n\t// \t\t\t\t\tEndPort: to.Ptr[int32](4000),\n\t// \t\t\t\t\tStartPort: to.Ptr[int32](3000),\n\t// \t\t\t\t},\n\t// \t\t\t\tHTTPGatewayEndpointPort: to.Ptr[int32](0),\n\t// \t\t\t\tIsPrimary: to.Ptr(false),\n\t// \t\t\t\tVMInstanceCount: to.Ptr[int32](3),\n\t// \t\t}},\n\t// \t\tNotifications: []*armservicefabric.Notification{\n\t// \t\t\t{\n\t// \t\t\t\tIsEnabled: to.Ptr(true),\n\t// \t\t\t\tNotificationCategory: to.Ptr(armservicefabric.NotificationCategoryWaveProgress),\n\t// \t\t\t\tNotificationLevel: to.Ptr(armservicefabric.NotificationLevelCritical),\n\t// \t\t\t\tNotificationTargets: []*armservicefabric.NotificationTarget{\n\t// \t\t\t\t\t{\n\t// \t\t\t\t\t\tNotificationChannel: to.Ptr(armservicefabric.NotificationChannelEmailUser),\n\t// \t\t\t\t\t\tReceivers: []*string{\n\t// \t\t\t\t\t\t\tto.Ptr(\"****@microsoft.com\"),\n\t// \t\t\t\t\t\t\tto.Ptr(\"****@microsoft.com\")},\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tNotificationChannel: to.Ptr(armservicefabric.NotificationChannelEmailSubscription),\n\t// \t\t\t\t\t\t\tReceivers: []*string{\n\t// \t\t\t\t\t\t\t\tto.Ptr(\"Owner\"),\n\t// \t\t\t\t\t\t\t\tto.Ptr(\"AccountAdmin\")},\n\t// \t\t\t\t\t\t}},\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\t{\n\t// \t\t\t\t\t\tIsEnabled: to.Ptr(true),\n\t// \t\t\t\t\t\tNotificationCategory: to.Ptr(armservicefabric.NotificationCategoryWaveProgress),\n\t// \t\t\t\t\t\tNotificationLevel: to.Ptr(armservicefabric.NotificationLevelAll),\n\t// \t\t\t\t\t\tNotificationTargets: []*armservicefabric.NotificationTarget{\n\t// \t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\tNotificationChannel: to.Ptr(armservicefabric.NotificationChannelEmailUser),\n\t// \t\t\t\t\t\t\t\tReceivers: []*string{\n\t// \t\t\t\t\t\t\t\t\tto.Ptr(\"****@microsoft.com\"),\n\t// \t\t\t\t\t\t\t\t\tto.Ptr(\"****@microsoft.com\")},\n\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\t\tNotificationChannel: to.Ptr(armservicefabric.NotificationChannelEmailSubscription),\n\t// \t\t\t\t\t\t\t\t\tReceivers: []*string{\n\t// \t\t\t\t\t\t\t\t\t\tto.Ptr(\"Owner\"),\n\t// \t\t\t\t\t\t\t\t\t\tto.Ptr(\"AccountAdmin\")},\n\t// \t\t\t\t\t\t\t\t}},\n\t// \t\t\t\t\t\t}},\n\t// \t\t\t\t\t\tProvisioningState: to.Ptr(armservicefabric.ProvisioningStateSucceeded),\n\t// \t\t\t\t\t\tReliabilityLevel: to.Ptr(armservicefabric.ReliabilityLevelBronze),\n\t// \t\t\t\t\t\tUpgradeDescription: &armservicefabric.ClusterUpgradePolicy{\n\t// \t\t\t\t\t\t\tDeltaHealthPolicy: &armservicefabric.ClusterUpgradeDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\t\tMaxPercentDeltaUnhealthyApplications: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t\tMaxPercentDeltaUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t\tMaxPercentUpgradeDomainDeltaUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\tForceRestart: to.Ptr(false),\n\t// \t\t\t\t\t\t\tHealthCheckRetryTimeout: to.Ptr(\"00:05:00\"),\n\t// \t\t\t\t\t\t\tHealthCheckStableDuration: to.Ptr(\"00:00:30\"),\n\t// \t\t\t\t\t\t\tHealthCheckWaitDuration: to.Ptr(\"00:00:30\"),\n\t// \t\t\t\t\t\t\tHealthPolicy: &armservicefabric.ClusterHealthPolicy{\n\t// \t\t\t\t\t\t\t\tMaxPercentUnhealthyApplications: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t\tMaxPercentUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\tUpgradeDomainTimeout: to.Ptr(\"00:15:00\"),\n\t// \t\t\t\t\t\t\tUpgradeReplicaSetCheckTimeout: to.Ptr(\"00:10:00\"),\n\t// \t\t\t\t\t\t\tUpgradeTimeout: to.Ptr(\"01:00:00\"),\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\tUpgradeMode: to.Ptr(armservicefabric.UpgradeModeAutomatic),\n\t// \t\t\t\t\t\tUpgradePauseEndTimestampUTC: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, \"2021-06-25T22:00:00Z\"); return t}()),\n\t// \t\t\t\t\t\tUpgradePauseStartTimestampUTC: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, \"2021-06-21T22:00:00Z\"); return t}()),\n\t// \t\t\t\t\t\tUpgradeWave: to.Ptr(armservicefabric.ClusterUpgradeCadenceWave2),\n\t// \t\t\t\t\t},\n\t// \t\t\t\t}\n}", "func initializeDaemonMetrics() {\n\t// CLUSTER METRICS\n\tnumACLRules = createClusterGauge(numACLRulesName, numACLRulesHelp)\n\tnumIPSets = createClusterGauge(numIPSetsName, numIPSetsHelp)\n\tnumIPSetEntries = createClusterGauge(numIPSetEntriesName, numIPSetEntriesHelp)\n\tipsetInventory = createClusterGaugeVec(ipsetInventoryName, ipsetInventoryHelp, ipsetInventoryLabels)\n\tipsetInventoryMap = make(map[string]int)\n\n\t// NODE METRICS\n\taddACLRuleExecTime = createNodeSummary(addACLRuleExecTimeName, addACLRuleExecTimeHelp)\n\taddIPSetExecTime = createNodeSummary(addIPSetExecTimeName, addIPSetExecTimeHelp)\n}", "func verifyAnnotationsAndNodeAffinity(allowedTopologyHAMap map[string][]string,\n\tcategories []string, pod *v1.Pod, nodeList *v1.NodeList,\n\tsvcPVC *v1.PersistentVolumeClaim, pv *v1.PersistentVolume, svcPVCName string) {\n\tframework.Logf(\"Verify SV PVC has TKG HA annotations set\")\n\terr := checkAnnotationOnSvcPvc(svcPVC, allowedTopologyHAMap, categories)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tframework.Logf(\"SVC PVC: %s has TKG HA annotations set\", svcPVC.Name)\n\n\tframework.Logf(\"Verify GV PV has has required PV node affinity details\")\n\t_, err = verifyVolumeTopologyForLevel5(pv, allowedTopologyHAMap)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tframework.Logf(\"GC PV: %s has required Pv node affinity details\", pv.Name)\n\n\tframework.Logf(\"Verify SV PV has has required PV node affinity details\")\n\tsvcPV := getPvFromSupervisorCluster(svcPVCName)\n\t_, err = verifyVolumeTopologyForLevel5(svcPV, allowedTopologyHAMap)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tframework.Logf(\"SVC PV: %s has required PV node affinity details\", svcPV.Name)\n\n\t_, err = verifyPodLocationLevel5(pod, nodeList, allowedTopologyHAMap)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n}", "func (r *ClusterTopologyReconciler) computeDesiredState(ctx context.Context, input *clusterTopologyClass, current *clusterTopologyState) (*clusterTopologyState, error) {\n\t// TODO: add compute logic\n\treturn nil, nil\n}", "func Test_Cluster_Availability(t *testing.T) {\n\ttotal := 5\n\tvar server [5]cluster.Server\n\t// server[4] is not started now.. (corresponding to pid=5)\n\tfor i := 0; i < total-1; i++ {\n\t\tserver[i] = cluster.New(i+1, \"../config.json\")\n\t}\n\n\t// Random messages\n\tmessage := \"hello\"\n\n\tcount := make([]int, 5)\n\tfor i := 0; i< total; i++ {\n\t\tcount[i] = 0\n\t}\n\t\n\tfor k :=0; k < total-1; k++ {\n\t\tserver[k].Outbox() <- &cluster.Envelope{SendTo: -1, SendBy: k+1, Msg: message}\n\t}\n\n\ttime.Sleep(time.Second)\n\n\tserver[total-1] = cluster.New(total, \"../config.json\")\n\n\twg := new(sync.WaitGroup)\n\tfor i := 0; i< total; i++ {\n\t\twg.Add(1)\n\t\tgo checkInput(server[i], &count[i], wg)\n\t}\n\n\tfor i := 0; i< total; i++ {\n\t\tclose(server[i].Outbox())\n\t}\n\twg.Wait()\n\n\n\tif count[4] != 4 {\n\t\tpanic (\"All messages not recieved..\")\n\t}\n\n\tt.Log(\"test of Availability of cluster passed.\")\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 (c *Cluster) Setup() error {\n\t// Setup masters.\n\tvar masters []*Master\n\tvar raftMembers []string\n\tfor i := 0; i < int(c.config.Masters); i++ {\n\t\tm := newMaster(fmt.Sprintf(\"m%d\", i), c.config.BinDir, c.config.RootDir, c.loggers)\n\t\tmasters = append(masters, m)\n\t\tc.masters = append(c.masters, m)\n\t\tc.masterAddrs = append(c.masterAddrs, m.serviceAddr)\n\t\tc.addProc(m)\n\t}\n\tfor _, m := range masters {\n\t\tm.setup(c.masterAddrs)\n\t}\n\n\t// Setup curators.\n\tfor g := 0; g < int(c.config.CuratorGroups); g++ {\n\t\traftMembers = nil\n\t\tvar curators []*Curator\n\t\tfor i := 0; i < int(c.config.Curators); i++ {\n\t\t\tcurator := newCurator(fmt.Sprintf(\"c%d.%d\", g, i), c.config.BinDir, c.config.RootDir, c.loggers)\n\t\t\tcurators = append(curators, curator)\n\t\t\traftMembers = append(raftMembers, curator.serviceAddr)\n\t\t\tc.addProc(curator)\n\t\t}\n\t\tc.curators = append(c.curators, curators)\n\t\tfor _, curator := range curators {\n\t\t\tcurator.setup(raftMembers, c.masterAddrs)\n\t\t}\n\t}\n\n\t// Setup tract servers.\n\tfor i := 0; i < int(c.config.Tractservers); i++ {\n\t\tts := newTractServer(fmt.Sprintf(\"t%d\", i), c.config.BinDir, c.config.RootDir, c.config.DisksPerTractserver, c.loggers)\n\t\tc.tractservers = append(c.tractservers, ts)\n\t\tc.addProc(ts)\n\t\tts.setup(c.masterAddrs)\n\t}\n\treturn nil\n}", "func (ck *clusterKinds) update() {\n\toutput, err := exec.Command(\"kubectl\", \"api-resources\").Output()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tlines := strings.Split(string(output), \"\\n\")\n\tfor _, line := range lines[1:] {\n\t\tif len(line) == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\ts := strings.Fields(line)\n\t\tkind := s[len(s)-1]\n\t\tnamespaced := s[len(s)-2] == \"true\"\n\n\t\tck.isNamespaced[kind] = namespaced\n\t}\n}", "func (s *StatusReconciler) resizeSubclusterStatus(ctx context.Context, sc *vapi.Subcluster, curStat *vapi.SubclusterStatus) error {\n\tscSize, err := s.getSubclusterSize(ctx, sc)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Grow the detail if needed\n\tfor ok := true; ok; ok = int32(len(curStat.Detail)) < scSize {\n\t\tcurStat.Detail = append(curStat.Detail, vapi.VerticaDBPodStatus{})\n\t}\n\t// Or shrink the size\n\tif int32(len(curStat.Detail)) > scSize {\n\t\tcurStat.Detail = curStat.Detail[0:scSize]\n\t}\n\treturn nil\n}", "func (r *reconciler) syncOperatorStatus() error {\n\tns := manifests.DNSNamespace()\n\n\tco := &configv1.ClusterOperator{ObjectMeta: metav1.ObjectMeta{Name: DNSOperatorName}}\n\tif err := r.client.Get(context.TODO(), types.NamespacedName{Name: co.Name}, co); err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\tinitializeClusterOperator(co)\n\t\t\tif err := r.client.Create(context.TODO(), co); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to create clusteroperator %s: %v\", co.Name, err)\n\t\t\t}\n\t\t\tlogrus.Infof(\"created clusteroperator %s\", co.Name)\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"failed to get clusteroperator %s: %v\", co.Name, err)\n\t\t}\n\t}\n\toldStatus := co.Status.DeepCopy()\n\n\tdnses, ns, err := r.getOperatorState(ns.Name)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get operator state: %v\", err)\n\t}\n\n\trelated := []configv1.ObjectReference{\n\t\t{\n\t\t\tResource: \"namespaces\",\n\t\t\tName: \"openshift-dns-operator\",\n\t\t},\n\t\t{\n\t\t\tResource: \"namespaces\",\n\t\t\tName: ns.Name,\n\t\t},\n\t\t{\n\t\t\tGroup: operatorv1.GroupName,\n\t\t\tResource: \"DNS\",\n\t\t},\n\t}\n\tco.Status.RelatedObjects = related\n\n\tdnsStatusConditionsCounts := computeDNSStatusConditionCounts(dnses)\n\tco.Status.Versions = r.computeOperatorStatusVersions(oldStatus.Versions, dnsStatusConditionsCounts)\n\tco.Status.Conditions = r.computeOperatorStatusConditions(oldStatus.Conditions, ns, dnsStatusConditionsCounts, oldStatus.Versions, co.Status.Versions)\n\n\tif !operatorStatusesEqual(*oldStatus, co.Status) {\n\t\tif err := r.client.Status().Update(context.TODO(), co); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to update clusteroperator %s: %v\", co.Name, err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func TestSyncClusterComplex(t *testing.T) {\n\tcontroller, clusterStore, machineSetStore, _, clusterOperatorClient := newTestClusterController()\n\n\tcluster := newClusterWithSizes(1,\n\t\tclusteroperator.ClusterMachineSet{\n\t\t\tMachineSetConfig: clusteroperator.MachineSetConfig{\n\t\t\t\tSize: 1,\n\t\t\t\tNodeType: clusteroperator.NodeTypeCompute,\n\t\t\t},\n\t\t\tName: \"realized and un-mutated\",\n\t\t},\n\t\tclusteroperator.ClusterMachineSet{\n\t\t\tMachineSetConfig: clusteroperator.MachineSetConfig{\n\t\t\t\tSize: 1,\n\t\t\t\tNodeType: clusteroperator.NodeTypeCompute,\n\t\t\t},\n\t\t\tName: \"realized but mutated\",\n\t\t},\n\t\tclusteroperator.ClusterMachineSet{\n\t\t\tMachineSetConfig: clusteroperator.MachineSetConfig{\n\t\t\t\tSize: 1,\n\t\t\t\tNodeType: clusteroperator.NodeTypeCompute,\n\t\t\t},\n\t\t\tName: \"unrealized\",\n\t\t},\n\t)\n\tclusterStore.Add(cluster)\n\n\tnewMachineSetsWithSizes(machineSetStore, cluster, 2,\n\t\tclusteroperator.ClusterMachineSet{\n\t\t\tMachineSetConfig: clusteroperator.MachineSetConfig{\n\t\t\t\tSize: 1,\n\t\t\t\tNodeType: clusteroperator.NodeTypeCompute,\n\t\t\t},\n\t\t\tName: \"realized and un-mutated\",\n\t\t},\n\t\tclusteroperator.ClusterMachineSet{\n\t\t\tMachineSetConfig: clusteroperator.MachineSetConfig{\n\t\t\t\tSize: 2,\n\t\t\t\tNodeType: clusteroperator.NodeTypeCompute,\n\t\t\t},\n\t\t\tName: \"realized but mutated\",\n\t\t},\n\t\tclusteroperator.ClusterMachineSet{\n\t\t\tMachineSetConfig: clusteroperator.MachineSetConfig{\n\t\t\t\tSize: 1,\n\t\t\t\tNodeType: clusteroperator.NodeTypeCompute,\n\t\t\t},\n\t\t\tName: \"removed from cluster\",\n\t\t},\n\t)\n\n\tcontroller.syncCluster(getKey(cluster, t))\n\n\tvalidateClientActions(t, \"TestSyncClusterComplex\", clusterOperatorClient,\n\t\tnewExpectedMachineSetDeleteAction(cluster, \"master\"),\n\t\tnewExpectedMachineSetCreateAction(cluster, \"master\"),\n\t\tnewExpectedMachineSetDeleteAction(cluster, \"realized but mutated\"),\n\t\tnewExpectedMachineSetCreateAction(cluster, \"realized but mutated\"),\n\t\tnewExpectedMachineSetCreateAction(cluster, \"unrealized\"),\n\t\tnewExpectedMachineSetDeleteAction(cluster, \"removed from cluster\"),\n\t\texpectedClusterStatusUpdateAction{machineSets: 3}, // status only counts the 2 realized compute nodes + 1 master\n\t)\n\n\tvalidateControllerExpectations(t, \"TestSyncClusterComplex\", controller, cluster, 3, 3)\n}", "func (h *Handler) updateUpstreamClusterState(upstreamSpec *eksv1.EKSClusterConfigSpec, config *eksv1.EKSClusterConfig, awsSVCs *awsServices, clusterARN string, ngARNs map[string]string) (*eksv1.EKSClusterConfig, error) {\n\tif awsSVCs == nil {\n\t\treturn config, fmt.Errorf(\"aws services not initialized\")\n\t}\n\n\t// check kubernetes version for update\n\tif config.Spec.KubernetesVersion != nil {\n\t\tupdated, err := awsservices.UpdateClusterVersion(&awsservices.UpdateClusterVersionOpts{\n\t\t\tEKSService: awsSVCs.eks,\n\t\t\tConfig: config,\n\t\t\tUpstreamClusterSpec: upstreamSpec,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn config, fmt.Errorf(\"error updating cluster version: %w\", err)\n\t\t}\n\t\tif updated {\n\t\t\treturn h.enqueueUpdate(config)\n\t\t}\n\t}\n\n\t// check tags for update\n\tif config.Spec.Tags != nil {\n\t\tupdated, err := awsservices.UpdateResourceTags(&awsservices.UpdateResourceTagsOpts{\n\t\t\tEKSService: awsSVCs.eks,\n\t\t\tTags: config.Spec.Tags,\n\t\t\tUpstreamTags: upstreamSpec.Tags,\n\t\t\tResourceARN: clusterARN,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn config, fmt.Errorf(\"error updating cluster tags: %w\", err)\n\t\t}\n\t\tif updated {\n\t\t\treturn h.enqueueUpdate(config)\n\t\t}\n\t}\n\n\tif config.Spec.LoggingTypes != nil {\n\t\t// check logging for update\n\t\tupdated, err := awsservices.UpdateClusterLoggingTypes(&awsservices.UpdateLoggingTypesOpts{\n\t\t\tEKSService: awsSVCs.eks,\n\t\t\tConfig: config,\n\t\t\tUpstreamClusterSpec: upstreamSpec,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn config, fmt.Errorf(\"error updating logging types: %w\", err)\n\t\t}\n\t\tif updated {\n\t\t\treturn h.enqueueUpdate(config)\n\t\t}\n\t}\n\n\tupdated, err := awsservices.UpdateClusterAccess(&awsservices.UpdateClusterAccessOpts{\n\t\tEKSService: awsSVCs.eks,\n\t\tConfig: config,\n\t\tUpstreamClusterSpec: upstreamSpec,\n\t})\n\tif err != nil {\n\t\treturn config, fmt.Errorf(\"error updating cluster access config: %w\", err)\n\t}\n\tif updated {\n\t\treturn h.enqueueUpdate(config)\n\t}\n\n\tif config.Spec.PublicAccessSources != nil {\n\t\tupdated, err := awsservices.UpdateClusterPublicAccessSources(&awsservices.UpdateClusterPublicAccessSourcesOpts{\n\t\t\tEKSService: awsSVCs.eks,\n\t\t\tConfig: config,\n\t\t\tUpstreamClusterSpec: upstreamSpec,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn config, fmt.Errorf(\"error updating cluster public access sources: %w\", err)\n\t\t}\n\t\tif updated {\n\t\t\treturn h.enqueueUpdate(config)\n\t\t}\n\t}\n\n\tif config.Spec.NodeGroups == nil {\n\t\tlogrus.Infof(\"cluster [%s] finished updating\", config.Name)\n\t\tconfig = config.DeepCopy()\n\t\tconfig.Status.Phase = eksConfigActivePhase\n\t\treturn h.eksCC.UpdateStatus(config)\n\t}\n\n\t// check nodegroups for updates\n\n\tupstreamNgs := make(map[string]eksv1.NodeGroup)\n\tngs := make(map[string]eksv1.NodeGroup)\n\n\tfor _, ng := range upstreamSpec.NodeGroups {\n\t\tupstreamNgs[aws.StringValue(ng.NodegroupName)] = ng\n\t}\n\n\tfor _, ng := range config.Spec.NodeGroups {\n\t\tngs[aws.StringValue(ng.NodegroupName)] = ng\n\t}\n\n\t// Deep copy the config object here, so it's not copied multiple times for each\n\t// nodegroup create/delete.\n\tconfig = config.DeepCopy()\n\n\t// check if node groups need to be created\n\tvar updatingNodegroups bool\n\ttemplateVersionsToAdd := make(map[string]string)\n\tfor _, ng := range config.Spec.NodeGroups {\n\t\tif _, ok := upstreamNgs[aws.StringValue(ng.NodegroupName)]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tif err := awsservices.CreateLaunchTemplate(&awsservices.CreateLaunchTemplateOptions{\n\t\t\tEC2Service: awsSVCs.ec2,\n\t\t\tConfig: config,\n\t\t}); err != nil {\n\t\t\treturn config, fmt.Errorf(\"error getting or creating launch template: %w\", err)\n\t\t}\n\t\t// in this case update is set right away because creating the\n\t\t// nodegroup may not be immediate\n\t\tif config.Status.Phase != eksConfigUpdatingPhase {\n\t\t\tconfig.Status.Phase = eksConfigUpdatingPhase\n\t\t\tconfig, err := h.eksCC.UpdateStatus(config)\n\t\t\tif err != nil {\n\t\t\t\treturn config, err\n\t\t\t}\n\t\t}\n\n\t\tltVersion, generatedNodeRole, err := awsservices.CreateNodeGroup(&awsservices.CreateNodeGroupOptions{\n\t\t\tEC2Service: awsSVCs.ec2,\n\t\t\tCloudFormationService: awsSVCs.cloudformation,\n\t\t\tEKSService: awsSVCs.eks,\n\t\t\tConfig: config,\n\t\t\tNodeGroup: ng,\n\t\t})\n\n\t\tif err != nil {\n\t\t\treturn config, fmt.Errorf(\"error creating nodegroup: %w\", err)\n\t\t}\n\n\t\t// if a generated node role has not been set on the Status yet and it\n\t\t// was just generated, set it\n\t\tif config.Status.GeneratedNodeRole == \"\" && generatedNodeRole != \"\" {\n\t\t\tconfig.Status.GeneratedNodeRole = generatedNodeRole\n\t\t}\n\t\tif err != nil {\n\t\t\treturn config, err\n\t\t}\n\t\ttemplateVersionsToAdd[aws.StringValue(ng.NodegroupName)] = ltVersion\n\t\tupdatingNodegroups = true\n\t}\n\n\t// check for node groups need to be deleted\n\ttemplateVersionsToDelete := make(map[string]string)\n\tfor _, ng := range upstreamSpec.NodeGroups {\n\t\tif _, ok := ngs[aws.StringValue(ng.NodegroupName)]; ok {\n\t\t\tcontinue\n\t\t}\n\t\ttemplateVersionToDelete, _, err := deleteNodeGroup(config, ng, awsSVCs.eks)\n\t\tif err != nil {\n\t\t\treturn config, err\n\t\t}\n\t\tupdatingNodegroups = true\n\t\tif templateVersionToDelete != nil {\n\t\t\ttemplateVersionsToDelete[aws.StringValue(ng.NodegroupName)] = *templateVersionToDelete\n\t\t}\n\t}\n\n\tif updatingNodegroups {\n\t\tif len(templateVersionsToDelete) != 0 || len(templateVersionsToAdd) != 0 {\n\t\t\tconfig.Status.Phase = eksConfigUpdatingPhase\n\t\t\tconfig.Status.TemplateVersionsToDelete = append(config.Status.TemplateVersionsToDelete, utils.ValuesFromMap(templateVersionsToDelete)...)\n\t\t\tconfig.Status.ManagedLaunchTemplateVersions = utils.SubtractMaps(config.Status.ManagedLaunchTemplateVersions, templateVersionsToDelete)\n\t\t\tconfig.Status.ManagedLaunchTemplateVersions = utils.MergeMaps(config.Status.ManagedLaunchTemplateVersions, templateVersionsToAdd)\n\t\t\treturn h.eksCC.UpdateStatus(config)\n\t\t}\n\t\treturn h.enqueueUpdate(config)\n\t}\n\n\t// check node groups for kubernetes version updates\n\tdesiredNgVersions := make(map[string]string)\n\tfor _, ng := range config.Spec.NodeGroups {\n\t\tif ng.Version != nil {\n\t\t\tdesiredVersion := aws.StringValue(ng.Version)\n\t\t\tif desiredVersion == \"\" {\n\t\t\t\tdesiredVersion = aws.StringValue(config.Spec.KubernetesVersion)\n\t\t\t}\n\t\t\tdesiredNgVersions[aws.StringValue(ng.NodegroupName)] = desiredVersion\n\t\t}\n\t}\n\n\tvar updateNodegroupProperties bool\n\ttemplateVersionsToDelete = make(map[string]string)\n\tfor _, upstreamNg := range upstreamSpec.NodeGroups {\n\t\t// if continue is used after an update, it means that update\n\t\t// must finish before others for that nodegroup can take place.\n\t\t// Some updates such as minSize, maxSize, and desiredSize can\n\t\t// happen together\n\n\t\tng := ngs[aws.StringValue(upstreamNg.NodegroupName)]\n\t\tngVersionInput := &eks.UpdateNodegroupVersionInput{\n\t\t\tNodegroupName: aws.String(aws.StringValue(ng.NodegroupName)),\n\t\t\tClusterName: aws.String(config.Spec.DisplayName),\n\t\t}\n\n\t\t// rancherManagedLaunchTemplate is true if user did not specify a custom launch template\n\t\trancherManagedLaunchTemplate := false\n\t\tif upstreamNg.LaunchTemplate != nil {\n\t\t\tupstreamTemplateVersion := aws.Int64Value(upstreamNg.LaunchTemplate.Version)\n\t\t\tvar err error\n\t\t\tlt := ng.LaunchTemplate\n\n\t\t\tif lt == nil && config.Status.ManagedLaunchTemplateID == aws.StringValue(upstreamNg.LaunchTemplate.ID) {\n\t\t\t\trancherManagedLaunchTemplate = true\n\t\t\t\t// In this case, Rancher is managing the launch template, so we check to see if we need a new version.\n\t\t\t\tlt, err = newLaunchTemplateVersionIfNeeded(config, upstreamNg, ng, awsSVCs.ec2)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn config, err\n\t\t\t\t}\n\n\t\t\t\tif lt != nil {\n\t\t\t\t\tif upstreamTemplateVersion > 0 {\n\t\t\t\t\t\ttemplateVersionsToDelete[aws.StringValue(upstreamNg.NodegroupName)] = strconv.FormatInt(upstreamTemplateVersion, 10)\n\t\t\t\t\t}\n\t\t\t\t\ttemplateVersionsToAdd[aws.StringValue(ng.NodegroupName)] = strconv.FormatInt(*lt.Version, 10)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif lt != nil && aws.Int64Value(lt.Version) != upstreamTemplateVersion {\n\t\t\t\tngVersionInput.LaunchTemplate = &eks.LaunchTemplateSpecification{\n\t\t\t\t\tId: lt.ID,\n\t\t\t\t\tVersion: aws.String(strconv.FormatInt(*lt.Version, 10)),\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// a node group created from a custom launch template can only be updated with a new version of the launch template\n\t\t// that uses an AMI with the desired kubernetes version, hence, only update on version mismatch if the node group was created with a rancher-managed launch template\n\t\tif ng.Version != nil && rancherManagedLaunchTemplate {\n\t\t\tif aws.StringValue(upstreamNg.Version) != desiredNgVersions[aws.StringValue(ng.NodegroupName)] {\n\t\t\t\tngVersionInput.Version = aws.String(desiredNgVersions[aws.StringValue(ng.NodegroupName)])\n\t\t\t}\n\t\t}\n\n\t\tif ngVersionInput.Version != nil || ngVersionInput.LaunchTemplate != nil {\n\t\t\tupdateNodegroupProperties = true\n\t\t\tif err := awsservices.UpdateNodegroupVersion(&awsservices.UpdateNodegroupVersionOpts{\n\t\t\t\tEKSService: awsSVCs.eks,\n\t\t\t\tEC2Service: awsSVCs.ec2,\n\t\t\t\tConfig: config,\n\t\t\t\tNodeGroup: &ng,\n\t\t\t\tNGVersionInput: ngVersionInput,\n\t\t\t\tLTVersions: templateVersionsToAdd,\n\t\t\t}); err != nil {\n\t\t\t\treturn config, err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tupdateNodegroupConfig, sendUpdateNodegroupConfig := getNodegroupConfigUpdate(config.Spec.DisplayName, ng, upstreamNg)\n\n\t\tif sendUpdateNodegroupConfig {\n\t\t\tupdateNodegroupProperties = true\n\t\t\t_, err := awsSVCs.eks.UpdateNodegroupConfig(&updateNodegroupConfig)\n\t\t\tif err != nil {\n\t\t\t\treturn config, err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif ng.Tags != nil {\n\t\t\tvar err error // initialize error here because we assign returned value to updateNodegroupProperties\n\t\t\tupdateNodegroupProperties, err = awsservices.UpdateResourceTags(&awsservices.UpdateResourceTagsOpts{\n\t\t\t\tEKSService: awsSVCs.eks,\n\t\t\t\tTags: aws.StringValueMap(ng.Tags),\n\t\t\t\tUpstreamTags: aws.StringValueMap(upstreamNg.Tags),\n\t\t\t\tResourceARN: ngARNs[aws.StringValue(ng.NodegroupName)],\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn config, fmt.Errorf(\"error updating cluster tags: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif updateNodegroupProperties {\n\t\t// if any updates are taking place on nodegroups, the config's phase needs\n\t\t// to be set to \"updating\" and the controller will wait for the updates to\n\t\t// finish before proceeding\n\t\tif len(templateVersionsToDelete) != 0 || len(templateVersionsToAdd) != 0 {\n\t\t\tconfig = config.DeepCopy()\n\t\t\tconfig.Status.TemplateVersionsToDelete = append(config.Status.TemplateVersionsToDelete, utils.ValuesFromMap(templateVersionsToDelete)...)\n\t\t\tconfig.Status.ManagedLaunchTemplateVersions = utils.SubtractMaps(config.Status.ManagedLaunchTemplateVersions, templateVersionsToAdd)\n\t\t\tconfig.Status.ManagedLaunchTemplateVersions = utils.MergeMaps(config.Status.ManagedLaunchTemplateVersions, templateVersionsToAdd)\n\t\t\tconfig.Status.Phase = eksConfigUpdatingPhase\n\t\t\treturn h.eksCC.UpdateStatus(config)\n\t\t}\n\t\treturn h.enqueueUpdate(config)\n\t}\n\n\t// check if ebs csi driver needs to be enabled\n\tif aws.BoolValue(config.Spec.EBSCSIDriver) {\n\t\tinstalledArn, err := awsservices.CheckEBSAddon(awsSVCs.eks, config)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error checking if ebs csi driver addon is installed: %w\", err)\n\t\t}\n\t\tif installedArn == \"\" {\n\t\t\tlogrus.Infof(\"enabling [ebs csi driver add-on] for cluster [%s]\", config.Spec.DisplayName)\n\t\t\tebsCSIDriverInput := awsservices.EnableEBSCSIDriverInput{\n\t\t\t\tEKSService: awsSVCs.eks,\n\t\t\t\tIAMService: awsSVCs.iam,\n\t\t\t\tCFService: awsSVCs.cloudformation,\n\t\t\t\tConfig: config,\n\t\t\t\tAddonVersion: \"latest\",\n\t\t\t}\n\t\t\tif err := awsservices.EnableEBSCSIDriver(&ebsCSIDriverInput); err != nil {\n\t\t\t\treturn config, fmt.Errorf(\"error enabling ebs csi driver addon: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\t// no new updates, set to active\n\tif config.Status.Phase != eksConfigActivePhase {\n\t\tlogrus.Infof(\"cluster [%s] finished updating\", config.Name)\n\t\tconfig = config.DeepCopy()\n\t\tconfig.Status.Phase = eksConfigActivePhase\n\t\treturn h.eksCC.UpdateStatus(config)\n\t}\n\n\t// check for node groups updates here\n\treturn config, nil\n}", "func GetCurrentNodeCount(ctx context.Context, projectID, targetLabel string) (map[string]int64, error) {\n\ts, err := container.NewService(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcomputeService, err := compute.NewService(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// get all clusters list\n\tclusters, err := container.NewProjectsLocationsClustersService(s).List(\"projects/\" + projectID + \"/locations/-\").Do()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := make(map[string]int64)\n\n\treZone := regexp.MustCompile(\".*/zones/\")\n\treInstance := regexp.MustCompile(\".*/instanceGroupManagers/\")\n\treEtc := regexp.MustCompile(\"/.*\")\n\n\tfor _, cluster := range filter(clusters.Clusters, targetLabel, \"true\") {\n\t\tfor _, nodePool := range cluster.NodePools {\n\t\t\t// nodePool.InstanceGroupUrls's format is below\n\t\t\t// [\"https://www.googleapis.com/compute/v1/projects/<projectID>/zones/<zone1>/instanceGroupManagers/gke-test-scheduler-2-default-pool-2b19b588-grp\",\n\t\t\t// \"https://www.googleapis.com/compute/v1/projects/<projectID>/zones/<zone2>/instanceGroupManagers/gke-test-scheduler-2-default-pool-2b19b588-grp\",\n\t\t\t// \"https://www.googleapis.com/compute/v1/projects/<projectID>/zones/<zone3>/instanceGroupManagers/gke-test-scheduler-2-default-pool-2b19b588-grp\"]\n\n\t\t\tzone := reZone.ReplaceAllString(nodePool.InstanceGroupUrls[0], \"\") //\"<zone1>/instanceGroupManagers/gke-test-scheduler-2-default-pool-2b19b588-grp\"\n\t\t\tzone = reEtc.ReplaceAllString(zone, \"\") //\"<zone1>\n\t\t\tinstanceGroup := reInstance.ReplaceAllString(nodePool.InstanceGroupUrls[0], \"\")\n\t\t\tresp, err := computeService.InstanceGroups.Get(projectID, zone, instanceGroup).Context(ctx).Do()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tsize := resp.Size\n\t\t\tresult[nodePool.Name] = size\n\t\t}\n\t}\n\treturn result, nil\n}" ]
[ "0.6054842", "0.593886", "0.5845953", "0.581711", "0.5627319", "0.5349552", "0.526581", "0.5252384", "0.52262604", "0.5159638", "0.5146171", "0.513784", "0.51282734", "0.5118211", "0.5116108", "0.5110766", "0.509067", "0.5069988", "0.5057845", "0.50446874", "0.5032809", "0.50314903", "0.5025387", "0.5018574", "0.5016573", "0.5008087", "0.50018126", "0.49887156", "0.49788827", "0.4977264", "0.49646828", "0.49549887", "0.49507824", "0.4938901", "0.49306372", "0.49188584", "0.49061397", "0.48977605", "0.48754603", "0.48603186", "0.4859759", "0.4847222", "0.4843157", "0.48325264", "0.4826049", "0.48133796", "0.48066494", "0.4805886", "0.4802706", "0.48000532", "0.47997198", "0.47995552", "0.4797615", "0.47893173", "0.47811976", "0.47803098", "0.4775181", "0.47641668", "0.47579423", "0.4756954", "0.47568825", "0.4756694", "0.4751179", "0.4729511", "0.47233647", "0.47233576", "0.4719231", "0.47177422", "0.4714215", "0.47130933", "0.47125027", "0.47115916", "0.4710297", "0.4708965", "0.4708574", "0.47028732", "0.47022343", "0.4701213", "0.46987683", "0.46978572", "0.4697031", "0.46965775", "0.4694664", "0.46911913", "0.46889964", "0.46881926", "0.46874866", "0.46825325", "0.46806756", "0.46768668", "0.4676022", "0.4674825", "0.46727857", "0.46707946", "0.46626016", "0.4662401", "0.46617737", "0.46603495", "0.46583003", "0.465716" ]
0.5302026
6
applyConfiguration apply new configuration if needed: add or delete pods configure the submarineserver process
func (c *Controller) applyConfiguration(admin submarine.AdminInterface, cluster *rapi.SubmarineCluster) (bool, error) { glog.Info("applyConfiguration START") defer glog.Info("applyConfiguration STOP") asChanged := false // expected replication factor and number of master nodes cReplicaFactor := *cluster.Spec.ReplicationFactor cNbMaster := *cluster.Spec.NumberOfMaster // Adapt, convert CR to structure in submarine package rCluster, nodes, err := newSubmarineCluster(admin, cluster) if err != nil { glog.Errorf("Unable to create the SubmarineCluster view, error:%v", err) return false, err } // PodTemplate changes require rolling updates if needRollingUpdate(cluster) { if setRollingUpdateCondition(&cluster.Status, true) { if cluster, err = c.updateHandler(cluster); err != nil { return false, err } } glog.Info("applyConfiguration needRollingUpdate") return c.manageRollingUpdate(admin, cluster, rCluster, nodes) } if setRollingUpdateCondition(&cluster.Status, false) { if cluster, err = c.updateHandler(cluster); err != nil { return false, err } } // if the number of Pods is greater than expected if needLessPods(cluster) { if setRebalancingCondition(&cluster.Status, true) { if cluster, err = c.updateHandler(cluster); err != nil { return false, err } } glog.Info("applyConfiguration needLessPods") // Configure Submarine cluster return c.managePodScaleDown(admin, cluster, rCluster, nodes) } // If it is not a rolling update, modify the Condition if setRebalancingCondition(&cluster.Status, false) { if cluster, err = c.updateHandler(cluster); err != nil { return false, err } } clusterStatus := &cluster.Status.Cluster if (clusterStatus.NbPods - clusterStatus.NbSubmarineRunning) != 0 { glog.V(3).Infof("All pods not ready wait to be ready, nbPods: %d, nbPodsReady: %d", clusterStatus.NbPods, clusterStatus.NbSubmarineRunning) return false, err } // First, we define the new masters // Select the desired number of Masters and assign Hashslots to each Master. The Master will be distributed to different K8S nodes as much as possible // Set the cluster status to Calculating Rebalancing newMasters, curMasters, allMaster, err := clustering.DispatchMasters(rCluster, nodes, cNbMaster, admin) if err != nil { glog.Errorf("Cannot dispatch slots to masters: %v", err) rCluster.Status = rapi.ClusterStatusError return false, err } // If the number of new and old masters is not the same if len(newMasters) != len(curMasters) { asChanged = true } // Second select Node that is already a slave currentSlaveNodes := nodes.FilterByFunc(submarine.IsSlave) //New slaves are slaves which is currently a master with no slots newSlave := nodes.FilterByFunc(func(nodeA *submarine.Node) bool { for _, nodeB := range newMasters { if nodeA.ID == nodeB.ID { return false } } for _, nodeB := range currentSlaveNodes { if nodeA.ID == nodeB.ID { return false } } return true }) // Depending on whether we scale up or down, we will dispatch slaves before/after the dispatch of slots if cNbMaster < int32(len(curMasters)) { // this happens usually after a scale down of the cluster // we should dispatch slots before dispatching slaves if err := clustering.DispatchSlotToNewMasters(rCluster, admin, newMasters, curMasters, allMaster); err != nil { glog.Error("Unable to dispatch slot on new master, err:", err) return false, err } // assign master/slave roles newSubmarineSlavesByMaster, bestEffort := clustering.PlaceSlaves(rCluster, newMasters, currentSlaveNodes, newSlave, cReplicaFactor) if bestEffort { rCluster.NodesPlacement = rapi.NodesPlacementInfoBestEffort } if err := clustering.AttachingSlavesToMaster(rCluster, admin, newSubmarineSlavesByMaster); err != nil { glog.Error("Unable to dispatch slave on new master, err:", err) return false, err } } else { // We are scaling up the nbmaster or the nbmaster doesn't change. // assign master/slave roles newSubmarineSlavesByMaster, bestEffort := clustering.PlaceSlaves(rCluster, newMasters, currentSlaveNodes, newSlave, cReplicaFactor) if bestEffort { rCluster.NodesPlacement = rapi.NodesPlacementInfoBestEffort } if err := clustering.AttachingSlavesToMaster(rCluster, admin, newSubmarineSlavesByMaster); err != nil { glog.Error("Unable to dispatch slave on new master, err:", err) return false, err } if err := clustering.DispatchSlotToNewMasters(rCluster, admin, newMasters, curMasters, allMaster); err != nil { glog.Error("Unable to dispatch slot on new master, err:", err) return false, err } } glog.V(4).Infof("new nodes status: \n %v", nodes) // Set the cluster status rCluster.Status = rapi.ClusterStatusOK // wait a bit for the cluster to propagate configuration to reduce warning logs because of temporary inconsistency time.Sleep(1 * time.Second) return asChanged, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (service *retrierMockService) ApplyConfiguration(_ interface{}) error {\n\tservice.applyConfCount++\n\treturn nil\n}", "func (c *Controller) deployConfiguration(config *dynamic.Configuration) error {\n\tsel := labels.Everything()\n\n\tr, err := labels.NewRequirement(\"component\", selection.Equals, []string{\"maesh-mesh\"})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsel = sel.Add(*r)\n\n\tpodList, err := c.PodLister.Pods(c.meshNamespace).List(sel)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to get pods: %w\", err)\n\t}\n\n\tif len(podList) == 0 {\n\t\treturn fmt.Errorf(\"unable to find any active mesh pods to deploy config : %+v\", config)\n\t}\n\n\tif err := c.deployToPods(podList, config); err != nil {\n\t\treturn fmt.Errorf(\"error deploying configuration: %v\", err)\n\t}\n\n\treturn nil\n}", "func (c *updateConfigCmd) Run(k *kong.Context, logger logging.Logger) error {\n\tlogger = logger.WithValues(\"Name\", c.Name)\n\tkubeConfig, err := ctrl.GetConfig()\n\tif err != nil {\n\t\tlogger.Debug(errKubeConfig, \"error\", err)\n\t\treturn errors.Wrap(err, errKubeConfig)\n\t}\n\tlogger.Debug(\"Found kubeconfig\")\n\tkube, err := typedclient.NewForConfig(kubeConfig)\n\tif err != nil {\n\t\tlogger.Debug(errKubeClient, \"error\", err)\n\t\treturn errors.Wrap(err, errKubeClient)\n\t}\n\tlogger.Debug(\"Created kubernetes client\")\n\tprevConf, err := kube.Configurations().Get(context.Background(), c.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\terr = warnIfNotFound(err)\n\t\tlogger.Debug(\"Failed to update configuration\", \"error\", err)\n\t\treturn errors.Wrap(err, \"cannot update configuration\")\n\t}\n\tlogger.Debug(\"Found previous configuration object\")\n\tpkg := prevConf.Spec.Package\n\tpkgReference, err := name.ParseReference(pkg, name.WithDefaultRegistry(\"\"))\n\tif err != nil {\n\t\terr = warnIfNotFound(err)\n\t\tlogger.Debug(\"Failed to update configuration\", \"error\", err)\n\t\treturn errors.Wrap(err, \"cannot update configuration\")\n\t}\n\tnewPkg := \"\"\n\tif strings.HasPrefix(c.Tag, \"sha256\") {\n\t\tnewPkg = pkgReference.Context().Digest(c.Tag).Name()\n\t} else {\n\t\tnewPkg = pkgReference.Context().Tag(c.Tag).Name()\n\t}\n\tprevConf.Spec.Package = newPkg\n\treq, err := json.Marshal(prevConf)\n\tif err != nil {\n\t\terr = warnIfNotFound(err)\n\t\tlogger.Debug(\"Failed to update configuration\", \"error\", err)\n\t\treturn errors.Wrap(err, \"cannot update configuration\")\n\t}\n\tres, err := kube.Configurations().Patch(context.Background(), c.Name, types.MergePatchType, req, metav1.PatchOptions{})\n\tif err != nil {\n\t\terr = warnIfNotFound(err)\n\t\tlogger.Debug(\"Failed to update configuration\", \"error\", err)\n\t\treturn errors.Wrap(err, \"cannot update configuration\")\n\t}\n\t_, err = fmt.Fprintf(k.Stdout, \"%s/%s updated\\n\", strings.ToLower(v1.ConfigurationGroupKind), res.GetName())\n\treturn err\n}", "func (m *Manager) ApplyConfig(cfg map[string]sd_config.ServiceDiscoveryConfig) error {\n\tm.mtx.Lock()\n\tdefer m.mtx.Unlock()\n\n\tm.cancelDiscoverers()\n\tfor name, scfg := range cfg {\n\t\tfor provName, prov := range m.providersFromConfig(scfg) {\n\t\t\tm.startProvider(m.ctx, poolKey{setName: name, provider: provName}, prov)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (b *Backend) ApplyConfiguration(config gw.GatewayConfiguration) error {\n\tfor i := range config.Channels {\n\t\tloRaModConfig := config.Channels[i].GetLoraModulationConfig()\n\t\tif loRaModConfig != nil {\n\t\t\tloRaModConfig.Bandwidth = loRaModConfig.Bandwidth * 1000\n\t\t}\n\n\t\tfskModConfig := config.Channels[i].GetFskModulationConfig()\n\t\tif fskModConfig != nil {\n\t\t\tfskModConfig.Bandwidth = fskModConfig.Bandwidth * 1000\n\t\t}\n\t}\n\n\tlog.WithFields(log.Fields{\n\t\t\"version\": config.Version,\n\t}).Info(\"backend/concentratord: forwarding configuration command\")\n\n\t_, err := b.commandRequest(\"config\", &config)\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"backend/concentratord: send configuration command error\")\n\t}\n\n\tcommandCounter(\"config\").Inc()\n\n\treturn nil\n}", "func (cac *EnvironmentServiceConfigController) Configure(client Client, deploymentName, namespace string) error {\n\t//cloudapp deployment config should be in place at this point, but check\n\tvar configurationStatus = ConfigurationStatus{Started: time.Now(), Log: []string{\"starting configuration for service \" + deploymentName}, Status: configInProgress}\n\tkey := namespace + \"/\" + deploymentName\n\tcac.StatusPublisher.Publish(key, configurationStatus)\n\tvar statusUpdate = func(message, status string) {\n\t\tconfigurationStatus.Status = status\n\t\tconfigurationStatus.Log = append(configurationStatus.Log, message)\n\t\tcac.StatusPublisher.Publish(key, configurationStatus)\n\t}\n\t// ensure we have the latest DeploymentConfig\n\tdeployment, err := client.GetDeploymentConfigByName(namespace, deploymentName)\n\tif err != nil {\n\t\tstatusUpdate(\"unexpected error retrieving DeploymentConfig\"+err.Error(), configError)\n\t\treturn err\n\t}\n\tif deployment == nil {\n\t\tstatusUpdate(\"could not find DeploymentConfig for \"+deploymentName, configError)\n\t\treturn errors.New(\"could not find DeploymentConfig for \" + deploymentName)\n\t}\n\t//find the deployed services\n\tservices, err := client.FindDeploymentConfigsByLabel(namespace, map[string]string{\"rhmap/type\": \"environmentService\"})\n\tif err != nil {\n\t\tstatusUpdate(\"failed to retrieve environment Service dcs during configuration of \"+deployment.Name+\" \"+err.Error(), \"error\")\n\t\treturn err\n\t}\n\terrs := []string{}\n\t//configure for any environment services already deployed\n\tfor _, s := range services {\n\t\tserviceName := s.Labels[\"rhmap/name\"]\n\t\tc := cac.ConfigurationFactory.Factory(serviceName)\n\t\t_, err := c.Configure(client, deployment, namespace)\n\t\tif err != nil {\n\t\t\terrs = append(errs, err.Error())\n\t\t}\n\t}\n\tif _, err := client.UpdateDeployConfigInNamespace(namespace, deployment); err != nil {\n\t\treturn errors.Wrap(err, \"failed to update deployment after configuring it \")\n\t}\n\t//TODO given we have a status updater do we really need to return errors from the configuration handlers\n\tif len(errs) > 0 {\n\t\treturn errors.New(\"some services failed to configure: \" + strings.Join(errs, \" : \"))\n\t}\n\treturn nil\n}", "func (d *Deployer) deployConfiguration(c *dynamic.Configuration) bool {\n\t// Make a copy to deploy, so changes to the main configuration don't propagate\n\tdeployConfig := c.DeepCopy()\n\n\tpodList, err := d.client.ListPodWithOptions(d.meshNamespace, metav1.ListOptions{\n\t\tLabelSelector: \"component==maesh-mesh\",\n\t})\n\tif err != nil {\n\t\tlog.Errorf(\"Could not retrieve pod list: %v\", err)\n\t\treturn false\n\t}\n\n\tif len(podList.Items) == 0 {\n\t\tlog.Errorf(\"Could not find any active mesh pods to deploy config : %+v\", c.HTTP)\n\t\treturn false\n\t}\n\n\tfor _, pod := range podList.Items {\n\t\tlog.Debugf(\"Add configuration to deploy queue for pod %s with IP %s\", pod.Name, pod.Status.PodIP)\n\n\t\td.DeployToPod(pod.Name, pod.Status.PodIP, deployConfig)\n\t}\n\n\treturn true\n}", "func (c *Controller) deployConfigurationToUnreadyNodes(config *dynamic.Configuration) error {\n\tsel := labels.Everything()\n\n\tr, err := labels.NewRequirement(\"component\", selection.Equals, []string{\"maesh-mesh\"})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsel = sel.Add(*r)\n\n\tpodList, err := c.PodLister.Pods(c.meshNamespace).List(sel)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to get pods: %w\", err)\n\t}\n\n\tif len(podList) == 0 {\n\t\treturn fmt.Errorf(\"unable to find any active mesh pods to deploy config : %+v\", config)\n\t}\n\n\tvar unreadyPods []*corev1.Pod\n\n\tfor _, pod := range podList {\n\t\tfor _, status := range pod.Status.ContainerStatuses {\n\t\t\tif !status.Ready {\n\t\t\t\tunreadyPods = append(unreadyPods, pod)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := c.deployToPods(unreadyPods, config); err != nil {\n\t\treturn fmt.Errorf(\"error deploying configuration: %v\", err)\n\t}\n\n\treturn nil\n}", "func (s *Service) ApplyConfiguration(config interface{}) error {\n\tif err := s.CheckConfiguration(config); err != nil {\n\t\treturn err\n\t}\n\tvar ok bool\n\ts.Cfg, ok = config.(Configuration)\n\tif !ok {\n\t\treturn fmt.Errorf(\"Invalid configuration\")\n\t}\n\n\ts.ServiceName = s.Cfg.Name\n\ts.ServiceType = sdk.TypeUI\n\ts.HTTPURL = s.Cfg.URL\n\ts.MaxHeartbeatFailures = s.Cfg.API.MaxHeartbeatFailures\n\ts.Router.Config = s.Cfg.HTTP\n\n\t// HTMLDir must contains the ui dist directory.\n\t// ui.tar.gz contains the dist directory\n\ts.HTMLDir = filepath.Join(s.Cfg.Staticdir, \"dist\")\n\ts.DocsDir = filepath.Join(s.Cfg.Staticdir, \"docs\")\n\ts.Cfg.BaseURL = strings.TrimSpace(s.Cfg.BaseURL)\n\tif s.Cfg.BaseURL == \"\" { // s.Cfg.BaseURL could not be empty\n\t\ts.Cfg.BaseURL = \"/\"\n\t}\n\n\treturn nil\n}", "func (s *Service) ApplyConfiguration(config interface{}) error {\n\tif err := s.CheckConfiguration(config); err != nil {\n\t\treturn err\n\t}\n\tvar ok bool\n\ts.Cfg, ok = config.(Configuration)\n\tif !ok {\n\t\treturn fmt.Errorf(\"ApplyConfiguration> Invalid Elasticsearch configuration\")\n\t}\n\ts.Router = &api.Router{\n\t\tMux: mux.NewRouter(),\n\t\tConfig: s.Cfg.HTTP,\n\t}\n\ts.HTTPURL = s.Cfg.URL\n\ts.ServiceName = s.Cfg.Name\n\ts.ServiceType = sdk.TypeElasticsearch\n\ts.MaxHeartbeatFailures = s.Cfg.API.MaxHeartbeatFailures\n\n\treturn nil\n}", "func createTargetConfig(c TargetConfigController, recorder events.Recorder, operatorConfig *operatorv1.KubeAPIServer) (bool, error) {\n\terrors := []error{}\n\n\tdirectResourceResults := resourceapply.ApplyDirectly(c.kubeClient, c.eventRecorder, v311_00_assets.Asset,\n\t\t\"v3.11.0/kube-apiserver/ns.yaml\",\n\t\t\"v3.11.0/kube-apiserver/svc.yaml\",\n\t)\n\n\tfor _, currResult := range directResourceResults {\n\t\tif currResult.Error != nil {\n\t\t\terrors = append(errors, fmt.Errorf(\"%q (%T): %v\", currResult.File, currResult.Type, currResult.Error))\n\t\t}\n\t}\n\n\t_, _, err := manageKubeAPIServerConfig(c.kubeClient.CoreV1(), recorder, operatorConfig)\n\tif err != nil {\n\t\terrors = append(errors, fmt.Errorf(\"%q: %v\", \"configmap/config\", err))\n\t}\n\t_, _, err = managePod(c.kubeClient.CoreV1(), recorder, operatorConfig, c.targetImagePullSpec)\n\tif err != nil {\n\t\terrors = append(errors, fmt.Errorf(\"%q: %v\", \"configmap/kube-apiserver-pod\", err))\n\t}\n\t_, _, err = manageClientCABundle(c.configMapLister, c.kubeClient.CoreV1(), recorder)\n\tif err != nil {\n\t\terrors = append(errors, fmt.Errorf(\"%q: %v\", \"configmap/client-ca\", err))\n\t}\n\t_, _, err = manageAggregatorClientCABundle(c.configMapLister, c.kubeClient.CoreV1(), recorder)\n\tif err != nil {\n\t\terrors = append(errors, fmt.Errorf(\"%q: %v\", \"configmap/aggregator-client-ca\", err))\n\t}\n\t_, _, err = manageKubeletServingCABundle(c.configMapLister, c.kubeClient.CoreV1(), recorder)\n\tif err != nil {\n\t\terrors = append(errors, fmt.Errorf(\"%q: %v\", \"configmap/kubelet-serving-ca\", err))\n\t}\n\n\tif len(errors) > 0 {\n\t\tcondition := operatorv1.OperatorCondition{\n\t\t\tType: \"TargetConfigControllerFailing\",\n\t\t\tStatus: operatorv1.ConditionTrue,\n\t\t\tReason: \"SynchronizationError\",\n\t\t\tMessage: v1helpers.NewMultiLineAggregate(errors).Error(),\n\t\t}\n\t\tif _, _, err := v1helpers.UpdateStaticPodStatus(c.operatorClient, v1helpers.UpdateStaticPodConditionFn(condition)); err != nil {\n\t\t\treturn true, err\n\t\t}\n\t\treturn true, nil\n\t}\n\n\tcondition := operatorv1.OperatorCondition{\n\t\tType: \"TargetConfigControllerFailing\",\n\t\tStatus: operatorv1.ConditionFalse,\n\t}\n\tif _, _, err := v1helpers.UpdateStaticPodStatus(c.operatorClient, v1helpers.UpdateStaticPodConditionFn(condition)); err != nil {\n\t\treturn true, err\n\t}\n\n\treturn false, nil\n}", "func (c *controller) ApplyConfigMap(namespace string, configMap *ConfigMap) error {\n\tcm := apicorev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: configMap.Name,\n\t\t\tNamespace: namespace,\n\t\t},\n\t\tData: map[string]string{\n\t\t\tconfigMap.FileName: configMap.Data,\n\t\t},\n\t}\n\t_, err := c.k8sCoreClient.ConfigMaps(namespace).Get(cm.Name, metav1.GetOptions{})\n\tif err == nil {\n\t\t// exists, we update instead\n\t\t_, err = c.k8sCoreClient.ConfigMaps(namespace).Update(&cm)\n\t\treturn err\n\t}\n\t_, err = c.k8sCoreClient.ConfigMaps(namespace).Create(&cm)\n\treturn err\n}", "func (nc *NabtoClient) ApplyConfig() {\n\n}", "func (r *Microk8sConfigReconciler) Reconcile(req ctrl.Request) (_ ctrl.Result, rerr error) {\n\tctx := context.Background()\n\tlog := r.Log.WithValues(\"microk8sconfig\", req.NamespacedName)\n\n\t// your logic here\n\tmicrok8sconfig := &bootstrapv1alpha1.Microk8sConfig{}\n\n\tif err := r.Client.Get(ctx, req.NamespacedName, microk8sconfig); err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn ctrl.Result{}, nil\n\t\t}\n\t\tlog.Error(err, \"failed to get config\")\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t// Look up the owner of this KubeConfig if there is one\n\tconfigOwner, err := bsutil.GetConfigOwner(ctx, r.Client, microk8sconfig)\n\tif apierrors.IsNotFound(err) {\n\t\t// Could not find the owner yet, this is not an error and will rereconcile when the owner gets set.\n\t\treturn ctrl.Result{}, nil\n\t}\n\tif err != nil {\n\t\tlog.Error(err, \"failed to get owner\")\n\t\treturn ctrl.Result{}, err\n\t}\n\tif configOwner == nil {\n\t\tlog.Error(err, \"failed to get config-owner\")\n\t\treturn ctrl.Result{}, nil\n\t}\n\tlog = log.WithValues(\"kind\", configOwner.GetKind(), \"version\", configOwner.GetResourceVersion(), \"name\", configOwner.GetName())\n\n\t// Initialize the patch helper\n\tpatchHelper, err := patch.NewHelper(microk8sconfig, r)\n\tif err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\n\tif configOwner.IsControlPlaneMachine() {\n\t\t_, err := r.setupControlPlaneBootstrapData(ctx, microk8sconfig)\n\t\tif err != nil {\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t\treturn ctrl.Result{}, patchHelper.Patch(ctx, microk8sconfig)\n\t} else {\n\t\t// Worker node\n\t\t_, err := r.setupWorkerBootstrapData(ctx, microk8sconfig)\n\t\tif err != nil {\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t\treturn ctrl.Result{}, patchHelper.Patch(ctx, microk8sconfig)\n\t}\n}", "func (d *DataMongoConfigure) Configure(client Client, deployment *dc.DeploymentConfig, namespace string) (*dc.DeploymentConfig, error) {\n\tesName := \"data-mongo\"\n\td.statusUpdate(deployment.Name, \"starting configuration of data service for \"+deployment.Name, configInProgress)\n\tif v, ok := deployment.Labels[\"rhmap/name\"]; ok {\n\t\tif v == esName {\n\t\t\td.statusUpdate(deployment.Name, \"no need to configure data DeploymentConfig \", configComplete)\n\t\t\treturn deployment, nil\n\t\t}\n\t}\n\tvar constructMongoURL = func(host, user, pass, db, replicaSet interface{}) string {\n\t\turl := fmt.Sprintf(\"mongodb://%s:%s@%s:27017/%s\", user.(string), pass.(string), host.(string), db.(string))\n\t\tif \"\" != replicaSet {\n\t\t\turl += \"?replicaSet=\" + replicaSet.(string)\n\t\t}\n\t\treturn url\n\t}\n\t// look for the Job if it already exists no need to run it again\n\texistingJob, err := client.FindJobByName(namespace, deployment.Name+\"-dataconfig-job\")\n\tif err != nil {\n\t\td.statusUpdate(deployment.Name, \"error finding existing Job \"+err.Error(), \"error\")\n\t\treturn deployment, nil\n\t}\n\tif existingJob != nil {\n\t\td.statusUpdate(deployment.Name, \"configuration job \"+deployment.Name+\"-dataconfig-job already exists. No need to run again \", \"complete\")\n\t\treturn deployment, nil\n\t}\n\tdataDc, err := client.FindDeploymentConfigsByLabel(namespace, map[string]string{\"rhmap/name\": esName})\n\tif err != nil {\n\t\td.statusUpdate(deployment.Name, \"failed to find data DeploymentConfig. Cannot continue \"+err.Error(), configError)\n\t\treturn nil, err\n\t}\n\tif len(dataDc) == 0 {\n\t\terr := errors.New(\"no data DeploymentConfig exists. Cannot continue\")\n\t\td.statusUpdate(deployment.Name, err.Error(), configError)\n\t\treturn nil, err\n\t}\n\tdataService, err := client.FindServiceByLabel(namespace, map[string]string{\"rhmap/name\": esName})\n\tif err != nil {\n\t\td.statusUpdate(deployment.Name, \"failed to find data service cannot continue \"+err.Error(), configError)\n\t\treturn nil, err\n\t}\n\tif len(dataService) == 0 {\n\t\terr := errors.New(\"no service for data found. Cannot continue\")\n\t\td.statusUpdate(deployment.Name, err.Error(), configError)\n\t\treturn nil, err\n\t}\n\t// if we get this far then the job does not exists so we will run another one which will update the FH_MONGODB_CONN_URL and create or update any database and user password definitions\n\tjobOpts := map[string]interface{}{}\n\t//we know we have a data deployment config and it will have 1 container\n\tcontainerEnv := dataDc[0].Spec.Template.Spec.Containers[0].Env\n\tfoundAdminPassword := false\n\tfor _, e := range containerEnv {\n\t\tif e.Name == \"MONGODB_ADMIN_PASSWORD\" {\n\t\t\tfoundAdminPassword = true\n\t\t\tjobOpts[\"admin-pass\"] = e.Value\n\t\t}\n\t\tif e.Name == \"MONGODB_REPLICA_NAME\" {\n\t\t\tjobOpts[\"replicaSet\"] = e.Value\n\t\t}\n\t}\n\tif !foundAdminPassword {\n\t\terr := errors.New(\"expected to find an admin password but there was non present\")\n\t\td.statusUpdate(deployment.Name, err.Error(), configError)\n\t\treturn nil, err\n\t}\n\tjobOpts[\"dbhost\"] = dataService[0].GetName()\n\tjobOpts[\"admin-user\"] = \"admin\"\n\tjobOpts[\"database\"] = deployment.Name\n\tjobOpts[\"name\"] = deployment.Name\n\tif v, ok := deployment.Labels[\"rhmap/guid\"]; ok {\n\t\tjobOpts[\"database\"] = v\n\t}\n\tjobOpts[\"database-pass\"] = genPass(16)\n\tjobOpts[\"database-user\"] = jobOpts[\"database\"]\n\tmongoURL := constructMongoURL(jobOpts[\"dbhost\"], jobOpts[\"database-user\"], jobOpts[\"database-pass\"], jobOpts[\"database\"], jobOpts[\"replicaSet\"])\n\tfor ci := range deployment.Spec.Template.Spec.Containers {\n\t\tenv := deployment.Spec.Template.Spec.Containers[ci].Env\n\t\tfound := false\n\t\tfor ei, e := range env {\n\t\t\tif e.Name == \"FH_MONGODB_CONN_URL\" {\n\t\t\t\tdeployment.Spec.Template.Spec.Containers[ci].Env[ei].Value = mongoURL\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\tdeployment.Spec.Template.Spec.Containers[ci].Env = append(deployment.Spec.Template.Spec.Containers[ci].Env, k8api.EnvVar{\n\t\t\t\tName: \"FH_MONGODB_CONN_URL\",\n\t\t\t\tValue: mongoURL,\n\t\t\t})\n\t\t}\n\t}\n\n\ttpl, err := d.TemplateLoader.Load(\"data-mongo-job\")\n\tif err != nil {\n\t\td.statusUpdate(deployment.Name, \"failed to load job template \"+err.Error(), configError)\n\t\treturn nil, errors.Wrap(err, \"failed to load template data-mongo-job \")\n\t}\n\tvar buf bytes.Buffer\n\tif err := tpl.ExecuteTemplate(&buf, \"data-mongo-job\", jobOpts); err != nil {\n\t\terr = errors.Wrap(err, \"failed to execute template: \")\n\t\td.statusUpdate(deployment.Name, err.Error(), configError)\n\t\treturn nil, err\n\t}\n\tj := &batch.Job{}\n\tif err := runtime.DecodeInto(k8api.Codecs.UniversalDecoder(), buf.Bytes(), j); err != nil {\n\t\terr = errors.Wrap(err, \"failed to Decode job\")\n\t\td.statusUpdate(deployment.Name, err.Error(), \"error\")\n\t\treturn nil, err\n\t}\n\t//set off job and watch it till complete\n\tgo func() {\n\t\tw, err := client.CreateJobToWatch(j, namespace)\n\t\tif err != nil {\n\t\t\td.statusUpdate(deployment.Name, \"failed to CreateJobToWatch \"+err.Error(), configError)\n\t\t\treturn\n\t\t}\n\t\tresult := w.ResultChan()\n\t\tfor ws := range result {\n\t\t\tswitch ws.Type {\n\t\t\tcase watch.Added, watch.Modified:\n\t\t\t\tj := ws.Object.(*batch.Job)\n\t\t\t\t// succeeded will always be 1 if a deadline is reached\n\t\t\t\tif j.Status.Succeeded >= 1 {\n\t\t\t\t\tw.Stop()\n\t\t\t\t\tfor _, condition := range j.Status.Conditions {\n\t\t\t\t\t\tif condition.Reason == \"DeadlineExceeded\" && condition.Type == \"Failed\" {\n\t\t\t\t\t\t\td.statusUpdate(deployment.Name, \"configuration job timed out and failed to configure database \"+condition.Message, configError)\n\t\t\t\t\t\t\t//TODO Maybe we should delete the job a this point to allow it to be retried.\n\t\t\t\t\t\t} else if condition.Type == \"Complete\" {\n\t\t\t\t\t\t\td.statusUpdate(deployment.Name, \"configuration job succeeded \", configComplete)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\td.statusUpdate(deployment.Name, fmt.Sprintf(\"job status succeeded %d failed %d\", j.Status.Succeeded, j.Status.Failed), configInProgress)\n\t\t\tcase watch.Error:\n\t\t\t\td.statusUpdate(deployment.Name, \" data configuration job error \", configError)\n\t\t\t\t//TODO maybe pull back the log from the pod here? also remove the job in this condition so it can be retried\n\t\t\t\tw.Stop()\n\t\t\t}\n\n\t\t}\n\t}()\n\n\treturn deployment, nil\n}", "func (w *worker) reconcileConfigMap(\n\tchi *chop.ClickHouseInstallation,\n\tconfigMap *core.ConfigMap,\n\tupdate bool,\n) error {\n\tw.a.V(2).M(chi).S().P()\n\tdefer w.a.V(2).M(chi).E().P()\n\n\t// Check whether this object already exists in k8s\n\tcurConfigMap, err := w.c.getConfigMap(&configMap.ObjectMeta, false)\n\n\tif curConfigMap != nil {\n\t\t// We have ConfigMap - try to update it\n\t\tif !update {\n\t\t\treturn nil\n\t\t}\n\t\terr = w.updateConfigMap(chi, configMap)\n\t}\n\n\tif apierrors.IsNotFound(err) {\n\t\t// ConfigMap not found - even during Update process - try to create it\n\t\terr = w.createConfigMap(chi, configMap)\n\t}\n\n\tif err != nil {\n\t\tw.a.WithEvent(chi, eventActionReconcile, eventReasonReconcileFailed).\n\t\t\tWithStatusAction(chi).\n\t\t\tWithStatusError(chi).\n\t\t\tM(chi).A().\n\t\t\tError(\"FAILED to reconcile ConfigMap: %s CHI: %s \", configMap.Name, chi.Name)\n\t}\n\n\treturn err\n}", "func ApplyConfiguration(configuration *pb.Configuration) (*LifecycleState, bb_grpc.ClientFactory, error) {\n\t// Set the umask, if requested.\n\tif setUmaskConfiguration := configuration.GetSetUmask(); setUmaskConfiguration != nil {\n\t\tif err := setUmask(setUmaskConfiguration.Umask); err != nil {\n\t\t\treturn nil, nil, util.StatusWrap(err, \"Failed to set umask\")\n\t\t}\n\t}\n\n\t// Logging.\n\tlogPaths := configuration.GetLogPaths()\n\tlogWriters := append(make([]io.Writer, 0, len(logPaths)+1), os.Stderr)\n\tfor _, logPath := range logPaths {\n\t\tw, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o666)\n\t\tif err != nil {\n\t\t\treturn nil, nil, util.StatusWrapf(err, \"Failed to open log path %#v\", logPath)\n\t\t}\n\t\tlogWriters = append(logWriters, w)\n\t}\n\tlog.SetOutput(io.MultiWriter(logWriters...))\n\n\tgrpcClientDialer := bb_grpc.NewLazyClientDialer(bb_grpc.BaseClientDialer)\n\tvar grpcUnaryInterceptors []grpc.UnaryClientInterceptor\n\tvar grpcStreamInterceptors []grpc.StreamClientInterceptor\n\n\t// Optional: gRPC metadata forwarding with reuse.\n\tif headers := configuration.GetGrpcForwardAndReuseMetadata(); len(headers) > 0 {\n\t\tinterceptor := bb_grpc.NewMetadataForwardingAndReusingInterceptor(headers)\n\t\tgrpcUnaryInterceptors = append(grpcUnaryInterceptors, interceptor.InterceptUnaryClient)\n\t\tgrpcStreamInterceptors = append(grpcStreamInterceptors, interceptor.InterceptStreamClient)\n\t}\n\n\t// Install Prometheus gRPC interceptors, only if the metrics\n\t// endpoint or Pushgateway is enabled.\n\tif configuration.GetDiagnosticsHttpServer().GetEnablePrometheus() || configuration.GetPrometheusPushgateway() != nil {\n\t\tgrpc_prometheus.EnableClientHandlingTimeHistogram(\n\t\t\tgrpc_prometheus.WithHistogramBuckets(\n\t\t\t\tutil.DecimalExponentialBuckets(-3, 6, 2)))\n\t\tgrpcUnaryInterceptors = append(grpcUnaryInterceptors, grpc_prometheus.UnaryClientInterceptor)\n\t\tgrpcStreamInterceptors = append(grpcStreamInterceptors, grpc_prometheus.StreamClientInterceptor)\n\t}\n\n\t// Perform tracing using OpenTelemetry.\n\tvar activeSpansReportingHTTPHandler *bb_otel.ActiveSpansReportingHTTPHandler\n\tif tracingConfiguration, enableActiveSpans := configuration.GetTracing(), configuration.GetDiagnosticsHttpServer().GetEnableActiveSpans(); tracingConfiguration != nil || enableActiveSpans {\n\t\ttracerProvider := trace.NewNoopTracerProvider()\n\t\tif tracingConfiguration != nil {\n\t\t\t// Special gRPC client factory that doesn't have tracing\n\t\t\t// enabled. This must be used by the OTLP span exporter\n\t\t\t// to prevent infinitely recursive traces.\n\t\t\tnonTracingGRPCClientFactory := bb_grpc.NewDeduplicatingClientFactory(\n\t\t\t\tbb_grpc.NewBaseClientFactory(\n\t\t\t\t\tgrpcClientDialer,\n\t\t\t\t\tgrpcUnaryInterceptors,\n\t\t\t\t\tgrpcStreamInterceptors))\n\n\t\t\tvar tracerProviderOptions []sdktrace.TracerProviderOption\n\t\t\tfor _, backend := range tracingConfiguration.Backends {\n\t\t\t\t// Construct a SpanExporter.\n\t\t\t\tvar spanExporter sdktrace.SpanExporter\n\t\t\t\tswitch spanExporterConfiguration := backend.SpanExporter.(type) {\n\t\t\t\tcase *pb.TracingConfiguration_Backend_JaegerCollectorSpanExporter_:\n\t\t\t\t\t// Convert Jaeger collector configuration\n\t\t\t\t\t// message to a list of options.\n\t\t\t\t\tjaegerConfiguration := spanExporterConfiguration.JaegerCollectorSpanExporter\n\t\t\t\t\tvar collectorEndpointOptions []jaeger.CollectorEndpointOption\n\t\t\t\t\tif endpoint := jaegerConfiguration.Endpoint; endpoint != \"\" {\n\t\t\t\t\t\tcollectorEndpointOptions = append(collectorEndpointOptions, jaeger.WithEndpoint(endpoint))\n\t\t\t\t\t}\n\t\t\t\t\troundTripper, err := bb_http.NewRoundTripperFromConfiguration(jaegerConfiguration.HttpClient)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, nil, util.StatusWrap(err, \"Failed to create Jaeger collector HTTP client\")\n\t\t\t\t\t}\n\t\t\t\t\tcollectorEndpointOptions = append(collectorEndpointOptions, jaeger.WithHTTPClient(&http.Client{\n\t\t\t\t\t\tTransport: bb_http.NewMetricsRoundTripper(roundTripper, \"Jaeger\"),\n\t\t\t\t\t}))\n\t\t\t\t\tif password := jaegerConfiguration.Password; password != \"\" {\n\t\t\t\t\t\tcollectorEndpointOptions = append(collectorEndpointOptions, jaeger.WithPassword(password))\n\t\t\t\t\t}\n\t\t\t\t\tif username := jaegerConfiguration.Password; username != \"\" {\n\t\t\t\t\t\tcollectorEndpointOptions = append(collectorEndpointOptions, jaeger.WithUsername(username))\n\t\t\t\t\t}\n\n\t\t\t\t\t// Construct a Jaeger span exporter.\n\t\t\t\t\texporter, err := jaeger.New(jaeger.WithCollectorEndpoint(collectorEndpointOptions...))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, nil, util.StatusWrap(err, \"Failed to create Jaeger collector span exporter\")\n\t\t\t\t\t}\n\t\t\t\t\tspanExporter = exporter\n\t\t\t\tcase *pb.TracingConfiguration_Backend_OtlpSpanExporter:\n\t\t\t\t\tclient, err := nonTracingGRPCClientFactory.NewClientFromConfiguration(spanExporterConfiguration.OtlpSpanExporter)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, nil, util.StatusWrap(err, \"Failed to create OTLP gRPC client\")\n\t\t\t\t\t}\n\t\t\t\t\tspanExporter, err = otlptrace.New(context.Background(), bb_otel.NewGRPCOTLPTraceClient(client))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, nil, util.StatusWrap(err, \"Failed to create OTLP span exporter\")\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\treturn nil, nil, status.Error(codes.InvalidArgument, \"Tracing backend does not contain a valid span exporter\")\n\t\t\t\t}\n\n\t\t\t\t// Wrap it in a SpanProcessor.\n\t\t\t\tvar spanProcessor sdktrace.SpanProcessor\n\t\t\t\tswitch spanProcessorConfiguration := backend.SpanProcessor.(type) {\n\t\t\t\tcase *pb.TracingConfiguration_Backend_SimpleSpanProcessor:\n\t\t\t\t\tspanProcessor = sdktrace.NewSimpleSpanProcessor(spanExporter)\n\t\t\t\tcase *pb.TracingConfiguration_Backend_BatchSpanProcessor_:\n\t\t\t\t\tvar batchSpanProcessorOptions []sdktrace.BatchSpanProcessorOption\n\t\t\t\t\tif d := spanProcessorConfiguration.BatchSpanProcessor.BatchTimeout; d != nil {\n\t\t\t\t\t\tif err := d.CheckValid(); err != nil {\n\t\t\t\t\t\t\treturn nil, nil, util.StatusWrap(err, \"Invalid batch span processor batch timeout\")\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbatchSpanProcessorOptions = append(batchSpanProcessorOptions, sdktrace.WithBatchTimeout(d.AsDuration()))\n\t\t\t\t\t}\n\t\t\t\t\tif spanProcessorConfiguration.BatchSpanProcessor.Blocking {\n\t\t\t\t\t\tbatchSpanProcessorOptions = append(batchSpanProcessorOptions, sdktrace.WithBlocking())\n\t\t\t\t\t}\n\t\t\t\t\tif d := spanProcessorConfiguration.BatchSpanProcessor.ExportTimeout; d != nil {\n\t\t\t\t\t\tif err := d.CheckValid(); err != nil {\n\t\t\t\t\t\t\treturn nil, nil, util.StatusWrap(err, \"Invalid batch span processor export timeout\")\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbatchSpanProcessorOptions = append(batchSpanProcessorOptions, sdktrace.WithExportTimeout(d.AsDuration()))\n\t\t\t\t\t}\n\t\t\t\t\tif size := spanProcessorConfiguration.BatchSpanProcessor.MaxExportBatchSize; size != 0 {\n\t\t\t\t\t\tbatchSpanProcessorOptions = append(batchSpanProcessorOptions, sdktrace.WithMaxExportBatchSize(int(size)))\n\t\t\t\t\t}\n\t\t\t\t\tif size := spanProcessorConfiguration.BatchSpanProcessor.MaxQueueSize; size != 0 {\n\t\t\t\t\t\tbatchSpanProcessorOptions = append(batchSpanProcessorOptions, sdktrace.WithMaxQueueSize(int(size)))\n\t\t\t\t\t}\n\t\t\t\t\tspanProcessor = sdktrace.NewBatchSpanProcessor(spanExporter, batchSpanProcessorOptions...)\n\t\t\t\tdefault:\n\t\t\t\t\treturn nil, nil, status.Error(codes.InvalidArgument, \"Tracing backend does not contain a valid span processor\")\n\t\t\t\t}\n\t\t\t\ttracerProviderOptions = append(tracerProviderOptions, sdktrace.WithSpanProcessor(spanProcessor))\n\t\t\t}\n\n\t\t\t// Set resource attributes, so that this process can be\n\t\t\t// identified uniquely.\n\t\t\tresourceAttributes, err := bb_otel.NewKeyValueListFromProto(tracingConfiguration.ResourceAttributes, \"\")\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, util.StatusWrap(err, \"Failed to create resource attributes\")\n\t\t\t}\n\t\t\ttracerProviderOptions = append(\n\t\t\t\ttracerProviderOptions,\n\t\t\t\tsdktrace.WithResource(resource.NewWithAttributes(semconv.SchemaURL, resourceAttributes...)))\n\n\t\t\t// Create a Sampler, acting as a policy for when to sample.\n\t\t\tsampler, err := newSamplerFromConfiguration(tracingConfiguration.Sampler)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, util.StatusWrap(err, \"Failed to create sampler\")\n\t\t\t}\n\t\t\ttracerProviderOptions = append(tracerProviderOptions, sdktrace.WithSampler(sampler))\n\t\t\ttracerProvider = sdktrace.NewTracerProvider(tracerProviderOptions...)\n\t\t}\n\n\t\tif enableActiveSpans {\n\t\t\tactiveSpansReportingHTTPHandler = bb_otel.NewActiveSpansReportingHTTPHandler(clock.SystemClock)\n\t\t\ttracerProvider = activeSpansReportingHTTPHandler.NewTracerProvider(tracerProvider)\n\t\t}\n\n\t\totel.SetTracerProvider(tracerProvider)\n\n\t\t// Construct a propagator which supports both the context and Zipkin B3 propagation standards.\n\t\tpropagator := propagation.NewCompositeTextMapPropagator(\n\t\t\tpropagation.TraceContext{},\n\t\t\tb3.New(b3.WithInjectEncoding(b3.B3MultipleHeader)),\n\t\t)\n\t\totel.SetTextMapPropagator(propagator)\n\n\t\tgrpcUnaryInterceptors = append(grpcUnaryInterceptors, otelgrpc.UnaryClientInterceptor())\n\t\tgrpcStreamInterceptors = append(grpcStreamInterceptors, otelgrpc.StreamClientInterceptor())\n\t}\n\n\t// Enable mutex profiling.\n\truntime.SetMutexProfileFraction(int(configuration.GetMutexProfileFraction()))\n\n\t// Periodically push metrics to a Prometheus Pushgateway, as\n\t// opposed to letting the Prometheus server scrape the metrics.\n\tif pushgateway := configuration.GetPrometheusPushgateway(); pushgateway != nil {\n\t\tpusher := push.New(pushgateway.Url, pushgateway.Job)\n\t\tpusher.Gatherer(prometheus.DefaultGatherer)\n\t\tfor key, value := range pushgateway.Grouping {\n\t\t\tpusher.Grouping(key, value)\n\t\t}\n\t\troundTripper, err := bb_http.NewRoundTripperFromConfiguration(pushgateway.HttpClient)\n\t\tif err != nil {\n\t\t\treturn nil, nil, util.StatusWrap(err, \"Failed to create Prometheus Pushgateway HTTP client\")\n\t\t}\n\t\tpusher.Client(&http.Client{\n\t\t\tTransport: bb_http.NewMetricsRoundTripper(roundTripper, \"Pushgateway\"),\n\t\t})\n\n\t\tpushInterval := pushgateway.PushInterval\n\t\tif err := pushInterval.CheckValid(); err != nil {\n\t\t\treturn nil, nil, util.StatusWrap(err, \"Failed to parse push interval\")\n\t\t}\n\t\tpushIntervalDuration := pushInterval.AsDuration()\n\n\t\tpushTimeout := pushgateway.PushTimeout\n\t\tif err := pushTimeout.CheckValid(); err != nil {\n\t\t\treturn nil, nil, util.StatusWrap(err, \"Failed to parse push timeout\")\n\t\t}\n\t\tpushTimeoutDuration := pushTimeout.AsDuration()\n\n\t\t// TODO: Run this as part of the program.Group, so that\n\t\t// it gets cleaned up upon shutdown.\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tctx, cancel := context.WithTimeout(context.Background(), pushTimeoutDuration)\n\t\t\t\terr := pusher.PushContext(ctx)\n\t\t\t\tcancel()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Print(\"Failed to push metrics to Prometheus Pushgateway: \", err)\n\t\t\t\t}\n\t\t\t\ttime.Sleep(pushIntervalDuration)\n\t\t\t}\n\t\t}()\n\t}\n\n\treturn &LifecycleState{\n\t\t\tconfig: configuration.GetDiagnosticsHttpServer(),\n\t\t\tactiveSpansReportingHTTPHandler: activeSpansReportingHTTPHandler,\n\t\t},\n\t\tbb_grpc.NewDeduplicatingClientFactory(\n\t\t\tbb_grpc.NewBaseClientFactory(\n\t\t\t\tgrpcClientDialer,\n\t\t\t\tgrpcUnaryInterceptors,\n\t\t\t\tgrpcStreamInterceptors)),\n\t\tnil\n}", "func (c *Config) Apply(cfg *Config) {\n\tif cfg == nil {\n\t\treturn\n\t}\n\n\tc.JrnlCtrlConfig.Apply(&cfg.JrnlCtrlConfig)\n\tc.PipesConfig.Apply(&cfg.PipesConfig)\n\n\tif cfg.BaseDir != \"\" {\n\t\tc.BaseDir = cfg.BaseDir\n\t}\n\tif cfg.HostHostId > 0 {\n\t\tc.HostHostId = cfg.HostHostId\n\t}\n\tif !reflect.DeepEqual(c.PublicApiRpc, cfg.PublicApiRpc) {\n\t\tc.PublicApiRpc = cfg.PublicApiRpc\n\t}\n\tif !reflect.DeepEqual(c.PrivateApiRpc, cfg.PrivateApiRpc) {\n\t\tc.PrivateApiRpc = cfg.PrivateApiRpc\n\t}\n\tif cfg.HostLeaseTTLSec > 0 {\n\t\tc.HostLeaseTTLSec = cfg.HostLeaseTTLSec\n\t}\n\tif cfg.HostRegisterTimeoutSec > 0 {\n\t\tc.HostRegisterTimeoutSec = cfg.HostRegisterTimeoutSec\n\t}\n}", "func applyLastAppliedConfigPatch(ctx context.Context, appIf application.ApplicationServiceClient, appName string, resourceNames []string, resources map[string]*argoappv1.ResourceDiff, dryRun bool) {\n\tif len(resources) != 0 { //\n\t\t//The remain deployments or rollouts need to be applied\n\t\tfor i := range resourceNames {\n\t\t\tresourceName := resourceNames[i]\n\t\t\tif resourceName != \"\" {\n\t\t\t\tvar resource = resources[resourceName]\n\t\t\t\tvar namespace = resource.Namespace\n\t\t\t\tvar liveObj, _ = resource.LiveObject()\n\t\t\t\tliveObjCopy := liveObj.DeepCopy()\n\t\t\t\tif namespace == \"\" {\n\t\t\t\t\tnamespace = liveObj.GetNamespace()\n\t\t\t\t}\n\n\t\t\t\tvar lastAppliedConfig = \"\"\n\n\t\t\t\tmetadataObj := liveObjCopy.Object[\"metadata\"]\n\t\t\t\tif metadataObj != nil && reflect.TypeOf(metadataObj).String() == \"map[string]interface {}\" {\n\t\t\t\t\tmetadata := metadataObj.(map[string]interface{})\n\t\t\t\t\tannoObj := metadata[\"annotations\"]\n\t\t\t\t\tif annoObj != nil && reflect.TypeOf(annoObj).String() == \"map[string]interface {}\" {\n\t\t\t\t\t\tanno := annoObj.(map[string]interface{})\n\t\t\t\t\t\tlastAppliedConfig = anno[\"kubectl.kubernetes.io/last-applied-configuration\"].(string)\n\t\t\t\t\t\tdelete(anno, \"kubectl.kubernetes.io/last-applied-configuration\")\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tvar lastAppliedConfigObj *unstructured.Unstructured = nil\n\t\t\t\tif lastAppliedConfig != \"\" { //Use the last-applied-configuration instead of liveObject\n\t\t\t\t\tlastAppliedConfigObj = &unstructured.Unstructured{}\n\t\t\t\t\terr := json.Unmarshal([]byte(lastAppliedConfig), lastAppliedConfigObj)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Errorf(\"Not able to unmarshal last-applied-configuration %s %v\", lastAppliedConfig, err)\n\t\t\t\t\t}\n\t\t\t\t\tliveObjCopy = lastAppliedConfigObj\n\t\t\t\t}\n\n\t\t\t\tspecObj := liveObjCopy.Object[\"spec\"]\n\t\t\t\tif specObj != nil && reflect.TypeOf(specObj).String() == \"map[string]interface {}\" {\n\t\t\t\t\tspec := specObj.(map[string]interface{})\n\t\t\t\t\tdelete(spec, \"replicas\")\n\t\t\t\t}\n\t\t\t\tdelete(liveObjCopy.Object, \"status\")\n\n\t\t\t\tbytes, err := json.Marshal(liveObjCopy)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"Not able to marshal %s Spec\", liveObjCopy.GetKind())\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\tnewPatch := make(map[string]interface{})\n\t\t\t\tnewMetadata := make(map[string]interface{})\n\t\t\t\tnewPatch[\"metadata\"] = newMetadata\n\t\t\t\tnewAnnotations := make(map[string]interface{})\n\t\t\t\tnewMetadata[\"annotations\"] = newAnnotations\n\t\t\t\tnewAnnotations[\"kubectl.kubernetes.io/last-applied-configuration\"] = string(bytes)\n\n\t\t\t\t//For debug\n\t\t\t\t//var tmpFileName = \"/tmp/\" + resourceName + strconv.FormatInt(time.Now().Unix(), 10) + \".yaml\"\n\t\t\t\t//f, err := os.Create(tmpFileName)\n\t\t\t\t//if err != nil {\n\t\t\t\t//\tlog.Errorf(\"Not able to create temp file:%s\", tmpFileName)\n\t\t\t\t//\tos.Exit(1)\n\t\t\t\t//}\n\t\t\t\t////log.Infof(\"Writing current resource to yaml file:%s\", tmpFileName)\n\t\t\t\tyamlBytes, err := json.Marshal(newPatch)\n\t\t\t\t//f.Write(yamlBytes)\n\t\t\t\t//f.Sync()\n\t\t\t\t//f.Close()\n\n\t\t\t\t//var fileNames = make([]string, 1)\n\t\t\t\t//fileNames[0] = tmpFileName\n\n\t\t\t\tif !dryRun {\n\t\t\t\t\t_, err = appIf.PatchResource(ctx, &application.ApplicationResourcePatchRequest{\n\t\t\t\t\t\tName: &appName,\n\t\t\t\t\t\tNamespace: namespace,\n\t\t\t\t\t\tResourceName: resourceName,\n\t\t\t\t\t\tVersion: liveObjCopy.GetAPIVersion(),\n\t\t\t\t\t\tGroup: resource.Group,\n\t\t\t\t\t\tKind: resource.Kind,\n\t\t\t\t\t\tPatch: string(yamlBytes),\n\t\t\t\t\t\tPatchType: \"application/merge-patch+json\",\n\t\t\t\t\t})\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Errorf(\"Patching annoation 'kubectl.kubernetes.io/last-applied-configuration' on resource: %s, error:%v\", resourceName, err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.Infof(\"Resource '%s' patched on 'kubectl.kubernetes.io/last-applied-configuration'\", resourceName)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlog.Infof(\"DryRun on resource '%s' patch of 'kubectl.kubernetes.io/last-applied-configuration'\", resourceName)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (updatePodConfig) reconcile(r *FoundationDBClusterReconciler, context ctx.Context, cluster *fdbtypes.FoundationDBCluster) *requeue {\n\tlogger := log.WithValues(\"namespace\", cluster.Namespace, \"cluster\", cluster.Name, \"reconciler\", \"updatePodConfig\")\n\tconfigMap, err := internal.GetConfigMap(cluster)\n\tif err != nil {\n\t\treturn &requeue{curError: err}\n\t}\n\n\tpods, err := r.PodLifecycleManager.GetPods(r, cluster, context, internal.GetPodListOptions(cluster, \"\", \"\")...)\n\tif err != nil {\n\t\treturn &requeue{curError: err}\n\t}\n\n\tpodMap := internal.CreatePodMap(cluster, pods)\n\n\tallSynced := true\n\thasUpdate := false\n\tvar errs []error\n\t// We try to update all instances and if we observe an error we add it to the error list.\n\tfor _, processGroup := range cluster.Status.ProcessGroups {\n\t\tcurLogger := logger.WithValues(\"processGroupID\", processGroup.ProcessGroupID)\n\n\t\tif processGroup.Remove {\n\t\t\tcurLogger.V(1).Info(\"Ignore process group marked for removal\")\n\t\t\tcontinue\n\t\t}\n\n\t\tif cluster.SkipProcessGroup(processGroup) {\n\t\t\tcurLogger.Info(\"Process group has pending Pod, will be skipped\")\n\t\t\tcontinue\n\t\t}\n\n\t\tpod, ok := podMap[processGroup.ProcessGroupID]\n\t\tif !ok || pod == nil {\n\t\t\tcurLogger.Info(\"Could not find Pod for process group\")\n\t\t\t// TODO (johscheuer): we should requeue if that happens.\n\t\t\tcontinue\n\t\t}\n\n\t\tserverPerPod, err := internal.GetStorageServersPerPodForPod(pod)\n\t\tif err != nil {\n\t\t\tcurLogger.Error(err, \"Error when receiving storage server per Pod\")\n\t\t\terrs = append(errs, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tprocessClass, err := podmanager.GetProcessClass(cluster, pod)\n\t\tif err != nil {\n\t\t\tcurLogger.Error(err, \"Error when fetching process class from Pod\")\n\t\t\terrs = append(errs, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tconfigMapHash, err := internal.GetDynamicConfHash(configMap, processClass, serverPerPod)\n\t\tif err != nil {\n\t\t\tcurLogger.Error(err, \"Error when receiving dynamic ConfigMap hash\")\n\t\t\terrs = append(errs, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif pod.ObjectMeta.Annotations[fdbtypes.LastConfigMapKey] == configMapHash {\n\t\t\tcontinue\n\t\t}\n\n\t\tsynced, err := r.updatePodDynamicConf(cluster, pod)\n\t\tif !synced {\n\t\t\tallSynced = false\n\t\t\thasUpdate = true\n\t\t\tcurLogger.Error(err, \"Update Pod ConfigMap annotation\")\n\t\t\tif internal.IsNetworkError(err) {\n\t\t\t\tprocessGroup.UpdateCondition(fdbtypes.SidecarUnreachable, true, cluster.Status.ProcessGroups, processGroup.ProcessGroupID)\n\t\t\t} else {\n\t\t\t\tprocessGroup.UpdateCondition(fdbtypes.IncorrectConfigMap, true, cluster.Status.ProcessGroups, processGroup.ProcessGroupID)\n\t\t\t}\n\n\t\t\tpod.ObjectMeta.Annotations[fdbtypes.OutdatedConfigMapKey] = time.Now().Format(time.RFC3339)\n\t\t\terr = r.PodLifecycleManager.UpdateMetadata(r, context, cluster, pod)\n\t\t\tif err != nil {\n\t\t\t\tallSynced = false\n\t\t\t\tcurLogger.Error(err, \"Update Pod ConfigMap annotation\")\n\t\t\t\terrs = append(errs, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tpod.ObjectMeta.Annotations[fdbtypes.LastConfigMapKey] = configMapHash\n\t\tdelete(pod.ObjectMeta.Annotations, fdbtypes.OutdatedConfigMapKey)\n\t\terr = r.PodLifecycleManager.UpdateMetadata(r, context, cluster, pod)\n\t\tif err != nil {\n\t\t\tallSynced = false\n\t\t\tcurLogger.Error(err, \"Update Pod metadata\")\n\t\t\terrs = append(errs, err)\n\t\t}\n\n\t\thasUpdate = true\n\t\tprocessGroup.UpdateCondition(fdbtypes.SidecarUnreachable, false, cluster.Status.ProcessGroups, processGroup.ProcessGroupID)\n\t}\n\n\tif hasUpdate {\n\t\terr = r.Status().Update(context, cluster)\n\t\tif err != nil {\n\t\t\treturn &requeue{curError: err}\n\t\t}\n\t}\n\n\t// If any error has happened requeue.\n\t// We don't provide an error here since we log all errors above.\n\tif len(errs) > 0 {\n\t\treturn &requeue{message: \"errors occurred during update pod config reconcile\"}\n\t}\n\n\t// If we return an error we don't requeue\n\t// So we just return that we can't continue but don't have an error\n\tif !allSynced {\n\t\treturn &requeue{message: \"Waiting for Pod to receive ConfigMap update\", delay: podSchedulingDelayDuration}\n\t}\n\n\treturn nil\n}", "func (r *ConfigMapResource) CreateConfiguration(\n\tctx context.Context,\n) (*configuration.GlobalConfiguration, error) {\n\tcfg := configuration.For(r.pandaCluster.Spec.Version)\n\tcfg.NodeConfiguration = *config.ProdDefault()\n\tmountPoints := resourcetypes.GetTLSMountPoints()\n\n\tc := r.pandaCluster.Spec.Configuration\n\tcr := &cfg.NodeConfiguration.Redpanda\n\n\tinternalListener := r.pandaCluster.InternalListener()\n\tinternalAuthN := &internalListener.AuthenticationMethod\n\tif *internalAuthN == \"\" {\n\t\tinternalAuthN = nil\n\t}\n\tcr.KafkaAPI = []config.NamedAuthNSocketAddress{} // we don't want to inherit default kafka port\n\tcr.KafkaAPI = append(cr.KafkaAPI, config.NamedAuthNSocketAddress{\n\t\tAddress: \"0.0.0.0\",\n\t\tPort: internalListener.Port,\n\t\tName: InternalListenerName,\n\t\tAuthN: internalAuthN,\n\t})\n\n\texternalListener := r.pandaCluster.ExternalListener()\n\tif externalListener != nil {\n\t\texternalAuthN := &externalListener.AuthenticationMethod\n\t\tif *externalAuthN == \"\" {\n\t\t\texternalAuthN = nil\n\t\t}\n\t\tcr.KafkaAPI = append(cr.KafkaAPI, config.NamedAuthNSocketAddress{\n\t\t\tAddress: \"0.0.0.0\",\n\t\t\tPort: calculateExternalPort(internalListener.Port, r.pandaCluster.ExternalListener().Port),\n\t\t\tName: ExternalListenerName,\n\t\t\tAuthN: externalAuthN,\n\t\t})\n\t}\n\n\tcr.RPCServer.Port = clusterCRPortOrRPKDefault(c.RPCServer.Port, cr.RPCServer.Port)\n\tcr.AdvertisedRPCAPI = &config.SocketAddress{\n\t\tAddress: \"0.0.0.0\",\n\t\tPort: clusterCRPortOrRPKDefault(c.RPCServer.Port, cr.RPCServer.Port),\n\t}\n\n\tcr.AdminAPI[0].Port = clusterCRPortOrRPKDefault(r.pandaCluster.AdminAPIInternal().Port, cr.AdminAPI[0].Port)\n\tcr.AdminAPI[0].Name = AdminPortName\n\tif r.pandaCluster.AdminAPIExternal() != nil {\n\t\texternalAdminAPI := config.NamedSocketAddress{\n\t\t\tAddress: cr.AdminAPI[0].Address,\n\t\t\tPort: calculateExternalPort(cr.AdminAPI[0].Port, r.pandaCluster.AdminAPIExternal().Port),\n\t\t\tName: AdminPortExternalName,\n\t\t}\n\t\tcr.AdminAPI = append(cr.AdminAPI, externalAdminAPI)\n\t}\n\n\tcr.DeveloperMode = c.DeveloperMode\n\tcr.Directory = dataDirectory\n\tkl := r.pandaCluster.KafkaTLSListeners()\n\tfor i := range kl {\n\t\ttls := config.ServerTLS{\n\t\t\tName: kl[i].Name,\n\t\t\tKeyFile: fmt.Sprintf(\"%s/%s\", mountPoints.KafkaAPI.NodeCertMountDir, corev1.TLSPrivateKeyKey), // tls.key\n\t\t\tCertFile: fmt.Sprintf(\"%s/%s\", mountPoints.KafkaAPI.NodeCertMountDir, corev1.TLSCertKey), // tls.crt\n\t\t\tEnabled: true,\n\t\t\tRequireClientAuth: kl[i].TLS.RequireClientAuth,\n\t\t}\n\t\tif kl[i].TLS.RequireClientAuth {\n\t\t\ttls.TruststoreFile = fmt.Sprintf(\"%s/%s\", mountPoints.KafkaAPI.ClientCAMountDir, cmetav1.TLSCAKey)\n\t\t}\n\t\tcr.KafkaAPITLS = append(cr.KafkaAPITLS, tls)\n\t}\n\tadminAPITLSListener := r.pandaCluster.AdminAPITLS()\n\tif adminAPITLSListener != nil {\n\t\t// Only one TLS listener is supported (restricted by the webhook).\n\t\t// Determine the listener name based on being internal or external.\n\t\tname := AdminPortName\n\t\tif adminAPITLSListener.External.Enabled {\n\t\t\tname = AdminPortExternalName\n\t\t}\n\t\tadminTLS := config.ServerTLS{\n\t\t\tName: name,\n\t\t\tKeyFile: fmt.Sprintf(\"%s/%s\", mountPoints.AdminAPI.NodeCertMountDir, corev1.TLSPrivateKeyKey),\n\t\t\tCertFile: fmt.Sprintf(\"%s/%s\", mountPoints.AdminAPI.NodeCertMountDir, corev1.TLSCertKey),\n\t\t\tEnabled: true,\n\t\t\tRequireClientAuth: adminAPITLSListener.TLS.RequireClientAuth,\n\t\t}\n\t\tif adminAPITLSListener.TLS.RequireClientAuth {\n\t\t\tadminTLS.TruststoreFile = fmt.Sprintf(\"%s/%s\", mountPoints.AdminAPI.ClientCAMountDir, cmetav1.TLSCAKey)\n\t\t}\n\t\tcr.AdminAPITLS = append(cr.AdminAPITLS, adminTLS)\n\t}\n\n\tif r.pandaCluster.Spec.CloudStorage.Enabled {\n\t\tif err := r.prepareCloudStorage(ctx, cfg); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"preparing cloud storage: %w\", err)\n\t\t}\n\t}\n\n\tfor _, user := range r.pandaCluster.Spec.Superusers {\n\t\tif err := cfg.AppendToAdditionalRedpandaProperty(superusersConfigurationKey, user.Username); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"appending superusers property: %w\", err)\n\t\t}\n\t}\n\n\tif r.pandaCluster.Spec.EnableSASL {\n\t\tcfg.SetAdditionalRedpandaProperty(\"enable_sasl\", true)\n\t}\n\tif r.pandaCluster.Spec.KafkaEnableAuthorization != nil && *r.pandaCluster.Spec.KafkaEnableAuthorization {\n\t\tcfg.SetAdditionalRedpandaProperty(\"kafka_enable_authorization\", true)\n\t}\n\n\tpartitions := r.pandaCluster.Spec.Configuration.GroupTopicPartitions\n\tif partitions != 0 {\n\t\tcfg.SetAdditionalRedpandaProperty(\"group_topic_partitions\", partitions)\n\t}\n\n\tcfg.SetAdditionalRedpandaProperty(\"auto_create_topics_enabled\", r.pandaCluster.Spec.Configuration.AutoCreateTopics)\n\n\tif featuregates.ShadowIndex(r.pandaCluster.Spec.Version) {\n\t\tintervalSec := 60 * 30 // 60s * 30 = 30 minutes\n\t\tcfg.SetAdditionalRedpandaProperty(\"cloud_storage_segment_max_upload_interval_sec\", intervalSec)\n\t}\n\n\tcfg.SetAdditionalRedpandaProperty(\"log_segment_size\", logSegmentSize)\n\n\tif err := r.PrepareSeedServerList(cr); err != nil {\n\t\treturn nil, fmt.Errorf(\"preparing seed server list: %w\", err)\n\t}\n\n\tr.preparePandaproxy(&cfg.NodeConfiguration)\n\tr.preparePandaproxyTLS(&cfg.NodeConfiguration, mountPoints)\n\terr := r.preparePandaproxyClient(ctx, cfg, mountPoints)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"preparing proxy client: %w\", err)\n\t}\n\n\tif sr := r.pandaCluster.Spec.Configuration.SchemaRegistry; sr != nil {\n\t\tvar authN *string\n\t\tif sr.AuthenticationMethod != \"\" {\n\t\t\tauthN = &sr.AuthenticationMethod\n\t\t}\n\t\tcfg.NodeConfiguration.SchemaRegistry.SchemaRegistryAPI = []config.NamedAuthNSocketAddress{\n\t\t\t{\n\t\t\t\tAddress: \"0.0.0.0\",\n\t\t\t\tPort: sr.Port,\n\t\t\t\tName: SchemaRegistryPortName,\n\t\t\t\tAuthN: authN,\n\t\t\t},\n\t\t}\n\t}\n\tr.prepareSchemaRegistryTLS(&cfg.NodeConfiguration, mountPoints)\n\terr = r.prepareSchemaRegistryClient(ctx, cfg, mountPoints)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"preparing schemaRegistry client: %w\", err)\n\t}\n\n\tif featuregates.RackAwareness(r.pandaCluster.Spec.Version) {\n\t\tcfg.SetAdditionalRedpandaProperty(\"enable_rack_awareness\", true)\n\t}\n\n\tif err := cfg.SetAdditionalFlatProperties(r.pandaCluster.Spec.AdditionalConfiguration); err != nil {\n\t\treturn nil, fmt.Errorf(\"adding additional flat properties: %w\", err)\n\t}\n\n\treturn cfg, nil\n}", "func (addon Addon) Apply(client clientset.Interface, addonConfiguration AddonConfiguration, skubaConfiguration *skuba.SkubaConfiguration, dryRun bool) error {\n\tklog.V(1).Infof(\"applying %q addon\", addon.Addon)\n\n\tvar err error\n\thasPreflight := false\n\tif addon.preflightTemplater != nil {\n\t\thasPreflight, err = addon.applyPreflight(addonConfiguration, addon.addonDir(), dryRun)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif addon.callbacks != nil && !dryRun {\n\t\tif err = addon.callbacks.beforeApply(client, addonConfiguration, skubaConfiguration); err != nil {\n\t\t\tklog.Errorf(\"failed on %q addon BeforeApply callback: %v\", addon.Addon, err)\n\t\t\treturn err\n\t\t}\n\t}\n\tif hasPreflight && !dryRun {\n\t\t// since we did not run applyPreflight if dryRun=true\n\t\t// bypass delete preflight manifests\n\t\tif err = addon.deletePreflight(addon.addonDir()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tpatchList, err := addon.listPatches()\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"could not list patches for %q addon\", addon.Addon)\n\t}\n\tkustomizeContents, err := addon.kustomizeContents([]string{addon.manifestFilename()}, patchList)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"could not render kustomize file\")\n\t}\n\tif err = ioutil.WriteFile(addon.kustomizePath(addon.addonDir()), []byte(kustomizeContents), 0600); err != nil {\n\t\treturn errors.Wrapf(err, \"could not create %q kustomize file\", addon.Addon)\n\t}\n\tkubectlArgs := []string{\n\t\t\"apply\",\n\t\t\"--kubeconfig\", skubaconstants.KubeConfigAdminFile(),\n\t\t\"-k\", addon.addonDir(),\n\t}\n\tif dryRun {\n\t\tflag, err := kubectlServerSideDryRunFlag()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tkubectlArgs = append(kubectlArgs, flag)\n\t}\n\tcmd := exec.Command(\"kubectl\", kubectlArgs...)\n\tvar stderr bytes.Buffer\n\tcmd.Stderr = &stderr\n\tif err := cmd.Run(); err != nil {\n\t\t// prints out stderr\n\t\tfmt.Printf(\"%s\", stderr.Bytes())\n\t\treturn err\n\t}\n\tif addon.callbacks != nil && !dryRun {\n\t\tif err = addon.callbacks.afterApply(client, addonConfiguration, skubaConfiguration); err != nil {\n\t\t\t// TODO: should we rollback here?\n\t\t\tklog.Errorf(\"failed on %q addon AfterApply callback: %v\", addon.Addon, err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif dryRun {\n\t\t// immediately return, do not update skuba-config ConfigMap\n\t\treturn nil\n\t}\n\treturn updateSkubaConfigMapWithAddonVersion(client, addon.Addon, addonConfiguration.ClusterVersion, skubaConfiguration)\n}", "func (*deployInsideDeployConfigMapHandler) updateConfigMap(_ context.Context, _ *apiv1.ConfigMap, _ *pipeline.CfgData, err error) error {\n\treturn nil\n}", "func (ctx *Context) updateConfigMaps(obj, newObj interface{}) {\n\tlog.Logger.Debug(\"trigger scheduler to reload configuration\")\n\t// When update event is received, it is not guaranteed the data mounted to the pod\n\t// is also updated. This is because the actual update in pod's volume is ensured\n\t// by kubelet, kubelet is checking whether the mounted ConfigMap is fresh on every\n\t// periodic sync. As a result, the total delay from the moment when the ConfigMap\n\t// is updated to the moment when new keys are projected to the pod can be as long\n\t// as kubelet sync period + ttl of ConfigMaps cache in kubelet.\n\t// We trigger configuration reload, on yunikorn-core side, it keeps checking config\n\t// file state once this is called. And the actual reload happens when it detects\n\t// actual changes on the content.\n\tctx.triggerReloadConfig()\n}", "func (s *Storage) ApplyConfig(conf *config.Config) error {\n\ts.mtx.Lock()\n\tdefer s.mtx.Unlock()\n\n\tif err := s.rws.ApplyConfig(conf); err != nil {\n\t\treturn err\n\t}\n\n\t// Update read clients\n\treadHashes := make(map[string]struct{})\n\tqueryables := make([]storage.SampleAndChunkQueryable, 0, len(conf.RemoteReadConfigs))\n\tfor _, rrConf := range conf.RemoteReadConfigs {\n\t\thash, err := toHash(rrConf)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Don't allow duplicate remote read configs.\n\t\tif _, ok := readHashes[hash]; ok {\n\t\t\treturn fmt.Errorf(\"duplicate remote read configs are not allowed, found duplicate for URL: %s\", rrConf.URL)\n\t\t}\n\t\treadHashes[hash] = struct{}{}\n\n\t\t// Set the queue name to the config hash if the user has not set\n\t\t// a name in their remote write config so we can still differentiate\n\t\t// between queues that have the same remote write endpoint.\n\t\tname := hash[:6]\n\t\tif rrConf.Name != \"\" {\n\t\t\tname = rrConf.Name\n\t\t}\n\n\t\tc, err := NewReadClient(name, &ClientConfig{\n\t\t\tURL: rrConf.URL,\n\t\t\tTimeout: rrConf.RemoteTimeout,\n\t\t\tHTTPClientConfig: rrConf.HTTPClientConfig,\n\t\t\tHeaders: rrConf.Headers,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\texternalLabels := conf.GlobalConfig.ExternalLabels\n\t\tif !rrConf.FilterExternalLabels {\n\t\t\texternalLabels = labels.EmptyLabels()\n\t\t}\n\t\tqueryables = append(queryables, NewSampleAndChunkQueryableClient(\n\t\t\tc,\n\t\t\texternalLabels,\n\t\t\tlabelsToEqualityMatchers(rrConf.RequiredMatchers),\n\t\t\trrConf.ReadRecent,\n\t\t\ts.localStartTimeCallback,\n\t\t))\n\t}\n\ts.queryables = queryables\n\n\treturn nil\n}", "func (c *Config) adjust(meta *toml.MetaData) error {\n\tconfigMetaData := configutil.NewConfigMetadata(meta)\n\tif err := configMetaData.CheckUndecoded(); err != nil {\n\t\tc.WarningMsgs = append(c.WarningMsgs, err.Error())\n\t}\n\n\tif c.Name == \"\" {\n\t\thostname, err := os.Hostname()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tconfigutil.AdjustString(&c.Name, fmt.Sprintf(\"%s-%s\", defaultName, hostname))\n\t}\n\tconfigutil.AdjustString(&c.DataDir, fmt.Sprintf(\"default.%s\", c.Name))\n\tconfigutil.AdjustPath(&c.DataDir)\n\n\tif err := c.validate(); err != nil {\n\t\treturn err\n\t}\n\n\tconfigutil.AdjustString(&c.BackendEndpoints, defaultBackendEndpoints)\n\tconfigutil.AdjustString(&c.ListenAddr, defaultListenAddr)\n\tconfigutil.AdjustString(&c.AdvertiseListenAddr, c.ListenAddr)\n\n\tif !configMetaData.IsDefined(\"enable-grpc-gateway\") {\n\t\tc.EnableGRPCGateway = utils.DefaultEnableGRPCGateway\n\t}\n\n\tc.adjustLog(configMetaData.Child(\"log\"))\n\tc.Security.Encryption.Adjust()\n\n\tif len(c.Log.Format) == 0 {\n\t\tc.Log.Format = utils.DefaultLogFormat\n\t}\n\n\tconfigutil.AdjustInt64(&c.LeaderLease, utils.DefaultLeaderLease)\n\n\tif err := c.Schedule.Adjust(configMetaData.Child(\"schedule\"), false); err != nil {\n\t\treturn err\n\t}\n\treturn c.Replication.Adjust(configMetaData.Child(\"replication\"))\n}", "func (s *Storage) ApplyConfig(conf *config.Config) error {\n\ts.mtx.Lock()\n\tdefer s.mtx.Unlock()\n\n\ts.externalLabels = conf.GlobalConfig.ExternalLabels\n\treturn nil\n}", "func (c *CacheRedisConfigure) Configure(client Client, deployment *dc.DeploymentConfig, namespace string) (*dc.DeploymentConfig, error) {\n\tvar configurationStatus = ConfigurationStatus{Started: time.Now(), Log: []string{\"starting configuration\"}, Status: configInProgress}\n\tc.StatusPublisher.Publish(deployment.GetResourceVersion(), configurationStatus)\n\tvar statusUpdate = func(message, status string) {\n\t\tconfigurationStatus.Status = status\n\t\tconfigurationStatus.Log = append(configurationStatus.Log, message)\n\t\tc.StatusPublisher.Publish(deployment.GetResourceVersion(), configurationStatus)\n\t}\n\tif v, ok := deployment.Labels[\"rhmap/name\"]; ok {\n\t\tif v == \"cache\" {\n\t\t\tstatusUpdate(\"no need to configure own DeploymentConfig \", configComplete)\n\t\t\treturn deployment, nil\n\t\t}\n\t}\n\t// likely needs to be broken out as it will be needed for all services\n\tstatusUpdate(\"updating containers env for deployment \"+deployment.GetName(), \"inProgress\")\n\tfor ci := range deployment.Spec.Template.Spec.Containers {\n\t\tenv := deployment.Spec.Template.Spec.Containers[ci].Env\n\t\tfor ei, e := range env {\n\t\t\tif e.Name == \"FH_REDIS_HOST\" && e.Value != \"data-cache\" {\n\t\t\t\tdeployment.Spec.Template.Spec.Containers[ci].Env[ei].Value = \"data-cache\" //hard coded for time being\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn deployment, nil\n}", "func (r *ReconcileConfigMap) Reconcile(request reconcile.Request) (reconcile.Result, error) {\n\t// Fetch the ConfigMap instance\n\tcminstance := &corev1.ConfigMap{}\n\tif err := r.client.Get(context.TODO(), request.NamespacedName, cminstance); err != nil {\n\t\treturn reconcile.Result{}, IgnoreNotFound(err)\n\t}\n\tpolicyName, ok := cminstance.Labels[\"appName\"]\n\tif !ok {\n\t\treturn reconcile.Result{}, nil\n\t}\n\tpolicyNamespace, ok := cminstance.Labels[\"appNamespace\"]\n\tif !ok {\n\t\treturn reconcile.Result{}, nil\n\t}\n\n\treqLogger := log.WithValues(\"SelinuxPolicy.Name\", policyName, \"SelinuxPolicy.Namespace\", policyNamespace)\n\n\tpolicyObjKey := types.NamespacedName{Name: policyName, Namespace: policyNamespace}\n\tpolicy := &spov1alpha1.SelinuxPolicy{}\n\tif err := r.client.Get(context.TODO(), policyObjKey, policy); err != nil {\n\t\treturn reconcile.Result{}, IgnoreNotFound(err)\n\t}\n\n\tif policy.Status.State == \"\" || policy.Status.State == spov1alpha1.PolicyStatePending {\n\t\tpolicyCopy := policy.DeepCopy()\n\t\tpolicyCopy.Status.State = spov1alpha1.PolicyStateInProgress\n\t\tpolicyCopy.Status.SetConditions(rcommonv1.Creating())\n\t\tif err := r.client.Status().Update(context.TODO(), policyCopy); err != nil {\n\t\t\treturn reconcile.Result{}, errors.Wrap(err, \"Updating policy without status\")\n\t\t}\n\t\treturn reconcile.Result{Requeue: true}, nil\n\t}\n\n\t// object is not being deleted\n\tif cminstance.ObjectMeta.DeletionTimestamp.IsZero() {\n\t\treturn r.reconcileInstallerPods(policy, cminstance, reqLogger)\n\t}\n\treturn reconcile.Result{}, nil\n}", "func (pod *Pod) setupConfig(manifest manifest.Manifest, launchables []launch.Launchable) error {\n\tuid, gid, err := user.IDs(manifest.RunAsUser())\n\tif err != nil {\n\t\treturn util.Errorf(\"Could not determine pod UID/GID: %s\", err)\n\t}\n\tvar configData bytes.Buffer\n\terr = manifest.WriteConfig(&configData)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar platConfigData bytes.Buffer\n\terr = manifest.WritePlatformConfig(&platConfigData)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = util.MkdirChownAll(pod.ConfigDir(), uid, gid, 0755)\n\tif err != nil {\n\t\treturn util.Errorf(\"Could not create config directory for pod %s: %s\", manifest.ID(), err)\n\t}\n\tconfigFileName, err := manifest.ConfigFileName()\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfigPath := filepath.Join(pod.ConfigDir(), configFileName)\n\terr = writeFileChown(configPath, configData.Bytes(), uid, gid)\n\tif err != nil {\n\t\treturn util.Errorf(\"Error writing config file for pod %s: %s\", manifest.ID(), err)\n\t}\n\tplatConfigFileName, err := manifest.PlatformConfigFileName()\n\tif err != nil {\n\t\treturn err\n\t}\n\tplatConfigPath := filepath.Join(pod.ConfigDir(), platConfigFileName)\n\terr = writeFileChown(platConfigPath, platConfigData.Bytes(), uid, gid)\n\tif err != nil {\n\t\treturn util.Errorf(\"Error writing platform config file for pod %s: %s\", manifest.ID(), err)\n\t}\n\n\terr = util.MkdirChownAll(pod.EnvDir(), uid, gid, 0755)\n\tif err != nil {\n\t\treturn util.Errorf(\"Could not create the environment dir for pod %s: %s\", manifest.ID(), err)\n\t}\n\terr = writeEnvFile(pod.EnvDir(), ConfigPathEnvVar, configPath, uid, gid)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = writeEnvFile(pod.EnvDir(), PlatformConfigPathEnvVar, platConfigPath, uid, gid)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = writeEnvFile(pod.EnvDir(), PodHomeEnvVar, pod.Home(), uid, gid)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = writeEnvFile(pod.EnvDir(), PodIDEnvVar, pod.Id.String(), uid, gid)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = writeEnvFile(pod.EnvDir(), PodUniqueKeyEnvVar, pod.uniqueKey.String(), uid, gid)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, launchable := range launchables {\n\t\t// we need to remove any unset env vars from a previous pod\n\t\terr = os.RemoveAll(launchable.EnvDir())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = util.MkdirChownAll(launchable.EnvDir(), uid, gid, 0755)\n\t\tif err != nil {\n\t\t\treturn util.Errorf(\"Could not create the environment dir for pod %s launchable %s: %s\", manifest.ID(), launchable.ServiceID(), err)\n\t\t}\n\t\terr = writeEnvFile(launchable.EnvDir(), LaunchableIDEnvVar, launchable.ID().String(), uid, gid)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = writeEnvFile(launchable.EnvDir(), LaunchableRootEnvVar, launchable.InstallDir(), uid, gid)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = writeEnvFile(launchable.EnvDir(), LaunchableRestartTimeoutEnvVar, fmt.Sprintf(\"%d\", int64(launchable.GetRestartTimeout().Seconds())), uid, gid)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// last, write the user-supplied env variables to ensure priority of user-supplied values\n\t\tfor envName, value := range launchable.EnvVars() {\n\t\t\terr = writeEnvFile(launchable.EnvDir(), envName, fmt.Sprint(value), uid, gid)\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 (x *Rest) ConfigurationUpdate(w http.ResponseWriter, r *http.Request,\n\tparams httprouter.Params) {\n\tdefer panicCatcher(w)\n\n\trequest := msg.New(r, params)\n\trequest.Section = msg.SectionConfiguration\n\trequest.Action = msg.ActionUpdate\n\n\tswitch request.Version {\n\tcase msg.ProtocolOne:\n\t\tcReq := &v1.ConfigurationItem{}\n\t\tif err := decodeJSONBody(r, cReq); err != nil {\n\t\t\tx.replyUnprocessableEntity(&w, &request, err)\n\t\t\treturn\n\t\t}\n\t\trequest.Configuration = v2.ConfigurationFromV1(cReq)\n\n\tcase msg.ProtocolTwo:\n\t\tcReq := v2.NewConfigurationRequest()\n\t\tif err := decodeJSONBody(r, &cReq); err != nil {\n\t\t\tx.replyUnprocessableEntity(&w, &request, err)\n\t\t\treturn\n\t\t}\n\t\trequest.Configuration = *cReq.Configuration\n\n\t\t// only the v2 API has request flags\n\t\tif err := resolveFlags(&cReq, &request); err != nil {\n\t\t\tx.replyBadRequest(&w, &request, err)\n\t\t\treturn\n\t\t}\n\n\tdefault:\n\t\tx.replyInternalError(&w, &request, nil)\n\t\treturn\n\t}\n\n\trequest.Configuration.InputSanatize()\n\trequest.LookupHash = calculateLookupID(\n\t\trequest.Configuration.HostID,\n\t\trequest.Configuration.Metric,\n\t)\n\trequest.Configuration.LookupID = request.LookupHash\n\n\tif request.Configuration.ID != strings.ToLower(params.ByName(`ID`)) {\n\t\tx.replyBadRequest(&w, &request, fmt.Errorf(\n\t\t\t\"Mismatched IDs in update: [%s] vs [%s]\",\n\t\t\trequest.Configuration.ID,\n\t\t\tstrings.ToLower(params.ByName(`ID`)),\n\t\t))\n\t}\n\n\tif _, err := uuid.FromString(request.Configuration.ID); err != nil {\n\t\tx.replyBadRequest(&w, &request, err)\n\t\treturn\n\t}\n\n\tx.somaSetFeedbackURL(&request)\n\n\tif !x.isAuthorized(&request) {\n\t\tx.replyForbidden(&w, &request, nil)\n\t\treturn\n\t}\n\n\thandler := x.handlerMap.Get(`configuration_w`)\n\thandler.Intake() <- request\n\tresult := <-request.Reply\n\tx.respond(&w, &result)\n}", "func loadConfiguration(ctx context.Context, kubeapi *KubeAPI) config {\n\tcfg := config{}\n\n\tcfg.namespace = getEnvRequired(\"NAMESPACE\")\n\tcfg.command = getEnvRequired(\"COMMAND\")\n\n\tcfg.container = os.Getenv(\"CONTAINER\")\n\tif cfg.container == \"\" {\n\t\tcfg.container = containerNameDefault\n\t}\n\tlog.Debugf(\"CONTAINER set to: %s\", cfg.container)\n\n\tcfg.commandOpts = os.Getenv(\"COMMAND_OPTS\")\n\tlog.Debugf(\"COMMAND_OPTS set to: %s\", cfg.commandOpts)\n\n\tcfg.selector = os.Getenv(\"SELECTOR\")\n\tlog.Debugf(\"SELECTOR set to: %s\", cfg.selector)\n\n\tcompareHashEnv := os.Getenv(\"COMPARE_HASH\")\n\tlog.Debugf(\"COMPARE_HASH set to: %s\", compareHashEnv)\n\tif compareHashEnv != \"\" {\n\t\t// default to false if an error parsing\n\t\tcfg.compareHash, _ = strconv.ParseBool(compareHashEnv)\n\t}\n\n\tif cfg.selector == \"\" {\n\t\t// if no selector then a Pod name must be provided\n\t\tcfg.podName = getEnvRequired(\"PODNAME\")\n\t} else {\n\t\t// if a selector is provided, then lookup the Pod via the provided selector to get the\n\t\t// Pod name\n\t\tpods, err := kubeapi.Client.CoreV1().Pods(cfg.namespace).List(ctx,\n\t\t\tmetav1.ListOptions{LabelSelector: cfg.selector})\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tif len(pods.Items) != 1 {\n\t\t\tlog.Fatalf(\"found %d Pods using selector, but only expected one\", len(pods.Items))\n\t\t}\n\t\tcfg.podName = pods.Items[0].GetName()\n\t}\n\tlog.Debugf(\"PODNAME set to: %s\", cfg.podName)\n\n\tcfg.repoType = os.Getenv(\"PGBACKREST_REPO1_TYPE\")\n\tlog.Debugf(\"PGBACKREST_REPO1_TYPE set to: %s\", cfg.repoType)\n\n\t// determine the setting of PGHA_PGBACKREST_LOCAL_S3_STORAGE\n\t// we will discard the error and treat the value as \"false\" if it is not\n\t// explicitly set\n\tcfg.localS3Storage, _ = strconv.ParseBool(os.Getenv(\"PGHA_PGBACKREST_LOCAL_S3_STORAGE\"))\n\tlog.Debugf(\"PGHA_PGBACKREST_LOCAL_S3_STORAGE set to: %t\", cfg.localS3Storage)\n\n\t// determine the setting of PGHA_PGBACKREST_LOCAL_GCS_STORAGE\n\t// we will discard the error and treat the value as \"false\" if it is not\n\t// explicitly set\n\tcfg.localGCSStorage, _ = strconv.ParseBool(os.Getenv(\"PGHA_PGBACKREST_LOCAL_GCS_STORAGE\"))\n\tlog.Debugf(\"PGHA_PGBACKREST_LOCAL_GCS_STORAGE set to: %t\", cfg.localGCSStorage)\n\n\t// parse the environment variable and store the appropriate boolean value\n\t// we will discard the error and treat the value as \"false\" if it is not\n\t// explicitly set\n\tcfg.s3VerifyTLS, _ = strconv.ParseBool(os.Getenv(\"PGHA_PGBACKREST_S3_VERIFY_TLS\"))\n\tlog.Debugf(\"PGHA_PGBACKREST_S3_VERIFY_TLS set to: %t\", cfg.s3VerifyTLS)\n\n\treturn cfg\n}", "func (m *hostConfiguredContainer) updateConfigurationStatus() error {\n\t// If there is no config files configured, don't do anything.\n\tif len(m.configFiles) == 0 {\n\t\treturn nil\n\t}\n\n\t// Build list of files we need to read from the container.\n\tfiles := []string{}\n\n\t// Keep map of original paths.\n\tpaths := map[string]string{}\n\n\t// Build list of the files we should read.\n\tfor p := range m.configFiles {\n\t\tcpath := path.Join(ConfigMountpoint, p)\n\t\tfiles = append(files, cpath)\n\t\tpaths[cpath] = p\n\t}\n\n\tconfigFiles, err := m.configContainer.Read(files)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"reading configuration status: %w\", err)\n\t}\n\n\tm.configFiles = map[string]string{}\n\n\tfor _, configFile := range configFiles {\n\t\tm.configFiles[paths[configFile.Path]] = configFile.Content\n\t}\n\n\treturn nil\n}", "func processConfig(item *yaml.RNode, meta yaml.ResourceMeta) error {\n\tif meta.APIVersion != \"hnc.x-k8s.io/v1alpha2\" || meta.Kind != \"HierarchyConfiguration\" {\n\t\treturn nil\n\t}\n\tns := forest[meta.Namespace]\n\tns.hasConfig = true\n\n\tspec, err := item.Pipe(yaml.Get(\"spec\"))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't get spec: %w\", err)\n\t}\n\tparent, err := spec.Pipe(yaml.Get(\"parent\"))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't get spec.parent: %w\", err)\n\t}\n\n\toldParent := strings.TrimSpace(parent.MustString())\n\tif oldParent != ns.parent {\n\t\tfmt.Fprintf(os.Stderr, \"HC config for %q has the wrong parent %q; updating to %q\\n\", meta.Namespace, oldParent, ns.parent)\n\t\tif err := spec.PipeE(yaml.SetField(\"parent\", yaml.MustParse(ns.parent))); err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't update HC config: %s\\n\", err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OpenShift) initDeploymentConfig(name string, service kobject.ServiceConfig, replicas int) *deployapi.DeploymentConfig {\n\tcontainerName := []string{name}\n\n\t// Properly add tags to the image name\n\ttag := GetImageTag(service.Image)\n\n\t// Use ContainerName if it was set\n\tif service.ContainerName != \"\" {\n\t\tcontainerName = []string{service.ContainerName}\n\t}\n\n\tvar podSpec corev1.PodSpec\n\tif len(service.Configs) > 0 {\n\t\tpodSpec = o.InitPodSpecWithConfigMap(name, \" \", service)\n\t} else {\n\t\tpodSpec = o.InitPodSpec(name, \" \", \"\")\n\t}\n\n\tdc := &deployapi.DeploymentConfig{\n\t\tTypeMeta: kapi.TypeMeta{\n\t\t\tKind: \"DeploymentConfig\",\n\t\t\tAPIVersion: \"apps.openshift.io/v1\",\n\t\t},\n\t\tObjectMeta: kapi.ObjectMeta{\n\t\t\tName: name,\n\t\t\tLabels: transformer.ConfigLabels(name),\n\t\t},\n\t\tSpec: deployapi.DeploymentConfigSpec{\n\t\t\tReplicas: int32(replicas),\n\t\t\tSelector: transformer.ConfigLabels(name),\n\t\t\t//UniqueLabelKey: p.Name,\n\t\t\tTemplate: &corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: kapi.ObjectMeta{\n\t\t\t\t\tLabels: transformer.ConfigLabels(name),\n\t\t\t\t},\n\t\t\t\tSpec: podSpec,\n\t\t\t},\n\t\t\tTriggers: []deployapi.DeploymentTriggerPolicy{\n\t\t\t\t// Trigger new deploy when DeploymentConfig is created (config change)\n\t\t\t\t{\n\t\t\t\t\tType: deployapi.DeploymentTriggerOnConfigChange,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tType: deployapi.DeploymentTriggerOnImageChange,\n\t\t\t\t\tImageChangeParams: &deployapi.DeploymentTriggerImageChangeParams{\n\t\t\t\t\t\t//Automatic - if new tag is detected - update image update inside the pod template\n\t\t\t\t\t\tAutomatic: true,\n\t\t\t\t\t\tContainerNames: containerName,\n\t\t\t\t\t\tFrom: corev1.ObjectReference{\n\t\t\t\t\t\t\tName: name + \":\" + tag,\n\t\t\t\t\t\t\tKind: \"ImageStreamTag\",\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\tupdate := service.GetOSUpdateStrategy()\n\tif update != nil {\n\t\tdc.Spec.Strategy = deployapi.DeploymentStrategy{\n\t\t\tType: deployapi.DeploymentStrategyTypeRolling,\n\t\t\tRollingParams: update,\n\t\t}\n\t\tlog.Debugf(\"Set deployment '%s' rolling update: MaxSurge: %s, MaxUnavailable: %s\", name, update.MaxSurge.String(), update.MaxUnavailable.String())\n\t}\n\n\treturn dc\n}", "func (a addPods) reconcile(ctx context.Context, r *FoundationDBClusterReconciler, cluster *fdbv1beta2.FoundationDBCluster, _ *fdbv1beta2.FoundationDBStatus, logger logr.Logger) *requeue {\n\tconfigMap, err := internal.GetConfigMap(cluster)\n\tif err != nil {\n\t\treturn &requeue{curError: err}\n\t}\n\texistingConfigMap := &corev1.ConfigMap{}\n\terr = r.Get(ctx, types.NamespacedName{Namespace: configMap.Namespace, Name: configMap.Name}, existingConfigMap)\n\tif err != nil && k8serrors.IsNotFound(err) {\n\t\tlogger.Info(\"Creating config map\", \"name\", configMap.Name)\n\t\terr = r.Create(ctx, configMap)\n\t\tif err != nil {\n\t\t\treturn &requeue{curError: err}\n\t\t}\n\t} else if err != nil {\n\t\treturn &requeue{curError: err}\n\t}\n\n\tfor _, processGroup := range cluster.Status.ProcessGroups {\n\t\t_, err := r.PodLifecycleManager.GetPod(ctx, r, cluster, processGroup.GetPodName(cluster))\n\t\t// If no error is returned the Pod exists\n\t\tif err == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ignore the is not found error, as we are checking here if we should create Pods.\n\t\tif err != nil {\n\t\t\tif !k8serrors.IsNotFound(err) {\n\t\t\t\treturn &requeue{curError: err}\n\t\t\t}\n\t\t}\n\n\t\t// If this process group is marked for removal, we normally don't want to spin it back up\n\t\t// again. However, in a downscaling scenario, it could be that this is a storage node that\n\t\t// is still draining its data onto another one. Therefore, we only want to leave it off\n\t\t// (by continuing) if the cluster says that this process group is fully drained and safe\n\t\t// to delete, which is the case if a previous run of the `removeProcessGroups` subreconciler\n\t\t// has marked it as excluded in the cluster status (it does so only after executing the\n\t\t// `exclude` FDB command and being told that the nodes in question are fully excluded).\n\t\tif processGroup.IsMarkedForRemoval() && processGroup.IsExcluded() {\n\t\t\tcontinue\n\t\t}\n\n\t\tidNum, err := processGroup.ProcessGroupID.GetIDNumber()\n\t\tif err != nil {\n\t\t\treturn &requeue{curError: err}\n\t\t}\n\n\t\tpod, err := internal.GetPod(cluster, processGroup.ProcessClass, idNum)\n\t\tif err != nil {\n\t\t\tr.Recorder.Event(cluster, corev1.EventTypeWarning, \"GetPod\", fmt.Sprintf(\"failed to get the PodSpec for %s/%d with error: %s\", processGroup.ProcessClass, idNum, err))\n\t\t\treturn &requeue{curError: err}\n\t\t}\n\n\t\tserverPerPod, err := internal.GetServersPerPodForPod(pod, processGroup.ProcessClass)\n\t\tif err != nil {\n\t\t\treturn &requeue{curError: err}\n\t\t}\n\n\t\timageType := internal.GetImageType(pod)\n\n\t\tconfigMapHash, err := internal.GetDynamicConfHash(configMap, processGroup.ProcessClass, imageType, serverPerPod)\n\t\tif err != nil {\n\t\t\treturn &requeue{curError: err}\n\t\t}\n\n\t\tpod.ObjectMeta.Annotations[fdbv1beta2.LastConfigMapKey] = configMapHash\n\n\t\tif cluster.GetPublicIPSource() == fdbv1beta2.PublicIPSourceService {\n\t\t\tservice := &corev1.Service{}\n\t\t\terr = r.Get(ctx, types.NamespacedName{Namespace: pod.Namespace, Name: pod.Name}, service)\n\t\t\tif err != nil {\n\t\t\t\treturn &requeue{curError: err}\n\t\t\t}\n\t\t\tip := service.Spec.ClusterIP\n\t\t\tif ip == \"\" {\n\t\t\t\tlogger.Info(\"Service does not have an IP address\", \"processGroupID\", processGroup.ProcessGroupID)\n\t\t\t\treturn &requeue{message: fmt.Sprintf(\"Service %s does not have an IP address\", service.Name)}\n\t\t\t}\n\t\t\tpod.Annotations[fdbv1beta2.PublicIPAnnotation] = ip\n\t\t}\n\n\t\terr = r.PodLifecycleManager.CreatePod(logr.NewContext(ctx, logger), r, pod)\n\t\tif err != nil {\n\t\t\tif internal.IsQuotaExceeded(err) {\n\t\t\t\treturn &requeue{curError: err, delayedRequeue: true}\n\t\t\t}\n\n\t\t\treturn &requeue{curError: err}\n\t\t}\n\t}\n\n\treturn nil\n}", "func Apply(cmd *cli.Cmd) {\n\tcmd.Spec = \"[-f=<FILENAME>] [--keep-weights] [--allowed-actions=<ACTIONS_SPEC>]\"\n\tvar (\n\t\tapplyFile = cmd.StringOpt(\"f\", \"/etc/ipvsctl.yaml\", \"File to apply. Use - for STDIN\")\n\t\tkeepWeights = cmd.BoolOpt(\"keep-weights\", false, \"Leave weights as they are when updating destinations\")\n\t\tactionSpec = cmd.StringOpt(\"allowed-actions\", \"*\", `\nComma-separated list of allowed actions.\nas=Add service, us=update service, ds=delete service,\nad=Add destination, ud=update destination, dd=delete destination.\nDefault * for all actions.\n`)\n\t)\n\n\tcmd.Action = func() {\n\n\t\tif *applyFile == \"\" {\n\t\t\tfmt.Fprintf(os.Stderr, \"Must specify an input file or - for stdin\\n\")\n\t\t\tos.Exit(exitInvalidFile)\n\t\t}\n\n\t\t// read new config from file\n\t\tnewConfig, err := readModelFromInput(applyFile)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error reading model: %s\\n\", err)\n\t\t\tos.Exit(exitValidateErr)\n\t\t}\n\n\t\tresolvedConfig, err := resolveParams(newConfig)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error resolving parameters: %s\\n\", err)\n\t\t\tos.Exit(exitParamErr)\n\t\t}\n\n\t\t// validate model before applying\n\t\terr = resolvedConfig.Validate()\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error validation model: %s\\n\", err)\n\t\t\tos.Exit(exitValidateErr)\n\t\t}\n\n\t\tallowedSet, err := parseAllowedActions(actionSpec)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"unable to process allowed actions: %s\\n\", err)\n\t\t\tos.Exit(exitInvalidInput)\n\t\t}\n\n\t\t// apply new configuration\n\t\terr = MustGetCurrentConfig().Apply(resolvedConfig, integration.ApplyOpts{\n\t\t\tKeepWeights: *keepWeights,\n\t\t\tAllowedActions: allowedSet,\n\t\t})\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error applying updates: %s\\n\", err)\n\t\t\tos.Exit(exitApplyErr)\n\t\t}\n\t\tfmt.Printf(\"Applied configuration from %s\\n\", *applyFile)\n\t}\n}", "func upgradeExistingConfig(cmd *cobra.Command, cc *config.ClusterConfig) {\n\tif cc == nil {\n\t\treturn\n\t}\n\n\tif cc.VMDriver != \"\" && cc.Driver == \"\" {\n\t\tklog.Infof(\"config upgrade: Driver=%s\", cc.VMDriver)\n\t\tcc.Driver = cc.VMDriver\n\t}\n\n\tif cc.Name == \"\" {\n\t\tklog.Infof(\"config upgrade: Name=%s\", ClusterFlagValue())\n\t\tcc.Name = ClusterFlagValue()\n\t}\n\n\tif cc.KicBaseImage == \"\" {\n\t\t// defaults to kic.BaseImage\n\t\tcc.KicBaseImage = viper.GetString(kicBaseImage)\n\t\tklog.Infof(\"config upgrade: KicBaseImage=%s\", cc.KicBaseImage)\n\t}\n\n\tif cc.CPUs == 0 {\n\t\tklog.Info(\"Existing config file was missing cpu. (could be an old minikube config), will use the default value\")\n\t\tcc.CPUs = viper.GetInt(cpus)\n\t}\n\n\tif cc.Memory == 0 {\n\t\tklog.Info(\"Existing config file was missing memory. (could be an old minikube config), will use the default value\")\n\t\tmemInMB := getMemorySize(cmd, cc.Driver)\n\t\tcc.Memory = memInMB\n\t}\n\n\t// pre minikube 1.9.2 cc.KubernetesConfig.NodePort was not populated.\n\t// in minikube config there were two fields for api server port.\n\t// one in cc.KubernetesConfig.NodePort and one in cc.Nodes.Port\n\t// this makes sure api server port not be set as 0!\n\tif cc.KubernetesConfig.NodePort == 0 {\n\t\tcc.KubernetesConfig.NodePort = viper.GetInt(apiServerPort)\n\t}\n\n\tif cc.CertExpiration == 0 {\n\t\tcc.CertExpiration = constants.DefaultCertExpiration\n\t}\n\n}", "func (a *applyConfigController) Begin() {\n\tnowApp := a.manager.store.GetAppService(a.appService.ServiceID)\n\tnowConfigMaps := nowApp.GetConfigMaps()\n\tnewConfigMaps := a.appService.GetConfigMaps()\n\tvar nowConfigMapMaps = make(map[string]*corev1.ConfigMap, len(nowConfigMaps))\n\tfor i, now := range nowConfigMaps {\n\t\tnowConfigMapMaps[now.Name] = nowConfigMaps[i]\n\t}\n\tfor _, new := range newConfigMaps {\n\t\tif nowConfig, ok := nowConfigMapMaps[new.Name]; ok {\n\t\t\tnew.UID = nowConfig.UID\n\t\t\tnewc, err := a.manager.client.CoreV1().ConfigMaps(nowApp.TenantID).Update(context.Background(), new, metav1.UpdateOptions{})\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Errorf(\"update config map failure %s\", err.Error())\n\t\t\t}\n\t\t\tnowApp.SetConfigMap(newc)\n\t\t\tnowConfigMapMaps[new.Name] = nil\n\t\t\tlogrus.Debugf(\"update configmap %s for service %s\", new.Name, a.appService.ServiceID)\n\t\t} else {\n\t\t\tnewc, err := a.manager.client.CoreV1().ConfigMaps(nowApp.TenantID).Create(context.Background(), new, metav1.CreateOptions{})\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Errorf(\"update config map failure %s\", err.Error())\n\t\t\t}\n\t\t\tnowApp.SetConfigMap(newc)\n\t\t\tlogrus.Debugf(\"create configmap %s for service %s\", new.Name, a.appService.ServiceID)\n\t\t}\n\t}\n\tfor name, handle := range nowConfigMapMaps {\n\t\tif handle != nil {\n\t\t\tif err := a.manager.client.CoreV1().ConfigMaps(nowApp.TenantID).Delete(context.Background(), name, metav1.DeleteOptions{}); err != nil {\n\t\t\t\tlogrus.Errorf(\"delete config map failure %s\", err.Error())\n\t\t\t}\n\t\t\tlogrus.Debugf(\"delete configmap %s for service %s\", name, a.appService.ServiceID)\n\t\t}\n\t}\n\ta.manager.callback(a.controllerID, nil)\n}", "func (r *ConjurConfigReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n\t_ = r.Log.WithValues(\"conjurconfig\", req.NamespacedName)\n\n\t// Fetch the ConjurConfig instance\n\tconjurConfig := &conjurv1alpha1.ConjurConfig{}\n\terr := r.Get(ctx, req.NamespacedName, conjurConfig)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// Request object not found, could have been deleted after reconcile request.\n\t\t\t// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.\n\t\t\t// Return and don't requeue\n\t\t\tlog.Info(\"ConjurConfig resource not found. Ignoring since object must be deleted\")\n\t\t\treturn ctrl.Result{}, nil\n\t\t}\n\t\t// Error reading the object - requeue the request.\n\t\tlog.Error(err, \"Failed to get ConjurConfig\")\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t// Check if the ConfigMap already exists, if not create a new one\n\tfound := &v1.ConfigMap{}\n\tcmName := getConfigMapName(conjurConfig)\n\tcmNamespace := conjurConfig.Namespace\n\terr = r.Get(ctx, types.NamespacedName{Name: cmName, Namespace: cmNamespace}, found)\n\tif err != nil && errors.IsNotFound(err) {\n\t\t// Define a new ConfigMap\n\t\tcm := r.configMapForConjurConfig(conjurConfig, cmName)\n\t\tlog.Info(\"Creating a new ConfigMap, \", \"ConfigMap.Name: \", cmName,\n\t\t\t\"ConfigMap.Namespace: \", cmNamespace)\n\t\terr = r.Create(ctx, cm)\n\t\tif err != nil {\n\t\t\tlog.Error(err, \"Failed to create new ConfigMap, \", \"ConfigMap.Name: \", cm.Name, \"ConfigMap.Namespace: \", cm.Namespace)\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t\t// ConfigMap created successfully - return and requeue\n\t\treturn ctrl.Result{Requeue: true}, nil\n\t} else if err != nil {\n\t\tlog.Error(err, \"Failed to get ConfigMap\")\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t// TODO: Ensure ConfigMap has correct content\n\n\t// TODO: Add ConfigMap created and/or timestamp to status?\n\n\treturn ctrl.Result{}, nil\n}", "func (x *Rest) ConfigurationAdd(w http.ResponseWriter, r *http.Request,\n\tparams httprouter.Params) {\n\tdefer panicCatcher(w)\n\n\trequest := msg.New(r, params)\n\trequest.Section = msg.SectionConfiguration\n\trequest.Action = msg.ActionAdd\n\n\tswitch request.Version {\n\tcase msg.ProtocolOne:\n\t\tcReq := &v1.ConfigurationItem{}\n\t\tif err := decodeJSONBody(r, cReq); err != nil {\n\t\t\tx.replyUnprocessableEntity(&w, &request, err)\n\t\t\treturn\n\t\t}\n\t\trequest.Configuration = v2.ConfigurationFromV1(cReq)\n\n\tcase msg.ProtocolTwo:\n\t\tcReq := v2.NewConfigurationRequest()\n\t\tif err := decodeJSONBody(r, &cReq); err != nil {\n\t\t\tx.replyUnprocessableEntity(&w, &request, err)\n\t\t\treturn\n\t\t}\n\t\trequest.Configuration = *cReq.Configuration\n\n\t\t// only the v2 API has request flags\n\t\tif err := resolveFlags(&cReq, &request); err != nil {\n\t\t\tx.replyBadRequest(&w, &request, err)\n\t\t\treturn\n\t\t}\n\n\tdefault:\n\t\tx.replyInternalError(&w, &request, nil)\n\t\treturn\n\t}\n\n\trequest.Configuration.InputSanatize()\n\trequest.LookupHash = calculateLookupID(\n\t\trequest.Configuration.HostID,\n\t\trequest.Configuration.Metric,\n\t)\n\trequest.Configuration.LookupID = request.LookupHash\n\n\tx.somaSetFeedbackURL(&request)\n\n\tif !x.isAuthorized(&request) {\n\t\tx.replyForbidden(&w, &request, nil)\n\t\treturn\n\t}\n\n\thandler := x.handlerMap.Get(`configuration_w`)\n\thandler.Intake() <- request\n\tresult := <-request.Reply\n\tx.respond(&w, &result)\n}", "func ApplyResouceToConfig(cfg interface{}) error {\n\tdp := GetDataplaneResource()\n\tagentRes := GetAgentResource()\n\tif dp == nil || agentRes == nil {\n\t\treturn nil\n\t}\n\n\tif objInterface, ok := cfg.(config.IResourceConfigCallback); ok {\n\t\terr := objInterface.ApplyResources(dp, agentRes)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// If the parameter is of struct pointer, use indirection to get the\n\t// real value object\n\tv := reflect.ValueOf(cfg)\n\tif v.Kind() == reflect.Ptr {\n\t\tv = reflect.Indirect(v)\n\t}\n\n\t// Look for Validate method on struct properties and invoke it\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tif v.Field(i).CanInterface() {\n\t\t\tfieldInterface := v.Field(i).Interface()\n\t\t\tif objInterface, ok := fieldInterface.(config.IResourceConfigCallback); ok {\n\t\t\t\terr := ApplyResouceToConfig(objInterface)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func ApplyConfigMapFromFile(clientset *kubernetes.Clientset, namespace string, configmap *corev1.ConfigMap, path string) error {\n\tlog.Printf(\"📦 Reading contents of %s\", path)\n\t_, filename := filepath.Split(path)\n\tfileContents, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfigMapData := make(map[string]string)\n\tconfigMapData[filename] = string(fileContents)\n\tconfigmap.Data = configMapData\n\t// Check if deployment exists\n\tdeploymentExists, err := configMapExists(clientset, namespace, configmap.Name)\n\tif deploymentExists {\n\t\tlog.Printf(\"📦 Found existing deployment. Updating %s.\", configmap.Name)\n\t\t_, err = clientset.CoreV1().ConfigMaps(namespace).Update(configmap)\n\t\treturn err\n\t}\n\t_, err = clientset.CoreV1().ConfigMaps(namespace).Create(configmap)\n\treturn err\n}", "func (a *Action) Execute(ctx *actions.ActionContext) error {\n\tctx.Status.Start(\"Writing configuration 📜\")\n\tdefer ctx.Status.End(false)\n\n\tproviderInfo, err := ctx.Provider.Info()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tallNodes, err := ctx.Nodes()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcontrolPlaneEndpoint, err := ctx.Provider.GetAPIServerInternalEndpoint(ctx.Config.Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// create kubeadm init config\n\tfns := []func() error{}\n\n\tprovider := fmt.Sprintf(\"%s\", ctx.Provider)\n\tconfigData := kubeadm.ConfigData{\n\t\tNodeProvider: provider,\n\t\tClusterName: ctx.Config.Name,\n\t\tControlPlaneEndpoint: controlPlaneEndpoint,\n\t\tAPIBindPort: common.APIServerInternalPort,\n\t\tAPIServerAddress: ctx.Config.Networking.APIServerAddress,\n\t\tToken: kubeadm.Token,\n\t\tPodSubnet: ctx.Config.Networking.PodSubnet,\n\t\tKubeProxyMode: string(ctx.Config.Networking.KubeProxyMode),\n\t\tServiceSubnet: ctx.Config.Networking.ServiceSubnet,\n\t\tControlPlane: true,\n\t\tIPFamily: ctx.Config.Networking.IPFamily,\n\t\tFeatureGates: ctx.Config.FeatureGates,\n\t\tRuntimeConfig: ctx.Config.RuntimeConfig,\n\t\tRootlessProvider: providerInfo.Rootless,\n\t}\n\n\tkubeadmConfigPlusPatches := func(node nodes.Node, data kubeadm.ConfigData) func() error {\n\t\treturn func() error {\n\t\t\tdata.NodeName = node.String()\n\t\t\tkubeadmConfig, err := getKubeadmConfig(ctx.Config, data, node, provider)\n\t\t\tif err != nil {\n\t\t\t\t// TODO(bentheelder): logging here\n\t\t\t\treturn errors.Wrap(err, \"failed to generate kubeadm config content\")\n\t\t\t}\n\n\t\t\tctx.Logger.V(2).Infof(\"Using the following kubeadm config for node %s:\\n%s\", node.String(), kubeadmConfig)\n\t\t\treturn writeKubeadmConfig(kubeadmConfig, node)\n\t\t}\n\t}\n\n\t// create the kubeadm join configuration for the kubernetes cluster nodes only\n\tkubeNodes, err := nodeutils.InternalNodes(allNodes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, node := range kubeNodes {\n\t\tnode := node // capture loop variable\n\t\tconfigData := configData // copy config data\n\t\tfns = append(fns, kubeadmConfigPlusPatches(node, configData))\n\t}\n\n\t// Create the kubeadm config in all nodes concurrently\n\tif err := errors.UntilErrorConcurrent(fns); err != nil {\n\t\treturn err\n\t}\n\n\t// if we have containerd config, patch all the nodes concurrently\n\tif len(ctx.Config.ContainerdConfigPatches) > 0 || len(ctx.Config.ContainerdConfigPatchesJSON6902) > 0 {\n\t\tfns := make([]func() error, len(kubeNodes))\n\t\tfor i, node := range kubeNodes {\n\t\t\tnode := node // capture loop variable\n\t\t\tfns[i] = func() error {\n\t\t\t\t// read and patch the config\n\t\t\t\tconst containerdConfigPath = \"/etc/containerd/config.toml\"\n\t\t\t\tvar buff bytes.Buffer\n\t\t\t\tif err := node.Command(\"cat\", containerdConfigPath).SetStdout(&buff).Run(); err != nil {\n\t\t\t\t\treturn errors.Wrap(err, \"failed to read containerd config from node\")\n\t\t\t\t}\n\t\t\t\tpatched, err := patch.TOML(buff.String(), ctx.Config.ContainerdConfigPatches, ctx.Config.ContainerdConfigPatchesJSON6902)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrap(err, \"failed to patch containerd config\")\n\t\t\t\t}\n\t\t\t\tif err := nodeutils.WriteFile(node, containerdConfigPath, patched); err != nil {\n\t\t\t\t\treturn errors.Wrap(err, \"failed to write patched containerd config\")\n\t\t\t\t}\n\t\t\t\t// restart containerd now that we've re-configured it\n\t\t\t\t// skip if containerd is not running\n\t\t\t\tif err := node.Command(\"bash\", \"-c\", `! pgrep --exact containerd || systemctl restart containerd`).Run(); err != nil {\n\t\t\t\t\treturn errors.Wrap(err, \"failed to restart containerd after patching config\")\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\tif err := errors.UntilErrorConcurrent(fns); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// mark success\n\tctx.Status.End(true)\n\treturn nil\n}", "func SetupConfiguration(mgr ctrl.Manager, o controller.Options) error {\n\tname := \"packages/\" + strings.ToLower(v1.ConfigurationGroupKind)\n\tnp := func() v1.Package { return &v1.Configuration{} }\n\tnr := func() v1.PackageRevision { return &v1.ConfigurationRevision{} }\n\tnrl := func() v1.PackageRevisionList { return &v1.ConfigurationRevisionList{} }\n\n\tclientset, err := kubernetes.NewForConfig(mgr.GetConfig())\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to initialize clientset\")\n\t}\n\tfetcher, err := xpkg.NewK8sFetcher(clientset, append(o.FetcherOptions, xpkg.WithNamespace(o.Namespace), xpkg.WithServiceAccount(o.ServiceAccount))...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"cannot build fetcher\")\n\t}\n\n\tr := NewReconciler(mgr,\n\t\tWithNewPackageFn(np),\n\t\tWithNewPackageRevisionFn(nr),\n\t\tWithNewPackageRevisionListFn(nrl),\n\t\tWithRevisioner(NewPackageRevisioner(fetcher, WithDefaultRegistry(o.DefaultRegistry))),\n\t\tWithLogger(o.Logger.WithValues(\"controller\", name)),\n\t\tWithRecorder(event.NewAPIRecorder(mgr.GetEventRecorderFor(name))),\n\t)\n\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\tNamed(name).\n\t\tFor(&v1.Configuration{}).\n\t\tOwns(&v1.ConfigurationRevision{}).\n\t\tWithOptions(o.ForControllerRuntime()).\n\t\tComplete(ratelimiter.NewReconciler(name, r, o.GlobalRateLimiter))\n}", "func configMapOperations(t *testing.T, kubeclient clientset.Interface, namespace string) {\n\t// create, get, watch, update, patch, list and delete configmap.\n\tconfigMap := &apiv1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"audit-configmap\",\n\t\t\tNamespace: namespace,\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"map-key\": \"map-value\",\n\t\t},\n\t}\n\t// add admission label to config maps that are to be sent to webhook\n\tif namespace != nonAdmissionWebhookNamespace {\n\t\tconfigMap.Labels = map[string]string{\n\t\t\t\"admission\": \"true\",\n\t\t}\n\t}\n\n\t_, err := kubeclient.CoreV1().ConfigMaps(namespace).Create(context.TODO(), configMap, metav1.CreateOptions{})\n\texpectNoError(t, err, \"failed to create audit-configmap\")\n\n\t_, err = kubeclient.CoreV1().ConfigMaps(namespace).Get(context.TODO(), configMap.Name, metav1.GetOptions{})\n\texpectNoError(t, err, \"failed to get audit-configmap\")\n\n\tconfigMapChan, err := kubeclient.CoreV1().ConfigMaps(namespace).Watch(context.TODO(), watchOptions)\n\texpectNoError(t, err, \"failed to create watch for config maps\")\n\tfor range configMapChan.ResultChan() {\n\t\t// Block until watchOptions.TimeoutSeconds expires.\n\t\t// If the test finishes before watchOptions.TimeoutSeconds expires, the watch audit\n\t\t// event at stage ResponseComplete will not be generated.\n\t}\n\n\t_, err = kubeclient.CoreV1().ConfigMaps(namespace).Update(context.TODO(), configMap, metav1.UpdateOptions{})\n\texpectNoError(t, err, \"failed to update audit-configmap\")\n\n\t_, err = kubeclient.CoreV1().ConfigMaps(namespace).Patch(context.TODO(), configMap.Name, types.JSONPatchType, patch, metav1.PatchOptions{})\n\texpectNoError(t, err, \"failed to patch configmap\")\n\n\t_, err = kubeclient.CoreV1().ConfigMaps(namespace).List(context.TODO(), metav1.ListOptions{})\n\texpectNoError(t, err, \"failed to list config maps\")\n\n\terr = kubeclient.CoreV1().ConfigMaps(namespace).Delete(context.TODO(), configMap.Name, metav1.DeleteOptions{})\n\texpectNoError(t, err, \"failed to delete audit-configmap\")\n}", "func (c ProducerConfig) Apply(kafkaConf *kafkalib.ConfigMap) {\n\tif timeout := c.DeliveryTimeout; timeout > 0 {\n\t\t_ = kafkaConf.SetKey(\"delivery.timeout.ms\", int(timeout.Milliseconds()))\n\t}\n\n\tif size := c.BatchSize; size > 0 {\n\t\t_ = kafkaConf.SetKey(\"queue.buffering.max.messages\", size)\n\t}\n\n\tif period := c.FlushPeriod; period > 0 {\n\t\t_ = kafkaConf.SetKey(\"queue.buffering.max.ms\", int(period.Milliseconds()))\n\t}\n}", "func (c config) Apply(address string, entriesBytes []byte, dryRun bool, threadPoolSize int) error {\n\t// Unmarshal the list of configured auth backends.\n\tvar entries []entry\n\tif err := yaml.Unmarshal(entriesBytes, &entries); err != nil {\n\t\tlog.WithError(err).Fatal(\"[Vault Auth] failed to decode auth backend configuration\")\n\t}\n\t// organize by instance\n\tinstancesToDesired := make(map[string][]entry)\n\tfor _, e := range entries {\n\t\tinstancesToDesired[e.Instance.Address] = append(instancesToDesired[e.Instance.Address], e)\n\t}\n\tupdateOptionalKubeDefaults(instancesToDesired[address])\n\n\tif unique := utils.ValidKeys(instancesToDesired[address],\n\t\tfunc(e entry) string {\n\t\t\treturn e.Key()\n\t\t}); !unique {\n\t\treturn fmt.Errorf(\"Duplicate key value detected within %s\", toplevelName)\n\t}\n\n\t// Get the existing auth backends\n\texistingAuthMounts, err := vault.ListAuthBackends(address)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Build a array of all the existing entries.\n\texistingBackends := make([]entry, 0)\n\n\tif existingAuthMounts != nil {\n\t\tfor path, backend := range existingAuthMounts {\n\t\t\texistingBackends = append(existingBackends, entry{\n\t\t\t\tPath: path,\n\t\t\t\tType: backend.Type,\n\t\t\t\tDescription: backend.Description,\n\t\t\t\tInstance: vault.Instance{Address: address},\n\t\t\t})\n\t\t}\n\t}\n\n\t// perform auth reconcile\n\ttoBeWritten, toBeDeleted, _ :=\n\t\tvault.DiffItems(asItems(instancesToDesired[address]), asItems(existingBackends))\n\terr = enableAuth(address, toBeWritten, dryRun)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = configureAuthMounts(address, instancesToDesired[address], dryRun)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = disableAuth(address, toBeDeleted, dryRun)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// apply github policy mappings\n\tfor _, e := range instancesToDesired[address] {\n\t\tif e.Type == \"github\" {\n\t\t\t//Build a array of existing policy mappings for current auth mount\n\t\t\texistingPolicyMappings := make([]policyMapping, 0)\n\t\t\tteamsList, err := vault.ListSecrets(address, filepath.Join(\"/auth\", e.Path, \"map/teams\"))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif teamsList != nil {\n\n\t\t\t\tvar mutex = &sync.Mutex{}\n\n\t\t\t\tteams := teamsList.Data[\"keys\"].([]interface{})\n\n\t\t\t\tbwg := utils.NewBoundedWaitGroup(threadPoolSize)\n\t\t\t\tch := make(chan error)\n\n\t\t\t\t// fill existing policy mappings array in parallel\n\t\t\t\tfor team := range teams {\n\t\t\t\t\tbwg.Add(1)\n\n\t\t\t\t\tgo func(team int, ch chan<- error) {\n\t\t\t\t\t\tdefer bwg.Done()\n\n\t\t\t\t\t\tpolicyMappingPath := filepath.Join(\"/auth/\", e.Path, \"map/teams\", teams[team].(string))\n\n\t\t\t\t\t\tpoliciesMappedToEntity, err := vault.ReadSecret(address, policyMappingPath, vault.KV_V1)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tch <- err\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tpolicies := make([]map[string]interface{}, 0)\n\t\t\t\t\t\tfor _, policy := range strings.Split(policiesMappedToEntity[\"value\"].(string), \",\") {\n\t\t\t\t\t\t\tpolicies = append(policies, map[string]interface{}{\"name\": policy})\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tmutex.Lock()\n\n\t\t\t\t\t\texistingPolicyMappings = append(existingPolicyMappings,\n\t\t\t\t\t\t\tpolicyMapping{GithubTeam: map[string]interface{}{\"team\": teams[team]}, Policies: policies})\n\n\t\t\t\t\t\tdefer mutex.Unlock()\n\t\t\t\t\t}(team, ch)\n\t\t\t\t}\n\n\t\t\t\tgo func() {\n\t\t\t\t\tbwg.Wait()\n\t\t\t\t\tclose(ch)\n\t\t\t\t}()\n\n\t\t\t\tfor e := range ch {\n\t\t\t\t\tif e != nil {\n\t\t\t\t\t\treturn e\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// remove all gh user policy mappings from vault\n\t\t\tusersList, err := vault.ListSecrets(address, filepath.Join(\"/auth\", e.Path, \"map/users\"))\n\t\t\tif usersList != nil {\n\n\t\t\t\tusers := usersList.Data[\"keys\"].([]interface{})\n\n\t\t\t\tbwg := utils.NewBoundedWaitGroup(threadPoolSize)\n\t\t\t\t// remove existing gh user policy mappings in parallel\n\t\t\t\tfor user := range users {\n\n\t\t\t\t\tbwg.Add(1)\n\n\t\t\t\t\tgo func(user int) {\n\n\t\t\t\t\t\tpolicyMappingPath := filepath.Join(\"/auth/\", e.Path, \"map/users\", users[user].(string))\n\n\t\t\t\t\t\tdeletePolicyMapping(address, policyMappingPath, dryRun)\n\n\t\t\t\t\t\tdefer bwg.Done()\n\n\t\t\t\t\t}(user)\n\t\t\t\t}\n\t\t\t\tbwg.Wait()\n\t\t\t}\n\n\t\t\tpoliciesMappingsToBeApplied, policiesMappingsToBeDeleted, _ :=\n\t\t\t\tvault.DiffItems(policyMappingsAsItems(e.PolicyMappings), policyMappingsAsItems(existingPolicyMappings))\n\n\t\t\t// apply policy mappings\n\t\t\tfor _, pm := range policiesMappingsToBeApplied {\n\t\t\t\tvar policies []string\n\t\t\t\tfor _, policy := range pm.(policyMapping).Policies {\n\t\t\t\t\tpolicies = append(policies, policy[\"name\"].(string))\n\t\t\t\t}\n\t\t\t\tghTeamName := pm.(policyMapping).GithubTeam[\"team\"].(string)\n\t\t\t\tpath := filepath.Join(\"/auth\", e.Path, \"map/teams\", ghTeamName)\n\t\t\t\tdata := map[string]interface{}{\"key\": ghTeamName, \"value\": strings.Join(policies, \",\")}\n\t\t\t\twritePolicyMapping(address, path, data, dryRun)\n\t\t\t}\n\n\t\t\t// delete policy mappings\n\t\t\tfor _, pm := range policiesMappingsToBeDeleted {\n\t\t\t\tpath := filepath.Join(\"/auth\", e.Path, \"map/teams\", pm.(policyMapping).GithubTeam[\"team\"].(string))\n\t\t\t\tdeletePolicyMapping(address, path, dryRun)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func ApplyMutatingWebhookConfiguration(client admissionregistrationclientv1.MutatingWebhookConfigurationsGetter, recorder events.Recorder,\n\trequiredOriginal *admissionregistrationv1.MutatingWebhookConfiguration, expectedGeneration int64) (*admissionregistrationv1.MutatingWebhookConfiguration, bool, error) {\n\n\tif requiredOriginal == nil {\n\t\treturn nil, false, fmt.Errorf(\"Unexpected nil instead of an object\")\n\t}\n\trequired := requiredOriginal.DeepCopy()\n\n\texisting, err := client.MutatingWebhookConfigurations().Get(context.TODO(), required.GetName(), metav1.GetOptions{})\n\tif apierrors.IsNotFound(err) {\n\t\tactual, err := client.MutatingWebhookConfigurations().Create(context.TODO(), required, metav1.CreateOptions{})\n\t\treportCreateEvent(recorder, required, err)\n\t\tif err != nil {\n\t\t\treturn nil, false, err\n\t\t}\n\t\treturn actual, true, nil\n\t} else if err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tmodified := resourcemerge.BoolPtr(false)\n\texistingCopy := existing.DeepCopy()\n\n\tresourcemerge.EnsureObjectMeta(modified, &existingCopy.ObjectMeta, required.ObjectMeta)\n\tif !*modified && existingCopy.GetGeneration() == expectedGeneration {\n\t\treturn existingCopy, false, nil\n\t}\n\t// at this point we know that we're going to perform a write. We're just trying to get the object correct\n\ttoWrite := existingCopy // shallow copy so the code reads easier\n\n\t// Providing upgrade compatibility with service-ca-bundle operator\n\t// and ignore clientConfig.caBundle changes on \"inject-cabundle\" label\n\tif required.GetAnnotations() != nil && required.GetAnnotations()[genericCABundleInjectorAnnotation] != \"\" {\n\t\tcopyMutatingWebhookCABundle(existing, required)\n\t}\n\ttoWrite.Webhooks = required.Webhooks\n\n\tklog.V(4).Infof(\"MutatingWebhookConfiguration %q changes: %v\", required.GetNamespace()+\"/\"+required.GetName(), JSONPatchNoError(existing, toWrite))\n\n\tactual, err := client.MutatingWebhookConfigurations().Update(context.TODO(), toWrite, metav1.UpdateOptions{})\n\treportUpdateEvent(recorder, required, err)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\treturn actual, *modified || actual.GetGeneration() > existingCopy.GetGeneration(), nil\n}", "func createCustomConfigMap(c kubernetes.Interface, pluginPath string, subvolgrpInfo map[string]string) {\n\tpath := pluginPath + configMap\n\tcm := v1.ConfigMap{}\n\terr := unmarshal(path, &cm)\n\tExpect(err).Should(BeNil())\n\n\t// get mon list\n\tmons := getMons(rookNamespace, c)\n\t// get clusterIDs\n\tvar clusterID []string\n\tfor key := range subvolgrpInfo {\n\t\tclusterID = append(clusterID, key)\n\t}\n\tconmap := []util.ClusterInfo{\n\t\t{\n\t\t\tClusterID: clusterID[0],\n\t\t\tMonitors: mons,\n\t\t},\n\t\t{\n\t\t\tClusterID: clusterID[1],\n\t\t\tMonitors: mons,\n\t\t}}\n\tfor i := 0; i < len(subvolgrpInfo); i++ {\n\t\tconmap[i].CephFS.SubvolumeGroup = subvolgrpInfo[clusterID[i]]\n\t}\n\tdata, err := json.Marshal(conmap)\n\tExpect(err).Should(BeNil())\n\tcm.Data[\"config.json\"] = string(data)\n\tcm.Namespace = cephCSINamespace\n\t// since a configmap is already created, update the existing configmap\n\t_, updateErr := c.CoreV1().ConfigMaps(cephCSINamespace).Update(context.TODO(), &cm, metav1.UpdateOptions{})\n\tExpect(updateErr).Should(BeNil())\n}", "func (whc *WebhookConfigController) reconcile(stopCh <-chan struct{}) {\n\tdefer whc.configWatcher.Close() // nolint: errcheck\n\n\t// Try to create the initial webhook configuration (if it doesn't\n\t// already exist). Setup a persistent monitor to reconcile the\n\t// configuration if the observed configuration doesn't match\n\t// the desired configuration.\n\tvar retryAfterSetup bool\n\tif err := whc.rebuildWebhookConfig(); err == nil {\n\t\tretryAfterSetup = whc.createOrUpdateWebhookConfig()\n\t}\n\twebhookChangedCh := whc.monitorWebhookChanges(stopCh)\n\n\t// use a timer to debounce file updates\n\tvar configTimerC <-chan time.Time\n\n\tif retryAfterSetup {\n\t\tconfigTimerC = time.After(retryUpdateAfterFailureTimeout)\n\t}\n\n\tvar retrying bool\n\tfor {\n\t\tselect {\n\t\tcase <-configTimerC:\n\t\t\tconfigTimerC = nil\n\n\t\t\t// rebuild the desired configuration and reconcile with the\n\t\t\t// existing configuration.\n\t\t\tif err := whc.rebuildWebhookConfig(); err == nil {\n\t\t\t\tif retry := whc.createOrUpdateWebhookConfig(); retry {\n\t\t\t\t\tconfigTimerC = time.After(retryUpdateAfterFailureTimeout)\n\t\t\t\t\tif !retrying {\n\t\t\t\t\t\tretrying = true\n\t\t\t\t\t\tlog.Infof(\"webhook create/update failed - retrying every %v until success\", retryUpdateAfterFailureTimeout)\n\t\t\t\t\t}\n\t\t\t\t} else if retrying {\n\t\t\t\t\tlog.Infof(\"Retried create/update succeeded\")\n\t\t\t\t\tretrying = false\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-webhookChangedCh:\n\t\t\tvar retry bool\n\t\t\tif whc.webhookParameters.EnableValidation {\n\t\t\t\t// reconcile the desired configuration\n\t\t\t\tif retry = whc.createOrUpdateWebhookConfig(); retry && !retrying {\n\t\t\t\t\tlog.Infof(\"webhook create/update failed - retrying every %v until success\", retryUpdateAfterFailureTimeout)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif retry = whc.deleteWebhookConfig(); retry && !retrying {\n\t\t\t\t\tlog.Infof(\"webhook delete failed - retrying every %v until success\", retryUpdateAfterFailureTimeout)\n\t\t\t\t}\n\t\t\t}\n\t\t\tretrying = retry\n\t\t\tif retry {\n\t\t\t\ttime.AfterFunc(retryUpdateAfterFailureTimeout, func() { webhookChangedCh <- struct{}{} })\n\t\t\t}\n\t\tcase event, more := <-whc.configWatcher.Event:\n\t\t\tif more && (event.IsModify() || event.IsCreate()) && configTimerC == nil {\n\t\t\t\tconfigTimerC = time.After(watchDebounceDelay)\n\t\t\t}\n\t\tcase err := <-whc.configWatcher.Error:\n\t\t\tscope.Errorf(\"configWatcher error: %v\", err)\n\t\tcase <-stopCh:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (r *Reconciler) reconcileScrapeConfigs(ctx context.Context, serverClient k8sclient.Client) (integreatlyv1alpha1.StatusPhase, error) {\n\ttemplateHelper := NewTemplateHelper(r.extraParams)\n\tthreeScaleConfig, err := r.ConfigManager.ReadThreeScale()\n\tif err != nil {\n\t\treturn integreatlyv1alpha1.PhaseFailed, fmt.Errorf(\"error reading config: %w\", err)\n\t}\n\n\tjobs := strings.Builder{}\n\tfor _, job := range r.Config.GetJobTemplates() {\n\t\t// Don't include the 3scale extra scrape config if the product is not installed\n\t\tif strings.Contains(job, \"3scale\") && threeScaleConfig.GetNamespace() == \"\" {\n\t\t\tr.Logger.Info(\"skipping 3scale additional scrape config\")\n\t\t\tcontinue\n\t\t}\n\n\t\tbytes, err := templateHelper.loadTemplate(job)\n\t\tif err != nil {\n\t\t\treturn integreatlyv1alpha1.PhaseFailed, fmt.Errorf(\"error loading template: %w\", err)\n\t\t}\n\n\t\tjobs.Write(bytes)\n\t\tjobs.WriteByte('\\n')\n\t}\n\n\tscrapeConfigSecret := &corev1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: r.Config.GetAdditionalScrapeConfigSecretName(),\n\t\t\tNamespace: r.Config.GetOperatorNamespace(),\n\t\t},\n\t}\n\n\tor, err := controllerutil.CreateOrUpdate(ctx, serverClient, scrapeConfigSecret, func() error {\n\t\tscrapeConfigSecret.Data = map[string][]byte{\n\t\t\tr.Config.GetAdditionalScrapeConfigSecretKey(): []byte(jobs.String()),\n\t\t}\n\t\tscrapeConfigSecret.Type = \"Opaque\"\n\t\tscrapeConfigSecret.Labels = map[string]string{\n\t\t\tr.Config.GetLabelSelectorKey(): r.Config.GetLabelSelector(),\n\t\t}\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn integreatlyv1alpha1.PhaseFailed, fmt.Errorf(\"error creating additional scrape config secret: %w\", err)\n\t}\n\n\tr.Logger.Info(fmt.Sprintf(\"operation result of creating additional scrape config secret was %v\", or))\n\n\treturn integreatlyv1alpha1.PhaseCompleted, nil\n}", "func (c *SetClusterConfigCommand) Apply(context raft.Context) (interface{}, error) {\n\tps, _ := context.Server().Context().(*PeerServer)\n\tps.SetClusterConfig(c.Config)\n\treturn nil, nil\n}", "func (c *ClusterController) createOnosConfigDeployment() error {\n\tnodes := int32(c.config.ConfigNodes)\n\tzero := int64(0)\n\tdep := &appsv1.Deployment{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"onos-config\",\n\t\t\tNamespace: c.clusterID,\n\t\t},\n\t\tSpec: appsv1.DeploymentSpec{\n\t\t\tReplicas: &nodes,\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: map[string]string{\n\t\t\t\t\t\"app\": \"onos\",\n\t\t\t\t\t\"type\": \"config\",\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: map[string]string{\n\t\t\t\t\t\t\"app\": \"onos\",\n\t\t\t\t\t\t\"type\": \"config\",\n\t\t\t\t\t\t\"resource\": \"onos-config\",\n\t\t\t\t\t},\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\t\"seccomp.security.alpha.kubernetes.io/pod\": \"unconfined\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tContainers: []corev1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"onos-config\",\n\t\t\t\t\t\t\tImage: \"onosproject/onos-config:debug\",\n\t\t\t\t\t\t\tImagePullPolicy: corev1.PullIfNotPresent,\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: \"ATOMIX_CONTROLLER\",\n\t\t\t\t\t\t\t\t\tValue: fmt.Sprintf(\"atomix-controller.%s.svc.cluster.local:5679\", c.clusterID),\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: \"ATOMIX_APP\",\n\t\t\t\t\t\t\t\t\tValue: \"test\",\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: \"ATOMIX_NAMESPACE\",\n\t\t\t\t\t\t\t\t\tValue: c.clusterID,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tArgs: []string{\n\t\t\t\t\t\t\t\t\"-caPath=/etc/onos-config/certs/onf.cacrt\",\n\t\t\t\t\t\t\t\t\"-keyPath=/etc/onos-config/certs/onos-config.key\",\n\t\t\t\t\t\t\t\t\"-certPath=/etc/onos-config/certs/onos-config.crt\",\n\t\t\t\t\t\t\t\t\"-configStore=/etc/onos-config/configs/configStore.json\",\n\t\t\t\t\t\t\t\t\"-changeStore=/etc/onos-config/configs/changeStore.json\",\n\t\t\t\t\t\t\t\t\"-deviceStore=/etc/onos-config/configs/deviceStore.json\",\n\t\t\t\t\t\t\t\t\"-networkStore=/etc/onos-config/configs/networkStore.json\",\n\t\t\t\t\t\t\t\t\"-modelPlugin=/usr/local/lib/testdevice-debug.so.1.0.0\",\n\t\t\t\t\t\t\t\t\"-modelPlugin=/usr/local/lib/testdevice-debug.so.2.0.0\",\n\t\t\t\t\t\t\t\t\"-modelPlugin=/usr/local/lib/devicesim-debug.so.1.0.0\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tPorts: []corev1.ContainerPort{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tName: \"grpc\",\n\t\t\t\t\t\t\t\t\tContainerPort: 5150,\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: \"debug\",\n\t\t\t\t\t\t\t\t\tContainerPort: 40000,\n\t\t\t\t\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tReadinessProbe: &corev1.Probe{\n\t\t\t\t\t\t\t\tHandler: corev1.Handler{\n\t\t\t\t\t\t\t\t\tTCPSocket: &corev1.TCPSocketAction{\n\t\t\t\t\t\t\t\t\t\tPort: intstr.FromInt(5150),\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\tInitialDelaySeconds: 5,\n\t\t\t\t\t\t\t\tPeriodSeconds: 10,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tLivenessProbe: &corev1.Probe{\n\t\t\t\t\t\t\t\tHandler: corev1.Handler{\n\t\t\t\t\t\t\t\t\tTCPSocket: &corev1.TCPSocketAction{\n\t\t\t\t\t\t\t\t\t\tPort: intstr.FromInt(5150),\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\tInitialDelaySeconds: 15,\n\t\t\t\t\t\t\t\tPeriodSeconds: 20,\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: \"config\",\n\t\t\t\t\t\t\t\t\tMountPath: \"/etc/onos-config/configs\",\n\t\t\t\t\t\t\t\t\tReadOnly: true,\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: \"secret\",\n\t\t\t\t\t\t\t\t\tMountPath: \"/etc/onos-config/certs\",\n\t\t\t\t\t\t\t\t\tReadOnly: true,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tSecurityContext: &corev1.SecurityContext{\n\t\t\t\t\t\t\t\tCapabilities: &corev1.Capabilities{\n\t\t\t\t\t\t\t\t\tAdd: []corev1.Capability{\n\t\t\t\t\t\t\t\t\t\t\"SYS_PTRACE\",\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\tSecurityContext: &corev1.PodSecurityContext{\n\t\t\t\t\t\tRunAsUser: &zero,\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: \"config\",\n\t\t\t\t\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\t\t\t\t\tConfigMap: &corev1.ConfigMapVolumeSource{\n\t\t\t\t\t\t\t\t\tLocalObjectReference: corev1.LocalObjectReference{\n\t\t\t\t\t\t\t\t\t\tName: \"onos-config\",\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\t{\n\t\t\t\t\t\t\tName: \"secret\",\n\t\t\t\t\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\t\t\t\t\tSecret: &corev1.SecretVolumeSource{\n\t\t\t\t\t\t\t\t\tSecretName: c.clusterID,\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\t_, err := c.kubeclient.AppsV1().Deployments(c.clusterID).Create(dep)\n\treturn err\n}", "func (h *PrometheusStatusHandler) ApplyConfig(conf *config.Config) {\n\th.mu.Lock()\n\th.Config = conf.String()\n\th.mu.Unlock()\n}", "func (r *ReconcileConfigMap) Reconcile(request reconcile.Request) (reconcile.Result, error) {\n\tif request.Namespace != \"openshift-file-integrity\" || request.Name != \"aide-conf\" {\n\t\treturn reconcile.Result{}, nil\n\t}\n\n\treqLogger := log.WithValues(\"Request.Namespace\", request.Namespace, \"Request.Name\", request.Name)\n\treqLogger.Info(\"Reconciling ConfigMap\")\n\n\t// Fetch the ConfigMap instance\n\tinstance := &corev1.ConfigMap{}\n\terr := r.client.Get(context.TODO(), request.NamespacedName, instance)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// Request object not found, could have been deleted after reconcile request.\n\t\t\t// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.\n\t\t\t// Return and don't requeue\n\t\t\treturn reconcile.Result{}, nil\n\t\t}\n\t\t// Error reading the object - requeue the request.\n\t\treturn reconcile.Result{}, err\n\t}\n\n\t// only continue if the configmap received an update through the user-provided config\n\tif _, ok := instance.Annotations[\"fileintegrity.openshift.io/updated\"]; !ok {\n\t\treqLogger.Info(\"DBG: updated annotation not found - removing from queue\")\n\t\treturn reconcile.Result{}, nil\n\t}\n\n\t// handling the re-init daemonSets: these are created by the FileIntegrity controller when the AIDE config has been\n\t// updated by the user. They touch a file on the node host and then sleep. The file signals to the AIDE pod\n\t// daemonSets that they need to back up and re-initialize the AIDE database. So once we've confirmed that the\n\t// re-init daemonSets have started running we can delete them and continue with the rollout of the AIDE pods.\n\treinitDS := &appsv1.DaemonSet{}\n\terr = r.client.Get(context.TODO(), types.NamespacedName{Name: common.ReinitDaemonSetName, Namespace: common.FileIntegrityNamespace}, reinitDS)\n\tif err != nil {\n\t\t// includes notFound, we will requeue here at least once.\n\t\treqLogger.Error(err, \"error getting reinit daemonSet\")\n\t\treturn reconcile.Result{}, err\n\t}\n\t// not ready, requeue\n\tif !daemonSetIsReady(reinitDS) {\n\t\treqLogger.Info(\"DBG: requeue of DS\")\n\t\treturn reconcile.Result{RequeueAfter: time.Duration(5 * time.Second)}, nil // guessing on 5 seconds as acceptable requeue rate\n\t}\n\n\treqLogger.Info(\"reinitDaemonSet statuses\", \"Status\", reinitDS.Status)\n\n\t// reinit daemonSet is ready, so we're finished with it\n\tif err := r.client.Delete(context.TODO(), reinitDS); err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\n\tds := &appsv1.DaemonSet{}\n\terr = r.client.Get(context.TODO(), types.NamespacedName{Name: common.DaemonSetName, Namespace: common.FileIntegrityNamespace}, ds)\n\tif err != nil {\n\t\treqLogger.Error(err, \"error getting daemonSet\")\n\t\treturn reconcile.Result{}, err\n\t}\n\n\tif err := triggerDaemonSetRollout(r.client, ds); err != nil {\n\t\treqLogger.Error(err, \"error triggering daemonSet rollout\")\n\t\treturn reconcile.Result{}, err\n\t}\n\n\treqLogger.Info(\"DBG: rollout triggered, clearing update annotation\")\n\t// unset update annotation\n\tconf := instance.DeepCopy()\n\tconf.Annotations = nil\n\tif err := r.client.Update(context.TODO(), conf); err != nil {\n\t\treqLogger.Error(err, \"error clearing configMap annotations\")\n\t\treturn reconcile.Result{}, err\n\t}\n\n\treturn reconcile.Result{}, nil\n}", "func CreateOrUpdateConfigMaps(dpl *v1alpha1.Elasticsearch) (err error) {\n\tkibanaIndexMode, err := kibanaIndexMode(\"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdataNodeCount := int((getDataCount(dpl)))\n\tmasterNodeCount := int((getMasterCount(dpl)))\n\n\tconfigmap := newConfigMap(\n\t\tdpl.Name,\n\t\tdpl.Namespace,\n\t\tdpl.Labels,\n\t\tkibanaIndexMode,\n\t\tesUnicastHost(dpl.Name, dpl.Namespace),\n\t\trootLogger(),\n\t\tstrconv.Itoa(masterNodeCount/2+1),\n\t\tstrconv.Itoa(dataNodeCount),\n\t\tstrconv.Itoa(dataNodeCount),\n\t\tstrconv.Itoa(calculateReplicaCount(dpl)),\n\t)\n\n\taddOwnerRefToObject(configmap, getOwnerRef(dpl))\n\n\terr = sdk.Create(configmap)\n\tif err != nil {\n\t\tif !errors.IsAlreadyExists(err) {\n\t\t\treturn fmt.Errorf(\"Failure constructing Elasticsearch ConfigMap: %v\", err)\n\t\t}\n\n\t\tif errors.IsAlreadyExists(err) {\n\t\t\t// Get existing configMap to check if it is same as what we want\n\t\t\tcurrent := configmap.DeepCopy()\n\t\t\terr = sdk.Get(current)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Unable to get Elasticsearch cluster configMap: %v\", err)\n\t\t\t}\n\n\t\t\tif configMapContentChanged(current, configmap) {\n\t\t\t\t// Cluster settings has changed, make sure it doesnt go unnoticed\n\t\t\t\tif err := updateConditionWithRetry(dpl, v1.ConditionTrue, updateUpdatingSettingsCondition); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\treturn retry.RetryOnConflict(retry.DefaultRetry, func() error {\n\t\t\t\t\tif getErr := sdk.Get(current); getErr != nil {\n\t\t\t\t\t\tlogrus.Debugf(\"Could not get Elasticsearch configmap %v: %v\", configmap.Name, getErr)\n\t\t\t\t\t\treturn getErr\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrent.Data = configmap.Data\n\t\t\t\t\tif updateErr := sdk.Update(current); updateErr != nil {\n\t\t\t\t\t\tlogrus.Debugf(\"Failed to update Elasticsearch configmap %v: %v\", configmap.Name, updateErr)\n\t\t\t\t\t\treturn updateErr\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}\n\t}\n\n\treturn nil\n}", "func configure(v *viper.Viper, p *pflag.FlagSet) {\n\tv.AllowEmptyEnv(true)\n\tv.AddConfigPath(\".\")\n\tv.AddConfigPath(\"./config\")\n\tv.AddConfigPath(fmt.Sprintf(\"$%s_CONFIG_DIR/\", strings.ToUpper(envPrefix)))\n\tp.Init(friendlyAppName, pflag.ExitOnError)\n\tpflag.Usage = func() {\n\t\t_, _ = fmt.Fprintf(os.Stderr, \"Usage of %s:\\n\", friendlyAppName)\n\t\tpflag.PrintDefaults()\n\t}\n\t_ = v.BindPFlags(p)\n\n\tv.SetEnvPrefix(envPrefix)\n\tv.SetEnvKeyReplacer(strings.NewReplacer(\"::\", \"_\", \".\", \"_\", \"-\", \"_\"))\n\tv.AutomaticEnv()\n\n\t// Load common configuration\n\tcmd.Configure(v, p)\n\n\t// Global configuration\n\tv.SetDefault(\"environment\", \"production\")\n\tv.SetDefault(\"debug\", false)\n\tv.SetDefault(\"shutdownTimeout\", 15*time.Second)\n\n\t// Cadence configuration\n\tv.SetDefault(\"cadence::createNonexistentDomain\", false)\n\tv.SetDefault(\"cadence::workflowExecutionRetentionPeriodInDays\", 3)\n\n\tv.SetDefault(\"pipeline::uuid\", \"\")\n\tv.SetDefault(\"pipeline::enterprise\", false)\n\tv.SetDefault(\"pipeline::external::url\", \"\")\n\tv.SetDefault(\"pipeline::external::insecure\", false)\n}", "func populateConfigOverrideConfigMap(clusterdContext *clusterd.Context, namespace string, ownerInfo *k8sutil.OwnerInfo, clusterMetadata metav1.ObjectMeta) error {\n\tctx := context.TODO()\n\n\texistingCM, err := clusterdContext.Clientset.CoreV1().ConfigMaps(namespace).Get(ctx, k8sutil.ConfigOverrideName, metav1.GetOptions{})\n\tif err != nil {\n\t\tif !kerrors.IsNotFound(err) {\n\t\t\tlogger.Warningf(\"failed to get cm %q to check labels and annotations\", k8sutil.ConfigOverrideName)\n\t\t\treturn nil\n\t\t}\n\n\t\tlabels := map[string]string{}\n\t\tannotations := map[string]string{}\n\t\tinitRequiredMetadata(clusterMetadata, labels, annotations)\n\n\t\t// Create the configmap since it doesn't exist yet\n\t\tplaceholderConfig := map[string]string{\n\t\t\tk8sutil.ConfigOverrideVal: \"\",\n\t\t}\n\t\tcm := &v1.ConfigMap{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: k8sutil.ConfigOverrideName,\n\t\t\t\tNamespace: namespace,\n\t\t\t\tLabels: labels,\n\t\t\t\tAnnotations: annotations,\n\t\t\t},\n\t\t\tData: placeholderConfig,\n\t\t}\n\n\t\terr := ownerInfo.SetControllerReference(cm)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to set owner reference to override configmap %q\", cm.Name)\n\t\t}\n\t\t_, err = clusterdContext.Clientset.CoreV1().ConfigMaps(namespace).Create(ctx, cm, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to create override configmap %s\", namespace)\n\t\t}\n\t\tlogger.Infof(\"created placeholder configmap for ceph overrides %q\", cm.Name)\n\t\treturn nil\n\t}\n\n\t// Ensure the annotations and labels are initialized\n\tif existingCM.Annotations == nil {\n\t\texistingCM.Annotations = map[string]string{}\n\t}\n\tif existingCM.Labels == nil {\n\t\texistingCM.Labels = map[string]string{}\n\t}\n\n\t// Add recommended labels and annotations to the existing configmap if it doesn't have any yet\n\tupdateRequired := initRequiredMetadata(clusterMetadata, existingCM.Labels, existingCM.Annotations)\n\tif updateRequired {\n\t\t_, err = clusterdContext.Clientset.CoreV1().ConfigMaps(namespace).Update(ctx, existingCM, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\tlogger.Warningf(\"failed to add recommended labels and annotations to configmap %q. %v\", existingCM.Name, err)\n\t\t} else {\n\t\t\tlogger.Infof(\"added expected labels and annotations to configmap %q\", existingCM.Name)\n\t\t}\n\t}\n\treturn nil\n}", "func (a *ExistingInfraMachineReconciler) updateConfigMap(ctx context.Context, namespace, name string, updater func(*v1.ConfigMap) error) error {\n\tretryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {\n\t\tvar result v1.ConfigMap\n\t\tgetErr := a.Client.Get(ctx, client.ObjectKey{Namespace: namespace, Name: name}, &result)\n\t\tif getErr != nil {\n\t\t\tlog.Errorf(\"failed to read config map, can't reschedule: %v\", getErr)\n\t\t\treturn getErr\n\t\t}\n\t\tif err := updater(&result); err != nil {\n\t\t\tlog.Errorf(\"failed to update cluster: %v\", err)\n\t\t\treturn err\n\t\t}\n\t\tupdateErr := a.Client.Update(ctx, &result)\n\t\tif updateErr != nil {\n\t\t\tlog.Errorf(\"failed to reschedule config map: %v\", updateErr)\n\t\t\treturn updateErr\n\t\t}\n\t\treturn nil\n\t})\n\tif retryErr != nil {\n\t\tlog.Errorf(\"failed to update config map: %v\", retryErr)\n\t\treturn retryErr\n\t}\n\treturn nil\n}", "func (pc *PodController) handleAddUpdatePod(obj interface{}) error {\n\tvar err error\n\tvar podCNIInfo *cnipodcache.CNIConfigInfo\n\tpod := obj.(*corev1.Pod)\n\tif len(pod.Status.PodIPs) == 0 {\n\t\t// Primary network configuration is not complete yet.\n\t\t// Note: Return nil here to unqueue Pod add event. Secondary network configuration will be handled with Pod update event.\n\t\treturn nil\n\t}\n\tsecondaryNetwork, ok := checkForPodSecondaryNetworkAttachement(pod)\n\tif !ok {\n\t\t// NOTE: We do not handle Pod annotation deletion/update scenario at present.\n\t\tklog.InfoS(\"Pod does not have a NetworkAttachmentDefinition\", \"Pod\", klog.KObj(pod))\n\t\treturn nil\n\t}\n\t// Retrieve Pod specific cache entry which has \"PodCNIDeleted = false\"\n\tif podCNIInfo = pc.podCache.GetValidCNIConfigInfoPerPod(pod.Name, pod.Namespace); podCNIInfo == nil {\n\t\treturn nil\n\t}\n\t// Valid cache entry retrieved from cache and we received a Pod add or update event.\n\t// Avoid processing Pod annotation, if we already have at least one secondary network successfully configured on this Pod.\n\t// We do not support/handle Annotation updates yet.\n\tif len(podCNIInfo.NetworkConfig) > 0 {\n\t\tklog.InfoS(\"Secondary network already configured on this Pod and annotation update not supported, skipping update\", \"pod\", klog.KObj(pod))\n\t\treturn nil\n\t}\n\t// Parse Pod annotation and proceed with the secondary network configuration.\n\tnetworklist, err := parsePodSecondaryNetworkAnnotation(secondaryNetwork)\n\tif err != nil {\n\t\t// Return error to requeue and retry.\n\t\treturn err\n\t}\n\n\terr = pc.configureSecondaryNetwork(pod, networklist, podCNIInfo)\n\t// We do not return error to retry, if at least one secondary network is configured.\n\tif (err != nil) && (len(podCNIInfo.NetworkConfig) == 0) {\n\t\t// Return error to requeue and retry.\n\t\treturn err\n\t}\n\treturn nil\n}", "func (fm *FakeManager) UpdateConfiguration(throttlerName string, configuration *throttlerdatapb.Configuration, copyZeroValues bool) ([]string, error) {\n\tpanic(panicMsg)\n}", "func updateExistingConfigFromFlags(cmd *cobra.Command, existing *config.ClusterConfig) config.ClusterConfig { //nolint to suppress cyclomatic complexity 45 of func `updateExistingConfigFromFlags` is high (> 30)\n\n\tvalidateFlags(cmd, existing.Driver)\n\n\tcc := *existing\n\n\tif cmd.Flags().Changed(memory) && getMemorySize(cmd, cc.Driver) != cc.Memory {\n\t\tout.WarningT(\"You cannot change the memory size for an existing minikube cluster. Please first delete the cluster.\")\n\t}\n\n\tif cmd.Flags().Changed(cpus) && viper.GetInt(cpus) != cc.CPUs {\n\t\tout.WarningT(\"You cannot change the CPUs for an existing minikube cluster. Please first delete the cluster.\")\n\t}\n\n\t// validate the memory size in case user changed their system memory limits (example change docker desktop or upgraded memory.)\n\tvalidateRequestedMemorySize(cc.Memory, cc.Driver)\n\n\tif cmd.Flags().Changed(humanReadableDiskSize) && getDiskSize() != existing.DiskSize {\n\t\tout.WarningT(\"You cannot change the disk size for an existing minikube cluster. Please first delete the cluster.\")\n\t}\n\n\tcheckExtraDiskOptions(cmd, cc.Driver)\n\tif cmd.Flags().Changed(extraDisks) && viper.GetInt(extraDisks) != existing.ExtraDisks {\n\t\tout.WarningT(\"You cannot add or remove extra disks for an existing minikube cluster. Please first delete the cluster.\")\n\t}\n\n\tif cmd.Flags().Changed(staticIP) && viper.GetString(staticIP) != existing.StaticIP {\n\t\tout.WarningT(\"You cannot change the static IP of an existing minikube cluster. Please first delete the cluster.\")\n\t}\n\n\tupdateBoolFromFlag(cmd, &cc.KeepContext, keepContext)\n\tupdateBoolFromFlag(cmd, &cc.EmbedCerts, embedCerts)\n\tupdateStringFromFlag(cmd, &cc.MinikubeISO, isoURL)\n\tupdateStringFromFlag(cmd, &cc.KicBaseImage, kicBaseImage)\n\tupdateStringFromFlag(cmd, &cc.Network, network)\n\tupdateStringFromFlag(cmd, &cc.HyperkitVpnKitSock, vpnkitSock)\n\tupdateStringSliceFromFlag(cmd, &cc.HyperkitVSockPorts, vsockPorts)\n\tupdateStringSliceFromFlag(cmd, &cc.NFSShare, nfsShare)\n\tupdateStringFromFlag(cmd, &cc.NFSSharesRoot, nfsSharesRoot)\n\tupdateStringFromFlag(cmd, &cc.HostOnlyCIDR, hostOnlyCIDR)\n\tupdateStringFromFlag(cmd, &cc.HypervVirtualSwitch, hypervVirtualSwitch)\n\tupdateBoolFromFlag(cmd, &cc.HypervUseExternalSwitch, hypervUseExternalSwitch)\n\tupdateStringFromFlag(cmd, &cc.HypervExternalAdapter, hypervExternalAdapter)\n\tupdateStringFromFlag(cmd, &cc.KVMNetwork, kvmNetwork)\n\tupdateStringFromFlag(cmd, &cc.KVMQemuURI, kvmQemuURI)\n\tupdateBoolFromFlag(cmd, &cc.KVMGPU, kvmGPU)\n\tupdateBoolFromFlag(cmd, &cc.KVMHidden, kvmHidden)\n\tupdateBoolFromFlag(cmd, &cc.DisableDriverMounts, disableDriverMounts)\n\tupdateStringFromFlag(cmd, &cc.UUID, uuid)\n\tupdateBoolFromFlag(cmd, &cc.NoVTXCheck, noVTXCheck)\n\tupdateBoolFromFlag(cmd, &cc.DNSProxy, dnsProxy)\n\tupdateBoolFromFlag(cmd, &cc.HostDNSResolver, hostDNSResolver)\n\tupdateStringFromFlag(cmd, &cc.HostOnlyNicType, hostOnlyNicType)\n\tupdateStringFromFlag(cmd, &cc.NatNicType, natNicType)\n\tupdateDurationFromFlag(cmd, &cc.StartHostTimeout, waitTimeout)\n\tupdateStringSliceFromFlag(cmd, &cc.ExposedPorts, ports)\n\tupdateStringFromFlag(cmd, &cc.SSHIPAddress, sshIPAddress)\n\tupdateStringFromFlag(cmd, &cc.SSHUser, sshSSHUser)\n\tupdateStringFromFlag(cmd, &cc.SSHKey, sshSSHKey)\n\tupdateIntFromFlag(cmd, &cc.SSHPort, sshSSHPort)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.Namespace, startNamespace)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.APIServerName, apiServerName)\n\tupdateStringSliceFromFlag(cmd, &cc.KubernetesConfig.APIServerNames, \"apiserver-names\")\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.DNSDomain, dnsDomain)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.FeatureGates, featureGates)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.ContainerRuntime, containerRuntime)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.CRISocket, criSocket)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.NetworkPlugin, networkPlugin)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.ServiceCIDR, serviceCIDR)\n\tupdateBoolFromFlag(cmd, &cc.KubernetesConfig.ShouldLoadCachedImages, cacheImages)\n\tupdateIntFromFlag(cmd, &cc.KubernetesConfig.NodePort, apiServerPort)\n\tupdateDurationFromFlag(cmd, &cc.CertExpiration, certExpiration)\n\tupdateBoolFromFlag(cmd, &cc.Mount, createMount)\n\tupdateStringFromFlag(cmd, &cc.MountString, mountString)\n\tupdateStringFromFlag(cmd, &cc.Mount9PVersion, mount9PVersion)\n\tupdateStringFromFlag(cmd, &cc.MountGID, mountGID)\n\tupdateStringFromFlag(cmd, &cc.MountIP, mountIPFlag)\n\tupdateIntFromFlag(cmd, &cc.MountMSize, mountMSize)\n\tupdateStringSliceFromFlag(cmd, &cc.MountOptions, mountOptions)\n\tupdateUint16FromFlag(cmd, &cc.MountPort, mountPortFlag)\n\tupdateStringFromFlag(cmd, &cc.MountType, mountTypeFlag)\n\tupdateStringFromFlag(cmd, &cc.MountUID, mountUID)\n\tupdateStringFromFlag(cmd, &cc.BinaryMirror, binaryMirror)\n\tupdateBoolFromFlag(cmd, &cc.DisableOptimizations, disableOptimizations)\n\tupdateStringFromFlag(cmd, &cc.CustomQemuFirmwarePath, qemuFirmwarePath)\n\tupdateStringFromFlag(cmd, &cc.SocketVMnetClientPath, socketVMnetClientPath)\n\tupdateStringFromFlag(cmd, &cc.SocketVMnetPath, socketVMnetPath)\n\n\tif cmd.Flags().Changed(kubernetesVersion) {\n\t\tkubeVer, err := getKubernetesVersion(existing)\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"failed getting Kubernetes version: %v\", err)\n\t\t}\n\t\tcc.KubernetesConfig.KubernetesVersion = kubeVer\n\t}\n\tif cmd.Flags().Changed(containerRuntime) {\n\t\tcc.KubernetesConfig.ContainerRuntime = getContainerRuntime(existing)\n\t}\n\n\tif cmd.Flags().Changed(\"extra-config\") {\n\t\tcc.KubernetesConfig.ExtraOptions = getExtraOptions()\n\t}\n\n\tif cmd.Flags().Changed(cniFlag) || cmd.Flags().Changed(enableDefaultCNI) {\n\t\tcc.KubernetesConfig.CNI = getCNIConfig(cmd)\n\t}\n\n\tif cmd.Flags().Changed(waitComponents) {\n\t\tcc.VerifyComponents = interpretWaitFlag(*cmd)\n\t}\n\n\tif cmd.Flags().Changed(\"apiserver-ips\") {\n\t\t// IPSlice not supported in Viper\n\t\t// https://github.com/spf13/viper/issues/460\n\t\tcc.KubernetesConfig.APIServerIPs = apiServerIPs\n\t}\n\n\t// Handle flags and legacy configuration upgrades that do not contain KicBaseImage\n\tif cmd.Flags().Changed(kicBaseImage) || cc.KicBaseImage == \"\" {\n\t\tcc.KicBaseImage = viper.GetString(kicBaseImage)\n\t}\n\n\t// If this cluster was stopped by a scheduled stop, clear the config\n\tif cc.ScheduledStop != nil && time.Until(time.Unix(cc.ScheduledStop.InitiationTime, 0).Add(cc.ScheduledStop.Duration)) <= 0 {\n\t\tcc.ScheduledStop = nil\n\t}\n\n\treturn cc\n}", "func (e *Explore) ApplyConfig(cfg *config.Config) error {\n\tjobs := make([]string, 0, len(cfg.ScrapeConfigs))\n\tfor _, j := range cfg.ScrapeConfigs {\n\t\tjobs = append(jobs, j.JobName)\n\t}\n\n\te.targetsLock.Lock()\n\tdefer e.targetsLock.Unlock()\n\n\tnewTargets := map[string]map[uint64]*exploringTarget{}\n\tfor k, v := range e.targets {\n\t\tif types.FindString(k, jobs...) {\n\t\t\tnewTargets[k] = v\n\t\t}\n\t}\n\te.targets = newTargets\n\treturn nil\n}", "func (c *Controller) createOrUpdateConfigMapResource(chi *chop.ClickHouseInstallation, configMap *core.ConfigMap) error {\n\t// Check whether object with such name already exists in k8s\n\tres, err := c.configMapLister.ConfigMaps(chi.Namespace).Get(configMap.Name)\n\tif res != nil {\n\t\t// Object with such name already exists, this is not an error\n\t\tglog.V(1).Infof(\"Update ConfigMap %s/%s\\n\", configMap.Namespace, configMap.Name)\n\t\t_, err := c.kubeClient.CoreV1().ConfigMaps(chi.Namespace).Update(configMap)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\t// Object with such name does not exist or error happened\n\n\tif apierrors.IsNotFound(err) {\n\t\t// Object with such name not found - create it\n\t\t_, err = c.kubeClient.CoreV1().ConfigMaps(chi.Namespace).Create(configMap)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Object created\n\treturn nil\n}", "func (r *Reconciler) reconcileCRwithConfig(ctx context.Context, service *operatorv1alpha1.ConfigService, namespace string, csv *olmv1alpha1.ClusterServiceVersion) error {\n\tmerr := &util.MultiErr{}\n\n\t// Create k8s resources required by service\n\tif service.Resources != nil {\n\t\tfor _, res := range service.Resources {\n\t\t\tif res.APIVersion == \"\" {\n\t\t\t\treturn fmt.Errorf(\"The APIVersion of k8s resource is empty for operator \" + service.Name)\n\t\t\t}\n\n\t\t\tif res.Kind == \"\" {\n\t\t\t\treturn fmt.Errorf(\"The Kind of k8s resource is empty for operator \" + service.Name)\n\t\t\t}\n\t\t\tif res.Name == \"\" {\n\t\t\t\treturn fmt.Errorf(\"The Name of k8s resource is empty for operator \" + service.Name)\n\t\t\t}\n\t\t\tvar k8sResNs string\n\t\t\tif res.Namespace == \"\" {\n\t\t\t\tk8sResNs = namespace\n\t\t\t} else {\n\t\t\t\tk8sResNs = res.Namespace\n\t\t\t}\n\n\t\t\tvar k8sRes unstructured.Unstructured\n\t\t\tk8sRes.SetAPIVersion(res.APIVersion)\n\t\t\tk8sRes.SetKind(res.Kind)\n\t\t\tk8sRes.SetName(res.Name)\n\t\t\tk8sRes.SetNamespace(k8sResNs)\n\n\t\t\terr := r.Client.Get(ctx, types.NamespacedName{\n\t\t\t\tName: res.Name,\n\t\t\t\tNamespace: k8sResNs,\n\t\t\t}, &k8sRes)\n\n\t\t\tif err != nil && !apierrors.IsNotFound(err) {\n\t\t\t\tmerr.Add(errors.Wrapf(err, \"failed to get k8s resource %s/%s\", k8sResNs, res.Name))\n\t\t\t} else if apierrors.IsNotFound(err) {\n\t\t\t\tif err := r.createK8sResource(ctx, k8sRes, res.Data, res.Labels, res.Annotations); err != nil {\n\t\t\t\t\tmerr.Add(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif checkLabel(k8sRes, map[string]string{constant.OpreqLabel: \"true\"}) && res.Force {\n\t\t\t\t\t// Update k8s resource\n\t\t\t\t\tklog.V(3).Info(\"Found existing k8s resource: \" + res.Name)\n\t\t\t\t\tif err := r.updateK8sResource(ctx, k8sRes, res.Data, res.Labels, res.Annotations); err != nil {\n\t\t\t\t\t\tmerr.Add(err)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tklog.V(2).Infof(\"Skip the k8s resource %s/%s which is not created by ODLM\", res.Kind, res.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(merr.Errors) != 0 {\n\t\t\treturn merr\n\t\t}\n\t}\n\n\talmExamples := csv.GetAnnotations()[\"alm-examples\"]\n\n\t// Convert CR template string to slice\n\tvar almExampleList []interface{}\n\terr := json.Unmarshal([]byte(almExamples), &almExampleList)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to convert alm-examples in the Subscription %s/%s to slice\", namespace, service.Name)\n\t}\n\n\tfoundMap := make(map[string]bool)\n\tfor cr := range service.Spec {\n\t\tfoundMap[cr] = false\n\t}\n\n\t// Merge OperandConfig and ClusterServiceVersion alm-examples\n\tfor _, almExample := range almExampleList {\n\t\t// Create an unstructured object for CR and check its value\n\t\tvar crFromALM unstructured.Unstructured\n\t\tcrFromALM.Object = almExample.(map[string]interface{})\n\n\t\tname := crFromALM.GetName()\n\t\tspec := crFromALM.Object[\"spec\"]\n\t\tif spec == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\terr := r.Client.Get(ctx, types.NamespacedName{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t}, &crFromALM)\n\n\t\tfor cr := range service.Spec {\n\t\t\tif strings.EqualFold(crFromALM.GetKind(), cr) {\n\t\t\t\tfoundMap[cr] = true\n\t\t\t}\n\t\t}\n\n\t\tif err != nil && !apierrors.IsNotFound(err) {\n\t\t\tmerr.Add(errors.Wrapf(err, \"failed to get the custom resource %s/%s\", namespace, name))\n\t\t\tcontinue\n\t\t} else if apierrors.IsNotFound(err) {\n\t\t\t// Create Custom Resource\n\t\t\tif err := r.compareConfigandExample(ctx, crFromALM, service, namespace); err != nil {\n\t\t\t\tmerr.Add(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else {\n\t\t\tif checkLabel(crFromALM, map[string]string{constant.OpreqLabel: \"true\"}) {\n\t\t\t\t// Update or Delete Custom Resource\n\t\t\t\tif err := r.existingCustomResource(ctx, crFromALM, spec.(map[string]interface{}), service, namespace); err != nil {\n\t\t\t\t\tmerr.Add(err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tklog.V(2).Info(\"Skip the custom resource not created by ODLM\")\n\t\t\t}\n\t\t}\n\t}\n\tif len(merr.Errors) != 0 {\n\t\treturn merr\n\t}\n\n\tfor cr, found := range foundMap {\n\t\tif !found {\n\t\t\tklog.Warningf(\"Custom resource %v doesn't exist in the alm-example of %v\", cr, csv.GetName())\n\t\t}\n\t}\n\n\treturn nil\n}", "func UpdateConfiguration(haproxyConfiguration *HaproxyConfiguration, loadBalancer *ActivityLoadBalancer) error {\n\tfrontendAttributes := map[string]common.ParserData{}\n\tfrontendAttributes[\"mode\"] = configStringC(\"http\")\n\tfrontendAttributes[\"bind\"] = &types.Bind{Path: \"0.0.0.0:8080\"}\n\tfrontendAttributes[\"log-format\"] = configStringC(\"httplog %Ts %ci %cp %si %sp %Tq %Tw %Tc %Tr %Tt %ST %U %B %f %b %s %ts %r %hrl\")\n\tfrontendAttributes[\"log\"] = &types.Log{Address: \"/var/lib/load-balancer-servo/haproxy.sock\", Facility: \"local2\", Level: \"info\"}\n\tfrontendAttributes[\"option forwardfor\"] = &types.OptionForwardFor{Except: \"127.0.0.1\"}\n\tfrontendAttributes[\"timeout client\"] = &types.SimpleTimeout{Value: \"60s\"}\n\tfrontendAttributes[\"default_backend\"] = configStringC(\"backend-http-8080\")\n\tfrontendAttributes[\"http-request\"] = []types.HTTPAction{\n\t\t&actions.SetHeader{Name: \"X-Forwarded-Proto\", Fmt: \"http\"},\n\t\t&actions.SetHeader{Name: \"X-Forwarded-Port\", Fmt: \"8080\"},\n\t\t//TODO syntax not supported by haproxy 1.5\n\t\t// &actions.Capture{Sample: \"hdr(User-Agent)\", Len: configInt64(8192)},\n\t}\n\terr := UpdateConfigurationSection(haproxyConfiguration, parser.Frontends, \"http-8080\", frontendAttributes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbackendAttributes := map[string]common.ParserData{}\n\tbackendAttributes[\"mode\"] = configStringC(\"http\")\n\tbackendAttributes[\"balance\"] = &types.Balance{\"roundrobin\", nil, \"\"}\n\tbackendAttributes[\"http-response\"] = &actions.SetHeader{Name: \"Cache-control\", Fmt: `no-cache=\"set-cookie\"`}\n\tbackendAttributes[\"cookie\"] = &types.Cookie{Name: \"AWSELB\", Type: \"insert\", Indirect: true, Maxidle: 300000, Maxlife: 300000}\n\tbackendAttributes[\"server\"] = []types.Server{{Name: \"http-8080\", Address: \"10.111.10.215:8080\", Params: []params.ServerOption{&params.ServerOptionValue{Name: \"cookie\", Value: \"MTAuMTExLjEwLjIxNQ==\"}}}}\n\tbackendAttributes[\"timeout server\"] = &types.SimpleTimeout{Value: \"60s\"}\n\terr = UpdateConfigurationSection(haproxyConfiguration, parser.Backends, \"backend-http-8080\", backendAttributes)\n\treturn err\n}", "func Apply(config string) error {\n\tcmd := exec.Command(\"kubectl\", \"apply\", \"-f\", \"-\")\n\tstdin, err := cmd.StdinPipe()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"could not create stdin pipe\")\n\t}\n\tgo func() {\n\t\tdefer stdin.Close()\n\t\t_, err := io.WriteString(stdin, config)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}()\n\n\toutput, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn errors.Wrap(err, config)\n\t}\n\tif !cmd.ProcessState.Success() {\n\t\treturn errors.Wrap(err, string(output))\n\t}\n\tlog.Println(string(output))\n\treturn nil\n}", "func setupConfigMapReconciler(mgr manager.Manager, log logr.Logger) error {\n\n\tlog = log.WithName(\"secret-reconciler\")\n\n\terr := ctrl.NewControllerManagedBy(mgr).\n\t\tFor(&corev1.Secret{}, builder.OnlyMetadata).\n\t\tComplete(reconcile.Func(func(_ context.Context, r reconcile.Request) (reconcile.Result, error) {\n\t\t\tlog := log\n\t\t\tlog = log.WithValues(\"secret\", r.NamespacedName)\n\t\t\tlog.Info(\"start\")\n\t\t\tdefer log.Info(\"end\")\n\n\t\t\tsecret := &corev1.Secret{}\n\t\t\terr := mgr.GetClient().Get(context.Background(), r.NamespacedName, secret)\n\t\t\tswitch {\n\t\t\t// If the secret doesn't exist, the reconciliation is done.\n\t\t\tcase apierrors.IsNotFound(err):\n\t\t\t\tlog.Info(\"secret not found\")\n\t\t\t\treturn reconcile.Result{}, nil\n\t\t\tcase err != nil:\n\t\t\t\treturn reconcile.Result{}, fmt.Errorf(\"looking for Secret %s: %w\", r.NamespacedName, err)\n\t\t\t}\n\n\t\t\tif secret.Annotations != nil && secret.Annotations[\"secret-found\"] == \"yes\" {\n\t\t\t\treturn reconcile.Result{}, nil\n\t\t\t}\n\n\t\t\tif secret.Annotations == nil {\n\t\t\t\tsecret.Annotations = make(map[string]string)\n\t\t\t}\n\t\t\tsecret.Annotations[\"secret-found\"] = \"yes\"\n\t\t\terr = mgr.GetClient().Update(context.Background(), secret)\n\t\t\tif err != nil {\n\t\t\t\treturn reconcile.Result{}, err\n\t\t\t}\n\n\t\t\treturn reconcile.Result{}, nil\n\t\t}))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"while completing new controller: %w\", err)\n\t}\n\n\treturn nil\n}", "func KustomizeAndApply(namespace, dir string, useOverlay bool) {\n\tpath, err := os.Getwd()\n\tExpect(err).ToNot(HaveOccurred())\n\n\tkustomizeDir := path + \"/../config/\" + dir\n\n\tif useOverlay {\n\t\tif overlay, found := os.LookupEnv(\"TEST_OVERLAY\"); found {\n\t\t\tkustomizeDir = filepath.Clean(kustomizeDir + \"/overlays/forks/\" + overlay)\n\t\t} else {\n\t\t\tkustomizeDir = filepath.Clean(kustomizeDir + \"/overlays/\" + defaultOverlay)\n\t\t}\n\t}\n\n\tGinkgoWriter.Write([]byte(\"RUNNING: kustomize build \" + kustomizeDir))\n\tkustomize := exec.Command(\"kustomize\", \"build\", kustomizeDir)\n\tvar stdout, stderr bytes.Buffer\n\tkustomize.Stdout = &stdout\n\tkustomize.Stderr = &stderr\n\terr = kustomize.Run()\n\tExpect(err).ToNot(HaveOccurred(), fmt.Sprintf(\"kustomize build failed: %s\", err))\n\n\tkubectl := exec.Command(\"kubectl\", \"-n\", namespace, \"apply\", \"-f\", \"-\")\n\tkubectl.Stdin = &stdout\n\tout, err := kubectl.CombinedOutput()\n\tGinkgoWriter.Write(out)\n\tExpect(err).ToNot(HaveOccurred(), fmt.Sprintf(\"kubectl apply failed: %s\", err))\n}", "func LoadOperatorConf(cmd *cobra.Command) *Conf {\n\tc := &Conf{}\n\n\tc.NS = util.KubeObject(bundle.File_deploy_namespace_yaml).(*corev1.Namespace)\n\tc.SA = util.KubeObject(bundle.File_deploy_service_account_yaml).(*corev1.ServiceAccount)\n\tc.SAEndpoint = util.KubeObject(bundle.File_deploy_service_account_endpoint_yaml).(*corev1.ServiceAccount)\n\tc.SAUI = util.KubeObject(bundle.File_deploy_service_account_ui_yaml).(*corev1.ServiceAccount)\n\tc.Role = util.KubeObject(bundle.File_deploy_role_yaml).(*rbacv1.Role)\n\tc.RoleEndpoint = util.KubeObject(bundle.File_deploy_role_endpoint_yaml).(*rbacv1.Role)\n\tc.RoleUI = util.KubeObject(bundle.File_deploy_role_ui_yaml).(*rbacv1.Role)\n\tc.RoleBinding = util.KubeObject(bundle.File_deploy_role_binding_yaml).(*rbacv1.RoleBinding)\n\tc.RoleBindingEndpoint = util.KubeObject(bundle.File_deploy_role_binding_endpoint_yaml).(*rbacv1.RoleBinding)\n\tc.ClusterRole = util.KubeObject(bundle.File_deploy_cluster_role_yaml).(*rbacv1.ClusterRole)\n\tc.ClusterRoleBinding = util.KubeObject(bundle.File_deploy_cluster_role_binding_yaml).(*rbacv1.ClusterRoleBinding)\n\tc.Deployment = util.KubeObject(bundle.File_deploy_operator_yaml).(*appsv1.Deployment)\n\n\tc.NS.Name = options.Namespace\n\tc.SA.Namespace = options.Namespace\n\tc.SAEndpoint.Namespace = options.Namespace\n\tc.Role.Namespace = options.Namespace\n\tc.RoleEndpoint.Namespace = options.Namespace\n\tc.RoleBinding.Namespace = options.Namespace\n\tc.RoleBindingEndpoint.Namespace = options.Namespace\n\tc.ClusterRole.Namespace = options.Namespace\n\tc.Deployment.Namespace = options.Namespace\n\n\tconfigureClusterRole(c.ClusterRole)\n\tc.ClusterRoleBinding.Name = c.ClusterRole.Name\n\tc.ClusterRoleBinding.RoleRef.Name = c.ClusterRole.Name\n\tfor i := range c.ClusterRoleBinding.Subjects {\n\t\tc.ClusterRoleBinding.Subjects[i].Namespace = options.Namespace\n\t}\n\n\tc.Deployment.Spec.Template.Spec.Containers[0].Image = options.OperatorImage\n\tif options.ImagePullSecret != \"\" {\n\t\tc.Deployment.Spec.Template.Spec.ImagePullSecrets =\n\t\t\t[]corev1.LocalObjectReference{{Name: options.ImagePullSecret}}\n\t}\n\tc.Deployment.Spec.Template.Spec.Containers[1].Image = options.CosiSideCarImage\n\n\treturn c\n}", "func (dn *Daemon) updateHypershift(oldConfig, newConfig *mcfgv1.MachineConfig, diff *machineConfigDiff) (retErr error) {\n\toldIgnConfig, err := ctrlcommon.ParseAndConvertConfig(oldConfig.Spec.Config.Raw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing old Ignition config failed: %w\", err)\n\t}\n\tnewIgnConfig, err := ctrlcommon.ParseAndConvertConfig(newConfig.Spec.Config.Raw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing new Ignition config failed: %w\", err)\n\t}\n\n\t// update files on disk that need updating\n\t// We should't skip the certificate write in HyperShift since it does not run the extra daemon process\n\tif err := dn.updateFiles(oldIgnConfig, newIgnConfig, false); err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\tif retErr != nil {\n\t\t\tif err := dn.updateFiles(newIgnConfig, oldIgnConfig, false); err != nil {\n\t\t\t\terrs := kubeErrs.NewAggregate([]error{err, retErr})\n\t\t\t\tretErr = fmt.Errorf(\"error rolling back files writes: %w\", errs)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tif err := dn.updateSSHKeys(newIgnConfig.Passwd.Users, oldIgnConfig.Passwd.Users); err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\tif retErr != nil {\n\t\t\tif err := dn.updateSSHKeys(newIgnConfig.Passwd.Users, oldIgnConfig.Passwd.Users); err != nil {\n\t\t\t\terrs := kubeErrs.NewAggregate([]error{err, retErr})\n\t\t\t\tretErr = fmt.Errorf(\"error rolling back SSH keys updates: %w\", errs)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tif dn.os.IsCoreOSVariant() {\n\t\tcoreOSDaemon := CoreOSDaemon{dn}\n\t\tif err := coreOSDaemon.applyOSChanges(*diff, oldConfig, newConfig); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdefer func() {\n\t\t\tif retErr != nil {\n\t\t\t\tif err := coreOSDaemon.applyOSChanges(*diff, newConfig, oldConfig); err != nil {\n\t\t\t\t\terrs := kubeErrs.NewAggregate([]error{err, retErr})\n\t\t\t\t\tretErr = fmt.Errorf(\"error rolling back changes to OS: %w\", errs)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t} else {\n\t\tklog.Info(\"updating the OS on non-CoreOS nodes is not supported\")\n\t}\n\n\tif err := UpdateTuningArgs(KernelTuningFile, CmdLineFile); err != nil {\n\t\treturn err\n\t}\n\n\tklog.Info(\"Successfully completed Hypershift config update\")\n\treturn nil\n}", "func enforceRequirements(flags *applyPlanFlags, args []string, dryRun bool, upgradeApply bool, printer output.Printer, loadConfig LoadConfigFunc) (clientset.Interface, upgrade.VersionGetter, *kubeadmapi.InitConfiguration, error) {\n\tclient, err := getClient(flags.kubeConfigPath, dryRun)\n\tif err != nil {\n\t\treturn nil, nil, nil, errors.Wrapf(err, \"couldn't create a Kubernetes client from file %q\", flags.kubeConfigPath)\n\t}\n\n\t// Fetch the configuration from a file or ConfigMap and validate it\n\tprinter.Printf(\"[upgrade/config] Making sure the configuration is correct:\\n\")\n\n\tvar newK8sVersion string\n\tcfg, legacyReconfigure, err := loadConfig(flags.cfgPath, client, !upgradeApply, printer)\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\tprinter.Printf(\"[upgrade/config] In order to upgrade, a ConfigMap called %q in the %s namespace must exist.\\n\", constants.KubeadmConfigConfigMap, metav1.NamespaceSystem)\n\t\t\tprinter.Printf(\"[upgrade/config] Without this information, 'kubeadm upgrade' won't know how to configure your upgraded cluster.\\n\")\n\t\t\tprinter.Println()\n\t\t\tprinter.Printf(\"[upgrade/config] Next steps:\\n\")\n\t\t\tprinter.Printf(\"\\t- OPTION 1: Run 'kubeadm config upload from-flags' and specify the same CLI arguments you passed to 'kubeadm init' when you created your control-plane.\\n\")\n\t\t\tprinter.Printf(\"\\t- OPTION 2: Run 'kubeadm config upload from-file' and specify the same config file you passed to 'kubeadm init' when you created your control-plane.\\n\")\n\t\t\tprinter.Printf(\"\\t- OPTION 3: Pass a config file to 'kubeadm upgrade' using the --config flag.\\n\")\n\t\t\tprinter.Println()\n\t\t\terr = errors.Errorf(\"the ConfigMap %q in the %s namespace used for getting configuration information was not found\", constants.KubeadmConfigConfigMap, metav1.NamespaceSystem)\n\t\t}\n\t\treturn nil, nil, nil, errors.Wrap(err, \"[upgrade/config] FATAL\")\n\t} else if legacyReconfigure {\n\t\t// Set the newK8sVersion to the value in the ClusterConfiguration. This is done, so that users who use the --config option\n\t\t// to supply a new ClusterConfiguration don't have to specify the Kubernetes version twice,\n\t\t// if they don't want to upgrade but just change a setting.\n\t\tnewK8sVersion = cfg.KubernetesVersion\n\t}\n\n\t// The version arg is mandatory, during upgrade apply, unless it's specified in the config file\n\tif upgradeApply && newK8sVersion == \"\" {\n\t\tif err := cmdutil.ValidateExactArgNumber(args, []string{\"version\"}); err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t}\n\n\t// If option was specified in both args and config file, args will overwrite the config file.\n\tif len(args) == 1 {\n\t\tnewK8sVersion = args[0]\n\t\tif upgradeApply {\n\t\t\t// The `upgrade apply` version always overwrites the KubernetesVersion in the returned cfg with the target\n\t\t\t// version. While this is not the same for `upgrade plan` where the KubernetesVersion should be the old\n\t\t\t// one (because the call to getComponentConfigVersionStates requires the currently installed version).\n\t\t\t// This also makes the KubernetesVersion value returned for `upgrade plan` consistent as that command\n\t\t\t// allows to not specify a target version in which case KubernetesVersion will always hold the currently\n\t\t\t// installed one.\n\t\t\tcfg.KubernetesVersion = newK8sVersion\n\t\t}\n\t}\n\n\tignorePreflightErrorsSet, err := validation.ValidateIgnorePreflightErrors(flags.ignorePreflightErrors, cfg.NodeRegistration.IgnorePreflightErrors)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\t// Also set the union of pre-flight errors to InitConfiguration, to provide a consistent view of the runtime configuration:\n\tcfg.NodeRegistration.IgnorePreflightErrors = sets.List(ignorePreflightErrorsSet)\n\n\t// Ensure the user is root\n\tklog.V(1).Info(\"running preflight checks\")\n\tif err := runPreflightChecks(client, ignorePreflightErrorsSet, &cfg.ClusterConfiguration, printer); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// Run healthchecks against the cluster\n\tif err := upgrade.CheckClusterHealth(client, &cfg.ClusterConfiguration, ignorePreflightErrorsSet); err != nil {\n\t\treturn nil, nil, nil, errors.Wrap(err, \"[upgrade/health] FATAL\")\n\t}\n\n\t// If features gates are passed to the command line, use it (otherwise use featureGates from configuration)\n\tif flags.featureGatesString != \"\" {\n\t\tcfg.FeatureGates, err = features.NewFeatureGate(&features.InitFeatureGates, flags.featureGatesString)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, errors.Wrap(err, \"[upgrade/config] FATAL\")\n\t\t}\n\t}\n\n\t// Check if feature gate flags used in the cluster are consistent with the set of features currently supported by kubeadm\n\tif msg := features.CheckDeprecatedFlags(&features.InitFeatureGates, cfg.FeatureGates); len(msg) > 0 {\n\t\tfor _, m := range msg {\n\t\t\tprinter.Printf(\"[upgrade/config] %s\\n\", m)\n\t\t}\n\t}\n\n\t// If the user told us to print this information out; do it!\n\tif flags.printConfig {\n\t\tprintConfiguration(&cfg.ClusterConfiguration, os.Stdout, printer)\n\t}\n\n\t// Use a real version getter interface that queries the API server, the kubeadm client and the Kubernetes CI system for latest versions\n\treturn client, upgrade.NewOfflineVersionGetter(upgrade.NewKubeVersionGetter(client), newK8sVersion), cfg, nil\n}", "func initConfiguration() {\n\tk = confident.New()\n\tk.WithConfiguration(&Conf)\n\tk.Name = \"config\"\n\tk.Type = \"json\"\n\tk.Path = configDirPath()\n\tk.Path = configDirPathEnsureExists()\n\tk.Permission = os.FileMode(0644)\n\tlogging.LogDebugf(\"config/initConfiguration() - Conf before read: %#v\", Conf)\n\tk.Read()\n\tlogging.LogDebugf(\"config/initConfiguration() - Conf after read: %#v\", Conf)\n\tif *dpRestURL != \"\" || *dpSomaURL != \"\" {\n\t\tif *dpConfigName != \"\" {\n\t\t\tvalidateDpConfigName()\n\t\t\tConf.DataPowerAppliances[*dpConfigName] = DataPowerAppliance{Domain: *dpDomain, Proxy: *proxy, RestUrl: *dpRestURL, SomaUrl: *dpSomaURL, Username: *dpUsername, Password: *dpPassword}\n\t\t\tCurrentApplianceName = *dpConfigName\n\t\t} else {\n\t\t\tConf.DataPowerAppliances[PreviousApplianceName] = DataPowerAppliance{Domain: *dpDomain, Proxy: *proxy, RestUrl: *dpRestURL, SomaUrl: *dpSomaURL, Username: *dpUsername, Password: *dpPassword}\n\t\t\tCurrentApplianceName = PreviousApplianceName\n\t\t}\n\t\tk.Persist()\n\t\tlogging.LogDebugf(\"config/initConfiguration() - Conf after persist: %#v\", Conf)\n\t}\n\tCurrentAppliance = DataPowerAppliance{Domain: *dpDomain, Proxy: *proxy, RestUrl: *dpRestURL, SomaUrl: *dpSomaURL, Username: *dpUsername, Password: *dpPassword}\n}", "func updateSplunkPodTemplateWithConfig(podTemplateSpec *corev1.PodTemplateSpec, cr *v1alpha1.SplunkEnterprise, instanceType InstanceType) error {\n\n\t// Add custom volumes to splunk containers\n\tif cr.Spec.SplunkVolumes != nil {\n\t\tpodTemplateSpec.Spec.Volumes = append(podTemplateSpec.Spec.Volumes, cr.Spec.SplunkVolumes...)\n\t\tfor idx := range podTemplateSpec.Spec.Containers {\n\t\t\tfor v := range cr.Spec.SplunkVolumes {\n\t\t\t\tpodTemplateSpec.Spec.Containers[idx].VolumeMounts = append(podTemplateSpec.Spec.Containers[idx].VolumeMounts, corev1.VolumeMount{\n\t\t\t\t\tName: cr.Spec.SplunkVolumes[v].Name,\n\t\t\t\t\tMountPath: \"/mnt/\" + cr.Spec.SplunkVolumes[v].Name,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\t// add defaults secrets to all splunk containers\n\taddSplunkVolumeToTemplate(podTemplateSpec, \"secrets\", corev1.VolumeSource{\n\t\tSecret: &corev1.SecretVolumeSource{\n\t\t\tSecretName: GetSplunkSecretsName(cr.GetIdentifier()),\n\t\t},\n\t})\n\n\t// add inline defaults to all splunk containers\n\tif cr.Spec.Defaults != \"\" {\n\t\taddSplunkVolumeToTemplate(podTemplateSpec, \"defaults\", corev1.VolumeSource{\n\t\t\tConfigMap: &corev1.ConfigMapVolumeSource{\n\t\t\t\tLocalObjectReference: corev1.LocalObjectReference{\n\t\t\t\t\tName: GetSplunkDefaultsName(cr.GetIdentifier()),\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t}\n\n\t// add spark and java mounts to search head containers\n\tif cr.Spec.EnableDFS && (instanceType == SplunkSearchHead || instanceType == SplunkStandalone) {\n\t\terr := addDFCToPodTemplate(podTemplateSpec, cr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// update security context\n\trunAsUser := int64(41812)\n\tfsGroup := int64(41812)\n\tpodTemplateSpec.Spec.SecurityContext = &corev1.PodSecurityContext{\n\t\tRunAsUser: &runAsUser,\n\t\tFSGroup: &fsGroup,\n\t}\n\n\t// prepare resource requirements\n\trequirements, err := GetSplunkRequirements(cr)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t// use script provided by enterprise container to check if pod is alive\n\tlivenessProbe := &corev1.Probe{\n\t\tHandler: corev1.Handler{\n\t\t\tExec: &corev1.ExecAction{\n\t\t\t\tCommand: []string{\n\t\t\t\t\t\"/sbin/checkstate.sh\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tInitialDelaySeconds: 300,\n\t\tTimeoutSeconds: 30,\n\t\tPeriodSeconds: 30,\n\t}\n\n\t// pod is ready if container artifact file is created with contents of \"started\".\n\t// this indicates that all the the ansible plays executed at startup have completed.\n\treadinessProbe := &corev1.Probe{\n\t\tHandler: corev1.Handler{\n\t\t\tExec: &corev1.ExecAction{\n\t\t\t\tCommand: []string{\n\t\t\t\t\t\"/bin/grep\",\n\t\t\t\t\t\"started\",\n\t\t\t\t\t\"/opt/container_artifact/splunk-container.state\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tInitialDelaySeconds: 10,\n\t\tTimeoutSeconds: 5,\n\t\tPeriodSeconds: 5,\n\t}\n\n\t// update each container in pod\n\tfor idx := range podTemplateSpec.Spec.Containers {\n\t\tpodTemplateSpec.Spec.Containers[idx].Resources = requirements\n\t\tpodTemplateSpec.Spec.Containers[idx].LivenessProbe = livenessProbe\n\t\tpodTemplateSpec.Spec.Containers[idx].ReadinessProbe = readinessProbe\n\t}\n\n\treturn nil\n}", "func (m *Microservice) CheckForNewConfiguration() {\n\tzap.L().Info(\"checking pending operations\")\n\tdata, _, err := m.GetOperations(c8y.OperationStatusPending)\n\n\tif err != nil {\n\t\tlog.Printf(\"Error getting operations. %s\", err)\n\t\treturn\n\t}\n\n\tfor _, op := range data.Items {\n\n\t\t//\n\t\t// Update Configuration Operation\n\t\t//\n\t\tif c8yConfig := op.Get(\"c8y_Configuration.config\"); c8yConfig.Exists() {\n\t\t\tm.onUpdateConfigurationOperation(op.Get(\"id\").String(), c8yConfig.String())\n\t\t\tconfigurationChangeCount.Inc()\n\t\t}\n\t}\n}", "func newConfigmapForCR(cr *sdewanv1alpha1.Sdewan) *corev1.ConfigMap {\n\tnetjson, _ := json.MarshalIndent(cr.Spec.Networks, \"\", \" \")\n\treturn &corev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.Name,\n\t\t\tNamespace: cr.Namespace,\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"networks.json\": string(netjson),\n\t\t\t\"entrypoint.sh\": `#!/bin/bash\n# Always exit on errors.\nset -e\n\necho \"\" > /etc/config/network\ncat > /etc/config/mwan3 <<EOF\nconfig globals 'globals'\n option mmx_mask '0x3F00'\n option local_source 'lan'\nEOF\nfor net in $(jq -c \".[]\" /tmp/sdewan/networks.json)\ndo\n interface=$(echo $net | jq -r .interface)\n ipaddr=$(ifconfig $interface | awk '/inet/{print $2}' | cut -f2 -d \":\" | awk 'NR==1 {print $1}')\n if [ \"$isProvider\" == \"true\" ] || [ \"$isProvider\" == \"1\" ]]\n then\n vif=\"wan_$interface\"\n else\n vif=\"lan_$interface\"\n fi\n netmask=$(ifconfig $interface | awk '/inet/{print $4}' | cut -f2 -d \":\" | awk 'NR==1 {print $1}')\n cat >> /etc/config/network <<EOF\nconfig interface '$vif'\n option ifname '$interface'\n option proto 'static'\n option ipaddr '$ipaddr'\n option netmask '$netmask'\nEOF\n cat >> /etc/config/mwan3 <<EOF\nconfig interface '$vif'\n option enabled '1'\n option family 'ipv4'\n option reliability '2'\n option count '1'\n option timeout '2'\n option failure_latency '1000'\n option recovery_latency '500'\n option failure_loss '20'\n option recovery_loss '5'\n option interval '5'\n option down '3'\n option up '8'\nEOF\ndone\n\n/sbin/procd &\n/sbin/ubusd &\niptables -S\nsleep 1\n/etc/init.d/rpcd start\n/etc/init.d/dnsmasq start\n/etc/init.d/network start\n/etc/init.d/odhcpd start\n/etc/init.d/uhttpd start\n/etc/init.d/log start\n/etc/init.d/dropbear start\n/etc/init.d/mwan3 restart\n\necho \"Entering sleep... (success)\"\n\n# Sleep forever.\nwhile true; do sleep 100; done`,\n\t\t},\n\t}\n}", "func updateKubeConfig(cf *CLIConf, tc *client.TeleportClient, path string) error {\n\t// Fetch proxy's advertised ports to check for k8s support.\n\tif _, err := tc.Ping(cf.Context); err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\tif tc.KubeProxyAddr == \"\" {\n\t\t// Kubernetes support disabled, don't touch kubeconfig.\n\t\treturn nil\n\t}\n\n\tkubeStatus, err := fetchKubeStatus(cf.Context, tc)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\tvalues, err := buildKubeConfigUpdate(cf, kubeStatus)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\tif path == \"\" {\n\t\tpath = kubeconfig.PathFromEnv()\n\t}\n\n\t// If this is a profile specific kubeconfig, we only need\n\t// to put the selected kube cluster into the kubeconfig.\n\tisKubeConfig, err := keypaths.IsProfileKubeConfigPath(path)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\tif isKubeConfig {\n\t\tif !strings.Contains(path, cf.KubernetesCluster) {\n\t\t\treturn trace.BadParameter(\"profile specific kubeconfig is in use, run 'eval $(tsh env --unset)' to switch contexts to another kube cluster\")\n\t\t}\n\t\tvalues.Exec.KubeClusters = []string{cf.KubernetesCluster}\n\t}\n\n\treturn trace.Wrap(kubeconfig.Update(path, *values))\n}", "func (c *ClusterController) addSimulatorToConfig(name string) error {\n\tlabelSelector := metav1.LabelSelector{MatchLabels: map[string]string{\"app\": \"onos\", \"type\": \"config\"}}\n\tpods, err := c.kubeclient.CoreV1().Pods(c.clusterID).List(metav1.ListOptions{\n\t\tLabelSelector: labels.Set(labelSelector.MatchLabels).String(),\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, pod := range pods.Items {\n\t\tif err = c.addSimulatorToPod(name, pod); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (r *Reconciler) reconcileKubeDNSConfigMap(log logr.Logger, desiredState k8sutil.DesiredState) error {\n\tvar cm apiv1.ConfigMap\n\n\terr := r.Client.Get(context.Background(), types.NamespacedName{\n\t\tName: \"kube-dns\",\n\t\tNamespace: \"kube-system\",\n\t}, &cm)\n\tif k8serrors.IsNotFound(err) {\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn emperror.Wrap(err, \"could not get kube-dns configmap\")\n\t}\n\n\tstubDomains := make(map[string][]string, 0)\n\tif cm.Data[\"stubDomains\"] != \"\" {\n\t\terr = json.Unmarshal([]byte(cm.Data[\"stubDomains\"]), &stubDomains)\n\t\tif err != nil {\n\t\t\treturn emperror.Wrap(err, \"could not unmarshal stubDomains\")\n\t\t}\n\t}\n\n\tif desiredState == k8sutil.DesiredStatePresent {\n\t\tvar svc apiv1.Service\n\t\terr = r.Client.Get(context.Background(), types.NamespacedName{\n\t\t\tName: serviceName,\n\t\t\tNamespace: r.Config.Namespace,\n\t\t}, &svc)\n\t\tif err != nil {\n\t\t\treturn emperror.Wrap(err, \"could not get Istio coreDNS service\")\n\t\t}\n\t\tstubDomains[\"global\"] = []string{svc.Spec.ClusterIP}\n\t} else if desiredState == k8sutil.DesiredStateAbsent {\n\t\t_, ok := stubDomains[\"global\"]\n\t\tif ok {\n\t\t\tdelete(stubDomains, \"global\")\n\t\t}\n\t}\n\n\tstubDomainsData, err := json.Marshal(&stubDomains)\n\tif err != nil {\n\t\treturn emperror.Wrap(err, \"could not marshal updated stub domains\")\n\t}\n\n\tif cm.Data == nil {\n\t\tcm.Data = make(map[string]string, 0)\n\t}\n\tcm.Data[\"stubDomains\"] = string(stubDomainsData)\n\n\terr = r.Client.Update(context.Background(), &cm)\n\tif err != nil {\n\t\treturn emperror.Wrap(err, \"could not update kube-dns configmap\")\n\t}\n\n\treturn nil\n}", "func (r *Reconciler) ReconcilePhaseConfiguring() error {\n\n\tr.SetPhase(\n\t\tnbv1.NooBaaAccountPhaseConfiguring,\n\t\t\"NooBaaAccountPhaseConfiguring\",\n\t\t\"noobaa operator started phase 2/2 - \\\"Configuring\\\"\",\n\t)\n\n\tsysClient, err := system.Connect(false)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.NBClient = sysClient.NBClient\n\n\tif r.NooBaaAccountInfo != nil {\n\t\tif err := r.UpdateNooBaaAccount(); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tif err := r.CreateNooBaaAccount(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (sparkMasterDeployment *SparkMasterDeployment) generateDeploymentConfig()(* appsv1.Deployment){\n\tspark_master_deployment := &appsv1.Deployment{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: sparkMasterDeployment.sparkMasterName,\n\t\t},\n\t\tSpec: appsv1.DeploymentSpec{\n\t\t\tReplicas: k8s_util.Int32Ptr(1),\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: sparkMasterDeployment.labels,\n\t\t\t},\n\t\t\tTemplate: apiv1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: sparkMasterDeployment.labels,\n\t\t\t\t},\n\t\t\t\tSpec: apiv1.PodSpec{\n\t\t\t\t\tImagePullSecrets: []apiv1.LocalObjectReference{\n\t\t\t\t\t\t{Name: \"image-pull-secret-ibm-cloud\"},\n\t\t\t\t\t},\n\t\t\t\t\tContainers: []apiv1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"spark-master\",\n\t\t\t\t\t\t\tImage: sparkMasterDeployment.image_name,\n\t\t\t\t\t\t\tCommand: []string{\n\t\t\t\t\t\t\t\t\"/bin/sh\",\n\t\t\t\t\t\t\t\t\"-c\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tArgs: []string{\n\t\t\t\t\t\t\t\t//\"echo $(hostname -i) \"+sparkMasterDeployment.sparkMasterName+\" >> /etc/hosts && python3 -m http.server\",\n\t\t\t\t\t\t\t\t\"echo $(hostname -i) \"+sparkMasterDeployment.sparkMasterName+\" >> /etc/hosts && \"+sparkMasterDeployment.sparkPath+\"/bin/spark-class org.apache.spark.deploy.master.Master\",\n\t\t\t\t\t\t\t},\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\tName: \"master\",\n\t\t\t\t\t\t\t\t\tProtocol: apiv1.ProtocolTCP,\n\t\t\t\t\t\t\t\t\tContainerPort: 7077,\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: \"webui\",\n\t\t\t\t\t\t\t\t\tProtocol: apiv1.ProtocolTCP,\n\t\t\t\t\t\t\t\t\tContainerPort: 8080,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tEnv: []apiv1.EnvVar{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tName: \"SPARK_DAEMON_MEMORY\",\n\t\t\t\t\t\t\t\t\tValue: \"1g\",\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: \"SPARK_MASTER_HOST\",\n\t\t\t\t\t\t\t\t\tValue: sparkMasterDeployment.sparkMasterName,\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: \"SPARK_MASTER_PORT\",\n\t\t\t\t\t\t\t\t\tValue: sparkMasterDeployment.sparkMasterSerivcePort,\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: \"SPARK_MASTER_WEBUI_PORT\",\n\t\t\t\t\t\t\t\t\tValue: sparkMasterDeployment.sparkMasterWebuiPort,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tResources: sparkMasterDeployment.deploymentResource.GenerateResourceRequirements(),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tNodeSelector: sparkMasterDeployment.nodeSelector,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\treturn spark_master_deployment\n}", "func (c *APIDryRunCompositeConfigurator) Configure(ctx context.Context, cm resource.CompositeClaim, cp resource.Composite) error { //nolint:gocyclo // Only slightly over (12).\n\tucm, ok := cm.(*claim.Unstructured)\n\tif !ok {\n\t\treturn nil\n\t}\n\tucp, ok := cp.(*composite.Unstructured)\n\tif !ok {\n\t\treturn nil\n\t}\n\n\ticmSpec := ucm.Object[\"spec\"]\n\tspec, ok := icmSpec.(map[string]any)\n\tif !ok {\n\t\treturn errors.New(errUnsupportedClaimSpec)\n\t}\n\n\texisting := ucp.GetClaimReference()\n\tproposed := meta.ReferenceTo(ucm, ucm.GetObjectKind().GroupVersionKind())\n\tif existing != nil && !cmp.Equal(existing, proposed, cmpopts.IgnoreFields(corev1.ObjectReference{}, \"UID\")) {\n\t\treturn errors.New(errBindCompositeConflict)\n\t}\n\n\t// It's possible we're being asked to configure a statically provisioned\n\t// composite resource in which case we should respect its existing name and\n\t// external name.\n\ten := meta.GetExternalName(ucp)\n\n\tmeta.AddAnnotations(ucp, ucm.GetAnnotations())\n\tmeta.AddLabels(ucp, cm.GetLabels())\n\tmeta.AddLabels(ucp, map[string]string{\n\t\txcrd.LabelKeyClaimName: ucm.GetName(),\n\t\txcrd.LabelKeyClaimNamespace: ucm.GetNamespace(),\n\t})\n\n\t// If our composite resource already exists we want to restore its\n\t// original external name (if set) in order to ensure we don't try to\n\t// rename anything after the fact.\n\tif meta.WasCreated(ucp) && en != \"\" {\n\t\tmeta.SetExternalName(ucp, en)\n\t}\n\n\t// We want to propagate the claim's spec to the composite's spec, but\n\t// first we must filter out any well-known fields that are unique to\n\t// claims. We do this by:\n\t// 1. Grabbing a map whose keys represent all well-known claim fields.\n\t// 2. Deleting any well-known fields that we want to propagate.\n\t// 3. Using the resulting map keys to filter the claim's spec.\n\twellKnownClaimFields := xcrd.CompositeResourceClaimSpecProps()\n\tfor _, field := range xcrd.PropagateSpecProps {\n\t\tdelete(wellKnownClaimFields, field)\n\t}\n\n\t// CompositionRevision is a special field which needs to be propagated\n\t// based on the Update policy. If the policy is `Manual`, we need to\n\t// remove CompositionRevisionRef from wellKnownClaimFields, so it\n\t// does not get filtered out and is set correctly in composite\n\tif cp.GetCompositionUpdatePolicy() != nil && *cp.GetCompositionUpdatePolicy() == xpv1.UpdateManual {\n\t\tdelete(wellKnownClaimFields, xcrd.CompositionRevisionRef)\n\t}\n\n\tclaimSpecFilter := xcrd.GetPropFields(wellKnownClaimFields)\n\tucp.Object[\"spec\"] = filter(spec, claimSpecFilter...)\n\n\t// Note that we overwrite the entire composite spec above, so we wait\n\t// until this point to set the claim reference. We compute the reference\n\t// earlier so we can return early if it would not be allowed.\n\tucp.SetClaimReference(proposed)\n\n\tif !meta.WasCreated(cp) {\n\t\t// The API server returns an available name derived from\n\t\t// generateName when we perform a dry-run create. This name is\n\t\t// likely (but not guaranteed) to be available when we create\n\t\t// the composite resource. If the API server generates a name\n\t\t// that is unavailable it will return a 500 ServerTimeout error.\n\t\tcp.SetGenerateName(fmt.Sprintf(\"%s-\", cm.GetName()))\n\t\treturn errors.Wrap(c.client.Create(ctx, cp, client.DryRunAll), errName)\n\t}\n\n\treturn nil\n}", "func (m *Manager) ApplyConfig(cfg *config.Config) error {\n\t// Update only if a config change is detected. If TLS configuration is\n\t// set, we have to restart the manager to make sure that new TLS\n\t// certificates are picked up.\n\tvar blankTLSConfig config_util.TLSConfig\n\tif reflect.DeepEqual(m.config, cfg.TracingConfig) && m.config.TLSConfig == blankTLSConfig {\n\t\treturn nil\n\t}\n\n\tif m.shutdownFunc != nil {\n\t\tif err := m.shutdownFunc(); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to shut down the tracer provider: %w\", err)\n\t\t}\n\t}\n\n\t// If no endpoint is set, assume tracing should be disabled.\n\tif cfg.TracingConfig.Endpoint == \"\" {\n\t\tm.config = cfg.TracingConfig\n\t\tm.shutdownFunc = nil\n\t\totel.SetTracerProvider(trace.NewNoopTracerProvider())\n\t\tlevel.Info(m.logger).Log(\"msg\", \"Tracing provider uninstalled.\")\n\t\treturn nil\n\t}\n\n\ttp, shutdownFunc, err := buildTracerProvider(context.Background(), cfg.TracingConfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to install a new tracer provider: %w\", err)\n\t}\n\n\tm.shutdownFunc = shutdownFunc\n\tm.config = cfg.TracingConfig\n\totel.SetTracerProvider(tp)\n\n\tlevel.Info(m.logger).Log(\"msg\", \"Successfully installed a new tracer provider.\")\n\treturn nil\n}", "func (dn *Daemon) performPostConfigChangeAction(postConfigChangeActions []string, configName string) error {\n\tif ctrlcommon.InSlice(postConfigChangeActionReboot, postConfigChangeActions) {\n\t\tlogSystem(\"Rebooting node\")\n\t\treturn dn.reboot(fmt.Sprintf(\"Node will reboot into config %s\", configName))\n\t}\n\n\tif ctrlcommon.InSlice(postConfigChangeActionNone, postConfigChangeActions) {\n\t\tif dn.nodeWriter != nil {\n\t\t\tdn.nodeWriter.Eventf(corev1.EventTypeNormal, \"SkipReboot\", \"Config changes do not require reboot.\")\n\t\t}\n\t\tlogSystem(\"Node has Desired Config %s, skipping reboot\", configName)\n\t}\n\n\tif ctrlcommon.InSlice(postConfigChangeActionReloadCrio, postConfigChangeActions) {\n\t\tserviceName := \"crio\"\n\n\t\tif err := reloadService(serviceName); err != nil {\n\t\t\tif dn.nodeWriter != nil {\n\t\t\t\tdn.nodeWriter.Eventf(corev1.EventTypeWarning, \"FailedServiceReload\", fmt.Sprintf(\"Reloading %s service failed. Error: %v\", serviceName, err))\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"could not apply update: reloading %s configuration failed. Error: %w\", serviceName, err)\n\t\t}\n\n\t\tif dn.nodeWriter != nil {\n\t\t\tdn.nodeWriter.Eventf(corev1.EventTypeNormal, \"SkipReboot\", \"Config changes do not require reboot. Service %s was reloaded.\", serviceName)\n\t\t}\n\t\tlogSystem(\"%s config reloaded successfully! Desired config %s has been applied, skipping reboot\", serviceName, configName)\n\t}\n\n\t// We are here, which means reboot was not needed to apply the configuration.\n\n\t// Get current state of node, in case of an error reboot\n\tstate, err := dn.getStateAndConfigs()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not apply update: error processing state and configs. Error: %w\", err)\n\t}\n\n\tvar inDesiredConfig bool\n\tif inDesiredConfig, err = dn.updateConfigAndState(state); err != nil {\n\t\treturn fmt.Errorf(\"could not apply update: setting node's state to Done failed. Error: %w\", err)\n\t}\n\tif inDesiredConfig {\n\t\t// (re)start the config drift monitor since rebooting isn't needed.\n\t\tdn.startConfigDriftMonitor()\n\t\treturn nil\n\t}\n\n\t// currentConfig != desiredConfig, kick off an update\n\treturn dn.triggerUpdateWithMachineConfig(state.currentConfig, state.desiredConfig, true)\n}", "func buildKubeConfigUpdate(cf *CLIConf, kubeStatus *kubernetesStatus) (*kubeconfig.Values, error) {\n\tv := &kubeconfig.Values{\n\t\tClusterAddr: kubeStatus.clusterAddr,\n\t\tTeleportClusterName: kubeStatus.teleportClusterName,\n\t\tCredentials: kubeStatus.credentials,\n\t\tProxyAddr: cf.Proxy,\n\t\tTLSServerName: kubeStatus.tlsServerName,\n\t}\n\n\tif cf.executablePath == \"\" {\n\t\t// Don't know tsh path.\n\t\t// Fall back to the old kubeconfig, with static credentials from v.Credentials.\n\t\treturn v, nil\n\t}\n\n\tif len(kubeStatus.kubeClusters) == 0 {\n\t\t// If there are no registered k8s clusters, we may have an older teleport cluster.\n\t\t// Fall back to the old kubeconfig, with static credentials from v.Credentials.\n\t\tlog.Debug(\"Disabling exec plugin mode for kubeconfig because this Teleport cluster has no Kubernetes clusters.\")\n\t\treturn v, nil\n\t}\n\n\tclusterNames := kubeClustersToStrings(kubeStatus.kubeClusters)\n\tv.Exec = &kubeconfig.ExecValues{\n\t\tTshBinaryPath: cf.executablePath,\n\t\tTshBinaryInsecure: cf.InsecureSkipVerify,\n\t\tKubeClusters: clusterNames,\n\t\tEnv: make(map[string]string),\n\t}\n\n\tif cf.HomePath != \"\" {\n\t\tv.Exec.Env[types.HomeEnvVar] = cf.HomePath\n\t}\n\n\t// Only switch the current context if kube-cluster is explicitly set on the command line.\n\tif cf.KubernetesCluster != \"\" {\n\t\tif !apiutils.SliceContainsStr(clusterNames, cf.KubernetesCluster) {\n\t\t\treturn nil, trace.BadParameter(\"Kubernetes cluster %q is not registered in this Teleport cluster; you can list registered Kubernetes clusters using 'tsh kube ls'.\", cf.KubernetesCluster)\n\t\t}\n\t\tv.Exec.SelectCluster = cf.KubernetesCluster\n\t}\n\treturn v, nil\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"deploymentconfig-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to DeploymentConfig\n\terr = c.Watch(&source.Kind{Type: &appsapi_v1.DeploymentConfig{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\tscope.Error(err.Error())\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *ExecKubectl) Apply(ctx context.Context, opt ApplierOptions) error {\n\tlog := log.FromContext(ctx)\n\n\tobjects := manifest.Objects{Items: opt.Objects}\n\tmanifestStr, err := objects.JSONManifest()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating JSON manifest: %w\", err)\n\t}\n\n\tlog.Info(\"applying manifest\")\n\n\targs := []string{\"apply\"}\n\tif opt.Namespace != \"\" {\n\t\targs = append(args, \"-n\", opt.Namespace)\n\t}\n\n\t// Not doing --validate avoids downloading the OpenAPI\n\t// which can save a lot work & memory\n\targs = append(args, \"--validate=\"+strconv.FormatBool(opt.Validate))\n\n\tif opt.RESTConfig != nil {\n\t\tkubeconfig, err := buildKubeconfig(opt.RESTConfig)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error building kubeconfig: %w\", err)\n\t\t}\n\n\t\tf, err := os.CreateTemp(\"\", \"kubeconfig\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error creating temp file: %w\", err)\n\t\t}\n\n\t\tdefer func() {\n\t\t\tif err := os.Remove(f.Name()); err != nil {\n\t\t\t\tklog.Errorf(\"error removing kubeconfig temp file %s: %v\", f.Name(), err)\n\t\t\t}\n\t\t}()\n\n\t\tif _, err := f.Write(kubeconfig); err != nil {\n\t\t\treturn fmt.Errorf(\"error writing kubeconfig: %w\", err)\n\t\t}\n\n\t\tif err := f.Close(); err != nil {\n\t\t\treturn fmt.Errorf(\"error writing kubeconfig: %w\", err)\n\t\t}\n\n\t\targs = append(args, \"--kubeconfig\", f.Name())\n\t}\n\n\tif opt.Force {\n\t\targs = append(args, \"--force\")\n\t}\n\n\targs = append(args, opt.ExtraArgs...)\n\targs = append(args, \"-f\", \"-\")\n\n\tlog.Info(\"applying manifest with kubectl %s\", strings.Join(args, \" \"))\n\n\tcmd := exec.Command(\"kubectl\", args...)\n\tcmd.Stdin = strings.NewReader(manifestStr)\n\n\tvar stdout bytes.Buffer\n\tvar stderr bytes.Buffer\n\tcmd.Stdout = &stdout\n\tcmd.Stderr = &stderr\n\n\tlog.WithValues(\"command\", \"kubectl\").WithValues(\"args\", args).Info(\"executing kubectl\")\n\n\tif err := c.cmdSite.Run(cmd); err != nil {\n\t\tlog.WithValues(\"stdout\", stdout.String()).WithValues(\"stderr\", stderr.String()).Error(err, \"error from running kubectl apply\")\n\t\tlog.Info(fmt.Sprintf(\"manifest:\\n%v\", manifestStr))\n\t\treturn fmt.Errorf(\"error from running kubectl apply: %v\", err)\n\t}\n\n\tlog.WithValues(\"stdout\", stdout.String()).WithValues(\"stderr\", stderr.String()).V(2).Info(\"ran kubectl apply\")\n\n\treturn nil\n}", "func RConfigs(context dtypes.RContext) (*v1.ConfigMap, error) {\n\n\tconst rConfigs = `\napiVersion: v1\nkind: ConfigMap\nmetadata:\n name: rapp-configs-{{ .Name }}\n labels:\n app.kubernetes.io/name: rapp-configs\n app.kubernetes.io/instance: \"{{ .Name }}\"\n app.kubernetes.io/managed-by: MetaController\ndata:\n start-rapp.sh: |\n #!/usr/bin/env bash\n\n set -o errexit -o pipefail\n\n #source activate dask-distributed\n [ -f \"${HOME}/.bash_profile\" ] && source \"${HOME}/.bash_profile\"\n\n mkdir -p /var/log/shiny-server\n chown shiny.shiny /var/log/shiny-server\n \n if [ \"$APPLICATION_LOGS_TO_STDOUT\" != \"false\" ];\n then\n # push the \"real\" application logs to stdout with xtail in detached mode\n exec xtail /var/log/shiny-server/ &\n fi\n # check if the apps directory is empty - if so copy over the sample\n mkdir -p /rscripts /rlibs\n DIR_EMPTY=\"$(ls -A /rscripts)\"\n if [ \"${DIR}\" == \"\" ]; then\n if [ -d \"/srv/shiny-server/01_hello\" ]; then\n cp -r /srv/shiny-server/01_hello/* /rscripts/\n fi\n fi\n\n # run install hook if found\n if [ -f /rscripts/rapps_install.sh ]; then\n cd /rscripts\n bash /rscripts/rapps_install.sh\n fi\n \n if [ -f /rscripts/launch.R ]; then\n cd /rscripts\n Rscript /rscripts/launch.R\n else\n #R -e \".libPaths( c( .libPaths(), '/rlibs') ); setwd('/rscripts'); library(shiny); runApp(appDir='/rscripts', port=${PORT}, host='${HOST}', launch.browser=FALSE, display.mode='normal')\" >/var/log/shiny-server/rapp.log 2>&1\n R -e \".libPaths( c( .libPaths(), '/rlibs') ); setwd('/rscripts'); library(shiny); runApp(appDir='/rscripts', port=${PORT}, host='${HOST}', launch.browser=FALSE, display.mode='normal')\" 2>&1\n fi\n \n`\n\tresult, err := utils.ApplyTemplate(rConfigs, context)\n\tif err != nil {\n\t\tlog.Debugf(\"ApplyTemplate Error: %+v\\n\", err)\n\t\treturn nil, err\n\t}\n\tconfigmap := &v1.ConfigMap{}\n\tif err := json.Unmarshal([]byte(result), configmap); err != nil {\n\t\treturn nil, err\n\t}\n\treturn configmap, err\n}", "func (c *K8sConfig) Create() error {\n\tc.log.Info(\"Applying Kubernetes configuration\", \"ref\", c.config.Name, \"config\", c.config.Paths)\n\n\terr := c.setup()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.client.Apply(c.config.Paths, c.config.WaitUntilReady)\n}", "func main() {\n\tdestCfg, err := config.GetConfig()\n\tdestCfg.Burst = 1000\n\tdestCfg.QPS = 1000\n\toldKubeConfigEnv := os.Getenv(\"KUBECONFIG\")\n\tos.Setenv(\"KUBECONFIG\", os.Getenv(\"HOME\")+\"/.kube/config\")\n\tsrcCfg, err := config.GetConfig()\n\tsrcCfg.Burst = 1000\n\tsrcCfg.QPS = 1000\n\tos.Setenv(\"KUBECONFIG\", oldKubeConfigEnv)\n\n\tscheme := runtime.NewScheme()\n\tif err := routev1.AddToScheme(scheme); err != nil {\n\t\tlog.Fatal(err, \"unable to add routev1 scheme\")\n\t}\n\tif err := v1.AddToScheme(scheme); err != nil {\n\t\tlog.Fatal(err, \"unable to add v1 scheme\")\n\t}\n\tif err := corev1.AddToScheme(scheme); err != nil {\n\n\t\tlog.Fatal(err, \"unable to add corev1 scheme\")\n\t}\n\n\tsrcClient, err := client.New(srcCfg, client.Options{Scheme: scheme})\n\tif err != nil {\n\t\tlog.Fatal(err, \"unable to create source client\")\n\t}\n\n\tdestClient, err := client.New(destCfg, client.Options{Scheme: scheme})\n\tif err != nil {\n\t\tlog.Fatal(err, \"unable to create destination client\")\n\t}\n\n\t// quiesce the applications if needed on the source side\n\terr = state_transfer.QuiesceApplications(srcCfg, srcNamespace)\n\tif err != nil {\n\t\tlog.Fatal(err, \"unable to quiesce application on source cluster\")\n\t}\n\n\t// set up the PVC on destination to receive the data\n\tpvc := &corev1.PersistentVolumeClaim{}\n\terr = srcClient.Get(context.TODO(), client.ObjectKey{Namespace: srcNamespace, Name: srcPVC}, pvc)\n\tif err != nil {\n\t\tlog.Fatal(err, \"unable to get source PVC\")\n\t}\n\n\tdestPVC := pvc.DeepCopy()\n\n\tdestPVC.ResourceVersion = \"\"\n\tdestPVC.Spec.VolumeName = \"\"\n\tpvc.Annotations = map[string]string{}\n\terr = destClient.Create(context.TODO(), destPVC, &client.CreateOptions{})\n\tif err != nil {\n\t\tlog.Fatal(err, \"unable to create destination PVC\")\n\t}\n\n\tpvcList, err := transfer.NewPVCPairList(\n\t\ttransfer.NewPVCPair(pvc, destPVC),\n\t)\n\tif err != nil {\n\t\tlog.Fatal(err, \"invalid pvc list\")\n\t}\n\n\tendpointPort := int32(2222)\n\t// create a route for data transfer\n\tr := route.NewEndpoint(\n\t\ttypes.NamespacedName{\n\t\t\tNamespace: pvc.Namespace,\n\t\t\tName: pvc.Name,\n\t\t}, endpointPort, route.EndpointTypePassthrough, labels.Labels)\n\te, err := endpoint.Create(r, destClient)\n\tif err != nil {\n\t\tlog.Fatal(err, \"unable to create route endpoint\")\n\t}\n\n\t_ = wait.PollUntil(time.Second*5, func() (done bool, err error) {\n\t\tready, err := e.IsHealthy(destClient)\n\t\tif err != nil {\n\t\t\tlog.Println(err, \"unable to check route health, retrying...\")\n\t\t\treturn false, nil\n\t\t}\n\t\treturn ready, nil\n\t}, make(<-chan struct{}))\n\n\t// create an stunnel transport to carry the data over the route\n\tproxyOptions := transport.ProxyOptions{\n\t\tURL: \"127.0.0.1\",\n\t\tUsername: \"foo\",\n\t\tPassword: \"bar\",\n\t}\n\ts := stunnel.NewTransport(&proxyOptions)\n\t_, err = transport.CreateServer(s, srcClient, e)\n\tif err != nil {\n\t\tlog.Fatal(err, \"error creating stunnel client\")\n\t}\n\n\t//_, err = transport.CreateClient(s, destClient, e)\n\t//if err != nil {\n\t//\tlog.Fatal(err, \"error creating stunnel server\")\n\t//}\n\n\t// Create Rclone Transfer Pod\n\tt, err := rclone.NewTransfer(s, r, srcCfg, destCfg, pvcList)\n\tif err != nil {\n\t\tlog.Fatal(err, \"errror creating rclone transfer\")\n\t}\n\n\terr = transfer.CreateServer(t)\n\tif err != nil {\n\t\tlog.Fatal(err, \"error creating rclone server\")\n\t}\n\n\t// Create Rclone Client Pod\n\terr = transfer.CreateClient(t)\n\tif err != nil {\n\t\tlog.Fatal(err, \"error creating rclone client\")\n\t}\n\n\t// TODO: check if the client is completed\n}", "func (s *ServerGroup) ApplyConfig(cfg *Config) error {\n\ts.Cfg = cfg\n\n\t// Copy/paste from upstream prometheus/common until https://github.com/prometheus/common/issues/144 is resolved\n\ttlsConfig, err := config_util.NewTLSConfig(&cfg.HTTPConfig.HTTPConfig.TLSConfig)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error loading TLS client config\")\n\t}\n\t// The only timeout we care about is the configured scrape timeout.\n\t// It is applied on request. So we leave out any timings here.\n\tvar rt http.RoundTripper = &http.Transport{\n\t\tProxy: http.ProxyURL(cfg.HTTPConfig.HTTPConfig.ProxyURL.URL),\n\t\tMaxIdleConns: 20000,\n\t\tMaxIdleConnsPerHost: 1000, // see https://github.com/golang/go/issues/13801\n\t\tDisableKeepAlives: false,\n\t\tTLSClientConfig: tlsConfig,\n\t\t// 5 minutes is typically above the maximum sane scrape interval. So we can\n\t\t// use keepalive for all configurations.\n\t\tIdleConnTimeout: 5 * time.Minute,\n\t\tDialContext: (&net.Dialer{Timeout: cfg.HTTPConfig.DialTimeout}).DialContext,\n\t\tResponseHeaderTimeout: cfg.Timeout,\n\t}\n\n\t// If a bearer token is provided, create a round tripper that will set the\n\t// Authorization header correctly on each request.\n\tif len(cfg.HTTPConfig.HTTPConfig.BearerToken) > 0 {\n\t\trt = config_util.NewAuthorizationCredentialsRoundTripper(\"Bearer\", cfg.HTTPConfig.HTTPConfig.BearerToken, rt)\n\t} else if len(cfg.HTTPConfig.HTTPConfig.BearerTokenFile) > 0 {\n\t\trt = config_util.NewAuthorizationCredentialsFileRoundTripper(\"Bearer\", cfg.HTTPConfig.HTTPConfig.BearerTokenFile, rt)\n\t}\n\n\tif cfg.HTTPConfig.HTTPConfig.BasicAuth != nil {\n\t\trt = config_util.NewBasicAuthRoundTripper(cfg.HTTPConfig.HTTPConfig.BasicAuth.Username, cfg.HTTPConfig.HTTPConfig.BasicAuth.Password, cfg.HTTPConfig.HTTPConfig.BasicAuth.PasswordFile, rt)\n\t}\n\n\ts.client = &http.Client{Transport: rt}\n\n\tif err := s.targetManager.ApplyConfig(map[string]discovery.Configs{\"foo\": cfg.ServiceDiscoveryConfigs}); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (h *PodCreateHandler) Handle(ctx context.Context, req types.Request) types.Response {\n\tobj := &corev1.Pod{}\n\terr := h.Decoder.Decode(req, obj)\n\tif err != nil {\n\t\treturn admission.ErrorResponse(http.StatusBadRequest, err)\n\t}\n\tcopy := obj.DeepCopy()\n\tconfigMap := &corev1.ConfigMap{}\n\tsidecarTemplateConfigMapName := os.Getenv(\"SIDECAR_CONFIGMAP_NAME\")\n\t// default configmap\n\tif sidecarTemplateConfigMapName == \"\" {\n\t\tsidecarTemplateConfigMapName = \"sidecar-templ-configmap\"\n\t}\n\t// sidecar configmap namespace is same with pod's namespace\n\tconfigmapNamespace := req.AdmissionRequest.Namespace\n\t// logf.Log.Info(\"get operatorNamespace\", \"operatorNamespace\", operatorNamespace)\n\terr = h.Client.Get(ctx, _types.NamespacedName{Namespace: configmapNamespace, Name: sidecarTemplateConfigMapName}, configMap)\n\tif err != nil {\n\t\tlogf.Log.Error(err, \"configMap not found\", configmapNamespace, sidecarTemplateConfigMapName)\n\t\treturn admission.ErrorResponse(http.StatusBadRequest, err)\n\t}\n\tlogf.Log.Info(\"Handle configMap.Data\", \"configMap.Data\", configMap.Data)\n\treplicas := 0\n\tcontainer := &corev1.Container{}\n\tif num, numExists := configMap.Data[\"num\"]; numExists {\n\t\treplicas, err = strconv.Atoi(num)\n\t\tif err != nil {\n\t\t\treturn admission.ErrorResponse(http.StatusBadRequest, err)\n\t\t}\n\n\t\tif replicas < 0 {\n\t\t\treturn admission.ErrorResponse(http.StatusBadRequest, errors.NewBadRequest(\"num cannot be less than 0\"))\n\t\t}\n\n\t\tif replicas > 1000 {\n\t\t\treturn admission.ErrorResponse(http.StatusBadRequest, errors.NewBadRequest(\"num cannot be greater than 1000\"))\n\t\t}\n\n\t\tif sidecarTemplate, exists := configMap.Data[\"sidecar-template\"]; exists {\n\t\t\terr = yaml.Unmarshal([]byte(sidecarTemplate), container)\n\t\t\tif err != nil {\n\t\t\t\treturn admission.ErrorResponse(http.StatusBadRequest, errors.NewBadRequest(\"sidecar-template content is invalid\"))\n\t\t\t}\n\t\t}\n\t}\n\n\tlogf.Log.Info(\"get sidecar container\", \"sidecar container\", container)\n\terr = h.mutatingPodFn(ctx, copy, *container, replicas)\n\tlogf.Log.Info(\"get pod spec containers\", \"pod containers\", copy.Spec.Containers)\n\tif err != nil {\n\t\treturn admission.ErrorResponse(http.StatusInternalServerError, err)\n\t}\n\treturn admission.PatchResponse(obj, copy)\n}", "func (config *internalConfiguration) setConfiguration(newConf *CoreConfiguration) {\n\n\tnewConf.apiPlatformClientID = config.APIPlatformClientID\n\tnewConf.apiPlatformHost = config.APIPlatformHost\n\tnewConf.idcsHost = config.IDCSHost\n\tnewConf.apiPlatformClientSecret = config.APIPlatformClientSecret\n\tnewConf.apiPlatformUser = config.APIPlatformUser\n\tnewConf.apiPlatformUserPassword = config.APIPlatformUserPassword\n\tnewConf.apiPlatformScope = config.APIPlatformScope\n}", "func createConfigMap(hostClientSet internalclientset.Interface, config util.AdminConfig, fedSystemNamespace, federationName, joiningClusterName, targetClusterContext, kubeconfigPath string, dryRun bool) (*api.ConfigMap, error) {\n\tcmDep, err := getCMDeployment(hostClientSet, fedSystemNamespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdomainMap, ok := cmDep.Annotations[util.FedDomainMapKey]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"kube-dns config map data missing from controller manager annotations\")\n\t}\n\n\ttargetFactory := config.ClusterFactory(targetClusterContext, kubeconfigPath)\n\ttargetClientSet, err := targetFactory.ClientSet()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\texistingConfigMap, err := targetClientSet.Core().ConfigMaps(metav1.NamespaceSystem).Get(util.KubeDnsConfigmapName, metav1.GetOptions{})\n\tif isNotFound(err) {\n\t\tnewConfigMap := &api.ConfigMap{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: util.KubeDnsConfigmapName,\n\t\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\tfederation.FederationNameAnnotation: federationName,\n\t\t\t\t\tfederation.ClusterNameAnnotation: joiningClusterName,\n\t\t\t\t},\n\t\t\t},\n\t\t\tData: map[string]string{\n\t\t\t\tutil.FedDomainMapKey: domainMap,\n\t\t\t},\n\t\t}\n\t\tnewConfigMap = populateStubDomainsIfRequired(newConfigMap, cmDep.Annotations)\n\n\t\tif dryRun {\n\t\t\treturn newConfigMap, nil\n\t\t}\n\t\treturn targetClientSet.Core().ConfigMaps(metav1.NamespaceSystem).Create(newConfigMap)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif existingConfigMap.Data == nil {\n\t\texistingConfigMap.Data = make(map[string]string)\n\t}\n\tif _, ok := existingConfigMap.Data[util.FedDomainMapKey]; ok {\n\t\t// Append this federation info\n\t\texistingConfigMap.Data[util.FedDomainMapKey] = appendConfigMapString(existingConfigMap.Data[util.FedDomainMapKey], cmDep.Annotations[util.FedDomainMapKey])\n\n\t} else {\n\t\t// For some reason the configMap exists but this data is empty\n\t\texistingConfigMap.Data[util.FedDomainMapKey] = cmDep.Annotations[util.FedDomainMapKey]\n\t}\n\n\tif dryRun {\n\t\treturn existingConfigMap, nil\n\t}\n\treturn targetClientSet.Core().ConfigMaps(metav1.NamespaceSystem).Update(existingConfigMap)\n}", "func (b *bgpserver) performReconfigure() {\n\n\tif b.noUpdatesReady() {\n\t\t// last update happened before the last reconfigure\n\t\treturn\n\t}\n\n\tstart := time.Now()\n\n\t// these are the VIP addresses\n\t// get both the v4 and v6 to use in CheckConfigParity below\n\taddressesV4, addressesV6, err := b.ipLoopback.Get()\n\tif err != nil {\n\t\tb.metrics.Reconfigure(\"error\", time.Now().Sub(start))\n\t\tb.logger.Infof(\"unable to compare configurations with error %v\", err)\n\t\treturn\n\t}\n\n\t// splice together to compare against the internal state of configs\n\t// addresses is sorted within the CheckConfigParity function\n\taddresses := append(addressesV4, addressesV6...)\n\n\t// compare configurations and apply new IPVS rules if they're different\n\tsame, err := b.ipvs.CheckConfigParity(b.nodes, b.config, addresses, b.configReady())\n\tif err != nil {\n\t\tb.metrics.Reconfigure(\"error\", time.Now().Sub(start))\n\t\tb.logger.Infof(\"unable to compare configurations with error %v\", err)\n\t\treturn\n\t}\n\n\tif same {\n\t\tb.logger.Debug(\"parity same\")\n\t\tb.metrics.Reconfigure(\"noop\", time.Now().Sub(start))\n\t\treturn\n\t}\n\n\tb.logger.Debug(\"parity different, reconfiguring\")\n\tif err := b.configure(); err != nil {\n\t\tb.metrics.Reconfigure(\"critical\", time.Now().Sub(start))\n\t\tb.logger.Infof(\"unable to apply ipv4 configuration. %v\", err)\n\t\treturn\n\t}\n\n\tif err := b.configure6(); err != nil {\n\t\tb.metrics.Reconfigure(\"critical\", time.Now().Sub(start))\n\t\tb.logger.Infof(\"unable to apply ipv6 configuration. %v\", err)\n\t\treturn\n\t}\n\tb.metrics.Reconfigure(\"complete\", time.Now().Sub(start))\n}", "func (p KopsProvisioner) update(sc *kapp.StackConfig, providerImpl provider.Provider,\n\tdryRun bool) error {\n\n\terr := p.patch(sc, providerImpl, dryRun)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tproviderVars := provider.GetVars(providerImpl)\n\n\tprovisionerValues := providerVars[PROVISIONER_KEY].(map[interface{}]interface{})\n\tkopsConfig, err := getKopsConfig(provisionerValues)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tlog.Infof(\"Performing a rolling update to apply config changes to the kops cluster...\")\n\t// todo make the --yes flag configurable, perhaps through a CLI arg so people can verify their\n\t// changes before applying them\n\targs := []string{\n\t\t\"rolling-update\",\n\t\t\"cluster\",\n\t\t\"--yes\",\n\t}\n\n\targs = parameteriseValues(args, kopsConfig.Params.Global)\n\targs = parameteriseValues(args, kopsConfig.Params.RollingUpdate)\n\n\tvar stdoutBuf bytes.Buffer\n\tvar stderrBuf bytes.Buffer\n\n\tcmd := exec.Command(KOPS_PATH, args...)\n\tcmd.Env = os.Environ()\n\tcmd.Stdout = &stdoutBuf\n\tcmd.Stderr = &stderrBuf\n\n\tif dryRun {\n\t\tlog.Infof(\"Dry run. Skipping invoking Kops, but would execute: %s %s\",\n\t\t\tKOPS_PATH, strings.Join(args, \" \"))\n\t} else {\n\t\tlog.Infof(\"Running Kops rolling update... Executing: %s %s\", KOPS_PATH,\n\t\t\tstrings.Join(args, \" \"))\n\n\t\terr := cmd.Run()\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"Failed to update Kops cluster: %s\", stderrBuf.String())\n\t\t}\n\n\t\tlog.Debugf(\"Kops returned:\\n%s\", stdoutBuf.String())\n\t\tlog.Infof(\"Kops cluster updated\")\n\t}\n\n\treturn nil\n}", "func updateConfigMapFunc(f *framework.Framework, tc *nodeConfigTestCase) error {\n\t// Clear ResourceVersion from the ConfigMap objects we use to initiate mutations\n\t// so that we don't get 409 (conflict) responses. ConfigMaps always allow updates\n\t// (with respect to concurrency control) when you omit ResourceVersion.\n\t// We know that we won't perform concurrent updates during this test.\n\ttc.configMap.ResourceVersion = \"\"\n\tcm, err := f.ClientSet.CoreV1().ConfigMaps(tc.configMap.Namespace).Update(tc.configMap)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// update tc.configMap's ResourceVersion to match the updated ConfigMap, this makes\n\t// sure our derived status checks have up-to-date information\n\ttc.configMap.ResourceVersion = cm.ResourceVersion\n\treturn nil\n}", "func (a *InternetProxyApiService) ModifySingleDCConfigurationExecute(r ApiModifySingleDCConfigurationRequest) (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"InternetProxyApiService.ModifySingleDCConfiguration\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/proxy/configuration\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.internetProxyChangeRequest == nil {\n\t\treturn nil, reportError(\"internetProxyChangeRequest is required and must be specified\")\n\t}\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{}\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 = r.internetProxyChangeRequest\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Api-Token\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.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(req)\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\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\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 (dn *Daemon) update(oldConfig, newConfig *mcfgv1.MachineConfig, skipCertificateWrite bool) (retErr error) {\n\toldConfig = canonicalizeEmptyMC(oldConfig)\n\n\tif dn.nodeWriter != nil {\n\t\tstate, err := getNodeAnnotationExt(dn.node, constants.MachineConfigDaemonStateAnnotationKey, true)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif state != constants.MachineConfigDaemonStateDegraded && state != constants.MachineConfigDaemonStateUnreconcilable {\n\t\t\tif err := dn.nodeWriter.SetWorking(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"error setting node's state to Working: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tdn.catchIgnoreSIGTERM()\n\tdefer func() {\n\t\t// now that we do rebootless updates, we need to turn off our SIGTERM protection\n\t\t// regardless of how we leave the \"update loop\"\n\t\tdn.cancelSIGTERM()\n\t}()\n\n\toldConfigName := oldConfig.GetName()\n\tnewConfigName := newConfig.GetName()\n\n\toldIgnConfig, err := ctrlcommon.ParseAndConvertConfig(oldConfig.Spec.Config.Raw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing old Ignition config failed: %w\", err)\n\t}\n\tnewIgnConfig, err := ctrlcommon.ParseAndConvertConfig(newConfig.Spec.Config.Raw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing new Ignition config failed: %w\", err)\n\t}\n\n\tklog.Infof(\"Checking Reconcilable for config %v to %v\", oldConfigName, newConfigName)\n\n\t// make sure we can actually reconcile this state\n\tdiff, reconcilableError := reconcilable(oldConfig, newConfig)\n\n\tif reconcilableError != nil {\n\t\twrappedErr := fmt.Errorf(\"can't reconcile config %s with %s: %w\", oldConfigName, newConfigName, reconcilableError)\n\t\tif dn.nodeWriter != nil {\n\t\t\tdn.nodeWriter.Eventf(corev1.EventTypeWarning, \"FailedToReconcile\", wrappedErr.Error())\n\t\t}\n\t\treturn &unreconcilableErr{wrappedErr}\n\t}\n\n\tlogSystem(\"Starting update from %s to %s: %+v\", oldConfigName, newConfigName, diff)\n\n\tdiffFileSet := ctrlcommon.CalculateConfigFileDiffs(&oldIgnConfig, &newIgnConfig)\n\tactions, err := calculatePostConfigChangeAction(diff, diffFileSet)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Check and perform node drain if required\n\tdrain, err := isDrainRequired(actions, diffFileSet, oldIgnConfig, newIgnConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif drain {\n\t\tif err := dn.performDrain(); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tklog.Info(\"Changes do not require drain, skipping.\")\n\t}\n\n\t// update files on disk that need updating\n\tif err := dn.updateFiles(oldIgnConfig, newIgnConfig, skipCertificateWrite); err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\tif retErr != nil {\n\t\t\tif err := dn.updateFiles(newIgnConfig, oldIgnConfig, skipCertificateWrite); err != nil {\n\t\t\t\terrs := kubeErrs.NewAggregate([]error{err, retErr})\n\t\t\t\tretErr = fmt.Errorf(\"error rolling back files writes: %w\", errs)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\t// update file permissions\n\tif err := dn.updateKubeConfigPermission(); err != nil {\n\t\treturn err\n\t}\n\n\t// only update passwd if it has changed (do not nullify)\n\t// we do not need to include SetPasswordHash in this, since only updateSSHKeys has issues on firstboot.\n\tif diff.passwd {\n\t\tif err := dn.updateSSHKeys(newIgnConfig.Passwd.Users, oldIgnConfig.Passwd.Users); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdefer func() {\n\t\t\tif retErr != nil {\n\t\t\t\tif err := dn.updateSSHKeys(newIgnConfig.Passwd.Users, oldIgnConfig.Passwd.Users); err != nil {\n\t\t\t\t\terrs := kubeErrs.NewAggregate([]error{err, retErr})\n\t\t\t\t\tretErr = fmt.Errorf(\"error rolling back SSH keys updates: %w\", errs)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\t// Set password hash\n\tif err := dn.SetPasswordHash(newIgnConfig.Passwd.Users, oldIgnConfig.Passwd.Users); err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\tif retErr != nil {\n\t\t\tif err := dn.SetPasswordHash(newIgnConfig.Passwd.Users, oldIgnConfig.Passwd.Users); err != nil {\n\t\t\t\terrs := kubeErrs.NewAggregate([]error{err, retErr})\n\t\t\t\tretErr = fmt.Errorf(\"error rolling back password hash updates: %w\", errs)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tif dn.os.IsCoreOSVariant() {\n\t\tcoreOSDaemon := CoreOSDaemon{dn}\n\t\tif err := coreOSDaemon.applyOSChanges(*diff, oldConfig, newConfig); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdefer func() {\n\t\t\tif retErr != nil {\n\t\t\t\tif err := coreOSDaemon.applyOSChanges(*diff, newConfig, oldConfig); err != nil {\n\t\t\t\t\terrs := kubeErrs.NewAggregate([]error{err, retErr})\n\t\t\t\t\tretErr = fmt.Errorf(\"error rolling back changes to OS: %w\", errs)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t} else {\n\t\tklog.Info(\"updating the OS on non-CoreOS nodes is not supported\")\n\t}\n\n\t// Ideally we would want to update kernelArguments only via MachineConfigs.\n\t// We are keeping this to maintain compatibility and OKD requirement.\n\tif err := UpdateTuningArgs(KernelTuningFile, CmdLineFile); err != nil {\n\t\treturn err\n\t}\n\n\t// At this point, we write the now expected to be \"current\" config to /etc.\n\t// When we reboot, we'll find this file and validate that we're in this state,\n\t// and that completes an update.\n\todc := &onDiskConfig{\n\t\tcurrentConfig: newConfig,\n\t}\n\n\tif err := dn.storeCurrentConfigOnDisk(odc); err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif retErr != nil {\n\t\t\todc.currentConfig = oldConfig\n\t\t\tif err := dn.storeCurrentConfigOnDisk(odc); err != nil {\n\t\t\t\terrs := kubeErrs.NewAggregate([]error{err, retErr})\n\t\t\t\tretErr = fmt.Errorf(\"error rolling back current config on disk: %w\", errs)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn dn.performPostConfigChangeAction(actions, newConfig.GetName())\n}" ]
[ "0.61599785", "0.59701127", "0.5963785", "0.5922146", "0.58306885", "0.5824726", "0.5786718", "0.57252824", "0.5631203", "0.5620179", "0.5617887", "0.56011736", "0.55913275", "0.5550719", "0.55310565", "0.55141616", "0.550688", "0.54669976", "0.54614884", "0.54555297", "0.5420957", "0.541707", "0.5408577", "0.535445", "0.5329342", "0.5311768", "0.52859163", "0.52829987", "0.52772677", "0.5230453", "0.5227394", "0.52036417", "0.51870716", "0.5164208", "0.51467085", "0.51440704", "0.51404047", "0.513671", "0.51290995", "0.51290214", "0.5124721", "0.5120827", "0.5120147", "0.5118266", "0.5115995", "0.51115525", "0.5105839", "0.51031774", "0.5102583", "0.5102008", "0.50862217", "0.50852984", "0.5082159", "0.5068467", "0.50647503", "0.50448453", "0.5040338", "0.503847", "0.5033515", "0.50303334", "0.50198096", "0.50160885", "0.5016035", "0.5011429", "0.50034577", "0.49978048", "0.49968198", "0.49951434", "0.4988584", "0.49851957", "0.49826837", "0.49800602", "0.497085", "0.49704397", "0.49690598", "0.4966417", "0.49505404", "0.49445665", "0.49408734", "0.49386036", "0.49342927", "0.49311957", "0.49280956", "0.49270254", "0.49172947", "0.4916982", "0.49136126", "0.49128246", "0.48983365", "0.4894022", "0.488769", "0.48857144", "0.48817393", "0.48804656", "0.48783523", "0.48731458", "0.48710555", "0.48708406", "0.48648947", "0.48619005" ]
0.71195805
0
manageRollingUpdate used to manage properly a cluster rolling update if the podtemplate spec has changed
func (c *Controller) manageRollingUpdate(admin submarine.AdminInterface, cluster *rapi.SubmarineCluster, rCluster *submarine.Cluster, nodes submarine.Nodes) (bool, error) { return true, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (view *ViewPodDemo) DemoRollingUpdate() {\n\n\tpod := view.randomPod()\n\tlog.Printf(\"Random pod: %v\", pod)\n\n\tnpart := strings.Split(pod.Name, \"-\")\n\tnewPrefix := fmt.Sprintf(\"%v-%x\", npart[0], rand.Intn(1<<16))\n\n\tseq := 0\n\tfor {\n\t\tnn := fmt.Sprintf(\"%v-%v-%x\", npart[0], npart[1], seq)\n\t\toldPod, ok := view.Pods[nn]\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\t// create new pod\n\t\tnewPod := view.RecreatePod(newPrefix, seq, oldPod)\n\t\tview.updateStatus(newPod, PodStatusSequenceStart)\n\n\t\t// delete old\n\t\tview.updateStatus(oldPod, PodStatusSequenceStop)\n\n\t\tseq++\n\t}\n\n}", "func (dsc *ReconcileDaemonSet) standardRollingUpdate(ds *appsv1alpha1.DaemonSet, hash string) error {\n\tnodeToDaemonPods, err := dsc.getNodesToDaemonPods(ds)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't get node to daemon pod mapping for daemon set %q: %v\", ds.Name, err)\n\t}\n\n\tmaxUnavailable, numUnavailable, err := dsc.getUnavailableNumbers(ds, nodeToDaemonPods)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't get unavailable numbers: %v\", err)\n\t}\n\n\t// calculate the cluster scope numUnavailable.\n\tif numUnavailable >= maxUnavailable {\n\t\t_, oldPods := dsc.getAllDaemonSetPods(ds, nodeToDaemonPods, hash)\n\t\t_, oldUnavailablePods := util.SplitByAvailablePods(ds.Spec.MinReadySeconds, oldPods)\n\n\t\t// for oldPods delete all not running pods\n\t\tvar oldPodsToDelete []string\n\t\tfor _, pod := range oldUnavailablePods {\n\t\t\t// Skip terminating pods. We won't delete them again\n\t\t\tif pod.DeletionTimestamp != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\toldPodsToDelete = append(oldPodsToDelete, pod.Name)\n\t\t}\n\t\treturn dsc.syncNodes(ds, oldPodsToDelete, []string{}, hash)\n\t}\n\n\tnodeToDaemonPods, err = dsc.filterDaemonPodsToUpdate(ds, hash, nodeToDaemonPods)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to filterDaemonPodsToUpdate: %v\", err)\n\t}\n\n\t_, oldPods := dsc.getAllDaemonSetPods(ds, nodeToDaemonPods, hash)\n\n\toldAvailablePods, oldUnavailablePods := util.SplitByAvailablePods(ds.Spec.MinReadySeconds, oldPods)\n\n\t// for oldPods delete all not running pods\n\tvar oldPodsToDelete []string\n\tfor _, pod := range oldUnavailablePods {\n\t\t// Skip terminating pods. We won't delete them again\n\t\tif pod.DeletionTimestamp != nil {\n\t\t\tcontinue\n\t\t}\n\t\toldPodsToDelete = append(oldPodsToDelete, pod.Name)\n\t}\n\n\tfor _, pod := range oldAvailablePods {\n\t\tif numUnavailable >= maxUnavailable {\n\t\t\tklog.V(0).Infof(\"%s/%s number of unavailable DaemonSet pods: %d, is equal to or exceeds allowed maximum: %d\", ds.Namespace, ds.Name, numUnavailable, maxUnavailable)\n\t\t\tdsc.eventRecorder.Eventf(ds, corev1.EventTypeWarning, \"numUnavailable >= maxUnavailable\", \"%s/%s number of unavailable DaemonSet pods: %d, is equal to or exceeds allowed maximum: %d\", ds.Namespace, ds.Name, numUnavailable, maxUnavailable)\n\t\t\tbreak\n\t\t}\n\t\tklog.V(6).Infof(\"Marking pod %s/%s for deletion\", ds.Name, pod.Name)\n\t\toldPodsToDelete = append(oldPodsToDelete, pod.Name)\n\t\tnumUnavailable++\n\t}\n\treturn dsc.syncNodes(ds, oldPodsToDelete, []string{}, hash)\n}", "func migRollingUpdate(tmpl string, nt time.Duration) error {\n\tBy(fmt.Sprintf(\"starting the MIG rolling update to %s\", tmpl))\n\tid, err := migRollingUpdateStart(tmpl, nt)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't start the MIG rolling update: %v\", err)\n\t}\n\n\tBy(fmt.Sprintf(\"polling the MIG rolling update (%s) until it completes\", id))\n\tif err := migRollingUpdatePoll(id, nt); err != nil {\n\t\treturn fmt.Errorf(\"err waiting until update completed: %v\", err)\n\t}\n\n\treturn nil\n}", "func rollingDeploy(clientset *kubernetes.Clientset, namespace, name, image string) error {\n\n\tfmt.Printf(\"rolling upgrade : %s \\n\", name)\n\n\tupdateClient := clientset.AppsV1().Deployments(namespace)\n\n\tretryErr := 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\tresult, getErr := updateClient.Get(name, metav1.GetOptions{})\n\t\tif getErr != nil {\n\t\t\tpanic(fmt.Errorf(\"Failed to get latest version of Deployment: %v\", getErr))\n\t\t}\n\n\t\tresult.Spec.Template.Spec.Containers[0].Image = image // change nginx version\n\n\t\t_, updateErr := updateClient.Update(result)\n\n\t\treturn updateErr\n\t})\n\n\tif retryErr != nil {\n\t\treturn retryErr\n\t}\n\n\treturn nil\n}", "func rollingStateful(clientset *kubernetes.Clientset, namespace, name, image string) error {\n\n\tfmt.Printf(\"rolling upgrade : %s \\n\", name)\n\n\tupdateClient := clientset.AppsV1().StatefulSets(namespace)\n\n\tretryErr := 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\tresult, getErr := updateClient.Get(name, metav1.GetOptions{})\n\t\tif getErr != nil {\n\t\t\tpanic(fmt.Errorf(\"Failed to get latest version of Deployment: %v\", getErr))\n\t\t}\n\n\t\tresult.Spec.Template.Spec.Containers[0].Image = image // change nginx version\n\n\t\t_, updateErr := updateClient.Update(result)\n\n\t\treturn updateErr\n\t})\n\n\tif retryErr != nil {\n\t\treturn retryErr\n\t}\n\n\treturn nil\n}", "func (dsc *ReconcileDaemonSet) rollingUpdate(ds *appsv1alpha1.DaemonSet, hash string) (delay time.Duration, err error) {\n\n\tif ds.Spec.UpdateStrategy.RollingUpdate.Type == appsv1alpha1.StandardRollingUpdateType {\n\t\treturn delay, dsc.standardRollingUpdate(ds, hash)\n\t} else if ds.Spec.UpdateStrategy.RollingUpdate.Type == appsv1alpha1.SurgingRollingUpdateType {\n\t\treturn dsc.surgingRollingUpdate(ds, hash)\n\t\t//} else if ds.Spec.UpdateStrategy.RollingUpdate.Type == appsv1alpha1.InplaceRollingUpdateType {\n\t\t//\treturn dsc.inplaceRollingUpdate(ds, hash)\n\t} else {\n\t\tklog.Errorf(\"no matched RollingUpdate type\")\n\t}\n\treturn\n}", "func (p KopsProvisioner) update(sc *kapp.StackConfig, providerImpl provider.Provider,\n\tdryRun bool) error {\n\n\terr := p.patch(sc, providerImpl, dryRun)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tproviderVars := provider.GetVars(providerImpl)\n\n\tprovisionerValues := providerVars[PROVISIONER_KEY].(map[interface{}]interface{})\n\tkopsConfig, err := getKopsConfig(provisionerValues)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tlog.Infof(\"Performing a rolling update to apply config changes to the kops cluster...\")\n\t// todo make the --yes flag configurable, perhaps through a CLI arg so people can verify their\n\t// changes before applying them\n\targs := []string{\n\t\t\"rolling-update\",\n\t\t\"cluster\",\n\t\t\"--yes\",\n\t}\n\n\targs = parameteriseValues(args, kopsConfig.Params.Global)\n\targs = parameteriseValues(args, kopsConfig.Params.RollingUpdate)\n\n\tvar stdoutBuf bytes.Buffer\n\tvar stderrBuf bytes.Buffer\n\n\tcmd := exec.Command(KOPS_PATH, args...)\n\tcmd.Env = os.Environ()\n\tcmd.Stdout = &stdoutBuf\n\tcmd.Stderr = &stderrBuf\n\n\tif dryRun {\n\t\tlog.Infof(\"Dry run. Skipping invoking Kops, but would execute: %s %s\",\n\t\t\tKOPS_PATH, strings.Join(args, \" \"))\n\t} else {\n\t\tlog.Infof(\"Running Kops rolling update... Executing: %s %s\", KOPS_PATH,\n\t\t\tstrings.Join(args, \" \"))\n\n\t\terr := cmd.Run()\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"Failed to update Kops cluster: %s\", stderrBuf.String())\n\t\t}\n\n\t\tlog.Debugf(\"Kops returned:\\n%s\", stdoutBuf.String())\n\t\tlog.Infof(\"Kops cluster updated\")\n\t}\n\n\treturn nil\n}", "func (c *Controller) applyConfiguration(admin submarine.AdminInterface, cluster *rapi.SubmarineCluster) (bool, error) {\n\tglog.Info(\"applyConfiguration START\")\n\tdefer glog.Info(\"applyConfiguration STOP\")\n\n\tasChanged := false\n\n\t// expected replication factor and number of master nodes\n\tcReplicaFactor := *cluster.Spec.ReplicationFactor\n\tcNbMaster := *cluster.Spec.NumberOfMaster\n\t// Adapt, convert CR to structure in submarine package\n\trCluster, nodes, err := newSubmarineCluster(admin, cluster)\n\tif err != nil {\n\t\tglog.Errorf(\"Unable to create the SubmarineCluster view, error:%v\", err)\n\t\treturn false, err\n\t}\n\t// PodTemplate changes require rolling updates\n\tif needRollingUpdate(cluster) {\n\t\tif setRollingUpdateCondition(&cluster.Status, true) {\n\t\t\tif cluster, err = c.updateHandler(cluster); err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\n\t\tglog.Info(\"applyConfiguration needRollingUpdate\")\n\t\treturn c.manageRollingUpdate(admin, cluster, rCluster, nodes)\n\t}\n\tif setRollingUpdateCondition(&cluster.Status, false) {\n\t\tif cluster, err = c.updateHandler(cluster); err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\t// if the number of Pods is greater than expected\n\tif needLessPods(cluster) {\n\t\tif setRebalancingCondition(&cluster.Status, true) {\n\t\t\tif cluster, err = c.updateHandler(cluster); err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\t\tglog.Info(\"applyConfiguration needLessPods\")\n\t\t// Configure Submarine cluster\n\t\treturn c.managePodScaleDown(admin, cluster, rCluster, nodes)\n\t}\n\t// If it is not a rolling update, modify the Condition\n\tif setRebalancingCondition(&cluster.Status, false) {\n\t\tif cluster, err = c.updateHandler(cluster); err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\tclusterStatus := &cluster.Status.Cluster\n\tif (clusterStatus.NbPods - clusterStatus.NbSubmarineRunning) != 0 {\n\t\tglog.V(3).Infof(\"All pods not ready wait to be ready, nbPods: %d, nbPodsReady: %d\", clusterStatus.NbPods, clusterStatus.NbSubmarineRunning)\n\t\treturn false, err\n\t}\n\n\t// First, we define the new masters\n\t// Select the desired number of Masters and assign Hashslots to each Master. The Master will be distributed to different K8S nodes as much as possible\n\t// Set the cluster status to Calculating Rebalancing\n\tnewMasters, curMasters, allMaster, err := clustering.DispatchMasters(rCluster, nodes, cNbMaster, admin)\n\tif err != nil {\n\t\tglog.Errorf(\"Cannot dispatch slots to masters: %v\", err)\n\t\trCluster.Status = rapi.ClusterStatusError\n\t\treturn false, err\n\t}\n\t// If the number of new and old masters is not the same\n\tif len(newMasters) != len(curMasters) {\n\t\tasChanged = true\n\t}\n\n\t// Second select Node that is already a slave\n\tcurrentSlaveNodes := nodes.FilterByFunc(submarine.IsSlave)\n\n\t//New slaves are slaves which is currently a master with no slots\n\tnewSlave := nodes.FilterByFunc(func(nodeA *submarine.Node) bool {\n\t\tfor _, nodeB := range newMasters {\n\t\t\tif nodeA.ID == nodeB.ID {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tfor _, nodeB := range currentSlaveNodes {\n\t\t\tif nodeA.ID == nodeB.ID {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n\n\t// Depending on whether we scale up or down, we will dispatch slaves before/after the dispatch of slots\n\tif cNbMaster < int32(len(curMasters)) {\n\t\t// this happens usually after a scale down of the cluster\n\t\t// we should dispatch slots before dispatching slaves\n\t\tif err := clustering.DispatchSlotToNewMasters(rCluster, admin, newMasters, curMasters, allMaster); err != nil {\n\t\t\tglog.Error(\"Unable to dispatch slot on new master, err:\", err)\n\t\t\treturn false, err\n\t\t}\n\n\t\t// assign master/slave roles\n\t\tnewSubmarineSlavesByMaster, bestEffort := clustering.PlaceSlaves(rCluster, newMasters, currentSlaveNodes, newSlave, cReplicaFactor)\n\t\tif bestEffort {\n\t\t\trCluster.NodesPlacement = rapi.NodesPlacementInfoBestEffort\n\t\t}\n\n\t\tif err := clustering.AttachingSlavesToMaster(rCluster, admin, newSubmarineSlavesByMaster); err != nil {\n\t\t\tglog.Error(\"Unable to dispatch slave on new master, err:\", err)\n\t\t\treturn false, err\n\t\t}\n\t} else {\n\t\t// We are scaling up the nbmaster or the nbmaster doesn't change.\n\t\t// assign master/slave roles\n\t\tnewSubmarineSlavesByMaster, bestEffort := clustering.PlaceSlaves(rCluster, newMasters, currentSlaveNodes, newSlave, cReplicaFactor)\n\t\tif bestEffort {\n\t\t\trCluster.NodesPlacement = rapi.NodesPlacementInfoBestEffort\n\t\t}\n\n\t\tif err := clustering.AttachingSlavesToMaster(rCluster, admin, newSubmarineSlavesByMaster); err != nil {\n\t\t\tglog.Error(\"Unable to dispatch slave on new master, err:\", err)\n\t\t\treturn false, err\n\t\t}\n\n\t\tif err := clustering.DispatchSlotToNewMasters(rCluster, admin, newMasters, curMasters, allMaster); err != nil {\n\t\t\tglog.Error(\"Unable to dispatch slot on new master, err:\", err)\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\tglog.V(4).Infof(\"new nodes status: \\n %v\", nodes)\n\n\t// Set the cluster status\n\trCluster.Status = rapi.ClusterStatusOK\n\t// wait a bit for the cluster to propagate configuration to reduce warning logs because of temporary inconsistency\n\ttime.Sleep(1 * time.Second)\n\treturn asChanged, nil\n}", "func migRollingUpdatePoll(id string, nt time.Duration) error {\n\t// Two keys and a val.\n\tstatus, progress, done := \"status\", \"statusMessage\", \"ROLLED_OUT\"\n\tstart, timeout := time.Now(), nt*time.Duration(testContext.CloudConfig.NumNodes)\n\tvar errLast error\n\tLogf(\"Waiting up to %v for MIG rolling update to complete.\", timeout)\n\t// TODO(mbforbes): Refactor this to use cluster_upgrade.go:retryCmd(...)\n\tif wait.Poll(restartPoll, timeout, func() (bool, error) {\n\t\to, err := exec.Command(\"gcloud\", \"preview\", \"rolling-updates\",\n\t\t\tfmt.Sprintf(\"--project=%s\", testContext.CloudConfig.ProjectID),\n\t\t\tfmt.Sprintf(\"--zone=%s\", testContext.CloudConfig.Zone),\n\t\t\t\"describe\",\n\t\t\tid).CombinedOutput()\n\t\tif err != nil {\n\t\t\terrLast = fmt.Errorf(\"Error calling rolling-updates describe %s: %v\", id, err)\n\t\t\tLogf(\"%v\", errLast)\n\t\t\treturn false, nil\n\t\t}\n\t\toutput := string(o)\n\n\t\t// The 'describe' call probably succeeded; parse the output and try to\n\t\t// find the line that looks like \"status: <status>\" and see whether it's\n\t\t// done.\n\t\tLogf(\"Waiting for MIG rolling update: %s (%v elapsed)\",\n\t\t\tparseKVLines(output, progress), time.Since(start))\n\t\tif st := parseKVLines(output, status); st == done {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t}) != nil {\n\t\treturn fmt.Errorf(\"timeout waiting %v for MIG rolling update to complete. Last error: %v\", timeout, errLast)\n\t}\n\tLogf(\"MIG rolling update complete after %v\", time.Since(start))\n\treturn nil\n}", "func PerformRollingUpgrade(client kubernetes.Interface, config util.Config, envarPostfix string, upgradeFuncs callbacks.RollingUpgradeFuncs) error {\n\titems := upgradeFuncs.ItemsFunc(client, config.Namespace)\n\tvar err error\n\tfor _, i := range items {\n\t\tcontainers := upgradeFuncs.ContainersFunc(i)\n\t\tresourceName := util.ToObjectMeta(i).Name\n\t\t// find correct annotation and update the resource\n\t\tannotationValue := util.ToObjectMeta(i).Annotations[config.Annotation]\n\t\tif annotationValue != \"\" {\n\t\t\tvalues := strings.Split(annotationValue, \",\")\n\t\t\tfor _, value := range values {\n\t\t\t\tif value == config.ResourceName {\n\t\t\t\t\tupdated := updateContainers(containers, value, config.SHAValue, envarPostfix)\n\t\t\t\t\tif !updated {\n\t\t\t\t\t\tlogrus.Warnf(\"Rolling upgrade failed because no container found to add environment variable in %s of type %s in namespace: %s\", resourceName, upgradeFuncs.ResourceType, config.Namespace)\n\t\t\t\t\t} else {\n\t\t\t\t\t\terr = upgradeFuncs.UpdateFunc(client, config.Namespace, i)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlogrus.Errorf(\"Update for %s of type %s in namespace %s failed with error %v\", resourceName, upgradeFuncs.ResourceType, config.Namespace, err)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlogrus.Infof(\"Updated %s of type %s in namespace: %s \", resourceName, upgradeFuncs.ResourceType, config.Namespace)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn err\n}", "func (c Controller) update(client Client, d *dc.DeploymentConfig, b *bc.BuildConfig, template *Template, nameSpace string, instanceID string, deploy *Payload) (*Dispatched, error) {\n\tvar (\n\t\tdispatched = &Dispatched{}\n\t\tstatusKey = StatusKey(instanceID, \"provision\")\n\t)\n\tfor _, ob := range template.Objects {\n\t\tswitch ob.(type) {\n\t\tcase *dc.DeploymentConfig:\n\t\t\tdeployment := ob.(*dc.DeploymentConfig)\n\t\t\tdeployment.SetResourceVersion(d.GetResourceVersion())\n\t\t\tdeployed, err := client.UpdateDeployConfigInNamespace(nameSpace, deployment)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"error updating deploy config: \")\n\t\t\t}\n\t\t\tdispatched.DeploymentName = deployed.Name\n\t\t\tc.statusPublisher.Publish(statusKey, configInProgress, \"updated DeploymentConfig\")\n\t\tcase *bc.BuildConfig:\n\t\t\tob.(*bc.BuildConfig).SetResourceVersion(b.GetResourceVersion())\n\t\t\tif _, err := client.UpdateBuildConfigInNamespace(nameSpace, ob.(*bc.BuildConfig)); err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"error updating build config: \")\n\t\t\t}\n\t\t\tc.statusPublisher.Publish(statusKey, configInProgress, \"updated BuildConfig\")\n\t\tcase *route.Route:\n\t\t\tr, err := client.UpdateRouteInNamespace(nameSpace, ob.(*route.Route))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdispatched.Route = r\n\t\t\tc.statusPublisher.Publish(statusKey, configInProgress, \"updated Route\")\n\t\t}\n\t}\n\treturn dispatched, nil\n}", "func triggerDaemonSetRollout(c client.Client, ds *appsv1.DaemonSet) error {\n\tannotations := map[string]string{}\n\tdscpy := ds.DeepCopy()\n\n\tif dscpy.Spec.Template.Annotations == nil {\n\t\tdscpy.Spec.Template.Annotations = annotations\n\t}\n\tdscpy.Spec.Template.Annotations[\"fileintegrity.openshift.io/restart-\"+fmt.Sprintf(\"%d\", time.Now().Unix())] = \"\"\n\treturn c.Update(context.TODO(), dscpy)\n}", "func (r *NamespaceTemplateReconciler) updatePod(ctx context.Context,\n\tnsName string, nstObj megav1.NamespaceTemplate, options map[string]string) error {\n\n\toldpod := &v1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: nsName,\n\t\t\tName: nstObj.Spec.AddResources.Pod.Name,\n\t\t},\n\t}\n\tif err := r.Delete(ctx, oldpod); err != nil {\n\t\tfmt.Printf(\"delete pod failed due to %v\\n\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func replicaUpdate(clientset *kubernetes.Clientset, metaname string, quantity string) {\n // Getting deployments\n deploymentsClient := clientset.AppsV1beta1().Deployments(apiv1.NamespaceDefault)\n\n // Updating deployment\n retryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {\n // Retrieve the latest version of Deployment before attempting update\n // RetryOnConflict uses exponential backoff to avoid exhausting the apiserver\n result, getErr := deploymentsClient.Get(metaname, metav1.GetOptions{})\n if getErr != nil {\n panic(fmt.Errorf(\"Failed to get latest version of Deployment: %v\", getErr))\n }\n\n fmt.Printf(\"Updating replica count of %v by %v\\n\", metaname, quantity)\n\n // Parsing quantity to int32\n i, err := strconv.ParseInt(quantity, 10, 32)\n if err != nil {\n panic(err)\n }\n\n // Modify replica count\n oldRep := result.Spec.Replicas\n result.Spec.Replicas = int32Ptr(*oldRep + int32(i))\n if *result.Spec.Replicas < int32(1) {\n result.Spec.Replicas = int32Ptr(1)\n }\n _, updateErr := deploymentsClient.Update(result)\n return updateErr\n })\n if retryErr != nil {\n panic(fmt.Errorf(\"Update failed: %v\", retryErr))\n }\n fmt.Printf(\"Updated replica count of Deployment %v\\n\", metaname)\n}", "func (pc *PodController) handleAddUpdatePod(obj interface{}) error {\n\tvar err error\n\tvar podCNIInfo *cnipodcache.CNIConfigInfo\n\tpod := obj.(*corev1.Pod)\n\tif len(pod.Status.PodIPs) == 0 {\n\t\t// Primary network configuration is not complete yet.\n\t\t// Note: Return nil here to unqueue Pod add event. Secondary network configuration will be handled with Pod update event.\n\t\treturn nil\n\t}\n\tsecondaryNetwork, ok := checkForPodSecondaryNetworkAttachement(pod)\n\tif !ok {\n\t\t// NOTE: We do not handle Pod annotation deletion/update scenario at present.\n\t\tklog.InfoS(\"Pod does not have a NetworkAttachmentDefinition\", \"Pod\", klog.KObj(pod))\n\t\treturn nil\n\t}\n\t// Retrieve Pod specific cache entry which has \"PodCNIDeleted = false\"\n\tif podCNIInfo = pc.podCache.GetValidCNIConfigInfoPerPod(pod.Name, pod.Namespace); podCNIInfo == nil {\n\t\treturn nil\n\t}\n\t// Valid cache entry retrieved from cache and we received a Pod add or update event.\n\t// Avoid processing Pod annotation, if we already have at least one secondary network successfully configured on this Pod.\n\t// We do not support/handle Annotation updates yet.\n\tif len(podCNIInfo.NetworkConfig) > 0 {\n\t\tklog.InfoS(\"Secondary network already configured on this Pod and annotation update not supported, skipping update\", \"pod\", klog.KObj(pod))\n\t\treturn nil\n\t}\n\t// Parse Pod annotation and proceed with the secondary network configuration.\n\tnetworklist, err := parsePodSecondaryNetworkAnnotation(secondaryNetwork)\n\tif err != nil {\n\t\t// Return error to requeue and retry.\n\t\treturn err\n\t}\n\n\terr = pc.configureSecondaryNetwork(pod, networklist, podCNIInfo)\n\t// We do not return error to retry, if at least one secondary network is configured.\n\tif (err != nil) && (len(podCNIInfo.NetworkConfig) == 0) {\n\t\t// Return error to requeue and retry.\n\t\treturn err\n\t}\n\treturn nil\n}", "func (o StorageClusterSpecUpdateStrategyOutput) RollingUpdate() StorageClusterSpecUpdateStrategyRollingUpdatePtrOutput {\n\treturn o.ApplyT(func(v StorageClusterSpecUpdateStrategy) *StorageClusterSpecUpdateStrategyRollingUpdate {\n\t\treturn v.RollingUpdate\n\t}).(StorageClusterSpecUpdateStrategyRollingUpdatePtrOutput)\n}", "func migRollingUpdateStart(templ string, nt time.Duration) (string, error) {\n\tvar errLast error\n\tvar id string\n\tprefix, suffix := \"Started [\", \"].\"\n\t// TODO(mbforbes): Refactor this to use cluster_upgrade.go:retryCmd(...)\n\tif err := wait.Poll(poll, singleCallTimeout, func() (bool, error) {\n\t\t// TODO(mbforbes): make this hit the compute API directly instead of\n\t\t// shelling out to gcloud.\n\t\t// NOTE(mbforbes): If you are changing this gcloud command, update\n\t\t// cluster/gce/upgrade.sh to match this EXACTLY.\n\t\to, err := exec.Command(\"gcloud\", \"preview\", \"rolling-updates\",\n\t\t\tfmt.Sprintf(\"--project=%s\", testContext.CloudConfig.ProjectID),\n\t\t\tfmt.Sprintf(\"--zone=%s\", testContext.CloudConfig.Zone),\n\t\t\t\"start\",\n\t\t\t// Required args.\n\t\t\tfmt.Sprintf(\"--group=%s\", testContext.CloudConfig.NodeInstanceGroup),\n\t\t\tfmt.Sprintf(\"--template=%s\", templ),\n\t\t\t// Optional args to fine-tune behavior.\n\t\t\tfmt.Sprintf(\"--instance-startup-timeout=%ds\", int(nt.Seconds())),\n\t\t\t// NOTE: We can speed up this process by increasing\n\t\t\t// --max-num-concurrent-instances.\n\t\t\tfmt.Sprintf(\"--max-num-concurrent-instances=%d\", 1),\n\t\t\tfmt.Sprintf(\"--max-num-failed-instances=%d\", 0),\n\t\t\tfmt.Sprintf(\"--min-instance-update-time=%ds\", 0)).CombinedOutput()\n\t\tif err != nil {\n\t\t\terrLast = fmt.Errorf(\"gcloud preview rolling-updates call failed with err: %v\", err)\n\t\t\treturn false, nil\n\t\t}\n\t\toutput := string(o)\n\n\t\t// The 'start' call probably succeeded; parse the output and try to find\n\t\t// the line that looks like \"Started [url/to/<id>].\" and return <id>.\n\t\tfor _, line := range strings.Split(output, \"\\n\") {\n\t\t\t// As a sanity check, ensure the line starts with prefix and ends\n\t\t\t// with suffix.\n\t\t\tif strings.Index(line, prefix) != 0 || strings.Index(line, suffix) != len(line)-len(suffix) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\turl := strings.Split(strings.TrimSuffix(strings.TrimPrefix(line, prefix), suffix), \"/\")\n\t\t\tid = url[len(url)-1]\n\t\t\tLogf(\"Started MIG rolling update; ID: %s\", id)\n\t\t\treturn true, nil\n\t\t}\n\t\terrLast = fmt.Errorf(\"couldn't find line like '%s ... %s' in output to MIG rolling-update start. Output: %s\",\n\t\t\tprefix, suffix, output)\n\t\treturn false, nil\n\t}); err != nil {\n\t\treturn \"\", fmt.Errorf(\"migRollingUpdateStart() failed with last error: %v\", errLast)\n\t}\n\treturn id, nil\n}", "func (dn *Daemon) updateHypershift(oldConfig, newConfig *mcfgv1.MachineConfig, diff *machineConfigDiff) (retErr error) {\n\toldIgnConfig, err := ctrlcommon.ParseAndConvertConfig(oldConfig.Spec.Config.Raw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing old Ignition config failed: %w\", err)\n\t}\n\tnewIgnConfig, err := ctrlcommon.ParseAndConvertConfig(newConfig.Spec.Config.Raw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing new Ignition config failed: %w\", err)\n\t}\n\n\t// update files on disk that need updating\n\t// We should't skip the certificate write in HyperShift since it does not run the extra daemon process\n\tif err := dn.updateFiles(oldIgnConfig, newIgnConfig, false); err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\tif retErr != nil {\n\t\t\tif err := dn.updateFiles(newIgnConfig, oldIgnConfig, false); err != nil {\n\t\t\t\terrs := kubeErrs.NewAggregate([]error{err, retErr})\n\t\t\t\tretErr = fmt.Errorf(\"error rolling back files writes: %w\", errs)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tif err := dn.updateSSHKeys(newIgnConfig.Passwd.Users, oldIgnConfig.Passwd.Users); err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\tif retErr != nil {\n\t\t\tif err := dn.updateSSHKeys(newIgnConfig.Passwd.Users, oldIgnConfig.Passwd.Users); err != nil {\n\t\t\t\terrs := kubeErrs.NewAggregate([]error{err, retErr})\n\t\t\t\tretErr = fmt.Errorf(\"error rolling back SSH keys updates: %w\", errs)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tif dn.os.IsCoreOSVariant() {\n\t\tcoreOSDaemon := CoreOSDaemon{dn}\n\t\tif err := coreOSDaemon.applyOSChanges(*diff, oldConfig, newConfig); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdefer func() {\n\t\t\tif retErr != nil {\n\t\t\t\tif err := coreOSDaemon.applyOSChanges(*diff, newConfig, oldConfig); err != nil {\n\t\t\t\t\terrs := kubeErrs.NewAggregate([]error{err, retErr})\n\t\t\t\t\tretErr = fmt.Errorf(\"error rolling back changes to OS: %w\", errs)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t} else {\n\t\tklog.Info(\"updating the OS on non-CoreOS nodes is not supported\")\n\t}\n\n\tif err := UpdateTuningArgs(KernelTuningFile, CmdLineFile); err != nil {\n\t\treturn err\n\t}\n\n\tklog.Info(\"Successfully completed Hypershift config update\")\n\treturn nil\n}", "func applyLastAppliedConfigPatch(ctx context.Context, appIf application.ApplicationServiceClient, appName string, resourceNames []string, resources map[string]*argoappv1.ResourceDiff, dryRun bool) {\n\tif len(resources) != 0 { //\n\t\t//The remain deployments or rollouts need to be applied\n\t\tfor i := range resourceNames {\n\t\t\tresourceName := resourceNames[i]\n\t\t\tif resourceName != \"\" {\n\t\t\t\tvar resource = resources[resourceName]\n\t\t\t\tvar namespace = resource.Namespace\n\t\t\t\tvar liveObj, _ = resource.LiveObject()\n\t\t\t\tliveObjCopy := liveObj.DeepCopy()\n\t\t\t\tif namespace == \"\" {\n\t\t\t\t\tnamespace = liveObj.GetNamespace()\n\t\t\t\t}\n\n\t\t\t\tvar lastAppliedConfig = \"\"\n\n\t\t\t\tmetadataObj := liveObjCopy.Object[\"metadata\"]\n\t\t\t\tif metadataObj != nil && reflect.TypeOf(metadataObj).String() == \"map[string]interface {}\" {\n\t\t\t\t\tmetadata := metadataObj.(map[string]interface{})\n\t\t\t\t\tannoObj := metadata[\"annotations\"]\n\t\t\t\t\tif annoObj != nil && reflect.TypeOf(annoObj).String() == \"map[string]interface {}\" {\n\t\t\t\t\t\tanno := annoObj.(map[string]interface{})\n\t\t\t\t\t\tlastAppliedConfig = anno[\"kubectl.kubernetes.io/last-applied-configuration\"].(string)\n\t\t\t\t\t\tdelete(anno, \"kubectl.kubernetes.io/last-applied-configuration\")\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tvar lastAppliedConfigObj *unstructured.Unstructured = nil\n\t\t\t\tif lastAppliedConfig != \"\" { //Use the last-applied-configuration instead of liveObject\n\t\t\t\t\tlastAppliedConfigObj = &unstructured.Unstructured{}\n\t\t\t\t\terr := json.Unmarshal([]byte(lastAppliedConfig), lastAppliedConfigObj)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Errorf(\"Not able to unmarshal last-applied-configuration %s %v\", lastAppliedConfig, err)\n\t\t\t\t\t}\n\t\t\t\t\tliveObjCopy = lastAppliedConfigObj\n\t\t\t\t}\n\n\t\t\t\tspecObj := liveObjCopy.Object[\"spec\"]\n\t\t\t\tif specObj != nil && reflect.TypeOf(specObj).String() == \"map[string]interface {}\" {\n\t\t\t\t\tspec := specObj.(map[string]interface{})\n\t\t\t\t\tdelete(spec, \"replicas\")\n\t\t\t\t}\n\t\t\t\tdelete(liveObjCopy.Object, \"status\")\n\n\t\t\t\tbytes, err := json.Marshal(liveObjCopy)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"Not able to marshal %s Spec\", liveObjCopy.GetKind())\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\tnewPatch := make(map[string]interface{})\n\t\t\t\tnewMetadata := make(map[string]interface{})\n\t\t\t\tnewPatch[\"metadata\"] = newMetadata\n\t\t\t\tnewAnnotations := make(map[string]interface{})\n\t\t\t\tnewMetadata[\"annotations\"] = newAnnotations\n\t\t\t\tnewAnnotations[\"kubectl.kubernetes.io/last-applied-configuration\"] = string(bytes)\n\n\t\t\t\t//For debug\n\t\t\t\t//var tmpFileName = \"/tmp/\" + resourceName + strconv.FormatInt(time.Now().Unix(), 10) + \".yaml\"\n\t\t\t\t//f, err := os.Create(tmpFileName)\n\t\t\t\t//if err != nil {\n\t\t\t\t//\tlog.Errorf(\"Not able to create temp file:%s\", tmpFileName)\n\t\t\t\t//\tos.Exit(1)\n\t\t\t\t//}\n\t\t\t\t////log.Infof(\"Writing current resource to yaml file:%s\", tmpFileName)\n\t\t\t\tyamlBytes, err := json.Marshal(newPatch)\n\t\t\t\t//f.Write(yamlBytes)\n\t\t\t\t//f.Sync()\n\t\t\t\t//f.Close()\n\n\t\t\t\t//var fileNames = make([]string, 1)\n\t\t\t\t//fileNames[0] = tmpFileName\n\n\t\t\t\tif !dryRun {\n\t\t\t\t\t_, err = appIf.PatchResource(ctx, &application.ApplicationResourcePatchRequest{\n\t\t\t\t\t\tName: &appName,\n\t\t\t\t\t\tNamespace: namespace,\n\t\t\t\t\t\tResourceName: resourceName,\n\t\t\t\t\t\tVersion: liveObjCopy.GetAPIVersion(),\n\t\t\t\t\t\tGroup: resource.Group,\n\t\t\t\t\t\tKind: resource.Kind,\n\t\t\t\t\t\tPatch: string(yamlBytes),\n\t\t\t\t\t\tPatchType: \"application/merge-patch+json\",\n\t\t\t\t\t})\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Errorf(\"Patching annoation 'kubectl.kubernetes.io/last-applied-configuration' on resource: %s, error:%v\", resourceName, err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.Infof(\"Resource '%s' patched on 'kubectl.kubernetes.io/last-applied-configuration'\", resourceName)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlog.Infof(\"DryRun on resource '%s' patch of 'kubectl.kubernetes.io/last-applied-configuration'\", resourceName)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (r *Reconciler) updatePodTemplateIfNeeded(logger logr.Logger, eds *datadoghqv1alpha1.ExtendedDaemonSet, podTpl *corev1.PodTemplate) (reconcile.Result, error) {\n\tspecHash, err := comparison.GenerateMD5PodTemplateSpec(&eds.Spec.Template)\n\tif err != nil {\n\t\treturn reconcile.Result{}, fmt.Errorf(\"cannot generate pod template hash: %w\", err)\n\t}\n\n\tif podTpl.Annotations != nil && podTpl.Annotations[datadoghqv1alpha1.MD5ExtendedDaemonSetAnnotationKey] == specHash {\n\t\t// Already up-to-date\n\t\treturn reconcile.Result{}, nil\n\t}\n\n\tlogger.Info(\"Updating PodTemplate\", \"podTemplate.Namespace\", podTpl.Namespace, \"podTemplate.Name\", podTpl.Name)\n\n\tnewPodTpl, err := r.newPodTemplate(eds)\n\tif err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\n\terr = r.client.Update(context.TODO(), newPodTpl)\n\tif err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\n\tr.recorder.Event(eds, corev1.EventTypeNormal, \"Update PodTemplate\", fmt.Sprintf(\"%s/%s\", podTpl.Namespace, podTpl.Name))\n\n\treturn reconcile.Result{}, nil\n}", "func (c *Controller) onUpdate(oldObj, newObj interface{}) {\n\toldcluster := oldObj.(*crv1.Pgcluster)\n\tnewcluster := newObj.(*crv1.Pgcluster)\n\n\tlog.Debugf(\"pgcluster onUpdate for cluster %s (namespace %s)\", newcluster.ObjectMeta.Namespace,\n\t\tnewcluster.ObjectMeta.Name)\n\n\t// if the status of the pgcluster shows that it has been bootstrapped, then proceed with\n\t// creating the cluster (i.e. the cluster deployment, services, etc.)\n\tif newcluster.Status.State == crv1.PgclusterStateBootstrapped {\n\t\tclusteroperator.AddClusterBase(c.Client, newcluster, newcluster.GetNamespace())\n\t\treturn\n\t}\n\n\t// if the 'shutdown' parameter in the pgcluster update shows that the cluster should be either\n\t// shutdown or started but its current status does not properly reflect that it is, then\n\t// proceed with the logic needed to either shutdown or start the cluster\n\tif newcluster.Spec.Shutdown && newcluster.Status.State != crv1.PgclusterStateShutdown {\n\t\tclusteroperator.ShutdownCluster(c.Client, *newcluster)\n\t} else if !newcluster.Spec.Shutdown &&\n\t\tnewcluster.Status.State == crv1.PgclusterStateShutdown {\n\t\tclusteroperator.StartupCluster(c.Client, *newcluster)\n\t}\n\n\t// check to see if the \"autofail\" label on the pgcluster CR has been changed from either true to false, or from\n\t// false to true. If it has been changed to false, autofail will then be disabled in the pg cluster. If has\n\t// been changed to true, autofail will then be enabled in the pg cluster\n\tif newcluster.ObjectMeta.Labels[config.LABEL_AUTOFAIL] != \"\" {\n\t\tautofailEnabledOld, err := strconv.ParseBool(oldcluster.ObjectMeta.Labels[config.LABEL_AUTOFAIL])\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t\tautofailEnabledNew, err := strconv.ParseBool(newcluster.ObjectMeta.Labels[config.LABEL_AUTOFAIL])\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t\tif autofailEnabledNew != autofailEnabledOld {\n\t\t\tutil.ToggleAutoFailover(c.Client, autofailEnabledNew,\n\t\t\t\tnewcluster.ObjectMeta.Labels[config.LABEL_PGHA_SCOPE],\n\t\t\t\tnewcluster.ObjectMeta.Namespace)\n\t\t}\n\n\t}\n\n\t// handle standby being enabled and disabled for the cluster\n\tif oldcluster.Spec.Standby && !newcluster.Spec.Standby {\n\t\tif err := clusteroperator.DisableStandby(c.Client, *newcluster); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t} else if !oldcluster.Spec.Standby && newcluster.Spec.Standby {\n\t\tif err := clusteroperator.EnableStandby(c.Client, *newcluster); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// see if any of the resource values have changed, and if so, update them\n\tif !reflect.DeepEqual(oldcluster.Spec.Resources, newcluster.Spec.Resources) ||\n\t\t!reflect.DeepEqual(oldcluster.Spec.Limits, newcluster.Spec.Limits) {\n\t\tif err := clusteroperator.UpdateResources(c.Client, c.Client.Config, newcluster); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// see if any of the pgBackRest repository resource values have changed, and\n\t// if so, update them\n\tif !reflect.DeepEqual(oldcluster.Spec.BackrestResources, newcluster.Spec.BackrestResources) ||\n\t\t!reflect.DeepEqual(oldcluster.Spec.BackrestLimits, newcluster.Spec.BackrestLimits) {\n\t\tif err := backrestoperator.UpdateResources(c.Client, newcluster); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// see if any of the pgBouncer values have changed, and if so, update the\n\t// pgBouncer deployment\n\tif !reflect.DeepEqual(oldcluster.Spec.PgBouncer, newcluster.Spec.PgBouncer) {\n\t\tif err := updatePgBouncer(c, oldcluster, newcluster); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// if we are not in a standby state, check to see if the tablespaces have\n\t// differed, and if so, add the additional volumes to the primary and replicas\n\tif !reflect.DeepEqual(oldcluster.Spec.TablespaceMounts, newcluster.Spec.TablespaceMounts) {\n\t\tif err := updateTablespaces(c, oldcluster, newcluster); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (o StorageClusterSpecUpdateStrategyPtrOutput) RollingUpdate() StorageClusterSpecUpdateStrategyRollingUpdatePtrOutput {\n\treturn o.ApplyT(func(v *StorageClusterSpecUpdateStrategy) *StorageClusterSpecUpdateStrategyRollingUpdate {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.RollingUpdate\n\t}).(StorageClusterSpecUpdateStrategyRollingUpdatePtrOutput)\n}", "func (dsc *ReconcileDaemonSet) surgingRollingUpdate(ds *appsv1alpha1.DaemonSet, hash string) (delay time.Duration, err error) {\n\tnodeToDaemonPods, err := dsc.getNodesToDaemonPods(ds)\n\tif err != nil {\n\t\treturn delay, fmt.Errorf(\"couldn't get node to daemon pod mapping for daemon set %q: %v\", ds.Name, err)\n\t}\n\n\tnodeToDaemonPods, err = dsc.filterDaemonPodsToUpdate(ds, hash, nodeToDaemonPods)\n\tif err != nil {\n\t\treturn delay, fmt.Errorf(\"failed to filterDaemonPodsToUpdate: %v\", err)\n\t}\n\n\tmaxSurge, numSurge, err := dsc.getSurgeNumbers(ds, nodeToDaemonPods, hash)\n\tif err != nil {\n\t\treturn delay, fmt.Errorf(\"couldn't get surge numbers: %v\", err)\n\t}\n\n\tnodesWantToRun, nodesShouldContinueRunning, err := dsc.getNodesShouldRunDaemonPod(ds)\n\tif err != nil {\n\t\treturn delay, fmt.Errorf(\"couldn't get nodes which want to run ds pod: %v\", err)\n\t}\n\n\tvar nodesToSurge []string\n\tvar oldPodsToDelete []string\n\tfor node, pods := range nodeToDaemonPods {\n\t\tvar newPod, oldPod *corev1.Pod\n\t\twantToRun := nodesWantToRun.Has(node)\n\t\tshouldContinueRunning := nodesShouldContinueRunning.Has(node)\n\t\t// if node has new taint, then the already existed pod does not want to run but should continue running\n\t\tif !wantToRun && !shouldContinueRunning {\n\t\t\tfor _, pod := range pods {\n\t\t\t\tklog.V(6).Infof(\"Marking pod %s/%s on unsuitable node %s for deletion\", ds.Name, pod.Name, node)\n\t\t\t\tif pod.DeletionTimestamp == nil {\n\t\t\t\t\toldPodsToDelete = append(oldPodsToDelete, pod.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tfoundAvailable := false\n\t\tfor _, pod := range pods {\n\t\t\tgeneration, err := GetTemplateGeneration(ds)\n\t\t\tif err != nil {\n\t\t\t\tgeneration = nil\n\t\t\t}\n\t\t\tif util.IsPodUpdated(pod, hash, generation) {\n\t\t\t\tif newPod != nil {\n\t\t\t\t\tklog.Warningf(\"Multiple new pods on node %s: %s, %s\", node, newPod.Name, pod.Name)\n\t\t\t\t}\n\t\t\t\tnewPod = pod\n\t\t\t} else {\n\t\t\t\tif oldPod != nil {\n\t\t\t\t\tklog.Warningf(\"Multiple old pods on node %s: %s, %s\", node, oldPod.Name, pod.Name)\n\t\t\t\t}\n\t\t\t\toldPod = pod\n\t\t\t}\n\t\t\tif !foundAvailable && podutil.IsPodAvailable(pod, ds.Spec.MinReadySeconds, metav1.Now()) {\n\t\t\t\tfoundAvailable = true\n\t\t\t}\n\t\t}\n\n\t\tif newPod != nil {\n\t\t\tklog.Infof(\"newPod IsPodAvailable is %v\", podutil.IsPodAvailable(newPod, ds.Spec.MinReadySeconds, metav1.Now()))\n\t\t}\n\t\tif newPod == nil && numSurge < maxSurge && wantToRun {\n\t\t\tif !foundAvailable && len(pods) >= 2 {\n\t\t\t\tklog.Warningf(\"Node %s already has %d unavailable pods, need clean first, skip surge new pod\", node, len(pods))\n\t\t\t} else {\n\t\t\t\tklog.V(6).Infof(\"Surging new pod on node %s\", node)\n\t\t\t\tnumSurge++\n\t\t\t\tnodesToSurge = append(nodesToSurge, node)\n\t\t\t}\n\t\t} else if newPod != nil && podutil.IsPodAvailable(newPod, ds.Spec.MinReadySeconds, metav1.Now()) && oldPod != nil && oldPod.DeletionTimestamp == nil {\n\t\t\tklog.V(6).Infof(\"Marking pod %s/%s for deletion\", ds.Name, oldPod.Name)\n\t\t\toldPodsToDelete = append(oldPodsToDelete, oldPod.Name)\n\t\t} else {\n\t\t\tif ds.Spec.MinReadySeconds > 0 {\n\t\t\t\tif newPod != nil {\n\t\t\t\t\tif podutil.IsPodAvailable(newPod, ds.Spec.MinReadySeconds, metav1.Now()) {\n\t\t\t\t\t\tif oldPod != nil && oldPod.DeletionTimestamp == nil {\n\t\t\t\t\t\t\tklog.V(6).Infof(\"Marking pod %s/%s for deletion\", ds.Name, oldPod.Name)\n\t\t\t\t\t\t\toldPodsToDelete = append(oldPodsToDelete, oldPod.Name)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn time.Duration(ds.Spec.MinReadySeconds) * time.Second, nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn delay, dsc.syncNodes(ds, oldPodsToDelete, nodesToSurge, hash)\n}", "func resourceVolterraNetworkPolicyRuleUpdate(d *schema.ResourceData, meta interface{}) error {\n\tclient := meta.(*APIClient)\n\n\tupdateMeta := &ves_io_schema.ObjectReplaceMetaType{}\n\tupdateSpec := &ves_io_schema_network_policy_rule.ReplaceSpecType{}\n\tupdateReq := &ves_io_schema_network_policy_rule.ReplaceRequest{\n\t\tMetadata: updateMeta,\n\t\tSpec: updateSpec,\n\t}\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\tupdateMeta.Annotations = ms\n\t}\n\n\tif v, ok := d.GetOk(\"description\"); ok && !isIntfNil(v) {\n\t\tupdateMeta.Description =\n\t\t\tv.(string)\n\t}\n\n\tif v, ok := d.GetOk(\"disable\"); ok && !isIntfNil(v) {\n\t\tupdateMeta.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\tupdateMeta.Labels = ms\n\t}\n\n\tif v, ok := d.GetOk(\"name\"); ok && !isIntfNil(v) {\n\t\tupdateMeta.Name =\n\t\t\tv.(string)\n\t}\n\n\tif v, ok := d.GetOk(\"namespace\"); ok && !isIntfNil(v) {\n\t\tupdateMeta.Namespace =\n\t\t\tv.(string)\n\t}\n\n\tif v, ok := d.GetOk(\"action\"); ok && !isIntfNil(v) {\n\n\t\tupdateSpec.Action = ves_io_schema_network_policy_rule.NetworkPolicyRuleAction(ves_io_schema_network_policy_rule.NetworkPolicyRuleAction_value[v.(string)])\n\n\t}\n\n\tif v, ok := d.GetOk(\"advanced_action\"); ok && !isIntfNil(v) {\n\n\t\tsl := v.(*schema.Set).List()\n\t\tadvancedAction := &ves_io_schema_network_policy_rule.NetworkPolicyRuleAdvancedAction{}\n\t\tupdateSpec.AdvancedAction = advancedAction\n\t\tfor _, set := range sl {\n\t\t\tadvancedActionMapStrToI := set.(map[string]interface{})\n\n\t\t\tif v, ok := advancedActionMapStrToI[\"action\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tadvancedAction.Action = ves_io_schema_network_policy_rule.LogAction(ves_io_schema_network_policy_rule.LogAction_value[v.(string)])\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tif v, ok := d.GetOk(\"label_matcher\"); ok && !isIntfNil(v) {\n\n\t\tsl := v.(*schema.Set).List()\n\t\tlabelMatcher := &ves_io_schema.LabelMatcherType{}\n\t\tupdateSpec.LabelMatcher = labelMatcher\n\t\tfor _, set := range sl {\n\t\t\tlabelMatcherMapStrToI := set.(map[string]interface{})\n\n\t\t\tif w, ok := labelMatcherMapStrToI[\"keys\"]; 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\tlabelMatcher.Keys = ls\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tif v, ok := d.GetOk(\"ports\"); ok && !isIntfNil(v) {\n\n\t\tls := make([]string, len(v.([]interface{})))\n\t\tfor i, v := range v.([]interface{}) {\n\t\t\tls[i] = v.(string)\n\t\t}\n\t\tupdateSpec.Ports = ls\n\n\t}\n\n\tif v, ok := d.GetOk(\"protocol\"); ok && !isIntfNil(v) {\n\n\t\tupdateSpec.Protocol =\n\t\t\tv.(string)\n\n\t}\n\n\tremoteEndpointTypeFound := false\n\n\tif v, ok := d.GetOk(\"ip_prefix_set\"); ok && !remoteEndpointTypeFound {\n\n\t\tremoteEndpointTypeFound = true\n\t\tremoteEndpointInt := &ves_io_schema_network_policy_rule.ReplaceSpecType_IpPrefixSet{}\n\t\tremoteEndpointInt.IpPrefixSet = &ves_io_schema.IpPrefixSetRefType{}\n\t\tupdateSpec.RemoteEndpoint = remoteEndpointInt\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[\"ref\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.([]interface{})\n\t\t\t\trefInt := make([]*ves_io_schema.ObjectRefType, len(sl))\n\t\t\t\tremoteEndpointInt.IpPrefixSet.Ref = refInt\n\t\t\t\tfor i, ps := range sl {\n\n\t\t\t\t\trMapToStrVal := ps.(map[string]interface{})\n\t\t\t\t\trefInt[i] = &ves_io_schema.ObjectRefType{}\n\n\t\t\t\t\trefInt[i].Kind = \"ip_prefix_set\"\n\n\t\t\t\t\tif v, ok := rMapToStrVal[\"name\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\trefInt[i].Name = v.(string)\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := rMapToStrVal[\"namespace\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\trefInt[i].Namespace = v.(string)\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := rMapToStrVal[\"tenant\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\trefInt[i].Tenant = v.(string)\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := rMapToStrVal[\"uid\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\trefInt[i].Uid = v.(string)\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\tif v, ok := d.GetOk(\"prefix\"); ok && !remoteEndpointTypeFound {\n\n\t\tremoteEndpointTypeFound = true\n\t\tremoteEndpointInt := &ves_io_schema_network_policy_rule.ReplaceSpecType_Prefix{}\n\t\tremoteEndpointInt.Prefix = &ves_io_schema.PrefixListType{}\n\t\tupdateSpec.RemoteEndpoint = remoteEndpointInt\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[\"ipv6_prefix\"]; 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\tremoteEndpointInt.Prefix.Ipv6Prefix = ls\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"prefix\"]; 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\tremoteEndpointInt.Prefix.Prefix = ls\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tif v, ok := d.GetOk(\"prefix_selector\"); ok && !remoteEndpointTypeFound {\n\n\t\tremoteEndpointTypeFound = true\n\t\tremoteEndpointInt := &ves_io_schema_network_policy_rule.ReplaceSpecType_PrefixSelector{}\n\t\tremoteEndpointInt.PrefixSelector = &ves_io_schema.LabelSelectorType{}\n\t\tupdateSpec.RemoteEndpoint = remoteEndpointInt\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[\"expressions\"]; 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\tremoteEndpointInt.PrefixSelector.Expressions = ls\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tlog.Printf(\"[DEBUG] Updating Volterra NetworkPolicyRule obj with struct: %+v\", updateReq)\n\n\terr := client.ReplaceObject(context.Background(), ves_io_schema_network_policy_rule.ObjectType, updateReq)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error updating NetworkPolicyRule: %s\", err)\n\t}\n\n\treturn resourceVolterraNetworkPolicyRuleRead(d, meta)\n}", "func (*deployInsideDeployConfigMapHandler) updateConfigMap(_ context.Context, _ *apiv1.ConfigMap, _ *pipeline.CfgData, err error) error {\n\treturn nil\n}", "func updateSplunkPodTemplateWithConfig(podTemplateSpec *corev1.PodTemplateSpec, cr *v1alpha1.SplunkEnterprise, instanceType InstanceType) error {\n\n\t// Add custom volumes to splunk containers\n\tif cr.Spec.SplunkVolumes != nil {\n\t\tpodTemplateSpec.Spec.Volumes = append(podTemplateSpec.Spec.Volumes, cr.Spec.SplunkVolumes...)\n\t\tfor idx := range podTemplateSpec.Spec.Containers {\n\t\t\tfor v := range cr.Spec.SplunkVolumes {\n\t\t\t\tpodTemplateSpec.Spec.Containers[idx].VolumeMounts = append(podTemplateSpec.Spec.Containers[idx].VolumeMounts, corev1.VolumeMount{\n\t\t\t\t\tName: cr.Spec.SplunkVolumes[v].Name,\n\t\t\t\t\tMountPath: \"/mnt/\" + cr.Spec.SplunkVolumes[v].Name,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\t// add defaults secrets to all splunk containers\n\taddSplunkVolumeToTemplate(podTemplateSpec, \"secrets\", corev1.VolumeSource{\n\t\tSecret: &corev1.SecretVolumeSource{\n\t\t\tSecretName: GetSplunkSecretsName(cr.GetIdentifier()),\n\t\t},\n\t})\n\n\t// add inline defaults to all splunk containers\n\tif cr.Spec.Defaults != \"\" {\n\t\taddSplunkVolumeToTemplate(podTemplateSpec, \"defaults\", corev1.VolumeSource{\n\t\t\tConfigMap: &corev1.ConfigMapVolumeSource{\n\t\t\t\tLocalObjectReference: corev1.LocalObjectReference{\n\t\t\t\t\tName: GetSplunkDefaultsName(cr.GetIdentifier()),\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t}\n\n\t// add spark and java mounts to search head containers\n\tif cr.Spec.EnableDFS && (instanceType == SplunkSearchHead || instanceType == SplunkStandalone) {\n\t\terr := addDFCToPodTemplate(podTemplateSpec, cr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// update security context\n\trunAsUser := int64(41812)\n\tfsGroup := int64(41812)\n\tpodTemplateSpec.Spec.SecurityContext = &corev1.PodSecurityContext{\n\t\tRunAsUser: &runAsUser,\n\t\tFSGroup: &fsGroup,\n\t}\n\n\t// prepare resource requirements\n\trequirements, err := GetSplunkRequirements(cr)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t// use script provided by enterprise container to check if pod is alive\n\tlivenessProbe := &corev1.Probe{\n\t\tHandler: corev1.Handler{\n\t\t\tExec: &corev1.ExecAction{\n\t\t\t\tCommand: []string{\n\t\t\t\t\t\"/sbin/checkstate.sh\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tInitialDelaySeconds: 300,\n\t\tTimeoutSeconds: 30,\n\t\tPeriodSeconds: 30,\n\t}\n\n\t// pod is ready if container artifact file is created with contents of \"started\".\n\t// this indicates that all the the ansible plays executed at startup have completed.\n\treadinessProbe := &corev1.Probe{\n\t\tHandler: corev1.Handler{\n\t\t\tExec: &corev1.ExecAction{\n\t\t\t\tCommand: []string{\n\t\t\t\t\t\"/bin/grep\",\n\t\t\t\t\t\"started\",\n\t\t\t\t\t\"/opt/container_artifact/splunk-container.state\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tInitialDelaySeconds: 10,\n\t\tTimeoutSeconds: 5,\n\t\tPeriodSeconds: 5,\n\t}\n\n\t// update each container in pod\n\tfor idx := range podTemplateSpec.Spec.Containers {\n\t\tpodTemplateSpec.Spec.Containers[idx].Resources = requirements\n\t\tpodTemplateSpec.Spec.Containers[idx].LivenessProbe = livenessProbe\n\t\tpodTemplateSpec.Spec.Containers[idx].ReadinessProbe = readinessProbe\n\t}\n\n\treturn nil\n}", "func resourceKeboolaTableauWriterTableUpdate(d *schema.ResourceData, meta interface{}) error {\n\tlog.Println(\"[INFO] Updating Tableau Writer Tables in Keboola.\")\n\n\tclient := meta.(*KBCClient)\n\n\twriterID := d.Get(\"writer_id\").(string)\n\ttableID := d.Get(\"title\").(string)\n\n\ttableauTableConfig := TableauTable{\n\t\tTitle: tableID,\n\t\tExport: d.Get(\"export\").(bool),\n\t}\n\n\tif d.Get(\"column\") != nil {\n\t\ttableauTableConfig.Columns = mapColumns(d)\n\t}\n\n\ttableauTableJSON, err := json.Marshal(tableauTableConfig)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttableauTableBuffer := bytes.NewBuffer(tableauTableJSON)\n\n\tupdateResponse, err := client.PostToSyrup(fmt.Sprintf(\"tde-exporter/v2/%s/tables/%s\", writerID, tableID), tableauTableBuffer)\n\n\tif hasErrors(err, updateResponse) {\n\t\treturn extractError(err, updateResponse)\n\t}\n\n\treturn resourceKeboolaTableauWriterTableRead(d, meta)\n}", "func Test_update_snapshot_rollout(t *testing.T) {\n\tappId := uuid.New()\n\tname := core.NewNamespacedName(\"myapp\", \"myns\")\n\n\tdeployments := &core.FakeDeploymentRepository{\n\t\tGetByNameFn: func(nameArg *core.NamespacedName, envName string) (*core.Deployment, error) {\n\t\t\tassert.Equal(t, name, nameArg)\n\t\t\treturn &core.Deployment{\n\t\t\t\tDeploymentReservation: core.DeploymentReservation{\n\t\t\t\t\tName: \"myapp\",\n\t\t\t\t\tAppId: appId,\n\t\t\t\t},\n\t\t\t\tDeploymentRecord: core.DeploymentRecord{\n\t\t\t\t\tDoc: core.DeploymentDoc{\n\t\t\t\t\t\tStatus: &core.DeploymentStatus{\n\t\t\t\t\t\t\tRevisions: []core.DeploymentRevisionStatus{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tRiserRevision: 1,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}, nil\n\t\t},\n\t}\n\n\tapps := &core.FakeAppRepository{\n\t\tGetFn: func(id uuid.UUID) (*core.App, error) {\n\t\t\tassert.Equal(t, appId, id)\n\t\t\treturn &core.App{\n\t\t\t\tId: id,\n\t\t\t\tName: \"myapp\",\n\t\t\t}, nil\n\t\t},\n\t}\n\n\ttraffic := core.TrafficConfig{\n\t\tcore.TrafficConfigRule{\n\t\t\tRiserRevision: 1,\n\t\t\tPercent: 100,\n\t\t},\n\t}\n\n\tsvc := service{apps, deployments}\n\n\tsnapshotPath, err := filepath.Abs(\"testdata/snapshots/rollout\")\n\trequire.NoError(t, err)\n\n\tcommitter, err := snapshot.CreateCommitter(snapshotPath)\n\trequire.NoError(t, err)\n\n\terr = svc.UpdateTraffic(name, \"dev\", traffic, committer)\n\n\tassert.NoError(t, err)\n\tif !snapshot.ShouldUpdate() {\n\t\tdryRunCommitter := committer.(*state.DryRunCommitter)\n\t\tsnapshot.AssertCommitter(t, snapshotPath, dryRunCommitter)\n\t\tassert.Equal(t, `Updating resources for \"myapp.myns\" in environment \"dev\"`, dryRunCommitter.Commits[0].Message)\n\t}\n}", "func AddPodStatus(\r\n client kubernetes.Interface,\r\n pod *corev1.Pod,\r\n options metav1.UpdateOptions,\r\n ){\r\n\r\n retryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {\r\n\r\n // Update Pod Status\r\n _ , err := client.CoreV1().Pods(pod.Namespace).UpdateStatus(context.TODO(), pod, metav1.UpdateOptions{});\r\n\r\n return err\r\n })\r\n\r\n if retryErr != nil {\r\n panic(fmt.Errorf(\"Update failed: %v\", retryErr))\r\n }\r\n\r\n}", "func TestRolling_deployInitialHooks(t *testing.T) {\n\tvar hookError error\n\n\tstrategy := &RollingDeploymentStrategy{\n\t\trcClient: fake.NewSimpleClientset().CoreV1(),\n\t\teventClient: fake.NewSimpleClientset().CoreV1(),\n\t\tinitialStrategy: &testStrategy{\n\t\t\tdeployFn: func(from *corev1.ReplicationController, to *corev1.ReplicationController, desiredReplicas int,\n\t\t\t\tupdateAcceptor strat.UpdateAcceptor) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\trollingUpdate: func(config *RollingUpdaterConfig) error {\n\t\t\treturn nil\n\t\t},\n\t\thookExecutor: &hookExecutorImpl{\n\t\t\texecuteFunc: func(hook *appsv1.LifecycleHook, deployment *corev1.ReplicationController, suffix, label string) error {\n\t\t\t\treturn hookError\n\t\t\t},\n\t\t},\n\t\tgetUpdateAcceptor: getUpdateAcceptor,\n\t\tapiRetryPeriod: 1 * time.Millisecond,\n\t\tapiRetryTimeout: 10 * time.Millisecond,\n\t}\n\n\tcases := []struct {\n\t\tparams *appsv1.RollingDeploymentStrategyParams\n\t\thookShouldFail bool\n\t\tdeploymentShouldFail bool\n\t}{\n\t\t{rollingParams(appsv1.LifecycleHookFailurePolicyAbort, \"\"), true, true},\n\t\t{rollingParams(appsv1.LifecycleHookFailurePolicyAbort, \"\"), false, false},\n\t\t{rollingParams(\"\", appsv1.LifecycleHookFailurePolicyAbort), true, true},\n\t\t{rollingParams(\"\", appsv1.LifecycleHookFailurePolicyAbort), false, false},\n\t}\n\n\tfor i, tc := range cases {\n\t\tconfig := appstest.OkDeploymentConfig(2)\n\t\tconfig.Spec.Strategy.RollingParams = tc.params\n\t\tdeployment, _ := appsutil.MakeDeployment(config)\n\t\thookError = nil\n\t\tif tc.hookShouldFail {\n\t\t\thookError = fmt.Errorf(\"hook failure\")\n\t\t}\n\t\tstrategy.out, strategy.errOut = &bytes.Buffer{}, &bytes.Buffer{}\n\t\terr := strategy.Deploy(nil, deployment, 2)\n\t\tif err != nil && tc.deploymentShouldFail {\n\t\t\tt.Logf(\"got expected error: %v\", err)\n\t\t}\n\t\tif err == nil && tc.deploymentShouldFail {\n\t\t\tt.Errorf(\"%d: expected an error for case: %v\", i, tc)\n\t\t}\n\t\tif err != nil && !tc.deploymentShouldFail {\n\t\t\tt.Errorf(\"%d: unexpected error for case: %v: %v\", i, tc, err)\n\t\t}\n\t}\n}", "func (m *MockClientInterface) RollingUpdateDeployment(arg0 *v1.Deployment) (*v1.Deployment, bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"RollingUpdateDeployment\", arg0)\n\tret0, _ := ret[0].(*v1.Deployment)\n\tret1, _ := ret[1].(bool)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func resourceKeboolaAWSRedShiftWriterTablesUpdate(d *schema.ResourceData, meta interface{}) error {\n\tlog.Println(\"[INFO] Updating AWS RedShift table in Keboola.\")\n\n\ttables := d.Get(\"table\").(*schema.Set).List()\n\n\tmappedTables := make([]AWSRedShiftWriterTable, 0, len(tables))\n\tstorageTables := make([]AWSRedShiftWriterStorageTable, 0, len(tables))\n\n\tfor _, table := range tables {\n\t\tconfig := table.(map[string]interface{})\n\n\t\tmappedTable := AWSRedShiftWriterTable{\n\t\t\tDatabaseName: config[\"db_name\"].(string),\n\t\t\tExport: config[\"export\"].(bool),\n\t\t\tTableID: config[\"table_id\"].(string),\n\t\t\tIncremental: config[\"incremental\"].(bool),\n\t\t}\n\t\tif q := config[\"primary_key\"]; q != nil {\n\t\t\tmappedTable.PrimaryKey = AsStringArray(q.([]interface{}))\n\t\t}\n\n\t\tstorageTable := AWSRedShiftWriterStorageTable{\n\t\t\tSource: mappedTable.TableID,\n\t\t\tDestination: fmt.Sprintf(\"%s.csv\", mappedTable.TableID),\n\t\t}\n\t\tif val, ok := config[\"changed_since\"]; ok {\n\t\t\tstorageTable.ChangedSince = val.(string)\n\t\t}\n\t\tif val, ok := config[\"where_column\"]; ok {\n\t\t\tstorageTable.WhereColumn = val.(string)\n\t\t}\n\n\t\tif val, ok := config[\"where_operator\"]; ok {\n\t\t\tstorageTable.WhereOperator = val.(string)\n\t\t}\n\n\t\tif q := config[\"where_values\"]; q != nil {\n\t\t\tstorageTable.WhereValues = AsStringArray(q.([]interface{}))\n\t\t}\n\n\t\titemConfigs := config[\"column\"].([]interface{})\n\t\tmappedColumns := make([]AWSRedShiftWriterTableItem, 0, len(itemConfigs))\n\t\tcolumnNames := make([]string, 0, len(itemConfigs))\n\t\tfor _, item := range itemConfigs {\n\t\t\tcolumnConfig := item.(map[string]interface{})\n\n\t\t\tmappedColumn := AWSRedShiftWriterTableItem{\n\t\t\t\tName: columnConfig[\"name\"].(string),\n\t\t\t\tDatabaseName: columnConfig[\"db_name\"].(string),\n\t\t\t\tType: columnConfig[\"type\"].(string),\n\t\t\t\tSize: columnConfig[\"size\"].(string),\n\t\t\t\tIsNullable: columnConfig[\"nullable\"].(bool),\n\t\t\t\tDefaultValue: columnConfig[\"default\"].(string),\n\t\t\t}\n\n\t\t\tmappedColumns = append(mappedColumns, mappedColumn)\n\t\t\tcolumnNames = append(columnNames, mappedColumn.Name)\n\n\t\t}\n\n\t\tmappedTable.Items = mappedColumns\n\t\tstorageTable.Columns = columnNames\n\n\t\tmappedTables = append(mappedTables, mappedTable)\n\t\tstorageTables = append(storageTables, storageTable)\n\t}\n\n\tclient := meta.(*KBCClient)\n\n\tgetWriterResponse, err := client.GetFromStorage(fmt.Sprintf(\"storage/components/keboola.wr-redshift-v2/configs/%s\", d.Id()))\n\n\tif hasErrors(err, getWriterResponse) {\n\t\treturn extractError(err, getWriterResponse)\n\t}\n\n\tvar awsredshiftWriter AWSRedShiftWriter\n\n\tdecoder := json.NewDecoder(getWriterResponse.Body)\n\terr = decoder.Decode(&awsredshiftWriter)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tawsredshiftWriter.Configuration.Parameters.Tables = mappedTables\n\tawsredshiftWriter.Configuration.Storage.Input.Tables = storageTables\n\n\tawsredshiftConfigJSON, err := json.Marshal(awsredshiftWriter.Configuration)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tupdateAWSRedShiftForm := url.Values{}\n\tupdateAWSRedShiftForm.Add(\"configuration\", string(awsredshiftConfigJSON))\n\tupdateAWSRedShiftForm.Add(\"changeDescription\", \"Update RedShift tables\")\n\n\tupdateAWSRedShiftBuffer := buffer.FromForm(updateAWSRedShiftForm)\n\n\tupdateResponse, err := client.PutToStorage(fmt.Sprintf(\"storage/components/keboola.wr-redshift-v2/configs/%s\", d.Id()), updateAWSRedShiftBuffer)\n\n\tif hasErrors(err, updateResponse) {\n\t\treturn extractError(err, updateResponse)\n\t}\n\n\treturn resourceKeboolaAWSRedShiftTablesRead(d, meta)\n}", "func (fc *FederatedController) updatePod(old, cur interface{}) {\n\tcurPod := cur.(*v1.Pod)\n\toldPod := old.(*v1.Pod)\n\n\t// no pod update, no queue\n\tif curPod.ResourceVersion == oldPod.ResourceVersion {\n\t\treturn\n\t}\n\n\tfc.addPod(curPod)\n}", "func StatefulSetRolloutStatus(sts *appsv1.StatefulSet) (string, bool, error) {\n\tif sts.Spec.UpdateStrategy.Type != appsv1.RollingUpdateStatefulSetStrategyType {\n\t\treturn \"\", true, fmt.Errorf(\"rollout status is only available for %s strategy type\", appsv1.RollingUpdateStatefulSetStrategyType)\n\t}\n\tif sts.Status.ObservedGeneration == 0 || sts.Generation > sts.Status.ObservedGeneration {\n\t\treturn \"Waiting for statefulset spec update to be observed...\\n\", false, nil\n\t}\n\tif sts.Spec.Replicas != nil && sts.Status.ReadyReplicas < *sts.Spec.Replicas {\n\t\treturn fmt.Sprintf(\"Waiting for %d pods to be ready...\\n\", *sts.Spec.Replicas-sts.Status.ReadyReplicas), false, nil\n\t}\n\tif sts.Spec.UpdateStrategy.Type == appsv1.RollingUpdateStatefulSetStrategyType && sts.Spec.UpdateStrategy.RollingUpdate != nil {\n\t\tif sts.Spec.Replicas != nil && sts.Spec.UpdateStrategy.RollingUpdate.Partition != nil {\n\t\t\tif sts.Status.UpdatedReplicas < (*sts.Spec.Replicas - *sts.Spec.UpdateStrategy.RollingUpdate.Partition) {\n\t\t\t\treturn fmt.Sprintf(\"Waiting for partitioned roll out to finish: %d out of %d new pods have been updated...\\n\",\n\t\t\t\t\tsts.Status.UpdatedReplicas, *sts.Spec.Replicas-*sts.Spec.UpdateStrategy.RollingUpdate.Partition), false, nil\n\t\t\t}\n\t\t}\n\t\treturn fmt.Sprintf(\"partitioned roll out complete: %d new pods have been updated...\\n\",\n\t\t\tsts.Status.UpdatedReplicas), true, nil\n\t}\n\tif sts.Status.UpdateRevision != sts.Status.CurrentRevision {\n\t\treturn fmt.Sprintf(\"waiting for statefulset rolling update to complete %d pods at revision %s...\\n\",\n\t\t\tsts.Status.UpdatedReplicas, sts.Status.UpdateRevision), false, nil\n\t}\n\treturn fmt.Sprintf(\"statefulset rolling update complete %d pods at revision %s...\\n\", sts.Status.CurrentReplicas, sts.Status.CurrentRevision), true, nil\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 alterPodFromTriggers(podWatch *watch.RaceFreeFakeWatcher) imageReactorFunc {\n\tcount := 2\n\treturn imageReactorFunc(func(obj runtime.Object, tagRetriever trigger.TagRetriever) error {\n\t\tpod := obj.DeepCopyObject()\n\n\t\tupdated, err := annotations.UpdateObjectFromImages(pod.(*kapi.Pod), tagRetriever)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif updated != nil {\n\t\t\tupdated.(*kapi.Pod).ResourceVersion = strconv.Itoa(count)\n\t\t\tcount++\n\t\t\tpodWatch.Modify(updated)\n\t\t}\n\t\treturn nil\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 (m *MockDeploymentClient) RollingUpdateDeployment(arg0 *v1.Deployment) (*v1.Deployment, bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"RollingUpdateDeployment\", arg0)\n\tret0, _ := ret[0].(*v1.Deployment)\n\tret1, _ := ret[1].(bool)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (ssc *StatefulSetController) updatePod(old, cur interface{}) {\n\tcurPod := cur.(*v1.Pod)\n\toldPod := old.(*v1.Pod)\n\tif curPod.ResourceVersion == oldPod.ResourceVersion {\n\t\t// Periodic resync will send update events for all known pods.\n\t\t// Two different versions of the same pod will always have different RVs.\n\t\treturn\n\t}\n\n\tlabelChanged := !reflect.DeepEqual(curPod.Labels, oldPod.Labels)\n\n\tcurControllerRef := metav1.GetControllerOf(curPod)\n\toldControllerRef := metav1.GetControllerOf(oldPod)\n\tcontrollerRefChanged := !reflect.DeepEqual(curControllerRef, oldControllerRef)\n\tif controllerRefChanged && oldControllerRef != nil {\n\t\t// The ControllerRef was changed. Sync the old controller, if any.\n\t\tif set := ssc.resolveControllerRef(oldPod.Namespace, oldControllerRef); set != nil {\n\t\t\tssc.enqueueStatefulSet(set)\n\t\t}\n\t}\n\n\t// If it has a ControllerRef, that's all that matters.\n\tif curControllerRef != nil {\n\t\tset := ssc.resolveControllerRef(curPod.Namespace, curControllerRef)\n\t\tif set == nil {\n\t\t\treturn\n\t\t}\n\t\tklog.V(4).Infof(\"Pod %s updated, objectMeta %+v -> %+v.\", curPod.Name, oldPod.ObjectMeta, curPod.ObjectMeta)\n\t\tssc.enqueueStatefulSet(set)\n\t\treturn\n\t}\n\n\t// Otherwise, it's an orphan. If anything changed, sync matching controllers\n\t// to see if anyone wants to adopt it now.\n\tif labelChanged || controllerRefChanged {\n\t\tsets := ssc.getStatefulSetsForPod(curPod)\n\t\tif len(sets) == 0 {\n\t\t\treturn\n\t\t}\n\t\tklog.V(4).Infof(\"Orphan Pod %s updated, objectMeta %+v -> %+v.\", curPod.Name, oldPod.ObjectMeta, curPod.ObjectMeta)\n\t\tfor _, set := range sets {\n\t\t\tssc.enqueueStatefulSet(set)\n\t\t}\n\t}\n}", "func TestRollingUpdateDaemonSetExistingPodAdoption(t *testing.T) {\n\tserver, closeFn, dc, informers, clientset := setup(t)\n\tdefer closeFn()\n\n\ttearDownFn := setupGC(t, server)\n\tdefer tearDownFn()\n\n\tns := framework.CreateTestingNamespace(\"rolling-update-daemonset-existing-pod-adoption-test\", server, t)\n\tdefer framework.DeleteTestingNamespace(ns, server, t)\n\n\tdsClient := clientset.AppsV1().DaemonSets(ns.Name)\n\tpodClient := clientset.CoreV1().Pods(ns.Name)\n\tnodeClient := clientset.CoreV1().Nodes()\n\tpodInformer := informers.Core().V1().Pods().Informer()\n\tcontrollerRevisionClient := clientset.AppsV1().ControllerRevisions(ns.Name)\n\tstopCh := make(chan struct{})\n\tdefer close(stopCh)\n\tinformers.Start(stopCh)\n\tgo dc.Run(5, stopCh)\n\n\t// Step 1: create a RollingUpdate DaemonSet\n\tdsName := \"daemonset\"\n\tds := newDaemonSet(dsName, ns.Name)\n\tds.Spec.UpdateStrategy = *newRollbackStrategy()\n\tds, err := dsClient.Create(ds)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create daemonset %q: %v\", dsName, err)\n\t}\n\n\tnodeName := \"single-node\"\n\tnode := newNode(nodeName, nil)\n\t_, err = nodeClient.Create(node)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create node %q: %v\", nodeName, err)\n\t}\n\n\t// Validate everything works correctly (include marking daemon pod as ready)\n\tvalidateDaemonSetPodsAndMarkReady(podClient, podInformer, 1, t)\n\tvalidateDaemonSetStatus(dsClient, ds.Name, ds.Namespace, 1, t)\n\n\t// Step 2: delete daemonset and orphan its pods\n\tdeleteDaemonSetAndOrphanPods(dsClient, podClient, controllerRevisionClient, podInformer, ds, t)\n\n\t// Step 3: create 2rd daemonset to adopt the pods (no restart) as long as template matches\n\tdsName2 := \"daemonset-adopt-template-matches\"\n\tds2 := newDaemonSet(dsName2, ns.Name)\n\tds2.Spec.UpdateStrategy = *newRollbackStrategy()\n\tds2, err = dsClient.Create(ds2)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create daemonset %q: %v\", dsName2, err)\n\t}\n\tif !apiequality.Semantic.DeepEqual(ds2.Spec.Template, ds.Spec.Template) {\n\t\tt.Fatalf(\".spec.template of new daemonset %q and old daemonset %q are not the same\", dsName2, dsName)\n\t}\n\n\t// Wait for pods and history to be adopted by 2nd daemonset\n\twaitDaemonSetAdoption(podClient, controllerRevisionClient, podInformer, ds2, ds.Name, t)\n\tvalidateDaemonSetStatus(dsClient, ds2.Name, ds2.Namespace, 1, 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 (ros *RolloutState) issueServiceRollout() (bool, error) {\n\tsm := ros.Statemgr\n\tversion := ros.Spec.Version\n\n\tserviceRollouts, err := sm.ListServiceRollouts()\n\tif err != nil {\n\t\tlog.Errorf(\"Error %v listing ServiceRollouts\", err)\n\t\treturn false, err\n\t}\n\tif len(serviceRollouts) != 0 {\n\t\tv := serviceRollouts[0]\n\t\tfound := false\n\t\tfor _, ops := range v.Spec.Ops {\n\t\t\tif ops.Op == protos.ServiceOp_ServiceRunVersion && ops.Version == version {\n\t\t\t\tfound = true\n\t\t\t}\n\t\t}\n\n\t\tstatusFound := false\n\t\tif v.status[protos.ServiceOp_ServiceRunVersion].OpStatus != \"\" {\n\t\t\tstatusFound = true\n\t\t}\n\n\t\tif !found {\n\t\t\tv.Spec.Ops = append(v.Spec.Ops, protos.ServiceOpSpec{Op: protos.ServiceOp_ServiceRunVersion, Version: version})\n\t\t\tlog.Infof(\"setting serviceRollout with version %v\", version)\n\t\t\terr = sm.memDB.UpdateObject(v)\n\t\t\treturn true, err // return pending servicerollout with err\n\t\t}\n\t\tif statusFound {\n\t\t\tlog.Infof(\"Spec and Status found. no pending serviceRollout\")\n\t\t\treturn false, nil // spec and status found. no pending servicerollout\n\t\t}\n\t\tlog.Infof(\"Spec found but no Status. pending serviceRollout\")\n\t\treturn true, nil // spec found but status not found. return pending servicerollout\n\t}\n\n\t// the servicerollout object not found - create one\n\tserviceRollout := protos.ServiceRollout{\n\t\tTypeMeta: api.TypeMeta{\n\t\t\tKind: kindServiceRollout,\n\t\t},\n\t\tObjectMeta: api.ObjectMeta{\n\t\t\tName: \"serviceRollout\",\n\t\t},\n\t\tSpec: protos.ServiceRolloutSpec{\n\t\t\tOps: []protos.ServiceOpSpec{\n\t\t\t\t{\n\t\t\t\t\tOp: protos.ServiceOp_ServiceRunVersion,\n\t\t\t\t\tVersion: version,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tlog.Infof(\"Creating serviceRollout\")\n\terr = sm.CreateServiceRolloutState(&serviceRollout, ros, nil)\n\tif err != nil {\n\t\tlog.Errorf(\"Error %v creating service rollout state\", err)\n\t}\n\treturn true, err\n}", "func (ctx *Context) updateConfigMaps(obj, newObj interface{}) {\n\tlog.Logger.Debug(\"trigger scheduler to reload configuration\")\n\t// When update event is received, it is not guaranteed the data mounted to the pod\n\t// is also updated. This is because the actual update in pod's volume is ensured\n\t// by kubelet, kubelet is checking whether the mounted ConfigMap is fresh on every\n\t// periodic sync. As a result, the total delay from the moment when the ConfigMap\n\t// is updated to the moment when new keys are projected to the pod can be as long\n\t// as kubelet sync period + ttl of ConfigMaps cache in kubelet.\n\t// We trigger configuration reload, on yunikorn-core side, it keeps checking config\n\t// file state once this is called. And the actual reload happens when it detects\n\t// actual changes on the content.\n\tctx.triggerReloadConfig()\n}", "func resourceVolterraK8SPodSecurityPolicyUpdate(d *schema.ResourceData, meta interface{}) error {\n\tclient := meta.(*APIClient)\n\n\tupdateMeta := &ves_io_schema.ObjectReplaceMetaType{}\n\tupdateSpec := &ves_io_schema_k8s_pod_security_policy.ReplaceSpecType{}\n\tupdateReq := &ves_io_schema_k8s_pod_security_policy.ReplaceRequest{\n\t\tMetadata: updateMeta,\n\t\tSpec: updateSpec,\n\t}\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\tupdateMeta.Annotations = ms\n\t}\n\n\tif v, ok := d.GetOk(\"description\"); ok && !isIntfNil(v) {\n\t\tupdateMeta.Description =\n\t\t\tv.(string)\n\t}\n\n\tif v, ok := d.GetOk(\"disable\"); ok && !isIntfNil(v) {\n\t\tupdateMeta.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\tupdateMeta.Labels = ms\n\t}\n\n\tif v, ok := d.GetOk(\"name\"); ok && !isIntfNil(v) {\n\t\tupdateMeta.Name =\n\t\t\tv.(string)\n\t}\n\n\tif v, ok := d.GetOk(\"namespace\"); ok && !isIntfNil(v) {\n\t\tupdateMeta.Namespace =\n\t\t\tv.(string)\n\t}\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.ReplaceSpecType_PspSpec{}\n\t\tconfigMethodChoiceInt.PspSpec = &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType{}\n\t\tupdateSpec.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.ReplaceSpecType_Yaml{}\n\n\t\tupdateSpec.ConfigMethodChoice = configMethodChoiceInt\n\n\t\tconfigMethodChoiceInt.Yaml = v.(string)\n\n\t}\n\n\tlog.Printf(\"[DEBUG] Updating Volterra K8SPodSecurityPolicy obj with struct: %+v\", updateReq)\n\n\terr := client.ReplaceObject(context.Background(), ves_io_schema_k8s_pod_security_policy.ObjectType, updateReq)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error updating K8SPodSecurityPolicy: %s\", err)\n\t}\n\n\treturn resourceVolterraK8SPodSecurityPolicyRead(d, meta)\n}", "func ConfigureStatefulSetForRollout(statefulSet *appsv1.StatefulSet) {\n\tstatefulSet.Spec.UpdateStrategy.Type = appsv1.RollingUpdateStatefulSetStrategyType\n\t//the canary rollout is for now directly started, the might move to a webhook instead\n\tstatefulSet.Spec.UpdateStrategy.RollingUpdate = &appsv1.RollingUpdateStatefulSetStrategy{\n\t\tPartition: pointers.Int32(util.MinInt32(*statefulSet.Spec.Replicas, statefulSet.Status.Replicas)),\n\t}\n\tstatefulSet.Annotations[AnnotationCanaryRollout] = rolloutStatePending\n\tstatefulSet.Annotations[AnnotationUpdateStartTime] = strconv.FormatInt(time.Now().Unix(), 10)\n}", "func (dn *Daemon) update(oldConfig, newConfig *mcfgv1.MachineConfig, skipCertificateWrite bool) (retErr error) {\n\toldConfig = canonicalizeEmptyMC(oldConfig)\n\n\tif dn.nodeWriter != nil {\n\t\tstate, err := getNodeAnnotationExt(dn.node, constants.MachineConfigDaemonStateAnnotationKey, true)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif state != constants.MachineConfigDaemonStateDegraded && state != constants.MachineConfigDaemonStateUnreconcilable {\n\t\t\tif err := dn.nodeWriter.SetWorking(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"error setting node's state to Working: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tdn.catchIgnoreSIGTERM()\n\tdefer func() {\n\t\t// now that we do rebootless updates, we need to turn off our SIGTERM protection\n\t\t// regardless of how we leave the \"update loop\"\n\t\tdn.cancelSIGTERM()\n\t}()\n\n\toldConfigName := oldConfig.GetName()\n\tnewConfigName := newConfig.GetName()\n\n\toldIgnConfig, err := ctrlcommon.ParseAndConvertConfig(oldConfig.Spec.Config.Raw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing old Ignition config failed: %w\", err)\n\t}\n\tnewIgnConfig, err := ctrlcommon.ParseAndConvertConfig(newConfig.Spec.Config.Raw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing new Ignition config failed: %w\", err)\n\t}\n\n\tklog.Infof(\"Checking Reconcilable for config %v to %v\", oldConfigName, newConfigName)\n\n\t// make sure we can actually reconcile this state\n\tdiff, reconcilableError := reconcilable(oldConfig, newConfig)\n\n\tif reconcilableError != nil {\n\t\twrappedErr := fmt.Errorf(\"can't reconcile config %s with %s: %w\", oldConfigName, newConfigName, reconcilableError)\n\t\tif dn.nodeWriter != nil {\n\t\t\tdn.nodeWriter.Eventf(corev1.EventTypeWarning, \"FailedToReconcile\", wrappedErr.Error())\n\t\t}\n\t\treturn &unreconcilableErr{wrappedErr}\n\t}\n\n\tlogSystem(\"Starting update from %s to %s: %+v\", oldConfigName, newConfigName, diff)\n\n\tdiffFileSet := ctrlcommon.CalculateConfigFileDiffs(&oldIgnConfig, &newIgnConfig)\n\tactions, err := calculatePostConfigChangeAction(diff, diffFileSet)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Check and perform node drain if required\n\tdrain, err := isDrainRequired(actions, diffFileSet, oldIgnConfig, newIgnConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif drain {\n\t\tif err := dn.performDrain(); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tklog.Info(\"Changes do not require drain, skipping.\")\n\t}\n\n\t// update files on disk that need updating\n\tif err := dn.updateFiles(oldIgnConfig, newIgnConfig, skipCertificateWrite); err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\tif retErr != nil {\n\t\t\tif err := dn.updateFiles(newIgnConfig, oldIgnConfig, skipCertificateWrite); err != nil {\n\t\t\t\terrs := kubeErrs.NewAggregate([]error{err, retErr})\n\t\t\t\tretErr = fmt.Errorf(\"error rolling back files writes: %w\", errs)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\t// update file permissions\n\tif err := dn.updateKubeConfigPermission(); err != nil {\n\t\treturn err\n\t}\n\n\t// only update passwd if it has changed (do not nullify)\n\t// we do not need to include SetPasswordHash in this, since only updateSSHKeys has issues on firstboot.\n\tif diff.passwd {\n\t\tif err := dn.updateSSHKeys(newIgnConfig.Passwd.Users, oldIgnConfig.Passwd.Users); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdefer func() {\n\t\t\tif retErr != nil {\n\t\t\t\tif err := dn.updateSSHKeys(newIgnConfig.Passwd.Users, oldIgnConfig.Passwd.Users); err != nil {\n\t\t\t\t\terrs := kubeErrs.NewAggregate([]error{err, retErr})\n\t\t\t\t\tretErr = fmt.Errorf(\"error rolling back SSH keys updates: %w\", errs)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\t// Set password hash\n\tif err := dn.SetPasswordHash(newIgnConfig.Passwd.Users, oldIgnConfig.Passwd.Users); err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\tif retErr != nil {\n\t\t\tif err := dn.SetPasswordHash(newIgnConfig.Passwd.Users, oldIgnConfig.Passwd.Users); err != nil {\n\t\t\t\terrs := kubeErrs.NewAggregate([]error{err, retErr})\n\t\t\t\tretErr = fmt.Errorf(\"error rolling back password hash updates: %w\", errs)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tif dn.os.IsCoreOSVariant() {\n\t\tcoreOSDaemon := CoreOSDaemon{dn}\n\t\tif err := coreOSDaemon.applyOSChanges(*diff, oldConfig, newConfig); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdefer func() {\n\t\t\tif retErr != nil {\n\t\t\t\tif err := coreOSDaemon.applyOSChanges(*diff, newConfig, oldConfig); err != nil {\n\t\t\t\t\terrs := kubeErrs.NewAggregate([]error{err, retErr})\n\t\t\t\t\tretErr = fmt.Errorf(\"error rolling back changes to OS: %w\", errs)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t} else {\n\t\tklog.Info(\"updating the OS on non-CoreOS nodes is not supported\")\n\t}\n\n\t// Ideally we would want to update kernelArguments only via MachineConfigs.\n\t// We are keeping this to maintain compatibility and OKD requirement.\n\tif err := UpdateTuningArgs(KernelTuningFile, CmdLineFile); err != nil {\n\t\treturn err\n\t}\n\n\t// At this point, we write the now expected to be \"current\" config to /etc.\n\t// When we reboot, we'll find this file and validate that we're in this state,\n\t// and that completes an update.\n\todc := &onDiskConfig{\n\t\tcurrentConfig: newConfig,\n\t}\n\n\tif err := dn.storeCurrentConfigOnDisk(odc); err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif retErr != nil {\n\t\t\todc.currentConfig = oldConfig\n\t\t\tif err := dn.storeCurrentConfigOnDisk(odc); err != nil {\n\t\t\t\terrs := kubeErrs.NewAggregate([]error{err, retErr})\n\t\t\t\tretErr = fmt.Errorf(\"error rolling back current config on disk: %w\", errs)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn dn.performPostConfigChangeAction(actions, newConfig.GetName())\n}", "func ResourceRollout(client dynamic.ResourceInterface, obj *unstructured.Unstructured, pause bool) error {\n\tkind := obj.GetKind()\n\tname := obj.GetName()\n\t// This takes care of conflicting updates for example by operator\n\t// Ref: https://github.com/kubernetes/client-go/blob/master/examples/dynamic-create-update-delete-deployment/main.go\n\tretryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {\n\t\tobjCopy, err := client.Get(context.TODO(), name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := unstructured.SetNestedField(objCopy.Object, pause, \"spec\", \"paused\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif pause {\n\t\t\taddGCLabel(objCopy)\n\t\t} else {\n\t\t\tremoveGCLabel(objCopy)\n\t\t}\n\n\t\t_, err = client.Update(context.TODO(), objCopy, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\n\tif retryErr != nil {\n\t\treturn fmt.Errorf(\"error setting 'spec.paused' to %t for %s %s: %v\", pause, kind, name, retryErr)\n\t}\n\treturn nil\n}", "func (n *NodeInfo) update(pod *v1.Pod, sign int64) {\n\t// TBD: check\n\n\tn.Generation = nextGeneration()\n}", "func (s *deploymentServer) updateDeployment(ctx context.Context, deployment *appsv1.Deployment, repo *Repository) (bool, error) {\n\tcontainers := deployment.Spec.Template.Spec.InitContainers\n\n\tif len(containers) > 0 {\n\t\tfmt.Println(\"deployment \" + deployment.Namespace + \".\" + deployment.Name + \" has initContainers\")\n\t} else {\n\t\tfmt.Println(\"deployment \" + deployment.Namespace + \".\" + deployment.Name + \" has not initContainers; can not update\")\n\t}\n\n\tvar grace int64 = 5\n\tpodsAPI := s.clientset.CoreV1().Pods(deployment.Namespace)\n\tif err := podsAPI.DeleteCollection(\n\t\tctx,\n\t\tmetav1.DeleteOptions{GracePeriodSeconds: &grace},\n\t\tmetav1.ListOptions{LabelSelector: \"sia-app=\" + deployment.Name}); err != nil {\n\t\treturn false, fmt.Errorf(\"could not find and delete pods for restart: %v\", err)\n\t}\n\n\treturn true, nil\n}", "func WebhookDeploymentReconciler(data operatingSystemManagerData) reconciling.NamedDeploymentReconcilerFactory {\n\treturn func() (string, reconciling.DeploymentReconciler) {\n\t\treturn resources.OperatingSystemManagerWebhookDeploymentName, func(dep *appsv1.Deployment) (*appsv1.Deployment, error) {\n\t\t\targs := []string{\n\t\t\t\t\"-logtostderr\",\n\t\t\t\t\"-v\", \"4\",\n\t\t\t\t\"-namespace\", \"kube-system\",\n\t\t\t}\n\n\t\t\tdep.Name = resources.OperatingSystemManagerWebhookDeploymentName\n\t\t\tdep.Labels = resources.BaseAppLabels(resources.OperatingSystemManagerWebhookDeploymentName, nil)\n\n\t\t\tdep.Spec.Replicas = resources.Int32(1)\n\t\t\tdep.Spec.Selector = &metav1.LabelSelector{\n\t\t\t\tMatchLabels: resources.BaseAppLabels(resources.OperatingSystemManagerWebhookDeploymentName, nil),\n\t\t\t}\n\n\t\t\tdep.Spec.Template.Spec.ImagePullSecrets = []corev1.LocalObjectReference{{Name: resources.ImagePullSecretName}}\n\n\t\t\tvolumes := []corev1.Volume{getWebhookKubeconfigVolume(), getServingCertVolume(), getCABundleVolume()}\n\t\t\tdep.Spec.Template.Spec.Volumes = volumes\n\n\t\t\tpodLabels, err := data.GetPodTemplateLabels(resources.OperatingSystemManagerWebhookDeploymentName, volumes, nil)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to create pod labels: %w\", err)\n\t\t\t}\n\n\t\t\tdep.Spec.Template.ObjectMeta = metav1.ObjectMeta{Labels: podLabels}\n\n\t\t\tdep.Spec.Template.Spec.InitContainers = []corev1.Container{}\n\n\t\t\trepository := registry.Must(data.RewriteImage(resources.RegistryQuay + \"/kubermatic/operating-system-manager\"))\n\t\t\tif r := data.OperatingSystemManagerImageRepository(); r != \"\" {\n\t\t\t\trepository = r\n\t\t\t}\n\n\t\t\ttag := Tag\n\t\t\tif t := data.OperatingSystemManagerImageTag(); t != \"\" {\n\t\t\t\ttag = t\n\t\t\t}\n\n\t\t\tdep.Spec.Template.Spec.Containers = []corev1.Container{\n\t\t\t\t{\n\t\t\t\t\tName: Name,\n\t\t\t\t\tImage: repository + \":\" + tag,\n\t\t\t\t\tCommand: []string{\"/usr/local/bin/webhook\"},\n\t\t\t\t\tArgs: args,\n\t\t\t\t\tEnv: []corev1.EnvVar{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"KUBECONFIG\",\n\t\t\t\t\t\t\tValue: \"/etc/kubernetes/worker-kubeconfig/kubeconfig\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tPorts: []corev1.ContainerPort{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"webhook-server\",\n\t\t\t\t\t\t\tContainerPort: 9443,\n\t\t\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tReadinessProbe: &corev1.Probe{\n\t\t\t\t\t\tProbeHandler: corev1.ProbeHandler{\n\t\t\t\t\t\t\tHTTPGet: &corev1.HTTPGetAction{\n\t\t\t\t\t\t\t\tPath: \"/readyz\",\n\t\t\t\t\t\t\t\tPort: intstr.FromInt(8081),\n\t\t\t\t\t\t\t\tScheme: corev1.URISchemeHTTP,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tFailureThreshold: 3,\n\t\t\t\t\t\tPeriodSeconds: 10,\n\t\t\t\t\t\tSuccessThreshold: 1,\n\t\t\t\t\t\tTimeoutSeconds: 15,\n\t\t\t\t\t},\n\t\t\t\t\tLivenessProbe: &corev1.Probe{\n\t\t\t\t\t\tFailureThreshold: 8,\n\t\t\t\t\t\tProbeHandler: corev1.ProbeHandler{\n\t\t\t\t\t\t\tHTTPGet: &corev1.HTTPGetAction{\n\t\t\t\t\t\t\t\tPath: \"/healthz\",\n\t\t\t\t\t\t\t\tPort: intstr.FromInt(8081),\n\t\t\t\t\t\t\t\tScheme: corev1.URISchemeHTTP,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tInitialDelaySeconds: 15,\n\t\t\t\t\t\tPeriodSeconds: 10,\n\t\t\t\t\t\tSuccessThreshold: 1,\n\t\t\t\t\t\tTimeoutSeconds: 15,\n\t\t\t\t\t},\n\t\t\t\t\tVolumeMounts: []corev1.VolumeMount{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: resources.OperatingSystemManagerWebhookKubeconfigSecretName,\n\t\t\t\t\t\t\tMountPath: \"/etc/kubernetes/worker-kubeconfig\",\n\t\t\t\t\t\t\tReadOnly: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: resources.OperatingSystemManagerWebhookServingCertSecretName,\n\t\t\t\t\t\t\tMountPath: \"/tmp/k8s-webhook-server/serving-certs\",\n\t\t\t\t\t\t\tReadOnly: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: resources.CABundleConfigMapName,\n\t\t\t\t\t\t\tMountPath: \"/etc/kubernetes/pki/ca-bundle\",\n\t\t\t\t\t\t\tReadOnly: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t\terr = resources.SetResourceRequirements(dep.Spec.Template.Spec.Containers, webhookResourceRequirements, nil, dep.Annotations)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to set resource requirements: %w\", err)\n\t\t\t}\n\n\t\t\twrappedPodSpec, err := apiserver.IsRunningWrapper(data, dep.Spec.Template.Spec, sets.New(Name))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to add apiserver.IsRunningWrapper: %w\", err)\n\t\t\t}\n\t\t\tdep.Spec.Template.Spec = *wrappedPodSpec\n\n\t\t\treturn dep, nil\n\t\t}\n\t}\n}", "func (k8s *Client) createPodLW() *cache.ListWatch {\n\tfieldSelector := selector.Everything()\n\tif k8s.nodeName != \"\" {\n\t\tfieldSelector = selector.OneTermEqualSelector(\"spec.nodeName\", k8s.nodeName)\n\t}\n\treturn cache.NewListWatchFromClient(k8s.CoreV1().RESTClient(), \"pods\", v1.NamespaceAll, fieldSelector)\n}", "func patchPods(cluster *imec_db.DB_INFRASTRUCTURE_CLUSTER, namespace string, podName string) (string, error) {\n\tlog.Println(pathLOG + \"COMPSs [patchPods] Generating 'pod patch' json ...\")\n\tlK8sPatchPod := structs.StructNewPodPatch(podName) // returns []structs.K8S_POD_PATCH_LINE\n\n\tstrTxt, _ := structs.CommPatchPodsListToString(lK8sPatchPod)\n\tlog.Println(pathLOG + \"COMPSs [patchPods] [\" + strTxt + \"]\")\n\n\t// CALL to Kubernetes API to launch a new deployment\n\tlog.Println(pathLOG + \"COMPSs [patchPods] Patching pod \" + podName + \" ...\")\n\tstatus, _, err := common.HTTPPATCHStruct(\n\t\turls.GetPathKubernetesPod(cluster, namespace, podName),\n\t\t//cfg.Config.Clusters[clusterIndex].KubernetesEndPoint+\"/api/v1/namespaces/\"+namespace+\"/pods/\"+podName,\n\t\ttrue,\n\t\tlK8sPatchPod)\n\tif err != nil {\n\t\tlog.Error(pathLOG+\"COMPSs [patchPods] ERROR\", err)\n\t\treturn \"error\", err\n\t}\n\tlog.Println(pathLOG + \"COMPSs [patchPods] RESPONSE: OK\")\n\n\treturn strconv.Itoa(status), nil\n}", "func (u *leaseUpdater) update(ctx context.Context) {\n\tlease, err := u.hubClient.CoordinationV1().Leases(u.clusterName).Get(ctx, u.leaseName, metav1.GetOptions{})\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to get cluster lease %q on hub cluster: %w\", u.leaseName, err))\n\t\treturn\n\t}\n\n\tlease.Spec.RenewTime = &metav1.MicroTime{Time: time.Now()}\n\tif _, err = u.hubClient.CoordinationV1().Leases(u.clusterName).Update(ctx, lease, metav1.UpdateOptions{}); err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to update cluster lease %q on hub cluster: %w\", u.leaseName, err))\n\t}\n}", "func (m *MockClientInterface) CreateOrRollingUpdateDeployment(arg0 *v1.Deployment) (*v1.Deployment, bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateOrRollingUpdateDeployment\", arg0)\n\tret0, _ := ret[0].(*v1.Deployment)\n\tret1, _ := ret[1].(bool)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func arangoMemberPodTemplateNeedsUpdate(ctx context.Context, log zerolog.Logger, apiObject k8sutil.APIObject, spec api.DeploymentSpec,\n\tgroup api.ServerGroup, status api.DeploymentStatus, m api.MemberStatus,\n\tcachedStatus inspectorInterface.Inspector, planCtx PlanBuilderContext) (string, bool) {\n\tchecksum, _, member, valid := getPodDetails(ctx, log, apiObject, spec, group, status, m, cachedStatus, planCtx)\n\tif valid && !member.Spec.Template.EqualPodSpecChecksum(checksum) {\n\t\treturn \"Pod Spec changed\", true\n\t}\n\n\treturn \"\", false\n}", "func RunDeploymentInformer(factory informers.SharedInformerFactory) {\n\tdeploymentInformer := factory.Apps().V1().Deployments().Informer()\n\n\tstopper := make(chan struct{})\n\tdefer close(stopper)\n\n\tdefer runtime.HandleCrash()\n\n\t// label change -->ver (2) --> policy-replicas=1\n\tdeploymentInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\t// When a resource gets updated\n\t\tUpdateFunc: func(oldObj interface{}, newObj interface{}) {\n\t\t\tdepNewObj := newObj.(*v1.Deployment)\n\t\t\tdepOldObj := oldObj.(*v1.Deployment)\n\n\t\t\toldManifest := depOldObj.GetAnnotations()[\"kubectl.kubernetes.io/last-applied-configuration\"]\n\t\t\tnewManifest := depNewObj.GetAnnotations()[\"kubectl.kubernetes.io/last-applied-configuration\"]\n\n\t\t\tif oldManifest != \"\" && newManifest != \"\" {\n\t\t\t\tvar oldDep v1.Deployment\n\t\t\t\terr := json.Unmarshal([]byte(oldManifest), &oldDep)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Print(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tvar newDep v1.Deployment\n\t\t\t\terr = json.Unmarshal([]byte(newManifest), &newDep)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Print(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif depNewObj.GetResourceVersion() != depOldObj.GetResourceVersion() && !reflect.DeepEqual(newDep, oldDep) {\n\t\t\t\t\tvar worflowid = depNewObj.GetAnnotations()[\"litmuschaos.io/workflow\"]\n\t\t\t\t\tif depNewObj.GetAnnotations()[\"litmuschaos.io/gitops\"] == \"true\" && worflowid != \"\" {\n\t\t\t\t\t\tlog.Print(\"EventType: Update \\n GitOps Notification for workflowID: %s, ResourceType: %s, ResourceName: %s, ResourceNamespace: %s\", worflowid, \"Deployment\", depNewObj.Name, depNewObj.Namespace)\n\t\t\t\t\t\terr := PolicyAuditor(\"Deployment\", depNewObj, worflowid)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlog.Print(err)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t})\n\n\tdeploymentInformer.Run(stopper)\n\tif !cache.WaitForCacheSync(stopper, deploymentInformer.HasSynced) {\n\t\truntime.HandleError(fmt.Errorf(\"Timed out waiting for caches to sync\"))\n\t\treturn\n\t}\n}", "func handleResourceUpdate(impl *controller.Impl) cache.ResourceEventHandler {\n\t// Since resources created by brokercell live in the same namespace as the brokercell, we use an\n\t// empty namespaceLabel so that the same namespace of the given object is used to enqueue.\n\tnamespaceLabel := \"\"\n\t// Resources created by the brokercell, including the indirectly created ingress service endpoints,\n\t// have such a label resources.BrokerCellLabelKey=<brokercellName>. Resources without this label\n\t// will be skipped by the function.\n\treturn controller.HandleAll(impl.EnqueueLabelOfNamespaceScopedResource(namespaceLabel, resources.BrokerCellLabelKey))\n}", "func (r *Reconciler) updateMemberPodTemplateSpec(ctx context.Context, apiObject k8sutil.APIObject,\n\tspec api.DeploymentSpec, status api.DeploymentStatus,\n\tcontext PlanBuilderContext) api.Plan {\n\tvar plan api.Plan\n\n\t// Update member specs\n\tfor _, e := range status.Members.AsList() {\n\t\tif e.Member.Phase != api.MemberPhaseNone {\n\t\t\tif reason, changed := r.arangoMemberPodTemplateNeedsUpdate(ctx, apiObject, spec, e.Group, status, e.Member, context); changed {\n\t\t\t\tplan = append(plan, actions.NewAction(api.ActionTypeArangoMemberUpdatePodSpec, e.Group, e.Member, reason))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn plan\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 (updatePodConfig) reconcile(r *FoundationDBClusterReconciler, context ctx.Context, cluster *fdbtypes.FoundationDBCluster) *requeue {\n\tlogger := log.WithValues(\"namespace\", cluster.Namespace, \"cluster\", cluster.Name, \"reconciler\", \"updatePodConfig\")\n\tconfigMap, err := internal.GetConfigMap(cluster)\n\tif err != nil {\n\t\treturn &requeue{curError: err}\n\t}\n\n\tpods, err := r.PodLifecycleManager.GetPods(r, cluster, context, internal.GetPodListOptions(cluster, \"\", \"\")...)\n\tif err != nil {\n\t\treturn &requeue{curError: err}\n\t}\n\n\tpodMap := internal.CreatePodMap(cluster, pods)\n\n\tallSynced := true\n\thasUpdate := false\n\tvar errs []error\n\t// We try to update all instances and if we observe an error we add it to the error list.\n\tfor _, processGroup := range cluster.Status.ProcessGroups {\n\t\tcurLogger := logger.WithValues(\"processGroupID\", processGroup.ProcessGroupID)\n\n\t\tif processGroup.Remove {\n\t\t\tcurLogger.V(1).Info(\"Ignore process group marked for removal\")\n\t\t\tcontinue\n\t\t}\n\n\t\tif cluster.SkipProcessGroup(processGroup) {\n\t\t\tcurLogger.Info(\"Process group has pending Pod, will be skipped\")\n\t\t\tcontinue\n\t\t}\n\n\t\tpod, ok := podMap[processGroup.ProcessGroupID]\n\t\tif !ok || pod == nil {\n\t\t\tcurLogger.Info(\"Could not find Pod for process group\")\n\t\t\t// TODO (johscheuer): we should requeue if that happens.\n\t\t\tcontinue\n\t\t}\n\n\t\tserverPerPod, err := internal.GetStorageServersPerPodForPod(pod)\n\t\tif err != nil {\n\t\t\tcurLogger.Error(err, \"Error when receiving storage server per Pod\")\n\t\t\terrs = append(errs, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tprocessClass, err := podmanager.GetProcessClass(cluster, pod)\n\t\tif err != nil {\n\t\t\tcurLogger.Error(err, \"Error when fetching process class from Pod\")\n\t\t\terrs = append(errs, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tconfigMapHash, err := internal.GetDynamicConfHash(configMap, processClass, serverPerPod)\n\t\tif err != nil {\n\t\t\tcurLogger.Error(err, \"Error when receiving dynamic ConfigMap hash\")\n\t\t\terrs = append(errs, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif pod.ObjectMeta.Annotations[fdbtypes.LastConfigMapKey] == configMapHash {\n\t\t\tcontinue\n\t\t}\n\n\t\tsynced, err := r.updatePodDynamicConf(cluster, pod)\n\t\tif !synced {\n\t\t\tallSynced = false\n\t\t\thasUpdate = true\n\t\t\tcurLogger.Error(err, \"Update Pod ConfigMap annotation\")\n\t\t\tif internal.IsNetworkError(err) {\n\t\t\t\tprocessGroup.UpdateCondition(fdbtypes.SidecarUnreachable, true, cluster.Status.ProcessGroups, processGroup.ProcessGroupID)\n\t\t\t} else {\n\t\t\t\tprocessGroup.UpdateCondition(fdbtypes.IncorrectConfigMap, true, cluster.Status.ProcessGroups, processGroup.ProcessGroupID)\n\t\t\t}\n\n\t\t\tpod.ObjectMeta.Annotations[fdbtypes.OutdatedConfigMapKey] = time.Now().Format(time.RFC3339)\n\t\t\terr = r.PodLifecycleManager.UpdateMetadata(r, context, cluster, pod)\n\t\t\tif err != nil {\n\t\t\t\tallSynced = false\n\t\t\t\tcurLogger.Error(err, \"Update Pod ConfigMap annotation\")\n\t\t\t\terrs = append(errs, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tpod.ObjectMeta.Annotations[fdbtypes.LastConfigMapKey] = configMapHash\n\t\tdelete(pod.ObjectMeta.Annotations, fdbtypes.OutdatedConfigMapKey)\n\t\terr = r.PodLifecycleManager.UpdateMetadata(r, context, cluster, pod)\n\t\tif err != nil {\n\t\t\tallSynced = false\n\t\t\tcurLogger.Error(err, \"Update Pod metadata\")\n\t\t\terrs = append(errs, err)\n\t\t}\n\n\t\thasUpdate = true\n\t\tprocessGroup.UpdateCondition(fdbtypes.SidecarUnreachable, false, cluster.Status.ProcessGroups, processGroup.ProcessGroupID)\n\t}\n\n\tif hasUpdate {\n\t\terr = r.Status().Update(context, cluster)\n\t\tif err != nil {\n\t\t\treturn &requeue{curError: err}\n\t\t}\n\t}\n\n\t// If any error has happened requeue.\n\t// We don't provide an error here since we log all errors above.\n\tif len(errs) > 0 {\n\t\treturn &requeue{message: \"errors occurred during update pod config reconcile\"}\n\t}\n\n\t// If we return an error we don't requeue\n\t// So we just return that we can't continue but don't have an error\n\tif !allSynced {\n\t\treturn &requeue{message: \"Waiting for Pod to receive ConfigMap update\", delay: podSchedulingDelayDuration}\n\t}\n\n\treturn nil\n}", "func deployment(deployment appsv1.Deployment) (*ResourceUsage, error) {\n\tvar (\n\t\tresourceOverhead float64 // max overhead compute resources (percent)\n\t\tpodOverhead int32 // max overhead pods during deployment\n\t)\n\n\treplicas := deployment.Spec.Replicas\n\tstrategy := deployment.Spec.Strategy\n\n\tif *replicas == 0 {\n\t\treturn &ResourceUsage{\n\t\t\tCPU: new(resource.Quantity),\n\t\t\tMemory: new(resource.Quantity),\n\t\t\tDetails: Details{\n\t\t\t\tVersion: deployment.APIVersion,\n\t\t\t\tKind: deployment.Kind,\n\t\t\t\tName: deployment.Name,\n\t\t\t\tReplicas: *replicas,\n\t\t\t\tMaxReplicas: *replicas,\n\t\t\t\tStrategy: string(strategy.Type),\n\t\t\t},\n\t\t}, nil\n\t}\n\n\tswitch strategy.Type {\n\tcase appsv1.RecreateDeploymentStrategyType:\n\t\t// no overhead on recreate\n\t\tresourceOverhead = 1\n\t\tpodOverhead = 0\n\tcase \"\":\n\t\t// RollingUpdate is the default an can be an empty string. If so, set the defaults\n\t\t// (https://pkg.go.dev/k8s.io/api/apps/v1?tab=doc#RollingUpdateDeployment) and continue calculation.\n\t\tdefaults := intstr.FromString(\"25%\")\n\t\tstrategy = appsv1.DeploymentStrategy{\n\t\t\tType: appsv1.RollingUpdateDeploymentStrategyType,\n\t\t\tRollingUpdate: &appsv1.RollingUpdateDeployment{\n\t\t\t\tMaxUnavailable: &defaults,\n\t\t\t\tMaxSurge: &defaults,\n\t\t\t},\n\t\t}\n\n\t\tfallthrough\n\tcase appsv1.RollingUpdateDeploymentStrategyType:\n\t\t// Documentation: https://pkg.go.dev/k8s.io/api/apps/v1?tab=doc#RollingUpdateDeployment\n\t\t// all default values are set as stated in the docs\n\t\tvar (\n\t\t\tmaxUnavailableValue intstr.IntOrString\n\t\t\tmaxSurgeValue intstr.IntOrString\n\t\t)\n\n\t\t// can be nil, if so apply default value\n\t\tif strategy.RollingUpdate == nil {\n\t\t\tmaxUnavailableValue = intstr.FromString(\"25%\")\n\t\t\tmaxSurgeValue = intstr.FromString(\"25%\")\n\t\t} else {\n\t\t\tmaxUnavailableValue = *strategy.RollingUpdate.MaxUnavailable\n\t\t\tmaxSurgeValue = *strategy.RollingUpdate.MaxSurge\n\t\t}\n\n\t\t// docs say, that the asolute number is calculated by rounding down.\n\t\tmaxUnavailable, err := intstr.GetValueFromIntOrPercent(&maxUnavailableValue, int(*replicas), false)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// docs say, absolute number is calculated by rounding up.\n\t\tmaxSurge, err := intstr.GetValueFromIntOrPercent(&maxSurgeValue, int(*replicas), true)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// podOverhead is the number of pods which can run more during a deployment\n\t\tpodOverhead = int32(maxSurge - maxUnavailable)\n\n\t\tresourceOverhead = (float64(podOverhead) / float64(*replicas)) + 1\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"deployment: %s deployment strategy %q is unknown\", deployment.Name, strategy.Type)\n\t}\n\n\tcpu, memory := podResources(&deployment.Spec.Template.Spec)\n\n\tmem := float64(memory.Value()) * float64(*replicas) * resourceOverhead\n\tmemory.Set(int64(math.Round(mem)))\n\n\tcpu.SetMilli(int64(math.Round(float64(cpu.MilliValue()) * float64(*replicas) * resourceOverhead)))\n\n\tresourceUsage := ResourceUsage{\n\t\tCPU: cpu,\n\t\tMemory: memory,\n\t\tDetails: Details{\n\t\t\tVersion: deployment.APIVersion,\n\t\t\tKind: deployment.Kind,\n\t\t\tName: deployment.Name,\n\t\t\tReplicas: *replicas,\n\t\t\tStrategy: string(strategy.Type),\n\t\t\tMaxReplicas: *replicas + podOverhead,\n\t\t},\n\t}\n\n\treturn &resourceUsage, nil\n}", "func (r *ReconcileComplianceScan) reconcileReplicatedTailoringConfigMap(scan *compv1alpha1.ComplianceScan, origName, origNs, privName, privNs, scanName string, logger logr.Logger) error {\n\tlogger.Info(\"Reconciling Tailoring ConfigMap\", \"ConfigMap.Name\", origName, \"ConfigMap.Namespace\", origNs)\n\n\torigCM := &corev1.ConfigMap{}\n\torigKey := types.NamespacedName{Name: origName, Namespace: origNs}\n\terr := r.client.Get(context.TODO(), origKey, origCM)\n\t// Tailoring ConfigMap not found\n\tif err != nil && errors.IsNotFound(err) {\n\t\t// We previously had dealt with this issue, just requeue\n\t\tif strings.HasPrefix(scan.Status.ErrorMessage, tailoringNotFoundPrefix) {\n\t\t\treturn common.NewRetriableCtrlErrorWithCustomHandler(func() (reconcile.Result, error) {\n\t\t\t\t// A ConfigMap not being found might be a temporary issue\n\t\t\t\tif r.recorder != nil {\n\t\t\t\t\tr.recorder.Eventf(\n\t\t\t\t\t\tscan, corev1.EventTypeWarning, \"TailoringError\",\n\t\t\t\t\t\t\"Tailoring ConfigMap '%s' not found\", origKey,\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\treturn reconcile.Result{RequeueAfter: requeueAfterDefault, Requeue: true}, nil\n\t\t\t}, \"Tailoring ConfigMap not found\")\n\t\t}\n\t\t// A ConfigMap not being found might be a temporary issue (update and let the reconcile loop requeue)\n\t\treturn common.NewRetriableCtrlErrorWithCustomHandler(func() (reconcile.Result, error) {\n\t\t\tif r.recorder != nil {\n\t\t\t\tr.recorder.Eventf(\n\t\t\t\t\tscan, corev1.EventTypeWarning, \"TailoringError\",\n\t\t\t\t\t\"Tailoring ConfigMap '%s' not found\", origKey,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tlog.Info(\"Updating scan status due to missing Tailoring ConfigMap\")\n\t\t\tscanCopy := scan.DeepCopy()\n\t\t\tscanCopy.Status.ErrorMessage = tailoringNotFoundPrefix + err.Error()\n\t\t\tscanCopy.Status.Result = compv1alpha1.ResultError\n\t\t\tif updateerr := r.client.Status().Update(context.TODO(), scanCopy); updateerr != nil {\n\t\t\t\tlog.Error(updateerr, \"Failed to update a scan\")\n\t\t\t\treturn reconcile.Result{}, updateerr\n\t\t\t}\n\t\t\treturn reconcile.Result{RequeueAfter: requeueAfterDefault, Requeue: true}, nil\n\t\t}, \"Tailoring ConfigMap not found\")\n\t} else if err != nil {\n\t\tlog.Error(err, \"Failed to get spec tailoring ConfigMap\", \"ConfigMap.Name\", origName, \"ConfigMap.Namespace\", origNs)\n\t\treturn err\n\t} else if scan.Status.Result == compv1alpha1.ResultError {\n\t\t// We had an error caused by a previously not found configmap. Let's remove it\n\t\tif strings.HasPrefix(scan.Status.ErrorMessage, tailoringNotFoundPrefix) {\n\t\t\treturn common.NewRetriableCtrlErrorWithCustomHandler(func() (reconcile.Result, error) {\n\t\t\t\tlog.Info(\"Updating scan status since Tailoring ConfigMap was now found\")\n\t\t\t\tscanCopy := scan.DeepCopy()\n\t\t\t\tscanCopy.Status.ErrorMessage = \"\"\n\t\t\t\tscanCopy.Status.Result = compv1alpha1.ResultNotAvailable\n\t\t\t\tif updateerr := r.client.Status().Update(context.TODO(), scanCopy); updateerr != nil {\n\t\t\t\t\tlog.Error(updateerr, \"Failed to update a scan\")\n\t\t\t\t\treturn reconcile.Result{}, updateerr\n\t\t\t\t}\n\t\t\t\treturn reconcile.Result{RequeueAfter: requeueAfterDefault, Requeue: true}, nil\n\t\t\t}, \"Tailoring ConfigMap previously not found, was now found\")\n\t\t}\n\t}\n\n\torigData, ok := origCM.Data[\"tailoring.xml\"]\n\tif !ok {\n\t\treturn common.NewNonRetriableCtrlError(\"Tailoring ConfigMap missing `tailoring.xml` key\")\n\t}\n\tif origData == \"\" {\n\t\treturn common.NewNonRetriableCtrlError(\"Tailoring ConfigMap's key `tailoring.xml` is empty\")\n\t}\n\n\tprivCM := &corev1.ConfigMap{}\n\tprivKey := types.NamespacedName{Name: privName, Namespace: privNs}\n\terr = r.client.Get(context.TODO(), privKey, privCM)\n\tif err != nil && errors.IsNotFound(err) {\n\t\tnewCM := &corev1.ConfigMap{}\n\t\tnewCM.SetName(privName)\n\t\tnewCM.SetNamespace(privNs)\n\t\tif newCM.Labels == nil {\n\t\t\tnewCM.Labels = make(map[string]string)\n\t\t}\n\t\tnewCM.Labels[compv1alpha1.ComplianceScanLabel] = scanName\n\t\tnewCM.Labels[compv1alpha1.ScriptLabel] = \"\"\n\t\tif newCM.Data == nil {\n\t\t\tnewCM.Data = make(map[string]string)\n\t\t}\n\t\tnewCM.Data[\"tailoring.xml\"] = origData\n\t\tlogger.Info(\"Creating private Tailoring ConfigMap\", \"ConfigMap.Name\", privName, \"ConfigMap.Namespace\", privNs)\n\t\terr = r.client.Create(context.TODO(), newCM)\n\t\t// Ignore error if CM already exists\n\t\tif err != nil && !errors.IsAlreadyExists(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t} else if err != nil {\n\t\tlog.Error(err, \"Failed to get private tailoring ConfigMap\", \"ConfigMap.Name\", privName, \"ConfigMap.Namespace\", privNs)\n\t\treturn err\n\t}\n\tprivData, _ := privCM.Data[\"tailoring.xml\"]\n\n\t// privCM needs update\n\tif privData != origData {\n\t\tupdatedCM := privCM.DeepCopy()\n\t\tif updatedCM.Data == nil {\n\t\t\tupdatedCM.Data = make(map[string]string)\n\t\t}\n\t\tif updatedCM.Labels == nil {\n\t\t\tupdatedCM.Labels = make(map[string]string)\n\t\t}\n\t\tupdatedCM.Labels[compv1alpha1.ComplianceScanLabel] = scanName\n\t\tupdatedCM.Labels[compv1alpha1.ScriptLabel] = \"\"\n\t\tupdatedCM.Data[\"tailoring.xml\"] = origData\n\t\tlogger.Info(\"Updating private Tailoring ConfigMap\", \"ConfigMap.Name\", privName, \"ConfigMap.Namespace\", privNs)\n\t\treturn r.client.Update(context.TODO(), updatedCM)\n\t}\n\tlogger.Info(\"Private Tailoring ConfigMap is up-to-date\", \"ConfigMap.Name\", privName, \"ConfigMap.Namespace\", privNs)\n\treturn nil\n}", "func resourceRepositoryUpdate(d *schema.ResourceData, meta interface{}) error {\n\treturn nil\n}", "func (whsvr *webhookServer) mutate(ar *v1beta1.AdmissionReview) *v1beta1.AdmissionResponse {\n\treq := ar.Request\n\tvar (\n\t\terr error\n\t\tpod corev1.Pod\n\t)\n\tswitch req.Kind.Kind {\n\tcase \"Pod\":\n\t\tklog.V(4).Infof(\"Raw request %v\", string(req.Object.Raw))\n\t\tif err := json.Unmarshal(req.Object.Raw, &pod); err != nil {\n\t\t\tklog.Errorf(\"Could not unmarshal raw object: %v\", err)\n\t\t\treturn &v1beta1.AdmissionResponse{\n\t\t\t\tResult: &metav1.Status{\n\t\t\t\t\tMessage: err.Error(),\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\tdefault:\n\t\treturn &v1beta1.AdmissionResponse{\n\t\t\tAllowed: false,\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn &v1beta1.AdmissionResponse{\n\t\t\tResult: &metav1.Status{\n\t\t\t\tMessage: err.Error(),\n\t\t\t},\n\t\t}\n\t}\n\tif req.Namespace == \"kube-system\" {\n\t\treturn &v1beta1.AdmissionResponse{\n\t\t\tAllowed: true,\n\t\t}\n\t}\n\tif pod.Labels != nil {\n\t\tif pod.Labels[util.CreatedbyDescheduler] == \"true\" {\n\t\t\treturn &v1beta1.AdmissionResponse{\n\t\t\t\tAllowed: true,\n\t\t\t}\n\t\t}\n\t}\n\n\tclone := pod.DeepCopy()\n\twhsvr.trySetNodeName(clone, req.Namespace)\n\tinject(clone, whsvr.ignoreSelectorKeys)\n\tklog.V(6).Infof(\"Final obj %+v\", clone)\n\tpatch, err := util.CreateJSONPatch(pod, clone)\n\tklog.Infof(\"Final patch %+v\", string(patch))\n\tvar result metav1.Status\n\tif err != nil {\n\t\tresult.Code = 403\n\t\tresult.Message = err.Error()\n\t}\n\tjsonPatch := v1beta1.PatchTypeJSONPatch\n\treturn &v1beta1.AdmissionResponse{\n\t\tAllowed: true,\n\t\tResult: &result,\n\t\tPatch: patch,\n\t\tPatchType: &jsonPatch,\n\t}\n}", "func (m *MockDeploymentClient) CreateOrRollingUpdateDeployment(arg0 *v1.Deployment) (*v1.Deployment, bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateOrRollingUpdateDeployment\", arg0)\n\tret0, _ := ret[0].(*v1.Deployment)\n\tret1, _ := ret[1].(bool)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m *manager) updateProvisionedBy(ctx context.Context) error {\n\tvar err error\n\tm.doc, err = m.db.PatchWithLease(ctx, m.doc.Key, func(doc *api.OpenShiftClusterDocument) error {\n\t\tdoc.OpenShiftCluster.Properties.ProvisionedBy = version.GitCommit\n\t\treturn nil\n\t})\n\treturn err\n}", "func CreateOrUpdate(ctx context.Context, log *logrus.Entry, oc *v20180930preview.OpenShiftManagedCluster, config *api.PluginConfig) (*v20180930preview.OpenShiftManagedCluster, error) {\n\t// instantiate the plugin\n\tp, errs := plugin.NewPlugin(log, config)\n\tif len(errs) > 0 {\n\t\treturn nil, kerrors.NewAggregate(errs)\n\t}\n\n\tvar err error\n\t// locate directories\n\tdataDir, err := FindDirectory(DataDirectory)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// read in the OpenShift config blob if it exists (i.e. we're updating)\n\t// in the update path, the RP should have access to the previous internal\n\t// API representation for comparison.\n\tvar oldCs *api.OpenShiftManagedCluster\n\tif IsUpdate() {\n\t\tlog.Info(\"read old config\")\n\t\toldCs, err = managedcluster.ReadConfig(filepath.Join(dataDir, \"containerservice.yaml\"))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\t// If containerservice.yaml does not exist - it is Create call\n\t\t// create DNS records only on first call\n\t\terr = CreateOCPDNS(ctx, os.Getenv(\"AZURE_SUBSCRIPTION_ID\"), os.Getenv(\"RESOURCEGROUP\"), os.Getenv(\"DNS_RESOURCEGROUP\"), os.Getenv(\"DNS_DOMAIN\"), oc)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\t// convert the external API manifest into the internal API representation\n\tlog.Info(\"convert to internal\")\n\tcs, err := api.ConvertFromV20180930preview(oc, oldCs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// the RP will enrich the internal API representation with data not included\n\t// in the original request. this should only be called during the initial\n\t// create request and not during a cluster update\n\tif !IsUpdate() {\n\t\tlog.Info(\"enrich\")\n\t\terr = enrich(cs)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// validate the internal API representation (with reference to the previous\n\t// internal API representation)\n\t// we set fqdn during enrichment which is slightly different than what the RP\n\t// will do so we are only validating once.\n\terrs = p.Validate(ctx, cs, oldCs, false)\n\tif len(errs) > 0 {\n\t\treturn nil, kerrors.NewAggregate(errs)\n\t}\n\n\t// generate or update the OpenShift config blob\n\terr = p.GenerateConfig(ctx, cs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// persist the OpenShift container service\n\tlog.Info(\"persist config\")\n\tbytes, err := yaml.Marshal(cs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = ioutil.WriteFile(filepath.Join(dataDir, \"containerservice.yaml\"), bytes, 0600)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = os.MkdirAll(filepath.Join(dataDir, \"_out\"), 0777)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// generate the ARM template\n\tazuretemplate, err := p.GenerateARM(ctx, cs, oldCs != nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// write out development files\n\tlog.Info(\"write helpers\")\n\terr = writeHelpers(cs, azuretemplate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = acceptMarketplaceAgreement(ctx, log, cs, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdeployer := GetDeployer(log, cs, config)\n\tif err := p.CreateOrUpdate(ctx, cs, azuretemplate, oldCs != nil, deployer); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// convert our (probably changed) internal API representation back to the\n\t// external API manifest to return it to the user\n\toc = api.ConvertToV20180930preview(cs)\n\n\treturn oc, nil\n}", "func (c *Config) adjust(meta *toml.MetaData) error {\n\tconfigMetaData := configutil.NewConfigMetadata(meta)\n\tif err := configMetaData.CheckUndecoded(); err != nil {\n\t\tc.WarningMsgs = append(c.WarningMsgs, err.Error())\n\t}\n\n\tif c.Name == \"\" {\n\t\thostname, err := os.Hostname()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tconfigutil.AdjustString(&c.Name, fmt.Sprintf(\"%s-%s\", defaultName, hostname))\n\t}\n\tconfigutil.AdjustString(&c.DataDir, fmt.Sprintf(\"default.%s\", c.Name))\n\tconfigutil.AdjustPath(&c.DataDir)\n\n\tif err := c.validate(); err != nil {\n\t\treturn err\n\t}\n\n\tconfigutil.AdjustString(&c.BackendEndpoints, defaultBackendEndpoints)\n\tconfigutil.AdjustString(&c.ListenAddr, defaultListenAddr)\n\tconfigutil.AdjustString(&c.AdvertiseListenAddr, c.ListenAddr)\n\n\tif !configMetaData.IsDefined(\"enable-grpc-gateway\") {\n\t\tc.EnableGRPCGateway = utils.DefaultEnableGRPCGateway\n\t}\n\n\tc.adjustLog(configMetaData.Child(\"log\"))\n\tc.Security.Encryption.Adjust()\n\n\tif len(c.Log.Format) == 0 {\n\t\tc.Log.Format = utils.DefaultLogFormat\n\t}\n\n\tconfigutil.AdjustInt64(&c.LeaderLease, utils.DefaultLeaderLease)\n\n\tif err := c.Schedule.Adjust(configMetaData.Child(\"schedule\"), false); err != nil {\n\t\treturn err\n\t}\n\treturn c.Replication.Adjust(configMetaData.Child(\"replication\"))\n}", "func reconcileBlueGreenTemplateChange(roCtx *blueGreenContext) bool {\n\tr := roCtx.Rollout()\n\tnewRS := roCtx.NewRS()\n\tif newRS == nil {\n\t\treturn true\n\t}\n\treturn r.Status.CurrentPodHash != newRS.Labels[v1alpha1.DefaultRolloutUniqueLabelKey]\n}", "func (m *MockClientInterface) RollingUpdateDeploymentMigrations(namespace, name string, f operatorclient.UpdateFunction) (*v1.Deployment, bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"RollingUpdateDeploymentMigrations\", namespace, name, f)\n\tret0, _ := ret[0].(*v1.Deployment)\n\tret1, _ := ret[1].(bool)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func createAllPodsLW(cl *client.Client) *listWatch {\n\treturn &listWatch{\n\t\tclient: cl,\n\t\tfieldSelector: labels.Everything(),\n\t\tresource: \"pods\",\n\t}\n}", "func handleResourceUpdate(impl *controller.Impl) cache.ResourceEventHandler {\n\t// Since resources created by brokercell live in the same namespace as the brokercell, we use an\n\t// empty namespaceLabel so that the same namespace of the given object is used to enqueue.\n\tnamespaceLabel := \"\"\n\t// Resources created by the brokercell, including the indirectly created ingress service endpoints,\n\t// have such a label resources.BrokerCellLabelKey=<brokercellName>. Resources without this label\n\t// will be skipped by the function.\n\treturn cache.FilteringResourceEventHandler{\n\t\tFilterFunc: pkgreconciler.LabelExistsFilterFunc(resources.BrokerCellLabelKey),\n\t\tHandler: controller.HandleAll(impl.EnqueueLabelOfNamespaceScopedResource(namespaceLabel, resources.BrokerCellLabelKey)),\n\t}\n}", "func (c *updateConfigCmd) Run(k *kong.Context, logger logging.Logger) error {\n\tlogger = logger.WithValues(\"Name\", c.Name)\n\tkubeConfig, err := ctrl.GetConfig()\n\tif err != nil {\n\t\tlogger.Debug(errKubeConfig, \"error\", err)\n\t\treturn errors.Wrap(err, errKubeConfig)\n\t}\n\tlogger.Debug(\"Found kubeconfig\")\n\tkube, err := typedclient.NewForConfig(kubeConfig)\n\tif err != nil {\n\t\tlogger.Debug(errKubeClient, \"error\", err)\n\t\treturn errors.Wrap(err, errKubeClient)\n\t}\n\tlogger.Debug(\"Created kubernetes client\")\n\tprevConf, err := kube.Configurations().Get(context.Background(), c.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\terr = warnIfNotFound(err)\n\t\tlogger.Debug(\"Failed to update configuration\", \"error\", err)\n\t\treturn errors.Wrap(err, \"cannot update configuration\")\n\t}\n\tlogger.Debug(\"Found previous configuration object\")\n\tpkg := prevConf.Spec.Package\n\tpkgReference, err := name.ParseReference(pkg, name.WithDefaultRegistry(\"\"))\n\tif err != nil {\n\t\terr = warnIfNotFound(err)\n\t\tlogger.Debug(\"Failed to update configuration\", \"error\", err)\n\t\treturn errors.Wrap(err, \"cannot update configuration\")\n\t}\n\tnewPkg := \"\"\n\tif strings.HasPrefix(c.Tag, \"sha256\") {\n\t\tnewPkg = pkgReference.Context().Digest(c.Tag).Name()\n\t} else {\n\t\tnewPkg = pkgReference.Context().Tag(c.Tag).Name()\n\t}\n\tprevConf.Spec.Package = newPkg\n\treq, err := json.Marshal(prevConf)\n\tif err != nil {\n\t\terr = warnIfNotFound(err)\n\t\tlogger.Debug(\"Failed to update configuration\", \"error\", err)\n\t\treturn errors.Wrap(err, \"cannot update configuration\")\n\t}\n\tres, err := kube.Configurations().Patch(context.Background(), c.Name, types.MergePatchType, req, metav1.PatchOptions{})\n\tif err != nil {\n\t\terr = warnIfNotFound(err)\n\t\tlogger.Debug(\"Failed to update configuration\", \"error\", err)\n\t\treturn errors.Wrap(err, \"cannot update configuration\")\n\t}\n\t_, err = fmt.Fprintf(k.Stdout, \"%s/%s updated\\n\", strings.ToLower(v1.ConfigurationGroupKind), res.GetName())\n\treturn err\n}", "func (s *K8sSvc) RollingRestartService(ctx context.Context, cluster string, service string, opts *containersvc.RollingRestartOptions) error {\n\tstartTime := metav1.Now()\n\tfor _, p := range opts.ServiceTasks {\n\t\t// delete the pod\n\t\terr := s.cliset.CoreV1().Pods(s.namespace).Delete(p, &metav1.DeleteOptions{})\n\t\tif err != nil {\n\t\t\tglog.Errorln(\"delete pod\", p, \"error\", err, \"service\", service)\n\t\t\treturn err\n\t\t}\n\n\t\topts.StatusMessage = fmt.Sprintf(\"pod %s is deleted, wait for pod terminated\", p)\n\n\t\tglog.Infoln(\"deleted pod\", p, \"service\", service, \"start time\", startTime)\n\n\t\t// currently k8s pod deletion will wait the pod.ObjectMeta.DeletionGracePeriodSeconds\n\t\t// before creating the pod again, even if the container is successfully terminated.\n\t\t// the default DeletionGracePeriodSeconds are 30 seconds.\n\t\t// here we don't want to wait the full DeletionGracePeriodSeconds. K8s would optimize\n\t\t// to terminate the old pod and create the new pod in the future. We simply check\n\t\t// every 5 seconds. So we will not need to change when K8s adds this optimization.\n\t\t// TODO could we use the Pod Watch API?\n\t\tretryWaitSeconds := time.Duration(5) * time.Second\n\t\tmaxWatiSeconds := time.Duration(common.DefaultServiceWaitSeconds) * time.Second\n\n\t\t// wait till the pod is recreated\n\t\tfor sec := time.Duration(0); sec < maxWatiSeconds; sec += retryWaitSeconds {\n\t\t\t// sleep first for the pod container to stop\n\t\t\ttime.Sleep(retryWaitSeconds)\n\n\t\t\tpod, err := s.cliset.CoreV1().Pods(s.namespace).Get(p, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\t// skip the error, simply retry\n\t\t\t\tglog.Errorln(\"get pod\", p, \"error\", err, \"service\", service)\n\t\t\t} else {\n\t\t\t\tpodready := false\n\t\t\t\tif pod.Status.Phase == corev1.PodRunning {\n\t\t\t\t\tfor _, cond := range pod.Status.Conditions {\n\t\t\t\t\t\tif cond.Type == corev1.PodReady && cond.Status == corev1.ConditionTrue && !cond.LastTransitionTime.Before(&startTime) {\n\t\t\t\t\t\t\tpodready = true\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tglog.Infoln(\"pod\", p, \"ready\", podready, \"status\", pod.Status)\n\n\t\t\t\tif podready {\n\t\t\t\t\topts.StatusMessage = fmt.Sprintf(\"pod %s is running\", p)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tfor _, cont := range pod.Status.ContainerStatuses {\n\t\t\t\t\t// the name of the main service container is the service name\n\t\t\t\t\tif cont.Name == service {\n\t\t\t\t\t\tif cont.State.Waiting != nil {\n\t\t\t\t\t\t\topts.StatusMessage = fmt.Sprintf(\"pod %s %s\", p, cont.State.Waiting.Reason)\n\t\t\t\t\t\t} else if cont.State.Terminated != nil {\n\t\t\t\t\t\t\topts.StatusMessage = fmt.Sprintf(\"pod %s is terminated, wait to run\", p)\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\topts.StatusMessage = fmt.Sprintf(\"pod %s is recreated\", p)\n\t}\n\n\tglog.Infoln(\"rolling restart service\", service)\n\treturn nil\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 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 RestartRollout(ctx context.Context, kubeClient client.Client, obj runtime.Object) error {\n\tnowString := time.Now().Format(time.RFC3339)\n\n\tpatchData := fmt.Sprintf(\"{\\\"spec\\\":{\\\"template\\\":{\\\"metadata\\\":{\\\"annotations\\\":{\\\"%s\\\":\\\"%s\\\"}}}}}\", restartAnnotation, nowString)\n\n\terr := kubeClient.Patch(ctx, obj, client.RawPatch(types.MergePatchType, []byte(patchData)))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to restart workload: %w\", err)\n\t}\n\n\treturn nil\n}", "func (dn *CoreOSDaemon) applyOSChanges(mcDiff machineConfigDiff, oldConfig, newConfig *mcfgv1.MachineConfig) (retErr error) {\n\t// We previously did not emit this event when kargs changed, so we still don't\n\tif mcDiff.osUpdate || mcDiff.extensions || mcDiff.kernelType {\n\t\t// We emitted this event before, so keep it\n\t\tif dn.nodeWriter != nil {\n\t\t\tdn.nodeWriter.Eventf(corev1.EventTypeNormal, \"InClusterUpgrade\", fmt.Sprintf(\"Updating from oscontainer %s\", newConfig.Spec.OSImageURL))\n\t\t}\n\t}\n\n\t// Only check the image type and excute OS changes if:\n\t// - machineconfig changed\n\t// - we're staying on a realtime kernel ( need to run rpm-ostree update )\n\t// - we have extensions ( need to run rpm-ostree update )\n\t// We have at least one customer that removes the pull secret from the cluster to \"shrinkwrap\" it for distribution and we want\n\t// to make sure we don't break that use case, but realtime kernel update and extensions update always ran\n\t// if they were in use, so we also need to preserve that behavior.\n\t// https://issues.redhat.com/browse/OCPBUGS-4049\n\tif mcDiff.osUpdate || mcDiff.extensions || mcDiff.kernelType || mcDiff.kargs ||\n\t\tcanonicalizeKernelType(newConfig.Spec.KernelType) == ctrlcommon.KernelTypeRealtime || len(newConfig.Spec.Extensions) > 0 {\n\n\t\t// Throw started/staged events only if there is any update required for the OS\n\t\tif dn.nodeWriter != nil {\n\t\t\tdn.nodeWriter.Eventf(corev1.EventTypeNormal, \"OSUpdateStarted\", mcDiff.osChangesString())\n\t\t}\n\n\t\tif err := dn.applyLayeredOSChanges(mcDiff, oldConfig, newConfig); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif dn.nodeWriter != nil {\n\t\t\tvar nodeName string\n\t\t\tvar nodeObjRef corev1.ObjectReference\n\t\t\tif dn.node != nil {\n\t\t\t\tnodeName = dn.node.ObjectMeta.GetName()\n\t\t\t\tnodeObjRef = corev1.ObjectReference{\n\t\t\t\t\tKind: \"Node\",\n\t\t\t\t\tName: dn.node.GetName(),\n\t\t\t\t\tUID: dn.node.GetUID(),\n\t\t\t\t}\n\t\t\t}\n\t\t\t// We send out the event OSUpdateStaged synchronously to ensure it is recorded.\n\t\t\t// Remove this when we can ensure all events are sent before exiting.\n\t\t\tt := metav1.NewTime(time.Now())\n\t\t\tevent := &corev1.Event{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: fmt.Sprintf(\"%v.%x\", nodeName, t.UnixNano()),\n\t\t\t\t\tNamespace: metav1.NamespaceDefault,\n\t\t\t\t},\n\t\t\t\tInvolvedObject: nodeObjRef,\n\t\t\t\tReason: \"OSUpdateStaged\",\n\t\t\t\tType: corev1.EventTypeNormal,\n\t\t\t\tMessage: \"Changes to OS staged\",\n\t\t\t\tFirstTimestamp: t,\n\t\t\t\tLastTimestamp: t,\n\t\t\t\tCount: 1,\n\t\t\t\tSource: corev1.EventSource{Component: \"machineconfigdaemon\", Host: dn.name},\n\t\t\t}\n\t\t\t// its ok to create a unique event for this low volume event\n\t\t\tif _, err := dn.kubeClient.CoreV1().Events(metav1.NamespaceDefault).Create(context.TODO(),\n\t\t\t\tevent, metav1.CreateOptions{}); err != nil {\n\t\t\t\tklog.Errorf(\"Failed to create event with reason 'OSUpdateStaged': %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *Config) createAssignedPodLW() *cache.ListWatch {\n\tselector := fields.ParseSelectorOrDie(\"spec.nodeName!=\" + \"\" + \",status.phase!=\" + string(api.PodSucceeded) + \",status.phase!=\" + string(api.PodFailed))\n\n\treturn cache.NewListWatchFromClient(c.Client, \"pods\", api.NamespaceAll, selector)\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 (m *MockDeploymentClient) RollingUpdateDeploymentMigrations(namespace, name string, f operatorclient.UpdateFunction) (*v1.Deployment, bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"RollingUpdateDeploymentMigrations\", namespace, name, f)\n\tret0, _ := ret[0].(*v1.Deployment)\n\tret1, _ := ret[1].(bool)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (ctx *Context) updatePod(obj, newObj interface{}) {\n\tlog.Logger.Debug(\"handling UpdatePod\")\n\told, err := utils.Convert2Pod(obj)\n\tif err != nil {\n\t\tlog.Logger.Error(\"failed to update pod\", zap.Error(err))\n\t\treturn\n\t}\n\tpod, err := utils.Convert2Pod(newObj)\n\tif err != nil {\n\t\tlog.Logger.Error(\"failed to update pod\", zap.Error(err))\n\t\treturn\n\t}\n\n\tlog.Logger.Debug(\"updatePod\",\n\t\tzap.String(\"podName\", old.Name),\n\t\tzap.String(\"oldState\", string(old.Status.Phase)),\n\t\tzap.String(\"newState\", string(pod.Status.Phase)))\n}", "func admitPod(req *v1beta1.AdmissionRequest) ([]patchOperation, error) {\n\traw := req.Object.Raw\n\tlogReq(raw)\n\t// This handler should only get called on Pod objects as per the MutatingWebhookConfiguration in the YAML file.\n\t// However, if (for whatever reason) this gets invoked on an object of a different kind, issue a log message but\n\t// let the object request pass through otherwise.\n\tif req.Resource != podResource {\n\t\tlog.Printf(\"expect resource to be %s\", podResource)\n\t\treturn nil, nil\n\t}\n\n\t// approve any pod that is in an un-monitored Namespace\n\tif !namespaceIsMonitored(req.Namespace) {\n\t\tlog.Printf(\"Approved pod name: %v namespace: %v. Namespace is exempt from webhook validation\\n\", req.Name, req.Namespace)\n\t\treturn nil, nil\n\t}\n\n\t// Parse the Pod object.\n\tpod := corev1.Pod{}\n\tif _, _, err := universalDeserializer.Decode(raw, nil, &pod); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not deserialize pod object: %v\", err)\n\t}\n\n\t// Retrieve the `runAsNonRoot` and `runAsUser` values.\n\tvar runAsNonRoot *bool\n\tvar runAsUser *int64\n\tif pod.Spec.SecurityContext != nil {\n\t\trunAsNonRoot = pod.Spec.SecurityContext.RunAsNonRoot\n\t\trunAsUser = pod.Spec.SecurityContext.RunAsUser\n\t}\n\n\t// Create patch operations to apply sensible defaults, if those options are not set explicitly.\n\tvar patches []patchOperation\n\tif runAsNonRoot == nil {\n\t\tpatches = append(patches, patchOperation{\n\t\t\tOp: \"add\",\n\t\t\tPath: \"/spec/securityContext/runAsNonRoot\",\n\t\t\t// The value must not be true if runAsUser is set to 0, as otherwise we would create a conflicting\n\t\t\t// configuration ourselves.\n\t\t\tValue: runAsUser == nil || *runAsUser != 0,\n\t\t})\n\n\t\tif runAsUser == nil {\n\t\t\tpatches = append(patches, patchOperation{\n\t\t\t\tOp: \"add\",\n\t\t\t\tPath: \"/spec/securityContext/runAsUser\",\n\t\t\t\tValue: 65534,\n\t\t\t})\n\t\t}\n\t} else if *runAsNonRoot == true && (runAsUser != nil && *runAsUser == 0) {\n\t\t// Make sure that the settings are not contradictory, and fail the object creation if they are.\n\t\treturn nil, errors.New(\"runAsNonRoot specified, but runAsUser set to 0 (the root user)\")\n\t}\n\n\treturn patches, nil\n}", "func updateConfigMapFunc(f *framework.Framework, tc *nodeConfigTestCase) error {\n\t// Clear ResourceVersion from the ConfigMap objects we use to initiate mutations\n\t// so that we don't get 409 (conflict) responses. ConfigMaps always allow updates\n\t// (with respect to concurrency control) when you omit ResourceVersion.\n\t// We know that we won't perform concurrent updates during this test.\n\ttc.configMap.ResourceVersion = \"\"\n\tcm, err := f.ClientSet.CoreV1().ConfigMaps(tc.configMap.Namespace).Update(tc.configMap)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// update tc.configMap's ResourceVersion to match the updated ConfigMap, this makes\n\t// sure our derived status checks have up-to-date information\n\ttc.configMap.ResourceVersion = cm.ResourceVersion\n\treturn nil\n}", "func (ck *clusterKinds) update() {\n\toutput, err := exec.Command(\"kubectl\", \"api-resources\").Output()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tlines := strings.Split(string(output), \"\\n\")\n\tfor _, line := range lines[1:] {\n\t\tif len(line) == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\ts := strings.Fields(line)\n\t\tkind := s[len(s)-1]\n\t\tnamespaced := s[len(s)-2] == \"true\"\n\n\t\tck.isNamespaced[kind] = namespaced\n\t}\n}", "func provideUpdatedResource(\n\tr *resource,\n\treplicationGroup *svcsdk.ReplicationGroup,\n) (*resource, error) {\n\t// Merge in the information we read from the API call above to the copy of\n\t// the original Kubernetes object we passed to the function\n\tko := r.ko.DeepCopy()\n\n\tif replicationGroup.AuthTokenEnabled != nil {\n\t\tko.Status.AuthTokenEnabled = replicationGroup.AuthTokenEnabled\n\t}\n\tif replicationGroup.AuthTokenLastModifiedDate != nil {\n\t\tko.Status.AuthTokenLastModifiedDate = &metav1.Time{*replicationGroup.AuthTokenLastModifiedDate}\n\t}\n\tif replicationGroup.AutomaticFailover != nil {\n\t\tko.Status.AutomaticFailover = replicationGroup.AutomaticFailover\n\t}\n\tif replicationGroup.ClusterEnabled != nil {\n\t\tko.Status.ClusterEnabled = replicationGroup.ClusterEnabled\n\t}\n\tif replicationGroup.ConfigurationEndpoint != nil {\n\t\tf7 := &svcapitypes.Endpoint{}\n\t\tif replicationGroup.ConfigurationEndpoint.Address != nil {\n\t\t\tf7.Address = replicationGroup.ConfigurationEndpoint.Address\n\t\t}\n\t\tif replicationGroup.ConfigurationEndpoint.Port != nil {\n\t\t\tf7.Port = replicationGroup.ConfigurationEndpoint.Port\n\t\t}\n\t\tko.Status.ConfigurationEndpoint = f7\n\t}\n\tif replicationGroup.Description != nil {\n\t\tko.Status.Description = replicationGroup.Description\n\t}\n\tif replicationGroup.GlobalReplicationGroupInfo != nil {\n\t\tf9 := &svcapitypes.GlobalReplicationGroupInfo{}\n\t\tif replicationGroup.GlobalReplicationGroupInfo.GlobalReplicationGroupId != nil {\n\t\t\tf9.GlobalReplicationGroupID = replicationGroup.GlobalReplicationGroupInfo.GlobalReplicationGroupId\n\t\t}\n\t\tif replicationGroup.GlobalReplicationGroupInfo.GlobalReplicationGroupMemberRole != nil {\n\t\t\tf9.GlobalReplicationGroupMemberRole = replicationGroup.GlobalReplicationGroupInfo.GlobalReplicationGroupMemberRole\n\t\t}\n\t\tko.Status.GlobalReplicationGroupInfo = f9\n\t}\n\tif replicationGroup.MemberClusters != nil {\n\t\tf11 := []*string{}\n\t\tfor _, f11iter := range replicationGroup.MemberClusters {\n\t\t\tvar f11elem string\n\t\t\tf11elem = *f11iter\n\t\t\tf11 = append(f11, &f11elem)\n\t\t}\n\t\tko.Status.MemberClusters = f11\n\t}\n\tif replicationGroup.MultiAZ != nil {\n\t\tko.Status.MultiAZ = replicationGroup.MultiAZ\n\t}\n\tif replicationGroup.NodeGroups != nil {\n\t\tf13 := []*svcapitypes.NodeGroup{}\n\t\tfor _, f13iter := range replicationGroup.NodeGroups {\n\t\t\tf13elem := &svcapitypes.NodeGroup{}\n\t\t\tif f13iter.NodeGroupId != nil {\n\t\t\t\tf13elem.NodeGroupID = f13iter.NodeGroupId\n\t\t\t}\n\t\t\tif f13iter.NodeGroupMembers != nil {\n\t\t\t\tf13elemf1 := []*svcapitypes.NodeGroupMember{}\n\t\t\t\tfor _, f13elemf1iter := range f13iter.NodeGroupMembers {\n\t\t\t\t\tf13elemf1elem := &svcapitypes.NodeGroupMember{}\n\t\t\t\t\tif f13elemf1iter.CacheClusterId != nil {\n\t\t\t\t\t\tf13elemf1elem.CacheClusterID = f13elemf1iter.CacheClusterId\n\t\t\t\t\t}\n\t\t\t\t\tif f13elemf1iter.CacheNodeId != nil {\n\t\t\t\t\t\tf13elemf1elem.CacheNodeID = f13elemf1iter.CacheNodeId\n\t\t\t\t\t}\n\t\t\t\t\tif f13elemf1iter.CurrentRole != nil {\n\t\t\t\t\t\tf13elemf1elem.CurrentRole = f13elemf1iter.CurrentRole\n\t\t\t\t\t}\n\t\t\t\t\tif f13elemf1iter.PreferredAvailabilityZone != nil {\n\t\t\t\t\t\tf13elemf1elem.PreferredAvailabilityZone = f13elemf1iter.PreferredAvailabilityZone\n\t\t\t\t\t}\n\t\t\t\t\tif f13elemf1iter.ReadEndpoint != nil {\n\t\t\t\t\t\tf13elemf1elemf4 := &svcapitypes.Endpoint{}\n\t\t\t\t\t\tif f13elemf1iter.ReadEndpoint.Address != nil {\n\t\t\t\t\t\t\tf13elemf1elemf4.Address = f13elemf1iter.ReadEndpoint.Address\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif f13elemf1iter.ReadEndpoint.Port != nil {\n\t\t\t\t\t\t\tf13elemf1elemf4.Port = f13elemf1iter.ReadEndpoint.Port\n\t\t\t\t\t\t}\n\t\t\t\t\t\tf13elemf1elem.ReadEndpoint = f13elemf1elemf4\n\t\t\t\t\t}\n\t\t\t\t\tf13elemf1 = append(f13elemf1, f13elemf1elem)\n\t\t\t\t}\n\t\t\t\tf13elem.NodeGroupMembers = f13elemf1\n\t\t\t}\n\t\t\tif f13iter.PrimaryEndpoint != nil {\n\t\t\t\tf13elemf2 := &svcapitypes.Endpoint{}\n\t\t\t\tif f13iter.PrimaryEndpoint.Address != nil {\n\t\t\t\t\tf13elemf2.Address = f13iter.PrimaryEndpoint.Address\n\t\t\t\t}\n\t\t\t\tif f13iter.PrimaryEndpoint.Port != nil {\n\t\t\t\t\tf13elemf2.Port = f13iter.PrimaryEndpoint.Port\n\t\t\t\t}\n\t\t\t\tf13elem.PrimaryEndpoint = f13elemf2\n\t\t\t}\n\t\t\tif f13iter.ReaderEndpoint != nil {\n\t\t\t\tf13elemf3 := &svcapitypes.Endpoint{}\n\t\t\t\tif f13iter.ReaderEndpoint.Address != nil {\n\t\t\t\t\tf13elemf3.Address = f13iter.ReaderEndpoint.Address\n\t\t\t\t}\n\t\t\t\tif f13iter.ReaderEndpoint.Port != nil {\n\t\t\t\t\tf13elemf3.Port = f13iter.ReaderEndpoint.Port\n\t\t\t\t}\n\t\t\t\tf13elem.ReaderEndpoint = f13elemf3\n\t\t\t}\n\t\t\tif f13iter.Slots != nil {\n\t\t\t\tf13elem.Slots = f13iter.Slots\n\t\t\t}\n\t\t\tif f13iter.Status != nil {\n\t\t\t\tf13elem.Status = f13iter.Status\n\t\t\t}\n\t\t\tf13 = append(f13, f13elem)\n\t\t}\n\t\tko.Status.NodeGroups = f13\n\t}\n\tif replicationGroup.PendingModifiedValues != nil {\n\t\tf14 := &svcapitypes.ReplicationGroupPendingModifiedValues{}\n\t\tif replicationGroup.PendingModifiedValues.AuthTokenStatus != nil {\n\t\t\tf14.AuthTokenStatus = replicationGroup.PendingModifiedValues.AuthTokenStatus\n\t\t}\n\t\tif replicationGroup.PendingModifiedValues.AutomaticFailoverStatus != nil {\n\t\t\tf14.AutomaticFailoverStatus = replicationGroup.PendingModifiedValues.AutomaticFailoverStatus\n\t\t}\n\t\tif replicationGroup.PendingModifiedValues.PrimaryClusterId != nil {\n\t\t\tf14.PrimaryClusterID = replicationGroup.PendingModifiedValues.PrimaryClusterId\n\t\t}\n\t\tif replicationGroup.PendingModifiedValues.Resharding != nil {\n\t\t\tf14f3 := &svcapitypes.ReshardingStatus{}\n\t\t\tif replicationGroup.PendingModifiedValues.Resharding.SlotMigration != nil {\n\t\t\t\tf14f3f0 := &svcapitypes.SlotMigration{}\n\t\t\t\tif replicationGroup.PendingModifiedValues.Resharding.SlotMigration.ProgressPercentage != nil {\n\t\t\t\t\tf14f3f0.ProgressPercentage = replicationGroup.PendingModifiedValues.Resharding.SlotMigration.ProgressPercentage\n\t\t\t\t}\n\t\t\t\tf14f3.SlotMigration = f14f3f0\n\t\t\t}\n\t\t\tf14.Resharding = f14f3\n\t\t}\n\t\tko.Status.PendingModifiedValues = f14\n\t}\n\tif replicationGroup.SnapshottingClusterId != nil {\n\t\tko.Status.SnapshottingClusterID = replicationGroup.SnapshottingClusterId\n\t}\n\tif replicationGroup.Status != nil {\n\t\tko.Status.Status = replicationGroup.Status\n\t}\n\n\treturn &resource{ko}, nil\n}", "func (a *ExistingInfraMachineReconciler) updateConfigMap(ctx context.Context, namespace, name string, updater func(*v1.ConfigMap) error) error {\n\tretryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {\n\t\tvar result v1.ConfigMap\n\t\tgetErr := a.Client.Get(ctx, client.ObjectKey{Namespace: namespace, Name: name}, &result)\n\t\tif getErr != nil {\n\t\t\tlog.Errorf(\"failed to read config map, can't reschedule: %v\", getErr)\n\t\t\treturn getErr\n\t\t}\n\t\tif err := updater(&result); err != nil {\n\t\t\tlog.Errorf(\"failed to update cluster: %v\", err)\n\t\t\treturn err\n\t\t}\n\t\tupdateErr := a.Client.Update(ctx, &result)\n\t\tif updateErr != nil {\n\t\t\tlog.Errorf(\"failed to reschedule config map: %v\", updateErr)\n\t\t\treturn updateErr\n\t\t}\n\t\treturn nil\n\t})\n\tif retryErr != nil {\n\t\tlog.Errorf(\"failed to update config map: %v\", retryErr)\n\t\treturn retryErr\n\t}\n\treturn nil\n}", "func (t *typhaAutoscaler) updateReplicas(expectedReplicas int32) error {\n\tkey := types.NamespacedName{Namespace: common.CalicoNamespace, Name: common.TyphaDeploymentName}\n\ttypha := &appsv1.Deployment{}\n\terr := t.client.Get(context.Background(), key, typha)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// The replicas field defaults to 1. We need this in case spec.Replicas is nil.\n\tvar prevReplicas int32\n\tprevReplicas = 1\n\tif typha.Spec.Replicas != nil {\n\t\tprevReplicas = *typha.Spec.Replicas\n\t}\n\n\tif prevReplicas == expectedReplicas {\n\t\treturn nil\n\t}\n\n\ttyphaLog.Info(fmt.Sprintf(\"Updating typha replicas from %d to %d\", prevReplicas, expectedReplicas))\n\ttypha.Spec.Replicas = &expectedReplicas\n\treturn t.client.Update(context.Background(), typha)\n}", "func applyToDeploymentPodSpec(dep *appsv1.Deployment, f func(*corev1.PodSpec)) {\n\tf(&dep.Spec.Template.Spec)\n}", "func (m *MockClientInterface) RollingPatchDeployment(arg0, arg1 *v1.Deployment) (*v1.Deployment, bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"RollingPatchDeployment\", arg0, arg1)\n\tret0, _ := ret[0].(*v1.Deployment)\n\tret1, _ := ret[1].(bool)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (c *HAProxyController) updateHAProxy() {\n\tlogger.Trace(\"HAProxy config sync started\")\n\n\terr := c.Client.APIStartTransaction()\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn\n\t}\n\tdefer func() {\n\t\tc.Client.APIDisposeTransaction()\n\t}()\n\n\treload, restart := c.handleGlobalConfig()\n\n\tif route.CustomRoutes {\n\t\tlogger.Error(route.RoutesReset(c.Client))\n\t\troute.CustomRoutes = false\n\t}\n\n\tfor _, namespace := range c.Store.Namespaces {\n\t\tif !namespace.Relevant {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, ingress := range namespace.Ingresses {\n\t\t\tif ingress.Status == DELETED {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !c.igClassIsSupported(ingress) {\n\t\t\t\tlogger.Debugf(\"ingress '%s/%s' ignored: no matching IngressClass\", ingress.Namespace, ingress.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif c.PublishService != nil {\n\t\t\t\tlogger.Error(c.k8s.UpdateIngressStatus(ingress, c.PublishService))\n\t\t\t}\n\t\t\tif ingress.DefaultBackend != nil {\n\t\t\t\tif r, errSvc := c.setDefaultService(ingress, []string{c.Cfg.FrontHTTP, c.Cfg.FrontHTTPS}); errSvc != nil {\n\t\t\t\t\tlogger.Errorf(\"Ingress '%s/%s': default backend: %s\", ingress.Namespace, ingress.Name, errSvc)\n\t\t\t\t} else {\n\t\t\t\t\treload = reload || r\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Ingress secrets\n\t\t\tlogger.Tracef(\"ingress '%s/%s': processing secrets...\", ingress.Namespace, ingress.Name)\n\t\t\tfor _, tls := range ingress.TLS {\n\t\t\t\tif tls.Status == store.DELETED {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tcrt, updated, _ := c.Cfg.Certificates.HandleTLSSecret(c.Store, haproxy.SecretCtx{\n\t\t\t\t\tDefaultNS: ingress.Namespace,\n\t\t\t\t\tSecretPath: tls.SecretName.Value,\n\t\t\t\t\tSecretType: haproxy.FT_CERT,\n\t\t\t\t})\n\t\t\t\tif crt != \"\" && updated {\n\t\t\t\t\treload = true\n\t\t\t\t\tlogger.Debugf(\"Secret '%s' in ingress '%s/%s' was updated, reload required\", tls.SecretName.Value, ingress.Namespace, ingress.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Ingress annotations\n\t\t\tlogger.Tracef(\"ingress '%s/%s': processing annotations...\", ingress.Namespace, ingress.Name)\n\t\t\tif len(ingress.Rules) == 0 {\n\t\t\t\tlogger.Debugf(\"Ingress %s/%s: no rules defined\", ingress.Namespace, ingress.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc.handleIngressAnnotations(ingress)\n\t\t\t// Ingress rules\n\t\t\tlogger.Tracef(\"ingress '%s/%s': processing rules...\", ingress.Namespace, ingress.Name)\n\t\t\tfor _, rule := range ingress.Rules {\n\t\t\t\tfor _, path := range rule.Paths {\n\t\t\t\t\tif r, errIng := c.handleIngressPath(ingress, rule.Host, path); errIng != nil {\n\t\t\t\t\t\tlogger.Errorf(\"Ingress '%s/%s': %s\", ingress.Namespace, ingress.Name, errIng)\n\t\t\t\t\t} else {\n\t\t\t\t\t\treload = reload || r\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, handler := range c.UpdateHandlers {\n\t\tr, errHandler := handler.Update(c.Store, &c.Cfg, c.Client)\n\t\tlogger.Error(errHandler)\n\t\treload = reload || r\n\t}\n\n\terr = c.Client.APICommitTransaction()\n\tif err != nil {\n\t\tlogger.Error(\"unable to Sync HAProxy configuration !!\")\n\t\tlogger.Error(err)\n\t\tc.clean(true)\n\t\treturn\n\t}\n\tc.clean(false)\n\tif !c.ready {\n\t\tc.setToReady()\n\t}\n\tswitch {\n\tcase restart:\n\t\tif err = c.haproxyService(\"restart\"); err != nil {\n\t\t\tlogger.Error(err)\n\t\t} else {\n\t\t\tlogger.Info(\"HAProxy restarted\")\n\t\t}\n\tcase reload:\n\t\tif err = c.haproxyService(\"reload\"); err != nil {\n\t\t\tlogger.Error(err)\n\t\t} else {\n\t\t\tlogger.Info(\"HAProxy reloaded\")\n\t\t}\n\t}\n\n\tlogger.Trace(\"HAProxy config sync ended\")\n}", "func (rm *resourceManager) sdkUpdate(\n\tctx context.Context,\n\tdesired *resource,\n\tlatest *resource,\n\tdiffReporter *ackcompare.Reporter,\n) (*resource, error) {\n\n\tcustomResp, customRespErr := rm.CustomModifyReplicationGroup(ctx, desired, latest, diffReporter)\n\tif customResp != nil || customRespErr != nil {\n\t\treturn customResp, customRespErr\n\t}\n\n\tinput, err := rm.newUpdateRequestPayload(desired)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, respErr := rm.sdkapi.ModifyReplicationGroupWithContext(ctx, input)\n\trm.metrics.RecordAPICall(\"UPDATE\", \"ModifyReplicationGroup\", respErr)\n\tif respErr != nil {\n\t\treturn nil, respErr\n\t}\n\t// Merge in the information we read from the API call above to the copy of\n\t// the original Kubernetes object we passed to the function\n\tko := desired.ko.DeepCopy()\n\n\tif ko.Status.ACKResourceMetadata == nil {\n\t\tko.Status.ACKResourceMetadata = &ackv1alpha1.ResourceMetadata{}\n\t}\n\tif resp.ReplicationGroup.ARN != nil {\n\t\tarn := ackv1alpha1.AWSResourceName(*resp.ReplicationGroup.ARN)\n\t\tko.Status.ACKResourceMetadata.ARN = &arn\n\t}\n\tif resp.ReplicationGroup.AuthTokenEnabled != nil {\n\t\tko.Status.AuthTokenEnabled = resp.ReplicationGroup.AuthTokenEnabled\n\t}\n\tif resp.ReplicationGroup.AuthTokenLastModifiedDate != nil {\n\t\tko.Status.AuthTokenLastModifiedDate = &metav1.Time{*resp.ReplicationGroup.AuthTokenLastModifiedDate}\n\t}\n\tif resp.ReplicationGroup.AutomaticFailover != nil {\n\t\tko.Status.AutomaticFailover = resp.ReplicationGroup.AutomaticFailover\n\t}\n\tif resp.ReplicationGroup.ClusterEnabled != nil {\n\t\tko.Status.ClusterEnabled = resp.ReplicationGroup.ClusterEnabled\n\t}\n\tif resp.ReplicationGroup.ConfigurationEndpoint != nil {\n\t\tf7 := &svcapitypes.Endpoint{}\n\t\tif resp.ReplicationGroup.ConfigurationEndpoint.Address != nil {\n\t\t\tf7.Address = resp.ReplicationGroup.ConfigurationEndpoint.Address\n\t\t}\n\t\tif resp.ReplicationGroup.ConfigurationEndpoint.Port != nil {\n\t\t\tf7.Port = resp.ReplicationGroup.ConfigurationEndpoint.Port\n\t\t}\n\t\tko.Status.ConfigurationEndpoint = f7\n\t}\n\tif resp.ReplicationGroup.Description != nil {\n\t\tko.Status.Description = resp.ReplicationGroup.Description\n\t}\n\tif resp.ReplicationGroup.GlobalReplicationGroupInfo != nil {\n\t\tf9 := &svcapitypes.GlobalReplicationGroupInfo{}\n\t\tif resp.ReplicationGroup.GlobalReplicationGroupInfo.GlobalReplicationGroupId != nil {\n\t\t\tf9.GlobalReplicationGroupID = resp.ReplicationGroup.GlobalReplicationGroupInfo.GlobalReplicationGroupId\n\t\t}\n\t\tif resp.ReplicationGroup.GlobalReplicationGroupInfo.GlobalReplicationGroupMemberRole != nil {\n\t\t\tf9.GlobalReplicationGroupMemberRole = resp.ReplicationGroup.GlobalReplicationGroupInfo.GlobalReplicationGroupMemberRole\n\t\t}\n\t\tko.Status.GlobalReplicationGroupInfo = f9\n\t}\n\tif resp.ReplicationGroup.MemberClusters != nil {\n\t\tf11 := []*string{}\n\t\tfor _, f11iter := range resp.ReplicationGroup.MemberClusters {\n\t\t\tvar f11elem string\n\t\t\tf11elem = *f11iter\n\t\t\tf11 = append(f11, &f11elem)\n\t\t}\n\t\tko.Status.MemberClusters = f11\n\t}\n\tif resp.ReplicationGroup.MemberClustersOutpostArns != nil {\n\t\tf12 := []*string{}\n\t\tfor _, f12iter := range resp.ReplicationGroup.MemberClustersOutpostArns {\n\t\t\tvar f12elem string\n\t\t\tf12elem = *f12iter\n\t\t\tf12 = append(f12, &f12elem)\n\t\t}\n\t\tko.Status.MemberClustersOutpostARNs = f12\n\t}\n\tif resp.ReplicationGroup.MultiAZ != nil {\n\t\tko.Status.MultiAZ = resp.ReplicationGroup.MultiAZ\n\t}\n\tif resp.ReplicationGroup.NodeGroups != nil {\n\t\tf14 := []*svcapitypes.NodeGroup{}\n\t\tfor _, f14iter := range resp.ReplicationGroup.NodeGroups {\n\t\t\tf14elem := &svcapitypes.NodeGroup{}\n\t\t\tif f14iter.NodeGroupId != nil {\n\t\t\t\tf14elem.NodeGroupID = f14iter.NodeGroupId\n\t\t\t}\n\t\t\tif f14iter.NodeGroupMembers != nil {\n\t\t\t\tf14elemf1 := []*svcapitypes.NodeGroupMember{}\n\t\t\t\tfor _, f14elemf1iter := range f14iter.NodeGroupMembers {\n\t\t\t\t\tf14elemf1elem := &svcapitypes.NodeGroupMember{}\n\t\t\t\t\tif f14elemf1iter.CacheClusterId != nil {\n\t\t\t\t\t\tf14elemf1elem.CacheClusterID = f14elemf1iter.CacheClusterId\n\t\t\t\t\t}\n\t\t\t\t\tif f14elemf1iter.CacheNodeId != nil {\n\t\t\t\t\t\tf14elemf1elem.CacheNodeID = f14elemf1iter.CacheNodeId\n\t\t\t\t\t}\n\t\t\t\t\tif f14elemf1iter.CurrentRole != nil {\n\t\t\t\t\t\tf14elemf1elem.CurrentRole = f14elemf1iter.CurrentRole\n\t\t\t\t\t}\n\t\t\t\t\tif f14elemf1iter.PreferredAvailabilityZone != nil {\n\t\t\t\t\t\tf14elemf1elem.PreferredAvailabilityZone = f14elemf1iter.PreferredAvailabilityZone\n\t\t\t\t\t}\n\t\t\t\t\tif f14elemf1iter.PreferredOutpostArn != nil {\n\t\t\t\t\t\tf14elemf1elem.PreferredOutpostARN = f14elemf1iter.PreferredOutpostArn\n\t\t\t\t\t}\n\t\t\t\t\tif f14elemf1iter.ReadEndpoint != nil {\n\t\t\t\t\t\tf14elemf1elemf5 := &svcapitypes.Endpoint{}\n\t\t\t\t\t\tif f14elemf1iter.ReadEndpoint.Address != nil {\n\t\t\t\t\t\t\tf14elemf1elemf5.Address = f14elemf1iter.ReadEndpoint.Address\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif f14elemf1iter.ReadEndpoint.Port != nil {\n\t\t\t\t\t\t\tf14elemf1elemf5.Port = f14elemf1iter.ReadEndpoint.Port\n\t\t\t\t\t\t}\n\t\t\t\t\t\tf14elemf1elem.ReadEndpoint = f14elemf1elemf5\n\t\t\t\t\t}\n\t\t\t\t\tf14elemf1 = append(f14elemf1, f14elemf1elem)\n\t\t\t\t}\n\t\t\t\tf14elem.NodeGroupMembers = f14elemf1\n\t\t\t}\n\t\t\tif f14iter.PrimaryEndpoint != nil {\n\t\t\t\tf14elemf2 := &svcapitypes.Endpoint{}\n\t\t\t\tif f14iter.PrimaryEndpoint.Address != nil {\n\t\t\t\t\tf14elemf2.Address = f14iter.PrimaryEndpoint.Address\n\t\t\t\t}\n\t\t\t\tif f14iter.PrimaryEndpoint.Port != nil {\n\t\t\t\t\tf14elemf2.Port = f14iter.PrimaryEndpoint.Port\n\t\t\t\t}\n\t\t\t\tf14elem.PrimaryEndpoint = f14elemf2\n\t\t\t}\n\t\t\tif f14iter.ReaderEndpoint != nil {\n\t\t\t\tf14elemf3 := &svcapitypes.Endpoint{}\n\t\t\t\tif f14iter.ReaderEndpoint.Address != nil {\n\t\t\t\t\tf14elemf3.Address = f14iter.ReaderEndpoint.Address\n\t\t\t\t}\n\t\t\t\tif f14iter.ReaderEndpoint.Port != nil {\n\t\t\t\t\tf14elemf3.Port = f14iter.ReaderEndpoint.Port\n\t\t\t\t}\n\t\t\t\tf14elem.ReaderEndpoint = f14elemf3\n\t\t\t}\n\t\t\tif f14iter.Slots != nil {\n\t\t\t\tf14elem.Slots = f14iter.Slots\n\t\t\t}\n\t\t\tif f14iter.Status != nil {\n\t\t\t\tf14elem.Status = f14iter.Status\n\t\t\t}\n\t\t\tf14 = append(f14, f14elem)\n\t\t}\n\t\tko.Status.NodeGroups = f14\n\t}\n\tif resp.ReplicationGroup.PendingModifiedValues != nil {\n\t\tf15 := &svcapitypes.ReplicationGroupPendingModifiedValues{}\n\t\tif resp.ReplicationGroup.PendingModifiedValues.AuthTokenStatus != nil {\n\t\t\tf15.AuthTokenStatus = resp.ReplicationGroup.PendingModifiedValues.AuthTokenStatus\n\t\t}\n\t\tif resp.ReplicationGroup.PendingModifiedValues.AutomaticFailoverStatus != nil {\n\t\t\tf15.AutomaticFailoverStatus = resp.ReplicationGroup.PendingModifiedValues.AutomaticFailoverStatus\n\t\t}\n\t\tif resp.ReplicationGroup.PendingModifiedValues.PrimaryClusterId != nil {\n\t\t\tf15.PrimaryClusterID = resp.ReplicationGroup.PendingModifiedValues.PrimaryClusterId\n\t\t}\n\t\tif resp.ReplicationGroup.PendingModifiedValues.Resharding != nil {\n\t\t\tf15f3 := &svcapitypes.ReshardingStatus{}\n\t\t\tif resp.ReplicationGroup.PendingModifiedValues.Resharding.SlotMigration != nil {\n\t\t\t\tf15f3f0 := &svcapitypes.SlotMigration{}\n\t\t\t\tif resp.ReplicationGroup.PendingModifiedValues.Resharding.SlotMigration.ProgressPercentage != nil {\n\t\t\t\t\tf15f3f0.ProgressPercentage = resp.ReplicationGroup.PendingModifiedValues.Resharding.SlotMigration.ProgressPercentage\n\t\t\t\t}\n\t\t\t\tf15f3.SlotMigration = f15f3f0\n\t\t\t}\n\t\t\tf15.Resharding = f15f3\n\t\t}\n\t\tif resp.ReplicationGroup.PendingModifiedValues.UserGroups != nil {\n\t\t\tf15f4 := &svcapitypes.UserGroupsUpdateStatus{}\n\t\t\tif resp.ReplicationGroup.PendingModifiedValues.UserGroups.UserGroupIdsToAdd != nil {\n\t\t\t\tf15f4f0 := []*string{}\n\t\t\t\tfor _, f15f4f0iter := range resp.ReplicationGroup.PendingModifiedValues.UserGroups.UserGroupIdsToAdd {\n\t\t\t\t\tvar f15f4f0elem string\n\t\t\t\t\tf15f4f0elem = *f15f4f0iter\n\t\t\t\t\tf15f4f0 = append(f15f4f0, &f15f4f0elem)\n\t\t\t\t}\n\t\t\t\tf15f4.UserGroupIDsToAdd = f15f4f0\n\t\t\t}\n\t\t\tif resp.ReplicationGroup.PendingModifiedValues.UserGroups.UserGroupIdsToRemove != nil {\n\t\t\t\tf15f4f1 := []*string{}\n\t\t\t\tfor _, f15f4f1iter := range resp.ReplicationGroup.PendingModifiedValues.UserGroups.UserGroupIdsToRemove {\n\t\t\t\t\tvar f15f4f1elem string\n\t\t\t\t\tf15f4f1elem = *f15f4f1iter\n\t\t\t\t\tf15f4f1 = append(f15f4f1, &f15f4f1elem)\n\t\t\t\t}\n\t\t\t\tf15f4.UserGroupIDsToRemove = f15f4f1\n\t\t\t}\n\t\t\tf15.UserGroups = f15f4\n\t\t}\n\t\tko.Status.PendingModifiedValues = f15\n\t}\n\tif resp.ReplicationGroup.SnapshottingClusterId != nil {\n\t\tko.Status.SnapshottingClusterID = resp.ReplicationGroup.SnapshottingClusterId\n\t}\n\tif resp.ReplicationGroup.Status != nil {\n\t\tko.Status.Status = resp.ReplicationGroup.Status\n\t}\n\n\trm.setStatusDefaults(ko)\n\n\t// custom set output from response\n\tko, err = rm.CustomModifyReplicationGroupSetOutput(ctx, desired, resp, ko)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &resource{ko}, nil\n}", "func patch(cli client.Client) error {\n\tpatch := &unstructured.Unstructured{}\n\tpatch.SetGroupVersionKind(schema.GroupVersionKind{\n\t\tGroup: \"apps\",\n\t\tVersion: \"v1\",\n\t\tKind: \"Deployment\",\n\t})\n\tpatch.SetNamespace(\"default\")\n\tpatch.SetName(\"test\")\n\tpatch.UnstructuredContent()[\"spec\"] = map[string]interface{}{\n\t\t\"replicas\": 2,\n\t}\n\n\terr := cli.Patch(context.Background(), patch, client.Apply, &client.PatchOptions{\n\t\tFieldManager: \"misc\",\n\t})\n\n\treturn err\n}", "func calculateStatus(allRSs []*apps.ReplicaSet, newRS *apps.ReplicaSet, deployment *apps.Deployment) apps.DeploymentStatus {\n\tavailableReplicas := deploymentutil.GetAvailableReplicaCountForReplicaSets(allRSs)\n\ttotalReplicas := deploymentutil.GetReplicaCountForReplicaSets(allRSs)\n\tunavailableReplicas := totalReplicas - availableReplicas\n\t// If unavailableReplicas is negative, then that means the Deployment has more available replicas running than\n\t// desired, e.g. whenever it scales down. In such a case we should simply default unavailableReplicas to zero.\n\tif unavailableReplicas < 0 {\n\t\tunavailableReplicas = 0\n\t}\n\n\tstatus := apps.DeploymentStatus{\n\t\t// TODO: Ensure that if we start retrying status updates, we won't pick up a new Generation value.\n\t\tObservedGeneration: deployment.Generation,\n\t\tReplicas: deploymentutil.GetActualReplicaCountForReplicaSets(allRSs),\n\t\tUpdatedReplicas: deploymentutil.GetActualReplicaCountForReplicaSets([]*apps.ReplicaSet{newRS}),\n\t\tReadyReplicas: deploymentutil.GetReadyReplicaCountForReplicaSets(allRSs),\n\t\tAvailableReplicas: availableReplicas,\n\t\tUnavailableReplicas: unavailableReplicas,\n\t\tCollisionCount: deployment.Status.CollisionCount,\n\t}\n\n\t// Copy conditions one by one so we won't mutate the original object.\n\tconditions := deployment.Status.Conditions\n\tfor i := range conditions {\n\t\tstatus.Conditions = append(status.Conditions, conditions[i])\n\t}\n\n\tif availableReplicas >= *(deployment.Spec.Replicas)-deploymentutil.MaxUnavailable(*deployment) {\n\t\tminAvailability := deploymentutil.NewDeploymentCondition(apps.DeploymentAvailable, v1.ConditionTrue, deploymentutil.MinimumReplicasAvailable, \"Deployment has minimum availability.\")\n\t\tdeploymentutil.SetDeploymentCondition(&status, *minAvailability)\n\t} else {\n\t\tnoMinAvailability := deploymentutil.NewDeploymentCondition(apps.DeploymentAvailable, v1.ConditionFalse, deploymentutil.MinimumReplicasUnavailable, \"Deployment does not have minimum availability.\")\n\t\tdeploymentutil.SetDeploymentCondition(&status, *noMinAvailability)\n\t}\n\n\treturn status\n}", "func add(mgr manager.Manager, r *MemberRollReconciler) error {\n\tlog := createLogger()\n\tctx := common.NewContextWithLog(common.NewContext(), log)\n\n\t// Create a new controller\n\twrappedReconciler := common.NewConflictHandlingReconciler(r)\n\tc, err := controller.New(controllerName, mgr, controller.Options{MaxConcurrentReconciles: common.Config.Controller.MemberRollReconcilers, Reconciler: wrappedReconciler})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource ServiceMeshMemberRoll\n\terr = c.Watch(&source.Kind{Type: &v1.ServiceMeshMemberRoll{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// TODO: should this be moved somewhere else?\n\terr = mgr.GetFieldIndexer().IndexField(ctx, &v1.ServiceMeshMemberRoll{}, \"spec.members\", func(obj runtime.Object) []string {\n\t\troll := obj.(*v1.ServiceMeshMemberRoll)\n\t\treturn roll.Spec.Members\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// watch namespaces and trigger reconcile requests as those that match a member roll come and go\n\terr = c.Watch(&source.Kind{Type: &corev1.Namespace{}}, &handler.EnqueueRequestsFromMapFunc{\n\t\tToRequests: handler.ToRequestsFunc(func(ns handler.MapObject) []reconcile.Request {\n\t\t\tlist := &v1.ServiceMeshMemberRollList{}\n\t\t\terr := mgr.GetClient().List(ctx, list, client.MatchingFields{\"spec.members\": ns.Meta.GetName()})\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(err, \"Could not list ServiceMeshMemberRolls\")\n\t\t\t}\n\n\t\t\tvar requests []reconcile.Request\n\t\t\tfor _, smmr := range list.Items {\n\t\t\t\trequests = append(requests, reconcile.Request{\n\t\t\t\t\tNamespacedName: common.ToNamespacedName(&smmr),\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn requests\n\t\t}),\n\t}, predicate.Funcs{\n\t\tGenericFunc: func(_ event.GenericEvent) bool {\n\t\t\t// we don't need to process the member roll on generic events\n\t\t\treturn false\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// watch control planes and trigger reconcile requests as they come and go\n\terr = c.Watch(&source.Kind{Type: &v2.ServiceMeshControlPlane{}}, &handler.EnqueueRequestsFromMapFunc{\n\t\tToRequests: handler.ToRequestsFunc(func(smcpMap handler.MapObject) []reconcile.Request {\n\t\t\tnamespacedName := types.NamespacedName{Name: common.MemberRollName, Namespace: smcpMap.Meta.GetNamespace()}\n\t\t\terr := mgr.GetClient().Get(ctx, namespacedName, &v1.ServiceMeshMemberRoll{})\n\t\t\tif err != nil {\n\t\t\t\tif !errors.IsNotFound(err) {\n\t\t\t\t\tlog.Error(err, \"Could not list ServiceMeshMemberRolls\")\n\t\t\t\t}\n\t\t\t\treturn []reconcile.Request{}\n\t\t\t}\n\n\t\t\treturn []reconcile.Request{{NamespacedName: namespacedName}}\n\t\t}),\n\t}, predicate.Funcs{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (m *kubePackage) kubeUpdate(ctx context.Context, r *apiResource, msg proto.Message) error {\n\turi := r.PathWithName()\n\tlive, found, err := m.kubePeek(ctx, m.Master+uri)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmethod := http.MethodPut\n\tif found {\n\t\t// Reset uri in case subresource update is requested.\n\t\turi = r.PathWithSubresource()\n\t\tif err := maybeRecreate(ctx, live, msg.(runtime.Object), m, r); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else { // Object doesn't exist so create it.\n\t\tif r.Subresource != \"\" {\n\t\t\treturn errors.New(\"parent resource does not exist\")\n\t\t}\n\n\t\tmethod = http.MethodPost\n\t\turi = r.Path()\n\t}\n\n\tbs, err := marshal(msg, r.GVK)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\turl := m.Master + uri\n\t// Set body type as marshaled Protobuf.\n\t// TODO(dmitry-ilyevskiy): Will not work for CRDs (only json encoding\n\t// is supported) so the user will have to indicate this is a\n\t// non-standard type (or we could deduce that ourselves).\n\tcontentType := \"application/vnd.kubernetes.protobuf\"\n\treq, err := http.NewRequest(method, url, bytes.NewReader(bs))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"Content-Type\", contentType)\n\n\tlog.V(1).Infof(\"%s to %s\", method, url)\n\n\tif log.V(2) {\n\t\ts, err := renderObj(msg.(runtime.Object), &r.GVK, bool(log.V(3)) /* If --v=3, only return JSON. */, m.diffFilters)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to render :live object for %s: %v\", r.String(), err)\n\t\t}\n\n\t\tlog.Infof(\"%s:\\n%s\", r.String(), s)\n\t}\n\n\tif m.diff {\n\t\tif err := printUnifiedDiff(os.Stdout, live, msg.(runtime.Object), r.GVK, maybeNamespaced(r.Name, r.Namespace), m.diffFilters); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif m.dryRun {\n\t\treturn printUnifiedDiff(os.Stdout, live, msg.(runtime.Object), r.GVK, maybeNamespaced(r.Name, r.Namespace), m.diffFilters)\n\t}\n\n\tresp, err := m.httpClient.Do(req.WithContext(ctx))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, rMsg, err := parseHTTPResponse(resp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tactionMsg := \"created\"\n\tif method == http.MethodPut {\n\t\tactionMsg = \"updated\"\n\t}\n\tlog.Infof(\"%s %s\", rMsg, actionMsg)\n\n\treturn nil\n}", "func (w *GovernanceWorker) handleNodePolicyUpdateForDeployment(updateCode int) {\n\n\t// node policy deleted\n\tif updateCode&externalpolicy.EP_COMPARE_DELETED == externalpolicy.EP_COMPARE_DELETED {\n\t\t// cancel all agreements for the policy case\n\t\tif w.devicePattern == \"\" {\n\t\t\tw.pm.DeletePolicyByName(exchange.GetOrg(w.GetExchangeId()), policy.MakeExternalPolicyHeaderName(w.GetExchangeId()))\n\t\t\tw.cancelAllAgreements()\n\t\t}\n\t\treturn\n\t}\n\n\t// now handle the policy updated case, update the policy in policy manager\n\t// for the non-pattern case\n\tif w.devicePattern == \"\" {\n\t\t// get the node policy\n\t\tnodePolicy, err := persistence.FindNodePolicy(w.db)\n\t\tif err != nil {\n\t\t\tglog.Errorf(logString(fmt.Sprintf(\"unable to read node policy from the local database. %v\", err)))\n\t\t\teventlog.LogDatabaseEvent(w.db, persistence.SEVERITY_ERROR,\n\t\t\t\tpersistence.NewMessageMeta(EL_GOV_ERR_RETRIEVE_NODE_POL_FROM_DB, err.Error()),\n\t\t\t\tpersistence.EC_DATABASE_ERROR)\n\t\t\treturn\n\t\t}\n\n\t\t// get the deployment policy from the node policy now that the node policy\n\t\t// containts both deployment and management policies.\n\t\tvar deploy_pol *externalpolicy.ExternalPolicy\n\t\tif nodePolicy != nil {\n\t\t\tdeploy_pol = nodePolicy.GetDeploymentPolicy()\n\t\t} else {\n\t\t\tdeploy_pol = nil\n\t\t}\n\n\t\t// add the node policy to the policy manager\n\t\tnewPol, err := policy.GenPolicyFromExternalPolicy(deploy_pol, policy.MakeExternalPolicyHeaderName(w.GetExchangeId()))\n\t\tif err != nil {\n\t\t\tglog.Errorf(logString(fmt.Sprintf(\"Failed to convert node policy to policy file format: %v\", err)))\n\t\t\treturn\n\t\t}\n\t\tw.pm.UpdatePolicy(exchange.GetOrg(w.GetExchangeId()), newPol)\n\t}\n\n\t// If node's allowPrivileged built-in property is changed, cancel all agreements\n\tif updateCode&externalpolicy.EP_ALLOWPRIVILEGED_CHANGED == externalpolicy.EP_ALLOWPRIVILEGED_CHANGED {\n\t\tw.cancelAllAgreements()\n\t}\n\n\t// Let governAgreements() function handle the policy re-evaluation and the rest\n\t// for other cases\n}", "func receiveAndManageRollups(ctx context.Context, client *influxdb.Client, ch <-chan kubernetes.ConfigMapUpdate) {\n\tfor {\n\t\tselect {\n\t\tcase update := <-ch:\n\t\t\tlog := log.WithField(\"configmap\", update.ResourceUpdate.Meta())\n\t\t\tfor _, v := range update.Data {\n\t\t\t\tvar rollups []influxdb.Rollup\n\t\t\t\terr := json.Unmarshal([]byte(v), &rollups)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"failed to unmarshal %s: %v\", update.Data, trace.DebugReport(err))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tfor _, rollup := range rollups {\n\t\t\t\t\tswitch update.EventType {\n\t\t\t\t\tcase watch.Added:\n\t\t\t\t\t\terr := client.CreateRollup(rollup)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlog.Errorf(\"failed to create rollup %v: %v\", rollup, trace.DebugReport(err))\n\t\t\t\t\t\t}\n\t\t\t\t\tcase watch.Deleted:\n\t\t\t\t\t\terr := client.DeleteRollup(rollup)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlog.Errorf(\"failed to delete rollup %v: %v\", rollup, trace.DebugReport(err))\n\t\t\t\t\t\t}\n\t\t\t\t\tcase watch.Modified:\n\t\t\t\t\t\terr := client.UpdateRollup(rollup)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlog.Errorf(\"failed to alter rollup %v: %v\", rollup, trace.DebugReport(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\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func UpdatePod(taskExecutionMetadata pluginsCore.TaskExecutionMetadata,\n\tresourceRequirements []v1.ResourceRequirements, podSpec *v1.PodSpec) {\n\tif len(podSpec.RestartPolicy) == 0 {\n\t\tpodSpec.RestartPolicy = v1.RestartPolicyNever\n\t}\n\tpodSpec.Tolerations = append(\n\t\tGetPodTolerations(taskExecutionMetadata.IsInterruptible(), resourceRequirements...), podSpec.Tolerations...)\n\tif len(podSpec.ServiceAccountName) == 0 {\n\t\tpodSpec.ServiceAccountName = taskExecutionMetadata.GetK8sServiceAccount()\n\t}\n\tif len(podSpec.SchedulerName) == 0 {\n\t\tpodSpec.SchedulerName = config.GetK8sPluginConfig().SchedulerName\n\t}\n\tpodSpec.NodeSelector = utils.UnionMaps(podSpec.NodeSelector, config.GetK8sPluginConfig().DefaultNodeSelector)\n\tif taskExecutionMetadata.IsInterruptible() {\n\t\tpodSpec.NodeSelector = utils.UnionMaps(podSpec.NodeSelector, config.GetK8sPluginConfig().InterruptibleNodeSelector)\n\t}\n\tif podSpec.Affinity == nil {\n\t\tpodSpec.Affinity = config.GetK8sPluginConfig().DefaultAffinity\n\t}\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}" ]
[ "0.65832686", "0.6538461", "0.64754593", "0.6443429", "0.6329279", "0.63052166", "0.61619335", "0.60634065", "0.59615046", "0.57940674", "0.5787343", "0.57812905", "0.577772", "0.5728809", "0.57158923", "0.56981456", "0.56562114", "0.5646921", "0.5629366", "0.5581582", "0.5576583", "0.5563627", "0.5450475", "0.54441607", "0.5428197", "0.5412102", "0.5396893", "0.53761154", "0.53725874", "0.5367323", "0.5363792", "0.5360733", "0.5352565", "0.53329086", "0.53263646", "0.5302411", "0.529324", "0.5281955", "0.5279722", "0.5258025", "0.52406746", "0.5228737", "0.520085", "0.5173083", "0.51562166", "0.515564", "0.51515853", "0.5147041", "0.5142771", "0.5141366", "0.51395315", "0.51332164", "0.51272744", "0.5126476", "0.5124202", "0.51226485", "0.51187867", "0.51131904", "0.51041466", "0.50955606", "0.5095457", "0.50666827", "0.50613153", "0.5058412", "0.5053375", "0.5028939", "0.5027553", "0.50221086", "0.50133365", "0.50097924", "0.5007719", "0.49905634", "0.498838", "0.49863324", "0.498579", "0.4984585", "0.49732828", "0.49703163", "0.4966334", "0.49578357", "0.4955775", "0.4946278", "0.49273643", "0.49191856", "0.4918404", "0.49183336", "0.49091753", "0.49082223", "0.49081907", "0.49035692", "0.48967376", "0.48954713", "0.48954597", "0.4890683", "0.48886907", "0.48827332", "0.48822358", "0.48791596", "0.48771855", "0.48738062" ]
0.7503964
0
managePodScaleDown used to manage properly the scale down of a cluster
func (c *Controller) managePodScaleDown(admin submarine.AdminInterface, cluster *rapi.SubmarineCluster, rCluster *submarine.Cluster, nodes submarine.Nodes) (bool, error) { return true, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Controller) processClusterScaleDown(ecs *ecsv1.KubernetesCluster) error {\n\t// diff work nodes\n\tvar oldSpec ecsv1.KubernetesClusterSpec\n\toldSpecStr := ecs.Annotations[enum.Spec]\n\terr := json.Unmarshal([]byte(oldSpecStr), &oldSpec)\n\tif err != nil {\n\t\tglog.Errorf(\"get old spec failed with:%v\", err)\n\t\treturn err\n\t}\n\tnodeList := diffNodeList(oldSpec.Cluster.NodeList, ecs.Spec.Cluster.NodeList, ecs.Annotations[enum.Operation])\n\n\tdeployMode := ecs.Spec.Cluster.DeployMode\n\tswitch deployMode {\n\tcase ecsv1.BinaryDeployMode:\n\t\terr = c.sshInstaller.ClusterScaleDown(ecs, nodeList)\n\tcase ecsv1.ContainerDeployMode:\n\t\terr = c.grpcInstaller.ClusterScaleDown(ecs, nodeList)\n\t}\n\n\tif err != nil {\n\t\tglog.Errorf(\"scaledown cluster %s failed with %v\", ecs.Name, err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Controller) processClusterScaleUp(ecs *ecsv1.KubernetesCluster) error {\n\t// diff work nodes\n\tvar oldSpec ecsv1.KubernetesClusterSpec\n\toldSpecStr := ecs.Annotations[enum.Spec]\n\terr := json.Unmarshal([]byte(oldSpecStr), &oldSpec)\n\tif err != nil {\n\t\tglog.Errorf(\"get old spec failed with:%v\", err)\n\t\treturn err\n\t}\n\tnodeList := diffNodeList(oldSpec.Cluster.NodeList, ecs.Spec.Cluster.NodeList, ecs.Annotations[enum.Operation])\n\n\tdeployMode := ecs.Spec.Cluster.DeployMode\n\tswitch deployMode {\n\tcase ecsv1.BinaryDeployMode:\n\t\terr = c.sshInstaller.ClusterScaleUp(ecs, nodeList)\n\tcase ecsv1.ContainerDeployMode:\n\t\terr = c.grpcInstaller.ClusterScaleUp(ecs, nodeList)\n\t}\n\n\tif err != nil {\n\t\tglog.Errorf(\"scaleup cluster %s failed with %v\", ecs.Name, err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (rcc *CassandraClusterReconciler) CheckNonAllowedScaleDown(cc *api.CassandraCluster,\n\toldCRD *api.CassandraCluster) bool {\n\n\tif ok, dcName, dc := cc.FindDCWithNodesTo0(); ok {\n\t\tlogrus.WithFields(logrus.Fields{\"cluster\": cc.Name}).Infof(\"Ask ScaleDown to 0 for dc %s\", dcName)\n\n\t\t//We take the first Rack\n\t\trackName := cc.GetRackName(dc, 0)\n\n\t\tselector := k8s.MergeLabels(k8s.LabelsForCassandraDCRack(cc, dcName, rackName))\n\t\tpodsList, err := rcc.ListPods(cc.Namespace, selector)\n\t\tif err != nil || len(podsList.Items) < 1 {\n\t\t\tif err != nil {\n\t\t\t\tlogrus.WithFields(logrus.Fields{\"cluster\": cc.Name}).Warningf(\n\t\t\t\t\t\"The Operator has refused the ScaleDown (no pod found). \"+\n\t\t\t\t\t\t\"topology %v restored to %v\", cc.Spec.Topology, oldCRD.Spec.Topology)\n\t\t\t\tcc.Spec.Topology = oldCRD.Spec.Topology\n\t\t\t\treturn true\n\t\t\t}\n\t\t\t//else there is already no pods so it's ok\n\t\t\treturn false\n\t\t}\n\n\t\t//We take the first available Pod\n\t\tfor _, pod := range podsList.Items {\n\t\t\tif pod.Status.Phase != v1.PodRunning || pod.DeletionTimestamp != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\thostName := k8s.PodHostname(pod)\n\t\t\tlogrus.WithFields(logrus.Fields{\"cluster\": cc.Name}).Debugf(\"The Operator will ask node %s\", hostName)\n\t\t\tjolokiaClient, err := NewJolokiaClient(hostName, JolokiaPort, rcc,\n\t\t\t\tcc.Spec.ImageJolokiaSecret, cc.Namespace)\n\t\t\tvar keyspacesWithData []string\n\t\t\tif err == nil {\n\t\t\t\tkeyspacesWithData, err = jolokiaClient.NonLocalKeyspacesInDC(dcName)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tlogrus.WithFields(logrus.Fields{\"cluster\": cc.Name}).Warningf(\n\t\t\t\t\t\"The Operator has refused the ScaleDown (NonLocalKeyspacesInDC failed %s). \", err)\n\t\t\t\tcc.Spec.Topology = oldCRD.Spec.Topology\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif len(keyspacesWithData) != 0 {\n\t\t\t\tlogrus.WithFields(logrus.Fields{\"cluster\": cc.Name}).Warningf(\n\t\t\t\t\t\"The Operator has refused the ScaleDown. Keyspaces still having data %v\", keyspacesWithData)\n\t\t\t\tcc.Spec.Topology = oldCRD.Spec.Topology\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tlogrus.WithFields(logrus.Fields{\"cluster\": cc.Name}).Warningf(\n\t\t\t\t\"Cassandra has no more replicated data on dc %s, we can scale Down to 0\", dcName)\n\t\t\treturn false\n\t\t}\n\t}\n\treturn false\n}", "func (c *Client) ScaleDownCluster(args *ScaleDownClusterArgs) error {\n\tvar params map[string]string\n\tif args != nil {\n\t\tparams = map[string]string{\n\t\t\t\"clientToken\": c.GenerateClientToken(),\n\t\t\t\"scalingDown\": \"\",\n\t\t}\n\t}\n\n\tklog.Infof(\"ScaleDownCluster args: %v\", params)\n\tpostContent, err := json.Marshal(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := bce.NewRequest(\"POST\", c.GetURL(\"v1/cluster\", params), bytes.NewBuffer(postContent))\n\tklog.Infof(\"ScaleDownCluster req: %v\", req)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = c.SendRequest(req, nil)\n\treturn err\n}", "func KubeScale(count string, deployment string) string {\n\tvar outputstring string\n\tif count == \"\" || deployment == \"\" {\n\t\toutputstring = \"\"\n\t} else if strings.HasSuffix(deployment, \".yaml\") {\n\t\toutputstring = fmt.Sprintf(\"scale --replicas=%s -f %s\", count, deployment)\n\t} else {\n\t\toutputstring = fmt.Sprintf(\"scale --replicas=%s %s\", count, deployment)\n\t}\n\treturn KubeCommand(outputstring)\n}", "func (s *ScalingService) ScaleDown() error {\n\tklog.Infoln(\"Scaling down the controller\")\n\treturn s.scaleTo(0)\n}", "func calculateScaleDownLimit(wpa *datadoghqv1alpha1.WatermarkPodAutoscaler, currentReplicas int32) int32 {\n\tif wpa.Spec.ScaleDownLimitFactor.Value() == 0 {\n\t\t// Scale down disabled\n\t\treturn currentReplicas\n\t}\n\treturn int32(float64(currentReplicas) - math.Max(1, math.Floor(float64(wpa.Spec.ScaleDownLimitFactor.MilliValue())/1000*float64(currentReplicas)/100)))\n}", "func (ts testState) assertScaleDown(ctx context.Context, client kubernetesClient) error {\n\td, err := client.c.AppsV1().Deployments(ts.namespace).Get(ctx, ts.deployment, meta.GetOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif d.Spec.Replicas != nil && *d.Spec.Replicas == 0 {\n\t\treturn nil\n\t}\n\treturn errors.Errorf(\"replicas not yet correct. expected=%v, got=%v\", 0, *d.Spec.Replicas)\n}", "func RegisterScaleDown(nodesCount int, gpuResourceName, gpuType string, reason NodeScaleDownReason) {\n\tscaleDownCount.WithLabelValues(string(reason)).Add(float64(nodesCount))\n\tif gpuType != gpu.MetricsNoGPU {\n\t\tgpuScaleDownCount.WithLabelValues(string(reason), gpuResourceName, gpuType).Add(float64(nodesCount))\n\t}\n}", "func (dc *DeploymentController) scale(ctx context.Context, deployment *apps.Deployment, newRS *apps.ReplicaSet, oldRSs []*apps.ReplicaSet) error {\n\t// If there is only one active replica set then we should scale that up to the full count of the\n\t// deployment. If there is no active replica set, then we should scale up the newest replica set.\n\tif activeOrLatest := deploymentutil.FindActiveOrLatest(newRS, oldRSs); activeOrLatest != nil {\n\t\tif *(activeOrLatest.Spec.Replicas) == *(deployment.Spec.Replicas) {\n\t\t\treturn nil\n\t\t}\n\t\t_, _, err := dc.scaleReplicaSetAndRecordEvent(ctx, activeOrLatest, *(deployment.Spec.Replicas), deployment)\n\t\treturn err\n\t}\n\n\t// If the new replica set is saturated, old replica sets should be fully scaled down.\n\t// This case handles replica set adoption during a saturated new replica set.\n\tif deploymentutil.IsSaturated(deployment, newRS) {\n\t\tfor _, old := range controller.FilterActiveReplicaSets(oldRSs) {\n\t\t\tif _, _, err := dc.scaleReplicaSetAndRecordEvent(ctx, old, 0, deployment); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\t// There are old replica sets with pods and the new replica set is not saturated.\n\t// We need to proportionally scale all replica sets (new and old) in case of a\n\t// rolling deployment.\n\tif deploymentutil.IsRollingUpdate(deployment) {\n\t\tallRSs := controller.FilterActiveReplicaSets(append(oldRSs, newRS))\n\t\tallRSsReplicas := deploymentutil.GetReplicaCountForReplicaSets(allRSs)\n\n\t\tallowedSize := int32(0)\n\t\tif *(deployment.Spec.Replicas) > 0 {\n\t\t\tallowedSize = *(deployment.Spec.Replicas) + deploymentutil.MaxSurge(*deployment)\n\t\t}\n\n\t\t// Number of additional replicas that can be either added or removed from the total\n\t\t// replicas count. These replicas should be distributed proportionally to the active\n\t\t// replica sets.\n\t\tdeploymentReplicasToAdd := allowedSize - allRSsReplicas\n\n\t\t// The additional replicas should be distributed proportionally amongst the active\n\t\t// replica sets from the larger to the smaller in size replica set. Scaling direction\n\t\t// drives what happens in case we are trying to scale replica sets of the same size.\n\t\t// In such a case when scaling up, we should scale up newer replica sets first, and\n\t\t// when scaling down, we should scale down older replica sets first.\n\t\tvar scalingOperation string\n\t\tswitch {\n\t\tcase deploymentReplicasToAdd > 0:\n\t\t\tsort.Sort(controller.ReplicaSetsBySizeNewer(allRSs))\n\t\t\tscalingOperation = \"up\"\n\n\t\tcase deploymentReplicasToAdd < 0:\n\t\t\tsort.Sort(controller.ReplicaSetsBySizeOlder(allRSs))\n\t\t\tscalingOperation = \"down\"\n\t\t}\n\n\t\t// Iterate over all active replica sets and estimate proportions for each of them.\n\t\t// The absolute value of deploymentReplicasAdded should never exceed the absolute\n\t\t// value of deploymentReplicasToAdd.\n\t\tdeploymentReplicasAdded := int32(0)\n\t\tnameToSize := make(map[string]int32)\n\t\tlogger := klog.FromContext(ctx)\n\t\tfor i := range allRSs {\n\t\t\trs := allRSs[i]\n\n\t\t\t// Estimate proportions if we have replicas to add, otherwise simply populate\n\t\t\t// nameToSize with the current sizes for each replica set.\n\t\t\tif deploymentReplicasToAdd != 0 {\n\t\t\t\tproportion := deploymentutil.GetProportion(logger, rs, *deployment, deploymentReplicasToAdd, deploymentReplicasAdded)\n\n\t\t\t\tnameToSize[rs.Name] = *(rs.Spec.Replicas) + proportion\n\t\t\t\tdeploymentReplicasAdded += proportion\n\t\t\t} else {\n\t\t\t\tnameToSize[rs.Name] = *(rs.Spec.Replicas)\n\t\t\t}\n\t\t}\n\n\t\t// Update all replica sets\n\t\tfor i := range allRSs {\n\t\t\trs := allRSs[i]\n\n\t\t\t// Add/remove any leftovers to the largest replica set.\n\t\t\tif i == 0 && deploymentReplicasToAdd != 0 {\n\t\t\t\tleftover := deploymentReplicasToAdd - deploymentReplicasAdded\n\t\t\t\tnameToSize[rs.Name] = nameToSize[rs.Name] + leftover\n\t\t\t\tif nameToSize[rs.Name] < 0 {\n\t\t\t\t\tnameToSize[rs.Name] = 0\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// TODO: Use transactions when we have them.\n\t\t\tif _, _, err := dc.scaleReplicaSet(ctx, rs, nameToSize[rs.Name], deployment, scalingOperation); err != nil {\n\t\t\t\t// Return as soon as we fail, the deployment is requeued\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func Scale(appName string, webCount int, workerCount int) error {\n\targs := []string{\"dokku\", \"ps:scale\", appName}\n\n\tif webCount > 0 {\n\t\twebPart := fmt.Sprintf(\"web=%v\", webCount)\n\t\targs = append(args, webPart)\n\t}\n\n\tif workerCount > 0 {\n\t\tworkerPart := fmt.Sprintf(\"worker=%v\", workerCount)\n\t\targs = append(args, workerPart)\n\t}\n\n\tlog.GeneralLogger.Println(args)\n\tcmd := common.NewShellCmd(strings.Join(args, \" \"))\n\tcmd.ShowOutput = false\n\tout, err := cmd.Output()\n\n\tif err != nil {\n\t\tlog.ErrorLogger.Println(\"Dokku ps:scale error:\", err.Error())\n\t\tlog.ErrorLogger.Println(\"Dokku ps:scale output:\", string(out))\n\t\treturn err\n\t}\n\tlog.GeneralLogger.Println(\"Dokku ps:scale output:\", string(out))\n\treturn nil\n}", "func (schedulerClient *Scheduler) ScaleOut(workerpoolName string) {\n\t// Get the current size of the node list\n\ttestInternetConnection := schedulerClient.clusterClient.getClusterResourceGroup()\n\tif testInternetConnection == \"\"{\n\t\tlog.Println(\"ScaleOut: network problem\")\n\t\treturn\n\t}\n\tprevSize := len(schedulerClient.clusterClient.getWorkersNodesIP(schedulerClient.workerPool))\n\tif prevSize == 0{\n\t\tlog.Println(\"Warning: the node list is empty, skip the action\")\n\t\treturn\n\t}\n\tsucceed := schedulerClient.clusterClient.addOneWorker(workerpoolName)\n\tif !succeed {\n\t\tlog.Println(\"Can not add a new worker node\")\n\t}else{\n\t\tlog.Println(\"Adding a new worker node\")\n\t\ttimeBegin := time.Now()\n\t\tfor {\n\t\t\tnodes := schedulerClient.clusterClient.getWorkersNodesIP(schedulerClient.workerPool)\n\t\t\tcurrSize := len(nodes)\t// get the current size\n\t\t\t// TODO : also this part, same as scale in\n\t\t\tif currSize == prevSize + 1{\n\t\t\t\tcanBreak := true\n\t\t\t\tfor _,val := range nodes {\n\t\t\t\t\tif val == \"\"{ canBreak = false}\n\t\t\t\t}\n\t\t\t\tif canBreak {\n\t\t\t\t\tlog.Println(\"Added a new worker node takes: \",time.Now().Sub(timeBegin).Minutes(),\" mins\")\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif int(time.Now().Sub(timeBegin).Minutes()) > 10 {break;}\n\t\t}\n\t}\n}", "func (a *ExistingInfraMachineReconciler) kubeadmUpOrDowngrade(ctx context.Context, c *existinginfrav1.ExistingInfraCluster, machine *clusterv1.Machine, eim *existinginfrav1.ExistingInfraMachine, node *corev1.Node, installer *os.OS,\n\tk8sVersion, planJSON string, ntype recipe.NodeType) error {\n\tb := plan.NewBuilder()\n\n\tupgradeRes, err := recipe.BuildUpgradePlan(installer.PkgType, k8sVersion, ntype)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tb.AddResource(\"upgrade:k8s\", upgradeRes)\n\n\tp, err := b.Plan()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := installer.SetupNode(ctx, &p); err != nil {\n\t\tlog.Infof(\"Failed to upgrade node %s: %v\", node.Name, err)\n\t\treturn err\n\t}\n\tlog.Infof(\"About to uncordon node %s...\", node.Name)\n\tif err := a.uncordon(ctx, node); err != nil {\n\t\tlog.Info(\"Failed to uncordon...\")\n\t\treturn err\n\t}\n\tlog.Info(\"Finished with uncordon...\")\n\tif err = a.setNodeAnnotation(ctx, node.Name, recipe.PlanKey, planJSON); err != nil {\n\t\treturn err\n\t}\n\ta.recordEvent(machine, corev1.EventTypeNormal, \"Update\", \"updated machine %s\", machine.Name)\n\treturn nil\n}", "func (m *Micropig) scaleDownSimple(asg *Asg) error {\n\trmCount := asg.CurrentSize() - asg.Desired\n\tfor i := 0; i < rmCount; i++ {\n\t\tdropID := asg.Droplets[i].ID\n\t\tm.MustDeleteDroplet(dropID)\n\t}\n\treturn nil\n}", "func (s *Service) scale(replicas int) {\n\tlog.WithField(\"replicas\", replicas).Debug(\"Service scaling\")\n\ts.state = StateScaling\n\tif s.CurrentReplicas != replicas {\n\t\ts.auklet.scaleService(s.ServiceID, replicas)\n\t\ts.auklet.Lock()\n\t\ts.auklet.metrics[MetricServiceScaleEventsTotal].(prometheus.Counter).Inc()\n\t\tif replicas > s.CurrentReplicas {\n\t\t\ts.auklet.serviceMetrics[s.ServiceID][MetricScaleUpEventsCount].(prometheus.Counter).Inc()\n\t\t} else {\n\t\t\ts.auklet.serviceMetrics[s.ServiceID][MetricScaleDownEventsCount].(prometheus.Counter).Inc()\n\t\t}\n\t\ts.auklet.Unlock()\n\t}\n\n\t// after scaling return to stable state\n\ts.stable()\n}", "func (this *Decider) ScaleAction(command common.Command) error {\n\tmessage := common.InformScaleDownAppMessage{}\n\terr := json.Unmarshal([]byte(command.Body), &message)\n\tif err != nil {\n\t}\n\n\tthis.Client.MetricalScaleAppsAction(message)\n\treturn err\n}", "func UpScaleCluster(brokerId, namespace, ccEndpoint, clusterName string) error {\n\n\terr := GetCruiseControlStatus(namespace, ccEndpoint, clusterName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar backoffConfig = backoff.ConstantBackoffConfig{\n\t\tDelay: 10 * time.Second,\n\t\tMaxRetries: 5,\n\t}\n\tvar backoffPolicy = backoff.NewConstantBackoffPolicy(&backoffConfig)\n\n\terr = backoff.Retry(func() error {\n\t\tready, err := isKafkaBrokerReady(brokerId, namespace, ccEndpoint, clusterName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !ready {\n\t\t\treturn errors.New(\"broker is not ready yet\")\n\t\t}\n\t\treturn nil\n\t}, backoffPolicy)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toptions := map[string]string{\n\t\t\"json\": \"true\",\n\t\t\"dryrun\": \"false\",\n\t\t\"brokerid\": brokerId,\n\t}\n\n\tvar uResp *http.Response\n\n\terr = backoff.Retry(func() error {\n\t\tuResp, err = postCruiseControl(addBrokerAction, namespace, options, ccEndpoint, clusterName)\n\t\tif err != nil && err != errCruiseControlNotReturned200 {\n\t\t\tlog.Error(err, \"can't upscale cluster gracefully since post to cruise-control failed\")\n\t\t\treturn err\n\t\t}\n\t\tif err == errCruiseControlNotReturned200 {\n\t\t\tlog.Info(\"trying to communicate with cc\")\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}, backoffPolicy)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Info(\"Initiated upscale in cruise control\")\n\n\tuTaskId := uResp.Header.Get(\"User-Task-Id\")\n\n\terr = checkIfCCTaskFinished(uTaskId, namespace, ccEndpoint, clusterName)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *Client) ScaleUpCluster(args *ScaleUpClusterArgs) (*ScaleUpClusterResponse, error) {\n\tvar params map[string]string\n\tif args != nil {\n\t\tparams = map[string]string{\n\t\t\t\"clientToken\": c.GenerateClientToken(),\n\t\t\t\"scalingUp\": \"\",\n\t\t}\n\t}\n\tpostContent, err := json.Marshal(args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tutil.Debug(\"\", fmt.Sprintf(\"ScaleUpCluster Post body: %s\", string(postContent)))\n\treq, err := bce.NewRequest(\"POST\", c.GetURL(\"v1/cluster\", params), bytes.NewBuffer(postContent))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := c.SendRequest(req, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyContent, err := resp.GetBodyContent()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar scResp *ScaleUpClusterResponse\n\terr = json.Unmarshal(bodyContent, &scResp)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn scResp, nil\n}", "func getScaleUpStatus(ctx context.Context, c clientset.Interface) (*scaleUpStatus, error) {\n\tconfigMap, err := c.CoreV1().ConfigMaps(\"kube-system\").Get(ctx, \"cluster-autoscaler-status\", metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstatus, ok := configMap.Data[\"status\"]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Status information not found in configmap\")\n\t}\n\n\ttimestamp, err := getStatusTimestamp(status)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmatcher, err := regexp.Compile(\"s*ScaleUp:\\\\s*([A-Za-z]+)\\\\s*\\\\(ready=([0-9]+)\\\\s*cloudProviderTarget=([0-9]+)\\\\s*\\\\)\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmatches := matcher.FindAllStringSubmatch(status, -1)\n\tif len(matches) < 1 {\n\t\treturn nil, fmt.Errorf(\"Failed to parse CA status configmap, raw status: %v\", status)\n\t}\n\n\tresult := scaleUpStatus{\n\t\tstatus: caNoScaleUpStatus,\n\t\tready: 0,\n\t\ttarget: 0,\n\t\ttimestamp: timestamp,\n\t}\n\tfor _, match := range matches {\n\t\tif match[1] == caOngoingScaleUpStatus {\n\t\t\tresult.status = caOngoingScaleUpStatus\n\t\t}\n\t\tnewReady, err := strconv.Atoi(match[2])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult.ready += newReady\n\t\tnewTarget, err := strconv.Atoi(match[3])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult.target += newTarget\n\t}\n\tklog.Infof(\"Cluster-Autoscaler scale-up status: %v (%v, %v)\", result.status, result.ready, result.target)\n\treturn &result, nil\n}", "func TestCheckNonAllowedChangesScaleDown(t *testing.T) {\n\tassert := assert.New(t)\n\n\trcc, cc := HelperInitCluster(t, \"cassandracluster-3DC.yaml\")\n\tstatus := cc.Status.DeepCopy()\n\trcc.updateCassandraStatus(cc, status)\n\n\t//Create the Pods wanted by the statefulset dc2-rack1 (1 node)\n\tpod := &v1.Pod{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"Pod\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"cassandra-demo-dc2-rack1-0\",\n\t\t\tNamespace: \"ns\",\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"app\": \"cassandracluster\",\n\t\t\t\t\"cassandracluster\": \"cassandra-demo\",\n\t\t\t\t\"cassandraclusters.db.orange.com.dc\": \"dc2\",\n\t\t\t\t\"cassandraclusters.db.orange.com.rack\": \"rack1\",\n\t\t\t\t\"cluster\": \"k8s.pic\",\n\t\t\t\t\"dc-rack\": \"dc2-rack1\",\n\t\t\t},\n\t\t},\n\t}\n\tpod.Status.Phase = v1.PodRunning\n\tpod.Spec.Hostname = \"cassandra-demo2-dc2-rack1-0\"\n\tpod.Spec.Subdomain = \"cassandra-demo2-dc2-rack1\"\n\thostName := k8s.PodHostname(*pod)\n\trcc.CreatePod(pod)\n\n\t//Mock Jolokia Call to NonLocalKeyspacesInDC\n\thttpmock.Activate()\n\tdefer httpmock.DeactivateAndReset()\n\tkeyspacesDescribed := []string{}\n\n\thttpmock.RegisterResponder(\"POST\", JolokiaURL(hostName, jolokiaPort),\n\t\tfunc(req *http.Request) (*http.Response, error) {\n\t\t\tvar execrequestdata execRequestData\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&execrequestdata); err != nil {\n\t\t\t\tt.Error(\"Can't decode request received\")\n\t\t\t}\n\t\t\tif execrequestdata.Attribute == \"Keyspaces\" {\n\t\t\t\treturn httpmock.NewStringResponse(200, keyspaceListString()), nil\n\t\t\t}\n\t\t\tkeyspace, ok := execrequestdata.Arguments[0].(string)\n\n\t\t\tif !ok {\n\t\t\t\tt.Error(\"Keyspace can't be nil\")\n\t\t\t}\n\n\t\t\tkeyspacesDescribed = append(keyspacesDescribed, keyspace)\n\n\t\t\tresponse := `{\"request\": {\"mbean\": \"org.apache.cassandra.db:type=StorageService\",\n\t\t\t\t\t\t \"arguments\": [\"%s\"],\n\t\t\t\t\t\t \"type\": \"exec\",\n\t\t\t\t\t\t \"operation\": \"describeRingJMX\"},\n\t\t\t\t \"timestamp\": 1541908753,\n\t\t\t\t \"status\": 200,`\n\n\t\t\t// For keyspace demo1 and demo2 we return token ranges with some of them assigned to nodes on dc2\n\t\t\tif keyspace[:4] == \"demo\" {\n\t\t\t\tresponse += `\"value\":\n\t\t\t\t\t [\"TokenRange(start_token:4572538884437204647, end_token:4764428918503636065, endpoints:[10.244.3.8], rpc_endpoints:[10.244.3.8], endpoint_details:[EndpointDetails(host:10.244.3.8, datacenter:dc1, rack:rack1)])\",\n\t\t\t\t\t\t\"TokenRange(start_token:-8547872176065322335, end_token:-8182289314504856691, endpoints:[10.244.2.5], rpc_endpoints:[10.244.2.5], endpoint_details:[EndpointDetails(host:10.244.2.5, datacenter:dc1, rack:rack1)])\",\n\t\t\t\t\t\t\"TokenRange(start_token:-2246208089217404881, end_token:-2021878843377619999, endpoints:[10.244.2.5], rpc_endpoints:[10.244.2.5], endpoint_details:[EndpointDetails(host:10.244.2.5, datacenter:dc2, rack:rack1)])\",\n\t\t\t\t\t\t\"TokenRange(start_token:-1308323778199165410, end_token:-1269907200339273513, endpoints:[10.244.2.6], rpc_endpoints:[10.244.2.6], endpoint_details:[EndpointDetails(host:10.244.2.6, datacenter:dc1, rack:rack1)])\",\n\t\t\t\t\t\t\"TokenRange(start_token:8544184416734424972, end_token:8568577617447026631, endpoints:[10.244.2.6], rpc_endpoints:[10.244.2.6], endpoint_details:[EndpointDetails(host:10.244.2.6, datacenter:dc2, rack:rack1)])\",\n\t\t\t\t\t\t\"TokenRange(start_token:2799723085723957315, end_token:3289697029162626204, endpoints:[10.244.3.7], rpc_endpoints:[10.244.3.7], endpoint_details:[EndpointDetails(host:10.244.3.7, datacenter:dc1, rack:rack1)])\"]}`\n\t\t\t\treturn httpmock.NewStringResponse(200, fmt.Sprintf(response, keyspace)), nil\n\t\t\t}\n\t\t\treturn httpmock.NewStringResponse(200, fmt.Sprintf(response+`\"value\": []}`, keyspace)), nil\n\t\t},\n\t)\n\n\t// ask scale down to 0\n\tvar nb int32\n\tcc.Spec.Topology.DC[1].NodesPerRacks = &nb\n\n\tres := rcc.CheckNonAllowedChanges(cc, status)\n\trcc.updateCassandraStatus(cc, status)\n\t//Change not allowed because DC still has nodes\n\tassert.Equal(true, res)\n\n\t//We have restore nodesperrack\n\tassert.Equal(int32(1), *cc.Spec.Topology.DC[1].NodesPerRacks)\n\n\t//Changes replicated keyspaces (remove demo1 and demo2 which still have replicated datas\n\t//allKeyspaces is a global test variable\n\tallKeyspaces = []string{\"system\", \"system_auth\", \"system_schema\", \"something\", \"else\"}\n\tcc.Spec.Topology.DC[1].NodesPerRacks = &nb\n\n\tres = rcc.CheckNonAllowedChanges(cc, status)\n\n\t//Change allowed because there is no more keyspace with replicated datas\n\tassert.Equal(false, res)\n\n\t//Nodes Per Rack is still 0\n\tassert.Equal(int32(0), *cc.Spec.Topology.DC[1].NodesPerRacks)\n}", "func (s *ScalingService) ScaleUp() error {\n\tklog.Infoln(\"Scaling up the controller\")\n\treturn s.scaleTo(1)\n}", "func (k *Instance) ScaleSharedAppsToZero() error {\n\tsharedDeps, sharedSS, err := k.GetPXSharedApps()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogrus.Infof(\"found %d deployments and %d statefulsets to scale down\", len(sharedDeps), len(sharedSS))\n\n\tvar valZero int32\n\tfor _, d := range sharedDeps {\n\t\tdeploymentName := d.Name\n\t\tdeploymentNamespace := d.Namespace\n\t\tlogrus.Infof(\"scaling down deployment: [%s] %s\", deploymentNamespace, deploymentName)\n\n\t\tt := func() (interface{}, bool, error) {\n\t\t\tdCopy, err := k.kubeClient.AppsV1().Deployments(deploymentNamespace).Get(context.TODO(), deploymentName, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\tif errors.IsNotFound(err) {\n\t\t\t\t\treturn nil, false, nil // done as deployment is deleted\n\t\t\t\t}\n\n\t\t\t\treturn nil, true, err\n\t\t\t}\n\n\t\t\tif *dCopy.Spec.Replicas == 0 {\n\t\t\t\tlogrus.Infof(\"app [%s] %s is already scaled down to 0\", dCopy.Namespace, dCopy.Name)\n\t\t\t\treturn nil, false, nil\n\t\t\t}\n\n\t\t\tdCopy = dCopy.DeepCopy()\n\n\t\t\t// save current replica count in annotations so it can be used later on to restore the replicas\n\t\t\tdCopy.Annotations[replicaMemoryKey] = fmt.Sprintf(\"%d\", *dCopy.Spec.Replicas)\n\t\t\tdCopy.Spec.Replicas = &valZero\n\n\t\t\t_, err = k.kubeClient.AppsV1().Deployments(dCopy.Namespace).Update(context.TODO(), dCopy, metav1.UpdateOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, true, err\n\t\t\t}\n\n\t\t\treturn nil, false, nil\n\t\t}\n\n\t\tif _, err := task.DoRetryWithTimeout(t, deploymentUpdateTimeout, defaultRetryInterval); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor _, s := range sharedSS {\n\t\tlogrus.Infof(\"scaling down statefulset: [%s] %s\", s.Namespace, s.Name)\n\n\t\tt := func() (interface{}, bool, error) {\n\t\t\tsCopy, err := k.kubeClient.AppsV1().StatefulSets(s.Namespace).Get(context.TODO(), s.Name, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\tif errors.IsNotFound(err) {\n\t\t\t\t\treturn nil, false, nil // done as statefulset is deleted\n\t\t\t\t}\n\n\t\t\t\treturn nil, true, err\n\t\t\t}\n\n\t\t\tsCopy = sCopy.DeepCopy()\n\t\t\t// save current replica count in annotations so it can be used later on to restore the replicas\n\t\t\tsCopy.Annotations[replicaMemoryKey] = fmt.Sprintf(\"%d\", *sCopy.Spec.Replicas)\n\t\t\tsCopy.Spec.Replicas = &valZero\n\n\t\t\t_, err = k.kubeClient.AppsV1().StatefulSets(sCopy.Namespace).Update(context.TODO(), sCopy, metav1.UpdateOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, true, err\n\t\t\t}\n\n\t\t\treturn nil, false, nil\n\t\t}\n\n\t\tif _, err := task.DoRetryWithTimeout(t, statefulSetUpdateTimeout, defaultRetryInterval); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func cassandraClusterScaleDownSimpleTest(t *testing.T, f *framework.Framework, ctx *framework.TestCtx) {\n\tt.Logf(\"0. Init Operator\")\n\n\tnamespace, err := ctx.GetNamespace()\n\tif err != nil {\n\t\tt.Fatalf(\"could not get namespace: %v\", err)\n\t}\n\n\t/*----\n\t */\n\tt.Logf(\"1. We Create the Cluster (1dc/1rack/2node\")\n\n\tcc := mye2eutil.HelperInitCluster(t, f, ctx, \"cassandracluster-1DC.yaml\", namespace)\n\tcc.Namespace = namespace\n\tcc.Spec.Topology.DC[0].NodesPerRacks = func(i int32) *int32 { return &i }(2)\n\n\tt.Logf(\"Create CassandraCluster cassandracluster-1DC.yaml in namespace %s\", namespace)\n\terr = f.Client.Create(goctx.TODO(), cc, &framework.CleanupOptions{TestContext: ctx,\n\t\tTimeout: mye2eutil.CleanupTimeout,\n\t\tRetryInterval: mye2eutil.CleanupRetryInterval})\n\tif err != nil && !apierrors.IsAlreadyExists(err) {\n\t\tt.Logf(\"Error Creating cassandracluster: %v\", err)\n\t\tt.Fatal(err)\n\t}\n\t// wait for statefulset dc1-rack1 2 nodes\n\terr = mye2eutil.WaitForStatefulset(t, f.KubeClient, namespace, \"cassandra-e2e-dc1-rack1\", 2,\n\t\tmye2eutil.RetryInterval,\n\t\tmye2eutil.Timeout)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = mye2eutil.WaitForStatusDone(t, f, namespace, \"cassandra-e2e\", mye2eutil.RetryInterval, mye2eutil.Timeout)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t//Get Updated cc\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\", Namespace: namespace}, cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t//locale dc-rack state is OK\n\tassert.Equal(t, api.ClusterPhaseInitial.Name, cc.Status.CassandraRackStatus[\"dc1-rack1\"].CassandraLastAction.Name)\n\tassert.Equal(t, api.StatusDone, cc.Status.CassandraRackStatus[\"dc1-rack1\"].CassandraLastAction.Status)\n\tassert.Equal(t, api.ClusterPhaseInitial.Name, cc.Status.LastClusterAction)\n\tassert.Equal(t, api.StatusDone, cc.Status.LastClusterActionStatus)\n\n\t/*----\n\t */\n\tt.Logf(\"3. We Request a ScaleDown to 1\")\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\", Namespace: namespace}, cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcc.Spec.Topology.DC[0].NodesPerRacks = func(i int32) *int32 { return &i }(1)\n\terr = f.Client.Update(goctx.TODO(), cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// wait for statefulset dc1-rack1\n\terr = mye2eutil.WaitForStatefulset(t, f.KubeClient, namespace, \"cassandra-e2e-dc1-rack1\", 1,\n\t\tmye2eutil.RetryInterval,\n\t\tmye2eutil.Timeout)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = mye2eutil.WaitForStatusDone(t, f, namespace, \"cassandra-e2e\", mye2eutil.RetryInterval, mye2eutil.Timeout)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tt.Log(\"Get Updated cc\")\n\tcc = &api.CassandraCluster{}\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\", Namespace: namespace}, cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t//Because AutoUpdateSeedList is false we stay on ScaleUp=Done status\n\tassert.Equal(t, api.ActionScaleDown.Name, cc.Status.CassandraRackStatus[\"dc1-rack1\"].CassandraLastAction.Name)\n\tassert.Equal(t, api.StatusDone, cc.Status.CassandraRackStatus[\"dc1-rack1\"].CassandraLastAction.Status)\n\t//Check Global state\n\tassert.Equal(t, api.ActionScaleDown.Name, cc.Status.LastClusterAction)\n\tassert.Equal(t, api.StatusDone, cc.Status.LastClusterActionStatus)\n}", "func getScaleUpCount(desired, total, nodePoolTotal int) int {\n\treturn (desired - total) + nodePoolTotal\n}", "func (o KubernetesClusterAutoScalerProfileOutput) ScaleDownUnneeded() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v KubernetesClusterAutoScalerProfile) *string { return v.ScaleDownUnneeded }).(pulumi.StringPtrOutput)\n}", "func (o OceanLaunchSpecOutput) RestrictScaleDown() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v *OceanLaunchSpec) pulumi.BoolOutput { return v.RestrictScaleDown }).(pulumi.BoolOutput)\n}", "func cassandraClusterScaleDownDC2Test(t *testing.T, f *framework.Framework, ctx *framework.TestCtx) {\n\tt.Logf(\"0. Init Operator\")\n\n\tnamespace, err := ctx.GetNamespace()\n\tif err != nil {\n\t\tt.Fatalf(\"could not get namespace: %v\", err)\n\t}\n\n\t/*----\n\t */\n\tt.Logf(\"1. We Create the Cluster (2dc/1rack/1node\")\n\n\tcc := mye2eutil.HelperInitCluster(t, f, ctx, \"cassandracluster-2DC.yaml\", namespace)\n\tcc.Namespace = namespace\n\tt.Logf(\"Create CassandraCluster cassandracluster-2DC.yaml in namespace %s\", namespace)\n\t// use TestCtx's create helper to create the object and add a cleanup function for the new object\n\terr = f.Client.Create(goctx.TODO(), cc, &framework.CleanupOptions{TestContext: ctx,\n\t\tTimeout: mye2eutil.CleanupTimeout,\n\t\tRetryInterval: mye2eutil.CleanupRetryInterval})\n\tif err != nil && !apierrors.IsAlreadyExists(err) {\n\t\tt.Logf(\"Error Creating cassandracluster: %v\", err)\n\t\tt.Fatal(err)\n\t}\n\t// wait for statefulset dc1-rack1\n\terr = mye2eutil.WaitForStatefulset(t, f.KubeClient, namespace, \"cassandra-e2e-dc1-rack1\", 1,\n\t\tmye2eutil.RetryInterval,\n\t\tmye2eutil.Timeout)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// wait for statefulset dc1-rack1\n\terr = mye2eutil.WaitForStatefulset(t, f.KubeClient, namespace, \"cassandra-e2e-dc2-rack1\", 1,\n\t\tmye2eutil.RetryInterval,\n\t\tmye2eutil.Timeout)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = mye2eutil.WaitForStatusDone(t, f, namespace, \"cassandra-e2e\", mye2eutil.RetryInterval, mye2eutil.Timeout)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t//Get Updated cc\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\", Namespace: namespace}, cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t//locale dc-rack state is OK\n\tassert.Equal(t, api.ClusterPhaseInitial.Name, cc.Status.CassandraRackStatus[\"dc1-rack1\"].CassandraLastAction.Name)\n\tassert.Equal(t, api.StatusDone, cc.Status.CassandraRackStatus[\"dc1-rack1\"].CassandraLastAction.Status)\n\tassert.Equal(t, api.ClusterPhaseInitial.Name, cc.Status.LastClusterAction)\n\tassert.Equal(t, api.StatusDone, cc.Status.LastClusterActionStatus)\n\n\t//Check that numTokens are 256 (default) for dc1 and 32 (as specified in the crd) for dc2\n\tgrepNumTokens := \"grep num_tokens: /etc/cassandra/cassandra.yaml\"\n\tres, _, _ := mye2eutil.ExecPodFromName(t, f, namespace, \"cassandra-e2e-dc1-rack1-0\", grepNumTokens)\n\tassert.Equal(t, \"num_tokens: 256\", res)\n\tres, _, _ = mye2eutil.ExecPodFromName(t, f, namespace, \"cassandra-e2e-dc2-rack1-0\", grepNumTokens)\n\tassert.Equal(t, \"num_tokens: 32\", res)\n\t/*----\n\t */\n\tconst Strategy1DC = \"cqlsh -u cassandra -p cassandra -e \\\"ALTER KEYSPACE %s WITH REPLICATION = {'class\" +\n\t\t\"' : 'NetworkTopologyStrategy', 'dc1' : 1};\\\"\"\n\tconst Strategy2DC = \"cqlsh -u cassandra -p cassandra -e \\\"ALTER KEYSPACE %s WITH REPLICATION = {'class\" +\n\t\t\"' : 'NetworkTopologyStrategy', 'dc1' : 1, 'dc2' : 1};\\\"\"\n\tkeyspaces := []string{\n\t\t\"system_auth\",\n\t\t\"system_distributed\",\n\t\t\"system_traces\",\n\t}\n\tpod := &v1.Pod{TypeMeta: metav1.TypeMeta{Kind: \"Pod\", APIVersion: \"v1\"}}\n\n\tt.Log(\"We Change Replication Topology to 2 DC \")\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e-dc1-rack1-0\", Namespace: namespace}, pod)\n\tfor i := range keyspaces {\n\t\tcmd := fmt.Sprintf(Strategy2DC, keyspaces[i])\n\t\t_, _, err = mye2eutil.ExecPod(t, f, cc.Namespace, pod, []string{\"bash\", \"-c\", cmd})\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Error exec change keyspace %s = %v\", keyspaces[i], err)\n\t\t}\n\t}\n\ttime.Sleep(2 * time.Second)\n\n\tt.Logf(\"2. Ask Scale Down to 0 but this will be refused\")\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\", Namespace: namespace}, cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcc.Spec.Topology.DC[1].NodesPerRacks = func(i int32) *int32 { return &i }(0)\n\terr = f.Client.Update(goctx.TODO(), cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\ttime.Sleep(30 * time.Second)\n\n\t//Check Result\n\tt.Log(\"Get Updated cc\")\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\", Namespace: namespace}, cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t//Operator has restore old CRD\n\tassert.Equal(t, api.ActionCorrectCRDConfig.Name, cc.Status.LastClusterAction)\n\tassert.Equal(t, api.StatusDone, cc.Status.LastClusterActionStatus)\n\n\t/*----\n\t */\n\tt.Logf(\"3. We Remove the replication to the dc2\")\n\t//pod := &v1.Pod{TypeMeta: metav1.TypeMeta{Kind: \"Pod\", APIVersion: \"v1\"}}\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e-dc1-rack1-0\", Namespace: namespace}, pod)\n\n\tfor i := range keyspaces {\n\t\tcmd := fmt.Sprintf(Strategy1DC, keyspaces[i])\n\t\t_, _, err = mye2eutil.ExecPod(t, f, cc.Namespace, pod, []string{\"bash\", \"-c\", cmd})\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Error exec change keyspace %s{%s} = %v\", keyspaces[i], cmd, err)\n\t\t}\n\t}\n\ttime.Sleep(2 * time.Second)\n\n\t/*----\n\t */\n\tt.Logf(\"4. We Request a ScaleDown to 0 prior to remove a DC\")\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\", Namespace: namespace}, cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcc.Spec.Topology.DC[1].NodesPerRacks = func(i int32) *int32 { return &i }(0)\n\terr = f.Client.Update(goctx.TODO(), cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// wait for statefulset dc1-rack1\n\terr = mye2eutil.WaitForStatefulset(t, f.KubeClient, namespace, \"cassandra-e2e-dc2-rack1\", 0,\n\t\tmye2eutil.RetryInterval,\n\t\tmye2eutil.Timeout)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = mye2eutil.WaitForStatusDone(t, f, namespace, \"cassandra-e2e\", mye2eutil.RetryInterval, mye2eutil.Timeout)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tt.Log(\"Get Updated cc\")\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\", Namespace: namespace}, cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t//Because AutoUpdateSeedList is false we stay on ScaleUp=Done status\n\tassert.Equal(t, api.ActionScaleDown.Name, cc.Status.CassandraRackStatus[\"dc2-rack1\"].CassandraLastAction.Name)\n\tassert.Equal(t, api.StatusDone, cc.Status.CassandraRackStatus[\"dc2-rack1\"].CassandraLastAction.Status)\n\n\tstatefulset, err := f.KubeClient.AppsV1().StatefulSets(namespace).Get(\"cassandra-e2e-dc2-rack1\",\n\t\tmetav1.GetOptions{})\n\tassert.Equal(t, int32(0), statefulset.Status.CurrentReplicas)\n\n\t/*----\n\t */\n\tt.Logf(\"5. We Remove the DC\")\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\", Namespace: namespace}, cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcc.Spec.Topology.DC.Remove(1)\n\terr = f.Client.Update(goctx.TODO(), cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\ttime.Sleep(30 * time.Second)\n\n\tt.Log(\"Check Statefulset is deleted\")\n\tstatefulset, err = f.KubeClient.AppsV1().StatefulSets(namespace).Get(\"cassandra-e2e-dc2-rack1\",\n\t\tmetav1.GetOptions{})\n\t//assert.Equal(t, true, apierrors.IsNotFound(err))\n\n\tt.Log(\"Check Service is deleted\")\n\tsvc := &v1.Pod{TypeMeta: metav1.TypeMeta{Kind: \"Service\", APIVersion: \"v1\"}}\n\tnames := []string{\n\t\t\"cassandra-e2e-dc2\",\n\t}\n\tfor i := range names {\n\t\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: names[i], Namespace: namespace}, svc)\n\t\tassert.Equal(t, true, apierrors.IsNotFound(err))\n\t}\n\n\tt.Log(\"Get Updated cc\")\n\tcc = &api.CassandraCluster{}\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\", Namespace: namespace}, cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tt.Logf(\"Actual status is %s\", cc.Status.LastClusterAction)\n\t//We have only 1 dcRack in status\n\tassert.Equal(t, 1, len(cc.Status.CassandraRackStatus))\n\tassert.Equal(t, api.ActionDeleteDC.Name, cc.Status.LastClusterAction)\n\tassert.Equal(t, api.StatusDone, cc.Status.LastClusterActionStatus)\n}", "func (ts testState) assertScaleUp(ctx context.Context, client kubernetesClient) error {\n\tdeploy, err := client.c.AppsV1().Deployments(ts.namespace).Get(ctx, ts.deployment, meta.GetOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif deploy.Spec.Replicas == nil {\n\t\treturn errors.Errorf(\"deployment does not have any replicas set\")\n\t}\n\n\tif *deploy.Spec.Replicas != ts.deploymentReplicas {\n\t\treturn errors.Errorf(\"deployment has wrong number of replicas. expected=%v, got=%v\",\n\t\t\tts.deploymentReplicas, *deploy.Spec.Replicas)\n\t}\n\n\treturn nil\n}", "func Scale(namespace string, app string, n *int32) error {\n\tc, err := k8s.NewInClusterClient()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get k8s client\")\n\t}\n\n\td, err := c.ExtensionsV1Beta1().GetDeployment(ctx, app, namespace)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to get deployment\")\n\t}\n\n\td.Spec.Replicas = n\n\n\t_, err = c.ExtensionsV1Beta1().UpdateDeployment(ctx, d)\n\treturn errors.Wrap(err, \"failed to scale deployment\")\n}", "func calculateScaleUpLimit(wpa *datadoghqv1alpha1.WatermarkPodAutoscaler, currentReplicas int32) int32 {\n\t// returns TO how much we can upscale, not BY how much.\n\tif wpa.Spec.ScaleUpLimitFactor.Value() == 0 {\n\t\t// Scale up disabled\n\t\treturn currentReplicas\n\t}\n\treturn int32(float64(currentReplicas) + math.Max(1, math.Floor(float64(wpa.Spec.ScaleUpLimitFactor.MilliValue())/1000*float64(currentReplicas)/100)))\n}", "func verifyVolumeProvisioningWithServiceDown(serviceName string, namespace string, client clientset.Interface,\n\tstoragePolicyName string, allowedTopologyHAMap map[string][]string, categories []string, isServiceStopped bool,\n\tf *framework.Framework) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tginkgo.By(\"CNS_TEST: Running for GC setup\")\n\tnodeList, err := fnodes.GetReadySchedulableNodes(client)\n\tframework.ExpectNoError(err, \"Unable to find ready and schedulable Node\")\n\tif !(len(nodeList.Items) > 0) {\n\t\tframework.Failf(\"Unable to find ready and schedulable Node\")\n\t}\n\n\tginkgo.By(fmt.Sprintf(\"Stopping %v on the vCenter host\", serviceName))\n\tvcAddress := e2eVSphere.Config.Global.VCenterHostname + \":\" + sshdPort\n\terr = invokeVCenterServiceControl(stopOperation, serviceName, vcAddress)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tisServiceStopped = true\n\terr = waitVCenterServiceToBeInState(serviceName, vcAddress, svcStoppedMessage)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\n\tdefer func() {\n\t\tif isServiceStopped {\n\t\t\tginkgo.By(fmt.Sprintf(\"Starting %v on the vCenter host\", serviceName))\n\t\t\terr = invokeVCenterServiceControl(startOperation, serviceName, vcAddress)\n\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t\terr = waitVCenterServiceToBeInState(serviceName, vcAddress, svcRunningMessage)\n\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t\tbootstrap()\n\t\t\tisServiceStopped = false\n\t\t}\n\t}()\n\n\tginkgo.By(\"Create statefulset with default pod management policy with replica 3\")\n\tcreateResourceQuota(client, namespace, rqLimit, storagePolicyName)\n\tstorageclass, err := client.StorageV1().StorageClasses().Get(ctx, storagePolicyName, metav1.GetOptions{})\n\tif !apierrors.IsNotFound(err) {\n\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t}\n\n\t// Creating StatefulSet service\n\tginkgo.By(\"Creating service\")\n\tservice := CreateService(namespace, client)\n\tdefer func() {\n\t\tdeleteService(namespace, client, service)\n\t}()\n\n\tstatefulset := GetStatefulSetFromManifest(namespace)\n\tginkgo.By(\"Creating statefulset\")\n\tstatefulset.Spec.VolumeClaimTemplates[len(statefulset.Spec.VolumeClaimTemplates)-1].\n\t\tSpec.StorageClassName = &storageclass.Name\n\t*statefulset.Spec.Replicas = 3\n\t_, err = client.AppsV1().StatefulSets(namespace).Create(ctx, statefulset, metav1.CreateOptions{})\n\tframework.ExpectNoError(err)\n\treplicas := *(statefulset.Spec.Replicas)\n\n\tdefer func() {\n\t\tscaleDownNDeleteStsDeploymentsInNamespace(ctx, client, namespace)\n\t\tpvcs, err := client.CoreV1().PersistentVolumeClaims(namespace).List(ctx, metav1.ListOptions{})\n\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\tfor _, claim := range pvcs.Items {\n\t\t\tpv := getPvFromClaim(client, namespace, claim.Name)\n\t\t\terr := fpv.DeletePersistentVolumeClaim(client, claim.Name, namespace)\n\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t\tginkgo.By(\"Verify it's PV and corresponding volumes are deleted from CNS\")\n\t\t\terr = fpv.WaitForPersistentVolumeDeleted(client, pv.Name, poll,\n\t\t\t\tpollTimeout)\n\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t\tvolumeHandle := pv.Spec.CSI.VolumeHandle\n\t\t\terr = e2eVSphere.waitForCNSVolumeToBeDeleted(volumeHandle)\n\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred(),\n\t\t\t\tfmt.Sprintf(\"Volume: %s should not be present in the CNS after it is deleted from \"+\n\t\t\t\t\t\"kubernetes\", volumeHandle))\n\t\t}\n\t}()\n\n\tginkgo.By(fmt.Sprintf(\"PVC and POD creations should be in pending state since %s is down\", serviceName))\n\tpvcs, err := client.CoreV1().PersistentVolumeClaims(namespace).List(ctx, metav1.ListOptions{})\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tfor _, pvc := range pvcs.Items {\n\t\terr = fpv.WaitForPersistentVolumeClaimPhase(v1.ClaimPending, client,\n\t\t\tpvc.Namespace, pvc.Name, framework.Poll, time.Minute)\n\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to find the volume in pending state with err: %v\", err))\n\t}\n\n\tpods := fss.GetPodList(client, statefulset)\n\tfor _, pod := range pods.Items {\n\t\tif pod.Status.Phase != v1.PodPending {\n\t\t\tframework.Failf(\"Expected pod to be in: %s state but is in: %s state\", v1.PodPending,\n\t\t\t\tpod.Status.Phase)\n\t\t}\n\t}\n\n\tginkgo.By(fmt.Sprintf(\"Starting %v on the vCenter host\", serviceName))\n\terr = invokeVCenterServiceControl(startOperation, serviceName, vcAddress)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tisServiceStopped = false\n\terr = waitVCenterServiceToBeInState(serviceName, vcAddress, svcRunningMessage)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\n\tbootstrap()\n\n\tverifyVolumeMetadataOnStatefulsets(client, ctx, namespace, statefulset, replicas,\n\t\tallowedTopologyHAMap, categories, storagePolicyName, nodeList, f)\n\n}", "func (o HorizontalPodAutoscalerBehaviorPatchOutput) ScaleDown() HPAScalingRulesPatchPtrOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerBehaviorPatch) *HPAScalingRulesPatch { return v.ScaleDown }).(HPAScalingRulesPatchPtrOutput)\n}", "func (this *Decider) OnScale(command common.Command) error {\n\tappMetrical := AppMetrical{}\n\terr := json.Unmarshal([]byte(command.Body), &appMetrical)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tappInfo, strategyName := this.getAppInfo(appMetrical.App)\n\tif appInfo == nil {\n\t\tlog.Printf(\"can not get app info, may be the strategy is disabled.\")\n\t\treturn nil\n\t}\n\n\tscaleNumber, err := getScaleNumber(appMetrical.Metrical, appInfo.AppConf)\n\tif err != nil {\n\t\tlog.Printf(\"get scale number error [%s] : %s\", appMetrical.App, err)\n\t\treturn err\n\t}\n\n\tlog.Printf(\"get scale number: %d\", scaleNumber)\n\n\tif scaleNumber <= 0 {\n\t\t// Do nothing except set the new metrical\n\t\treturn nil\n\t} else if scaleNumber > 0 {\n\t\tappScales := this.getAppScales(strategyName, appInfo, scaleNumber)\n\t\tfmt.Println(\"===need scale=====\", appScales)\n\n\t\tmetricalAppScales := []common.MetricalAppScale{}\n\n\t\tfor _, app := range appScales {\n\t\t\taInfo, _ := this.getAppInfo(app.App)\n\t\t\tmetricalAppScales = append(metricalAppScales,\n\t\t\t\tcommon.MetricalAppScale{app.App, app.Number, aInfo.AppConf.MinNum})\n\t\t}\n\n\t\tmetricalAppScales = append(metricalAppScales,\n\t\t\tcommon.MetricalAppScale{appInfo.AppConf.App,\n\t\t\t\tscaleNumber, appInfo.AppConf.MinNum})\n\n\t\tmetricalAppScaleHosts, e := this.Client.MetricalScaleApps(metricalAppScales)\n\n\t\tif e != nil {\n\t\t\tlog.Printf(\"get metrical app scale hosts failed [%s]\", e)\n\t\t\treturn e\n\t\t}\n\t\tfmt.Println(\"get metrical app scale hosts\", metricalAppScaleHosts)\n\t\t// publish messages to apps\n\t\tpublishMessagesToApps(metricalAppScaleHosts, appInfo.AppConf.App)\n\t}\n\n\tdefer func() {\n\t\t// update current metrical\n\t\t(*appInfo).CurrentMetrical = appMetrical.Metrical\n\t}()\n\n\treturn nil\n}", "func (o HorizontalPodAutoscalerBehaviorOutput) ScaleDown() HPAScalingRulesPtrOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerBehavior) *HPAScalingRules { return v.ScaleDown }).(HPAScalingRulesPtrOutput)\n}", "func (e Engine) randomScaleDown(nodepools []*godo.KubernetesNodePool, numToScale int) error {\n\tnodepools = shuffle(nodepools)\n\tfor _, np := range nodepools {\n\t\tif numToScale == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\t// limitations in DigitalOcean prevent scaling a node pool to less than 1\n\t\tif np.Count == 1 {\n\t\t\tcontinue\n\t\t}\n\n\t\tscaleNodePoolTo := getMinNodesNeededInNodePoolCount(np.Count, numToScale)\n\t\terr := e.scaleNodePoolToCount(np, scaleNodePoolTo)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnumToScale = numToScale - (np.Count - scaleNodePoolTo)\n\t}\n\n\t// this case can happen if the total number of desired nodes is less than the\n\t// number of node pools in the cluster since there has to be 1 node per node pool\n\tif numToScale != 0 {\n\t\treturn errors.New(\"unable to scale to desired node count\")\n\t}\n\n\treturn nil\n}", "func TestScaleDeployment(t *testing.T) {\n\tt.Log(\"Scale deployment\")\n\tclientset, err := k8sutils.MustGetClientset()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tctx := context.Background()\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\tdeploymentsClient := clientset.AppsV1().Deployments(namespace)\n\terr = k8sutils.MustScaleDeployment(ctx, deploymentsClient, deployment, clientset, namespace, podLabelSelector, *replicas, *skipWait)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func (o KubernetesClusterAutoScalerProfilePtrOutput) ScaleDownUnneeded() 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.ScaleDownUnneeded\n\t}).(pulumi.StringPtrOutput)\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 (p *Planner) categorizeNodes(podDestinations map[string]bool, scaleDownCandidates []*apiv1.Node) {\n\tunremovableTimeout := p.latestUpdate.Add(p.context.AutoscalingOptions.UnremovableNodeRecheckTimeout)\n\tunremovableCount := 0\n\tvar removableList []simulator.NodeToBeRemoved\n\tp.unremovableNodes.Update(p.context.ClusterSnapshot.NodeInfos(), p.latestUpdate)\n\tcurrentlyUnneededNodeNames, utilizationMap, ineligible := p.eligibilityChecker.FilterOutUnremovable(p.context, scaleDownCandidates, p.latestUpdate, p.unremovableNodes)\n\tfor _, n := range ineligible {\n\t\tp.unremovableNodes.Add(n)\n\t}\n\tp.nodeUtilizationMap = utilizationMap\n\ttimer := time.NewTimer(p.context.ScaleDownSimulationTimeout)\n\n\tfor i, node := range currentlyUnneededNodeNames {\n\t\tif timedOut(timer) {\n\t\t\tklog.Warningf(\"%d out of %d nodes skipped in scale down simulation due to timeout.\", len(currentlyUnneededNodeNames)-i, len(currentlyUnneededNodeNames))\n\t\t\tbreak\n\t\t}\n\t\tif len(removableList) >= p.unneededNodesLimit() {\n\t\t\tklog.V(4).Infof(\"%d out of %d nodes skipped in scale down simulation: there are already %d unneeded nodes so no point in looking for more.\", len(currentlyUnneededNodeNames)-i, len(currentlyUnneededNodeNames), len(removableList))\n\t\t\tbreak\n\t\t}\n\t\tremovable, unremovable := p.rs.SimulateNodeRemoval(node, podDestinations, p.latestUpdate, p.context.RemainingPdbTracker.GetPdbs())\n\t\tif removable != nil {\n\t\t\t_, inParallel, _ := p.context.RemainingPdbTracker.CanRemovePods(removable.PodsToReschedule)\n\t\t\tif !inParallel {\n\t\t\t\tremovable.IsRisky = true\n\t\t\t}\n\t\t\tdelete(podDestinations, removable.Node.Name)\n\t\t\tp.context.RemainingPdbTracker.RemovePods(removable.PodsToReschedule)\n\t\t\tremovableList = append(removableList, *removable)\n\t\t}\n\t\tif unremovable != nil {\n\t\t\tunremovableCount += 1\n\t\t\tp.unremovableNodes.AddTimeout(unremovable, unremovableTimeout)\n\t\t}\n\t}\n\tp.unneededNodes.Update(removableList, p.latestUpdate)\n\tif unremovableCount > 0 {\n\t\tklog.V(1).Infof(\"%v nodes found to be unremovable in simulation, will re-check them at %v\", unremovableCount, unremovableTimeout)\n\t}\n}", "func UpdateScaleDownInCooldown(inCooldown bool) {\n\tif inCooldown {\n\t\tscaleDownInCooldown.Set(1.0)\n\t} else {\n\t\tscaleDownInCooldown.Set(0.0)\n\t}\n}", "func convertDesiredReplicasWithRules(logger logr.Logger, wpa *datadoghqv1alpha1.WatermarkPodAutoscaler, currentReplicas, desiredReplicas, wpaMinReplicas, wpaMaxReplicas int32, readyReplicas int32) (int32, string, string) {\n\tvar minimumAllowedReplicas int32\n\tvar maximumAllowedReplicas int32\n\tvar possibleLimitingCondition string\n\tvar possibleLimitingReason string\n\n\tscaleDownLimit := calculateScaleDownLimit(wpa, currentReplicas)\n\tpromLabelsForWpa := prometheus.Labels{\n\t\twpaNamePromLabel: wpa.Name,\n\t\twpaNamespacePromLabel: wpa.Namespace,\n\t\tresourceNamespacePromLabel: wpa.Namespace,\n\t\tresourceNamePromLabel: wpa.Spec.ScaleTargetRef.Name,\n\t\tresourceKindPromLabel: wpa.Spec.ScaleTargetRef.Kind,\n\t\treasonPromLabel: \"downscale_capping\",\n\t}\n\t// Compute the maximum and minimum number of replicas we can have\n\tswitch {\n\tcase wpaMinReplicas == 0:\n\t\tminimumAllowedReplicas = 1\n\tcase desiredReplicas < scaleDownLimit:\n\t\tminimumAllowedReplicas = int32(math.Max(float64(scaleDownLimit), float64(wpaMinReplicas)))\n\t\trestrictedScaling.With(promLabelsForWpa).Set(1)\n\t\tpossibleLimitingCondition = \"ScaleDownLimit\"\n\t\tpossibleLimitingReason = \"the desired replica count is decreasing faster than the maximum scale rate\"\n\t\tlogger.Info(\"Downscaling rate higher than limit set by `scaleDownLimitFactor`, capping the maximum downscale to 'minimumAllowedReplicas'\", \"scaleDownLimitFactor\", fmt.Sprintf(\"%.1f\", float64(wpa.Spec.ScaleDownLimitFactor.MilliValue()/1000)), \"wpaMinReplicas\", wpaMinReplicas, \"minimumAllowedReplicas\", minimumAllowedReplicas)\n\t\tif readyReplicas < minimumAllowedReplicas && readyReplicas > 0 {\n\t\t\tlogger.Info(\"Maximum downscale recommendation is higher than current number of ready replicas, aborting\", \"readyReplicas\", readyReplicas, \"currentReplicas\", currentReplicas, \"minimumAllowedReplicas\", minimumAllowedReplicas)\n\t\t\tminimumAllowedReplicas = currentReplicas\n\t\t}\n\tcase desiredReplicas >= scaleDownLimit:\n\t\tminimumAllowedReplicas = wpaMinReplicas\n\t\trestrictedScaling.With(promLabelsForWpa).Set(0)\n\t\tpossibleLimitingCondition = \"TooFewReplicas\"\n\t\tpossibleLimitingReason = \"the desired replica count is below the minimum replica count\"\n\t}\n\n\tif desiredReplicas < minimumAllowedReplicas {\n\t\treturn minimumAllowedReplicas, possibleLimitingCondition, possibleLimitingReason\n\t}\n\n\tscaleUpLimit := calculateScaleUpLimit(wpa, currentReplicas)\n\n\tif desiredReplicas > scaleUpLimit {\n\t\tmaximumAllowedReplicas = int32(math.Min(float64(scaleUpLimit), float64(wpaMaxReplicas)))\n\t\tpromLabelsForWpa[reasonPromLabel] = upscaleCappingPromLabelVal\n\t\trestrictedScaling.With(promLabelsForWpa).Set(1)\n\t\tlogger.Info(\"Upscaling rate higher than limit set by 'ScaleUpLimitFactor', capping the maximum upscale to 'maximumAllowedReplicas'\", \"scaleUpLimitFactor\", fmt.Sprintf(\"%.1f\", float64(wpa.Spec.ScaleUpLimitFactor.MilliValue()/1000)), \"wpaMaxReplicas\", wpaMaxReplicas, \"maximumAllowedReplicas\", maximumAllowedReplicas)\n\t\tpossibleLimitingCondition = \"ScaleUpLimit\"\n\t\tpossibleLimitingReason = \"the desired replica count is increasing faster than the maximum scale rate\"\n\t} else {\n\t\tmaximumAllowedReplicas = wpaMaxReplicas\n\t\trestrictedScaling.With(promLabelsForWpa).Set(0)\n\t\tpossibleLimitingCondition = \"TooManyReplicas\"\n\t\tpossibleLimitingReason = \"the desired replica count is above the maximum replica count\"\n\t}\n\n\t// make sure the desiredReplicas is between the allowed boundaries.\n\tif desiredReplicas > maximumAllowedReplicas {\n\t\tlogger.Info(\"Returning replicas, condition and reason\", \"replicas\", maximumAllowedReplicas, \"condition\", possibleLimitingCondition, reasonPromLabel, possibleLimitingReason)\n\t\treturn maximumAllowedReplicas, possibleLimitingCondition, possibleLimitingReason\n\t}\n\n\tpossibleLimitingCondition = \"DesiredWithinRange\"\n\tpossibleLimitingReason = desiredCountAcceptable\n\n\treturn desiredReplicas, possibleLimitingCondition, possibleLimitingReason\n}", "func (c *KubeTestPlatform) Scale(name string, replicas int32) error {\n\tapp := c.AppResources.FindActiveResource(name)\n\tappManager := app.(*kube.AppManager)\n\n\tif err := appManager.ScaleDeploymentReplica(replicas); err != nil {\n\t\treturn err\n\t}\n\n\t_, err := appManager.WaitUntilDeploymentState(appManager.IsDeploymentDone)\n\n\treturn err\n}", "func DownsizeCluster(brokerId, namespace, ccEndpoint, clusterName string) error {\n\n\terr := GetCruiseControlStatus(namespace, ccEndpoint, clusterName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toptions := map[string]string{\n\t\t\"brokerid\": brokerId,\n\t\t\"dryrun\": \"false\",\n\t\t\"json\": \"true\",\n\t}\n\n\tvar backoffConfig = backoff.ConstantBackoffConfig{\n\t\tDelay: 10 * time.Second,\n\t\tMaxRetries: 5,\n\t}\n\tvar backoffPolicy = backoff.NewConstantBackoffPolicy(&backoffConfig)\n\n\tvar dResp *http.Response\n\n\terr = backoff.Retry(func() error {\n\n\t\tdResp, err = postCruiseControl(removeBrokerAction, namespace, options, ccEndpoint, clusterName)\n\t\tif err != nil && err != errCruiseControlNotReturned200 {\n\t\t\tlog.Error(err, \"can't downsize cluster gracefully since post to cruise-control failed\")\n\t\t\treturn err\n\t\t}\n\t\tif err == errCruiseControlNotReturned200 {\n\t\t\tlog.Info(\"trying to communicate with cc\")\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}, backoffPolicy)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Info(\"Initiated downsize in cruise control\")\n\n\tuTaskId := dResp.Header.Get(\"User-Task-Id\")\n\n\terr = checkIfCCTaskFinished(uTaskId, namespace, ccEndpoint, clusterName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c mockK8sClient) Scale(resource *kubernetes.Workload, replicas int32) error {\n\tc.Counts.NumPods = replicas\n\treturn nil\n}", "func (o KubernetesClusterDefaultNodePoolOutput) ScaleDownMode() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v KubernetesClusterDefaultNodePool) *string { return v.ScaleDownMode }).(pulumi.StringPtrOutput)\n}", "func (db *Db) reconcilePds() error {\n\tvar (\n\t\terr error\n\t\tp = db.Pd\n\t\tchanged = 0\n\t\tpods []v1.Pod\n\t)\n\n\te := db.Event(eventPd, \"reconcile\")\n\tdefer func() {\n\t\tparseError(db, err)\n\t\tif changed > 0 || err != nil {\n\t\t\tif err != nil {\n\t\t\t\tlogs.Error(\"reconcile pd %q cluster error: %v\", db.GetName(), err)\n\t\t\t}\n\t\t\te.Trace(err, \"Reconcile pd cluster\")\n\t\t}\n\t}()\n\n\tpods, err = k8sutil.GetPods(db.GetName(), \"pd\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// mark not running pod\n\tfor _, mb := range p.Members {\n\t\tst := PodFailed\n\t\tfor _, pod := range pods {\n\t\t\tif pod.GetName() == mb.Name && k8sutil.IsPodOk(pod) {\n\t\t\t\tst = PodRunning\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tmb.State = st\n\t}\n\n\t// delete failed pod and create a new pod\n\tfor i, mb := range p.Members {\n\t\tif mb.State == PodRunning {\n\t\t\tcontinue\n\t\t}\n\t\tchanged++\n\t\tlogs.Info(\"start deleting member %q, because it is not available\", mb.Name)\n\t\ttries := 3\n\t\tfor i := 0; i < tries; i++ {\n\t\t\tif err = pdutil.PdMemberDelete(p.OuterAddresses[0], mb.Name); err == nil {\n\t\t\t\t// rejoin a deleted pd\n\t\t\t\tp.join = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlogs.Warn(\"retry delete member %q: %d times\", mb.Name, i+1)\n\t\t\t// maybe is electing\n\t\t\ttime.Sleep(time.Duration(i) * time.Second)\n\t\t}\n\t\tif err != nil {\n\t\t\t// maybe majority members of the cluster fail,\n\t\t\t// the etcd cluster fails and cannot accept more writes\n\t\t\tlogs.Critical(\"failed to delete member, because pd %q cluster is unavailable\", p.Db.GetName())\n\t\t}\n\t\tif err = k8sutil.DeletePod(mb.Name, terminationGracePeriodSeconds); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tp.Member = i + 1\n\t\tp.initialClusterState = \"existing\"\n\t\tif err = p.createPod(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmb.State = PodRunning\n\t}\n\n\tif changed > 0 {\n\t\tif err = p.waitForOk(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// check pd cluster whether normal\n\tjs, err := pdutil.RetryGetPdMembers(p.OuterAddresses[0])\n\tif err != nil {\n\t\tlogs.Critical(\"pd %q cluster is unavailable\", p.Db.GetName())\n\t\t// Perhaps because of pod missing can not be elected\n\t\treturn err\n\t}\n\n\t// Remove uncontrolled member\n\tret := gjson.Get(js, \"members.#.name\")\n\tif ret.Type == gjson.Null {\n\t\tlogs.Critical(\"could not get pd %q members, maybe cluster is unavailable\", p.Db.GetName())\n\t\treturn ErrPdUnavailable\n\t}\n\tfor _, r := range ret.Array() {\n\t\thave := false\n\t\tfor _, mb := range p.Members {\n\t\t\tif r.String() == mb.Name {\n\t\t\t\thave = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !have {\n\t\t\tlogs.Warn(\"delete member %s from pd cluster\", r.String())\n\t\t\tif err = pdutil.PdMemberDelete(p.OuterAddresses[0], r.String()); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// Add missing member\n\tfor i, mb := range p.Members {\n\t\thave := false\n\t\tfor _, r := range ret.Array() {\n\t\t\tif r.String() == mb.Name {\n\t\t\t\thave = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !have {\n\t\t\tchanged++\n\t\t\tlogs.Info(\"restart tikv %q, becase of that not in pd cluster\", mb.Name)\n\t\t\tif err = k8sutil.DeletePod(mb.Name, terminationGracePeriodSeconds); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tp.Member = i + 1\n\t\t\tp.join = true\n\t\t\tp.initialClusterState = \"existing\"\n\t\t\tif err = p.createPod(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tmb.State = PodRunning\n\t\t}\n\t}\n\tif changed > 0 {\n\t\tif err = p.waitForOk(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (schedulerClient *Scheduler) ScaleIn(workerpoolName string, nodeIP string) {\n\t//first try to get the cluster information to exclude network issue\n\ttestInternetConnection := schedulerClient.clusterClient.getClusterResourceGroup()\n\tif testInternetConnection == \"\"{\n\t\tlog.Println(\"ScaleIn: network problem\")\n\t\treturn\n\t}\n\tprevSize := len(schedulerClient.clusterClient.getWorkersNodesIP(schedulerClient.workerPool))\n\tif prevSize == 0{\n\t\tlog.Println(\"Warning: the node list can't empty, skip the action\")\n\t\treturn\n\t}\n\tsucceed := schedulerClient.clusterClient.removeWorker(workerpoolName,nodeIP)\n\tif !succeed {\n\t\tlog.Printf(\"Node %s in %s can not be removed\\n\",nodeIP,workerpoolName)\n\t}else {\n\t\tlog.Printf(\"Node %s in %s is being removed\\n\", nodeIP, workerpoolName)\n\t\ttimeBegin := time.Now()\n\t\tfor {\n\t\t\tnodes := schedulerClient.clusterClient.getWorkersNodesIP(schedulerClient.workerPool)\n\t\t\tcurrSize := len(nodes)\t// get the current size\n\t\t\t//TODO: rework on the logic for next version, cuz now any inference on cluster ui might cause an issue\n\t\t\tif currSize == prevSize - 1 {\n\t\t\t\tcanBreak := true\n\t\t\t\tfor _,val := range nodes {\n\t\t\t\t\tif val == nodeIP {canBreak = false}\n\t\t\t\t}\n\t\t\t\tif canBreak {\n\t\t\t\t\tlog.Println(\"Removed worker node takes: \",time.Now().Sub(timeBegin).Minutes(),\" mins\")\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif int(time.Now().Sub(timeBegin).Minutes()) > 10 {break;}\n\t\t}\n\t}\n}", "func runReplicatedPodOnEachNode(ctx context.Context, f *framework.Framework, nodes []v1.Node, namespace string, podsPerNode int, id string, labels map[string]string, memRequest int64) error {\n\tginkgo.By(\"Run a pod on each node\")\n\tfor _, node := range nodes {\n\t\terr := makeNodeUnschedulable(ctx, f.ClientSet, &node)\n\n\t\tn := node\n\t\tginkgo.DeferCleanup(makeNodeSchedulable, f.ClientSet, &n, false)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tconfig := &testutils.RCConfig{\n\t\tClient: f.ClientSet,\n\t\tName: id,\n\t\tNamespace: namespace,\n\t\tTimeout: defaultTimeout,\n\t\tImage: imageutils.GetPauseImageName(),\n\t\tReplicas: 0,\n\t\tLabels: labels,\n\t\tMemRequest: memRequest,\n\t}\n\terr := e2erc.RunRC(ctx, *config)\n\tif err != nil {\n\t\treturn err\n\t}\n\trc, err := f.ClientSet.CoreV1().ReplicationControllers(namespace).Get(ctx, id, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor i, node := range nodes {\n\t\terr = makeNodeSchedulable(ctx, f.ClientSet, &node, false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Update replicas count, to create new pods that will be allocated on node\n\t\t// (we retry 409 errors in case rc reference got out of sync)\n\t\tfor j := 0; j < 3; j++ {\n\t\t\t*rc.Spec.Replicas = int32((i + 1) * podsPerNode)\n\t\t\trc, err = f.ClientSet.CoreV1().ReplicationControllers(namespace).Update(ctx, rc, metav1.UpdateOptions{})\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif !apierrors.IsConflict(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tklog.Warningf(\"Got 409 conflict when trying to scale RC, retries left: %v\", 3-j)\n\t\t\trc, err = f.ClientSet.CoreV1().ReplicationControllers(namespace).Get(ctx, id, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\terr = wait.PollImmediate(5*time.Second, podTimeout, func() (bool, error) {\n\t\t\trc, err = f.ClientSet.CoreV1().ReplicationControllers(namespace).Get(ctx, id, metav1.GetOptions{})\n\t\t\tif err != nil || rc.Status.ReadyReplicas < int32((i+1)*podsPerNode) {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn true, nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to coerce RC into spawning a pod on node %s within timeout\", node.Name)\n\t\t}\n\t\terr = makeNodeUnschedulable(ctx, f.ClientSet, &node)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (w *Worker) scaleDeployment(dep types.Deployment, replicas int64) {\n\tlockRes := strconv.FormatInt(dep.ID, 10)\n\terr := w.distLock.Lock(lockRes)\n\tif err != nil {\n\t\tw.log.Error(\"Failed to acquire deployment lock\", err)\n\t\treturn\n\t}\n\tscaledOk, stdout := w.kubectl.ScaleDeployment(dep.K8SName, replicas)\n\terr = w.distLock.Unlock(lockRes)\n\tif err != nil {\n\t\tw.log.Error(\"Failed to release deployment lock\", err)\n\t}\n\tdep.Replicas = replicas\n\terr = w.recordRevision(dep, stdout)\n\tif err != nil {\n\t\tw.log.Error(\"Failed to record revision\", err)\n\t}\n\tif scaledOk == true {\n\t\terr = w.databaseClient.SaveDeployment(&dep)\n\t\tif err != nil {\n\t\t\tw.log.Error(\"Failed to save deployment to db\", err)\n\t\t\treturn\n\t\t}\n\t}\n}", "func Pod(\n\tinCluster *v1beta1.PostgresCluster,\n\tinConfigMap *corev1.ConfigMap,\n\toutPod *corev1.PodSpec, pgAdminVolume *corev1.PersistentVolumeClaim,\n) {\n\tif inCluster.Spec.UserInterface == nil || inCluster.Spec.UserInterface.PGAdmin == nil {\n\t\t// pgAdmin is disabled; there is nothing to do.\n\t\treturn\n\t}\n\n\t// create the pgAdmin Pod volumes\n\ttmp := corev1.Volume{Name: tmpVolume}\n\ttmp.EmptyDir = &corev1.EmptyDirVolumeSource{\n\t\tMedium: corev1.StorageMediumMemory,\n\t}\n\n\tpgAdminLog := corev1.Volume{Name: logVolume}\n\tpgAdminLog.EmptyDir = &corev1.EmptyDirVolumeSource{\n\t\tMedium: corev1.StorageMediumMemory,\n\t}\n\n\tpgAdminData := corev1.Volume{Name: dataVolume}\n\tpgAdminData.VolumeSource = corev1.VolumeSource{\n\t\tPersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{\n\t\t\tClaimName: pgAdminVolume.Name,\n\t\t\tReadOnly: false,\n\t\t},\n\t}\n\n\tconfigVolumeMount := corev1.VolumeMount{\n\t\tName: \"pgadmin-config\", MountPath: configMountPath, ReadOnly: true,\n\t}\n\tconfigVolume := corev1.Volume{Name: configVolumeMount.Name}\n\tconfigVolume.Projected = &corev1.ProjectedVolumeSource{\n\t\tSources: podConfigFiles(inConfigMap, *inCluster.Spec.UserInterface.PGAdmin),\n\t}\n\n\tstartupVolumeMount := corev1.VolumeMount{\n\t\tName: \"pgadmin-startup\", MountPath: startupMountPath, ReadOnly: true,\n\t}\n\tstartupVolume := corev1.Volume{Name: startupVolumeMount.Name}\n\tstartupVolume.EmptyDir = &corev1.EmptyDirVolumeSource{\n\t\tMedium: corev1.StorageMediumMemory,\n\n\t\t// When this volume is too small, the Pod will be evicted and recreated\n\t\t// by the StatefulSet controller.\n\t\t// - https://kubernetes.io/docs/concepts/storage/volumes/#emptydir\n\t\t// NOTE: tmpfs blocks are PAGE_SIZE, usually 4KiB, and size rounds up.\n\t\tSizeLimit: resource.NewQuantity(32<<10, resource.BinarySI),\n\t}\n\n\t// pgadmin container\n\tcontainer := corev1.Container{\n\t\tName: naming.ContainerPGAdmin,\n\t\tEnv: []corev1.EnvVar{\n\t\t\t{\n\t\t\t\tName: \"PGADMIN_SETUP_EMAIL\",\n\t\t\t\tValue: loginEmail,\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"PGADMIN_SETUP_PASSWORD\",\n\t\t\t\tValue: loginPassword,\n\t\t\t},\n\t\t\t// Setting the KRB5_CONFIG for kerberos\n\t\t\t// - https://web.mit.edu/kerberos/krb5-current/doc/admin/conf_files/krb5_conf.html\n\t\t\t{\n\t\t\t\tName: \"KRB5_CONFIG\",\n\t\t\t\tValue: configMountPath + \"/krb5.conf\",\n\t\t\t},\n\t\t\t// In testing it was determined that we need to set this env var for the replay cache\n\t\t\t// otherwise it defaults to the read-only location `/var/tmp/`\n\t\t\t// - https://web.mit.edu/kerberos/krb5-current/doc/basic/rcache_def.html#replay-cache-types\n\t\t\t{\n\t\t\t\tName: \"KRB5RCACHEDIR\",\n\t\t\t\tValue: \"/tmp\",\n\t\t\t},\n\t\t},\n\t\tCommand: []string{\"bash\", \"-c\", startupScript},\n\t\tImage: config.PGAdminContainerImage(inCluster),\n\t\tImagePullPolicy: inCluster.Spec.ImagePullPolicy,\n\t\tResources: inCluster.Spec.UserInterface.PGAdmin.Resources,\n\n\t\tSecurityContext: initialize.RestrictedSecurityContext(),\n\n\t\tPorts: []corev1.ContainerPort{{\n\t\t\tName: naming.PortPGAdmin,\n\t\t\tContainerPort: int32(pgAdminPort),\n\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t}},\n\t\tVolumeMounts: []corev1.VolumeMount{\n\t\t\tstartupVolumeMount,\n\t\t\tconfigVolumeMount,\n\t\t\t{\n\t\t\t\tName: tmpVolume,\n\t\t\t\tMountPath: runMountPath,\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: logVolume,\n\t\t\t\tMountPath: logMountPath,\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: dataVolume,\n\t\t\t\tMountPath: dataMountPath,\n\t\t\t},\n\t\t},\n\t\tReadinessProbe: &corev1.Probe{\n\t\t\tProbeHandler: corev1.ProbeHandler{\n\t\t\t\tTCPSocket: &corev1.TCPSocketAction{\n\t\t\t\t\tPort: intstr.FromInt(pgAdminPort),\n\t\t\t\t},\n\t\t\t},\n\t\t\tInitialDelaySeconds: 20,\n\t\t\tPeriodSeconds: 10,\n\t\t},\n\t\tLivenessProbe: &corev1.Probe{\n\t\t\tProbeHandler: corev1.ProbeHandler{\n\t\t\t\tTCPSocket: &corev1.TCPSocketAction{\n\t\t\t\t\tPort: intstr.FromInt(pgAdminPort),\n\t\t\t\t},\n\t\t\t},\n\t\t\tInitialDelaySeconds: 15,\n\t\t\tPeriodSeconds: 20,\n\t\t},\n\t}\n\n\tstartup := corev1.Container{\n\t\tName: naming.ContainerPGAdminStartup,\n\t\tCommand: startupCommand(),\n\n\t\tImage: container.Image,\n\t\tImagePullPolicy: container.ImagePullPolicy,\n\t\tResources: container.Resources,\n\t\tSecurityContext: initialize.RestrictedSecurityContext(),\n\t\tVolumeMounts: []corev1.VolumeMount{\n\t\t\tstartupVolumeMount,\n\t\t\tconfigVolumeMount,\n\t\t},\n\t}\n\n\t// The startup container is the only one allowed to write to the startup volume.\n\tstartup.VolumeMounts[0].ReadOnly = false\n\n\toutPod.InitContainers = []corev1.Container{startup}\n\t// add all volumes other than 'tmp' as that is added later\n\toutPod.Volumes = []corev1.Volume{pgAdminLog, pgAdminData, configVolume, startupVolume}\n\n\toutPod.Containers = []corev1.Container{container}\n}", "func (o KubernetesClusterAutoScalerProfileOutput) ScaleDownUnready() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v KubernetesClusterAutoScalerProfile) *string { return v.ScaleDownUnready }).(pulumi.StringPtrOutput)\n}", "func (s *K8sSvc) ScaleService(ctx context.Context, cluster string, service string, desiredCount int64) error {\n\trequuid := utils.GetReqIDFromContext(ctx)\n\n\t// get statefulset\n\tstatefulset, err := s.cliset.AppsV1beta2().StatefulSets(s.namespace).Get(service, metav1.GetOptions{})\n\tif err != nil {\n\t\tglog.Errorln(\"get statefulset error\", err, \"requuid\", requuid, \"service\", service, \"namespace\", s.namespace)\n\t\treturn err\n\t}\n\n\tglog.Infoln(\"get statefulset for service\", service, \"requuid\", requuid, statefulset.Status)\n\n\t// update statefulset Replicas\n\tstatefulset.Spec.Replicas = utils.Int32Ptr(int32(desiredCount))\n\t_, err = s.cliset.AppsV1beta2().StatefulSets(s.namespace).Update(statefulset)\n\tif err != nil {\n\t\tglog.Errorln(\"update statefulset error\", err, \"requuid\", requuid, \"service\", service, \"namespace\", s.namespace)\n\t\treturn err\n\t}\n\n\tglog.Infoln(\"ScaleService complete\", service, \"desiredCount\", desiredCount, \"requuid\", requuid)\n\treturn nil\n}", "func TestAutoscalingMachinePool(t *testing.T) {\n\t// minReplicas is the minimum number of replicas for the machine pool.\n\t// It is set to 10 to ensure that it is at least as large as the number\n\t// of zones in whichever platform and region the test is running on. If\n\t// the min replicas is less than the number of zones, then the machine pool\n\t// controller will reject the machine pool.\n\tconst minReplicas = 10\n\tconst maxReplicas = 12\n\n\tcd := common.MustGetInstalledClusterDeployment()\n\tcfg := common.MustGetClusterDeploymentClientConfig()\n\n\tswitch p := cd.Spec.Platform; {\n\tcase p.AWS == nil:\n\tcase p.GCP == nil:\n\tdefault:\n\t\tt.Log(\"Scaling the machine pool is only implemented for AWS and GCP\")\n\t}\n\n\tc := common.MustGetClient()\n\trc := common.MustGetClientFromConfig(cfg)\n\n\t// Scale up\n\tpool := common.GetMachinePool(cd, \"worker\")\n\tif pool == nil {\n\t\tt.Fatal(\"worker machine pool does not exist\")\n\t}\n\tpool.Spec.Replicas = nil\n\tpool.Spec.Autoscaling = &hivev1.MachinePoolAutoscaling{\n\t\tMinReplicas: minReplicas,\n\t\tMaxReplicas: maxReplicas,\n\t}\n\tif err := c.Update(context.TODO(), pool); err != nil {\n\t\tt.Fatalf(\"cannot update worker machine pool to reduce replicas: %v\", err)\n\t}\n\n\t// Lower autoscaler delays so that scaling down happens faster\n\tclusterAutoscaler := &autoscalingv1.ClusterAutoscaler{}\n\tfor i := 0; i < 10; i++ {\n\t\tswitch err := rc.Get(context.Background(), client.ObjectKey{Name: \"default\"}, clusterAutoscaler); {\n\t\tcase apierrors.IsNotFound(err):\n\t\t\tt.Log(\"waiting for Hive to create cluster autoscaler\")\n\t\t\ttime.Sleep(10 * time.Second)\n\t\tcase err != nil:\n\t\t\tt.Fatalf(\"could not get the cluster autoscaler: %v\", err)\n\t\t}\n\t}\n\tif clusterAutoscaler.Name == \"\" {\n\t\tt.Fatalf(\"timed out waiting for cluster autoscaler\")\n\t}\n\tif clusterAutoscaler.Spec.ScaleDown == nil {\n\t\tclusterAutoscaler.Spec.ScaleDown = &autoscalingv1.ScaleDownConfig{}\n\t}\n\tclusterAutoscaler.Spec.ScaleDown.DelayAfterAdd = pointer.StringPtr(\"10s\")\n\tclusterAutoscaler.Spec.ScaleDown.DelayAfterDelete = pointer.StringPtr(\"10s\")\n\tclusterAutoscaler.Spec.ScaleDown.DelayAfterFailure = pointer.StringPtr(\"10s\")\n\tclusterAutoscaler.Spec.ScaleDown.UnneededTime = pointer.StringPtr(\"10s\")\n\tif err := rc.Update(context.Background(), clusterAutoscaler); err != nil {\n\t\tt.Fatalf(\"could not update the cluster autoscaler: %v\", err)\n\t}\n\n\t// busyboxDeployment creates a large number of pods to place CPU pressure\n\t// on the machine pool. With 50 replicas and a CPU request for each pod of\n\t// 2, the total CPU request from the deployment is 100. For AWS using m4.xlarge,\n\t// each machine has a CPU limit of 4. For the max replicas of 12, the total\n\t// CPU limit is 48.\n\tbusyboxDeployment := &extensionsv1beta1.Deployment{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: \"default\",\n\t\t\tName: \"busybox\",\n\t\t},\n\t\tSpec: extensionsv1beta1.DeploymentSpec{\n\t\t\tReplicas: pointer.Int32Ptr(50),\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: map[string]string{\n\t\t\t\t\t\"scaling-app\": \"busybox\",\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: map[string]string{\n\t\t\t\t\t\t\"scaling-app\": \"busybox\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tContainers: []corev1.Container{{\n\t\t\t\t\t\tName: \"sleep\",\n\t\t\t\t\t\tImage: \"busybox\",\n\t\t\t\t\t\tCommand: []string{\"sleep\", \"3600\"},\n\t\t\t\t\t\tResources: corev1.ResourceRequirements{\n\t\t\t\t\t\t\tRequests: corev1.ResourceList{\n\t\t\t\t\t\t\t\tcorev1.ResourceCPU: func() resource.Quantity {\n\t\t\t\t\t\t\t\t\tq, err := resource.ParseQuantity(\"2\")\n\t\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\t\tt.Fatalf(\"could not parse quantity\")\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn q\n\t\t\t\t\t\t\t\t}(),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tif err := rc.Create(context.TODO(), busyboxDeployment); err != nil {\n\t\tt.Fatalf(\"cannot create busybox deployment: %v\", err)\n\t}\n\n\tif err := waitForMachines(cfg, cd, \"worker\", maxReplicas); err != nil {\n\t\tt.Errorf(\"timed out waiting for machines to be created\")\n\t}\n\tif err := waitForNodes(cfg, cd, \"worker\", maxReplicas); err != nil {\n\t\tt.Errorf(\"timed out waiting for nodes to be created\")\n\t}\n\n\t// Scale down\n\tif err := rc.Get(context.TODO(), client.ObjectKey{Namespace: \"default\", Name: \"busybox\"}, busyboxDeployment); err != nil {\n\t\tt.Fatalf(\"could not get busybox deployment: %v\", err)\n\t}\n\tbusyboxDeployment.Spec.Replicas = pointer.Int32Ptr(0)\n\tif err := rc.Update(context.TODO(), busyboxDeployment); err != nil {\n\t\tt.Fatalf(\"could not update busybox deployment to scale down replicas: %v\", err)\n\t}\n\tif err := waitForMachines(cfg, cd, \"worker\", minReplicas); err != nil {\n\t\tt.Errorf(\"timed out waiting for machines to be created\")\n\t}\n\tif err := waitForNodes(cfg, cd, \"worker\", minReplicas); err != nil {\n\t\tt.Errorf(\"timed out waiting for nodes to be created\")\n\t}\n\n\t// Disable auto-scaling\n\tpool = common.GetMachinePool(cd, \"worker\")\n\tif pool == nil {\n\t\tt.Fatal(\"worker machine pool does not exist\")\n\t}\n\tpool.Spec.Replicas = pointer.Int64Ptr(3)\n\tpool.Spec.Autoscaling = nil\n\tif err := c.Update(context.TODO(), pool); err != nil {\n\t\tt.Fatalf(\"cannot update worker machine pool to turn off auto-scaling: %v\", err)\n\t}\n\tif err := waitForMachines(cfg, cd, \"worker\", 3); err != nil {\n\t\tt.Errorf(\"timed out waiting for machines to be created\")\n\t}\n\tif err := waitForNodes(cfg, cd, \"worker\", 3); err != nil {\n\t\tt.Errorf(\"timed out waiting for nodes to be created\")\n\t}\n}", "func testDeployment(replicas int32, podLabels map[string]string, nodeSelector map[string]string, namespace string, pvclaims []*v1.PersistentVolumeClaim, securityLevel admissionapi.Level, command string) *appsv1.Deployment {\n\tif len(command) == 0 {\n\t\tcommand = \"trap exit TERM; while true; do sleep 1; done\"\n\t}\n\tzero := int64(0)\n\tdeploymentName := \"deployment-\" + string(uuid.NewUUID())\n\tdeploymentSpec := &appsv1.Deployment{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: deploymentName,\n\t\t\tNamespace: namespace,\n\t\t},\n\t\tSpec: appsv1.DeploymentSpec{\n\t\t\tReplicas: &replicas,\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: podLabels,\n\t\t\t},\n\t\t\tTemplate: v1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: podLabels,\n\t\t\t\t},\n\t\t\t\tSpec: v1.PodSpec{\n\t\t\t\t\tTerminationGracePeriodSeconds: &zero,\n\t\t\t\t\tContainers: []v1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"write-pod\",\n\t\t\t\t\t\t\tImage: e2epod.GetDefaultTestImage(),\n\t\t\t\t\t\t\tCommand: e2epod.GenerateScriptCmd(command),\n\t\t\t\t\t\t\tSecurityContext: e2epod.GenerateContainerSecurityContext(securityLevel),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tRestartPolicy: v1.RestartPolicyAlways,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tvar volumeMounts = make([]v1.VolumeMount, len(pvclaims))\n\tvar volumes = make([]v1.Volume, len(pvclaims))\n\tfor index, pvclaim := range pvclaims {\n\t\tvolumename := fmt.Sprintf(\"volume%v\", index+1)\n\t\tvolumeMounts[index] = v1.VolumeMount{Name: volumename, MountPath: \"/mnt/\" + volumename}\n\t\tvolumes[index] = v1.Volume{Name: volumename, VolumeSource: v1.VolumeSource{PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{ClaimName: pvclaim.Name, ReadOnly: false}}}\n\t}\n\tdeploymentSpec.Spec.Template.Spec.Containers[0].VolumeMounts = volumeMounts\n\tdeploymentSpec.Spec.Template.Spec.Volumes = volumes\n\tif nodeSelector != nil {\n\t\tdeploymentSpec.Spec.Template.Spec.NodeSelector = nodeSelector\n\t}\n\treturn deploymentSpec\n}", "func (c *RolloutController) scaleDownOldReplicaSetsForBlueGreen(oldRSs []*appsv1.ReplicaSet, rollout *v1alpha1.Rollout) (bool, error) {\n\tlogCtx := logutil.WithRollout(rollout)\n\tsort.Sort(sort.Reverse(replicasetutil.ReplicaSetsByRevisionNumber(oldRSs)))\n\n\thasScaled := false\n\tannotationedRSs := int32(0)\n\trolloutReplicas := defaults.GetReplicasOrDefault(rollout.Spec.Replicas)\n\tfor _, targetRS := range oldRSs {\n\t\tdesiredReplicaCount := int32(0)\n\t\tif scaleDownAtStr, ok := targetRS.Annotations[v1alpha1.DefaultReplicaSetScaleDownDeadlineAnnotationKey]; ok {\n\t\t\tannotationedRSs++\n\t\t\tscaleDownAtTime, err := time.Parse(time.RFC3339, scaleDownAtStr)\n\t\t\tif err != nil {\n\t\t\t\tlogCtx.Warnf(\"Unable to read scaleDownAt label on rs '%s'\", targetRS.Name)\n\t\t\t} else if rollout.Spec.Strategy.BlueGreen.ScaleDownDelayRevisionLimit != nil && annotationedRSs == *rollout.Spec.Strategy.BlueGreen.ScaleDownDelayRevisionLimit {\n\t\t\t\tlogCtx.Info(\"At ScaleDownDelayRevisionLimit and scaling down the rest\")\n\t\t\t} else {\n\t\t\t\tnow := metav1.Now()\n\t\t\t\tscaleDownAt := metav1.NewTime(scaleDownAtTime)\n\t\t\t\tif scaleDownAt.After(now.Time) {\n\t\t\t\t\tlogCtx.Infof(\"RS '%s' has not reached the scaleDownTime\", targetRS.Name)\n\t\t\t\t\tremainingTime := scaleDownAt.Sub(now.Time)\n\t\t\t\t\tif remainingTime < c.resyncPeriod {\n\t\t\t\t\t\tc.enqueueRolloutAfter(rollout, remainingTime)\n\t\t\t\t\t}\n\t\t\t\t\tdesiredReplicaCount = rolloutReplicas\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif *(targetRS.Spec.Replicas) == desiredReplicaCount {\n\t\t\t// at desired account\n\t\t\tcontinue\n\t\t}\n\t\t// Scale down.\n\t\t_, _, err := c.scaleReplicaSetAndRecordEvent(targetRS, desiredReplicaCount, rollout)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\thasScaled = true\n\t}\n\n\treturn hasScaled, nil\n}", "func (c *ConfigMapScaler) ExecuteScale(context *contextinternal.Context,\n\tclusterStateRegistry *clusterstate.ClusterStateRegistry,\n\tsd *ScaleDown, nodes []*corev1.Node, options ScaleUpOptions,\n\tcandidates ScaleDownCandidates,\n\tnodeNameToNodeInfo map[string]*schedulernodeinfo.NodeInfo) error {\n\n\terr := ExecuteScaleUp(context, clusterStateRegistry, options, c.maxBulkScaleUpCount)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(options) > 0 {\n\t\tklog.Infof(\"Scaling up node groups now, skip scaling down progress\")\n\t\treturn nil\n\t}\n\n\terr = ExecuteScaleDown(context, sd, nodes, candidates, nodeNameToNodeInfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func scaleInSafely() (bool, error) {\n\ttc, err := cli.PingcapV1alpha1().TidbClusters(ns).Get(clusterName, metav1.GetOptions{})\n\tif err != nil {\n\t\tlogf(\"failed to get tidbcluster when scale in tidbcluster, error: %v\", err)\n\t\treturn false, nil\n\t}\n\n\ttikvSetName := controller.TiKVMemberName(clusterName)\n\ttikvSet, err := kubeCli.AppsV1beta1().StatefulSets(ns).Get(tikvSetName, metav1.GetOptions{})\n\tif err != nil {\n\t\tlogf(\"failed to get tikvSet statefulset: [%s], error: %v\", tikvSetName, err)\n\t\treturn false, nil\n\t}\n\n\tpdClient := controller.NewDefaultPDControl().GetPDClient(tc)\n\tstores, err := pdClient.GetStores()\n\tif err != nil {\n\t\tlogf(\"pdClient.GetStores failed,error: %v\", err)\n\t\treturn false, nil\n\t}\n\tif len(stores.Stores) > int(*tikvSet.Spec.Replicas) {\n\t\tlogf(\"stores.Stores: %v\", stores.Stores)\n\t\tlogf(\"tikvSet.Spec.Replicas: %d\", *tikvSet.Spec.Replicas)\n\t\treturn false, fmt.Errorf(\"the tikvSet.Spec.Replicas may reduce before tikv complete offline\")\n\t}\n\n\tif *tikvSet.Spec.Replicas == tc.Spec.TiKV.Replicas {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}", "func compssScalingOutBackgroundTasks(cluster *imec_db.DB_INFRASTRUCTURE_CLUSTER, dbTask structs.DB_TASK, items map[string]interface{}) []structs.DB_TASK_POD {\n\tlog.Println(pathLOG + \"COMPSs [compssScalingOutBackgroundTasks] Exposing new services ...\")\n\n\t// get main port and protocol\n\tmainPort, mainProtocol := adapt_common.GetMainPort(dbTask.TaskDefinition)\n\n\t// get list of pods - all pods\n\tlTaskPods := checkCurrentPodsInfoFromTask(cluster, items, mainPort, mainProtocol, dbTask)\n\n\t// add new services\n\tlog.Println(pathLOG + \"COMPSs [compssScalingOutBackgroundTasks] Updating new pods (/metadata/labels/pod-name) / Creating and exposing new pods services ...\")\n\tfor _, pod := range lTaskPods { // iterate all pods (including new pods)\n\t\tnotfound := true\n\t\tfor _, podold := range dbTask.Pods { // check if pod is new or old\n\t\t\tif pod.Name == podold.Name {\n\t\t\t\tnotfound = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif notfound == true {\n\t\t\tlog.Println(pathLOG + \"COMPSs [compssScalingOutBackgroundTasks] Updating pod \" + pod.Name)\n\t\t\tstatus, err := patchPods(cluster, dbTask.TaskDefinition.Dock, pod.Name)\n\t\t\t// TODO check errors\n\t\t\tlog.Println(pathLOG + \"COMPSs [compssScalingOutBackgroundTasks] status: \" + status)\n\n\t\t\tif err == nil {\n\t\t\t\tlog.Println(pathLOG + \"COMPSs [compssScalingOutBackgroundTasks] Creating and exposing pod's service ...\")\n\t\t\t\t_, _ = podService(cluster, dbTask.TaskDefinition.Dock, pod)\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Println(pathLOG + \"COMPSs [compssScalingOutBackgroundTasks] Update finished\")\n\treturn lTaskPods\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 ScaleClusterNodeCount(ctx context.Context, clusterClient containerservice.ManagedClustersClient, resourceName string, nodePool string, count int32) (status string, err error) {\n\tresourceGroupName := resourceName + \"-group\"\n\n\t// get current cluster\n\tc, err := clusterClient.Get(ctx, resourceGroupName, resourceName)\n\tif err != nil {\n\t\tfmt.Printf(\"Error getting cluster %v: %v\\n\", resourceName, err)\n\t}\n\n\t// check cluster status before scaling\n\tif *c.ProvisioningState != \"Succeeded\" {\n\t\treturn \"\", fmt.Errorf(\"Unable to update cluster while it is currently %v\", *c.ProvisioningState)\n\t}\n\n\t// get the current VMSize from the cluster\n\tvar vmSize containerservice.VMSizeTypes\n\tfor _, v := range *c.ManagedClusterProperties.AgentPoolProfiles {\n\t\tif *v.Name == nodePool {\n\t\t\tvmSize = v.VMSize\n\t\t}\n\t}\n\n\t// scale cluster\n\tfuture, err := clusterClient.CreateOrUpdate(\n\t\tctx,\n\t\tresourceGroupName,\n\t\tresourceName,\n\t\tcontainerservice.ManagedCluster{\n\t\t\tLocation: c.Location,\n\t\t\tManagedClusterProperties: &containerservice.ManagedClusterProperties{\n\t\t\t\tAgentPoolProfiles: &[]containerservice.ManagedClusterAgentPoolProfile{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: to.StringPtr(nodePool),\n\t\t\t\t\t\tCount: to.Int32Ptr(count),\n\t\t\t\t\t\tVMSize: vmSize,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"cannot scale cluster: %v\", err)\n\t}\n\n\tstatus = future.Status()\n\tif status != \"Updating\" {\n\t\treturn \"\", fmt.Errorf(\"unable to scale: %v\", err)\n\t}\n\n\treturn status, nil\n}", "func TestServiceScale(t *testing.T) {\n\tt.Parallel()\n\n\ts := NewSystemTest(t, \"cases/service_scale\", nil)\n\ts.Terraform.Apply()\n\tdefer s.Terraform.Destroy()\n\n\tserviceID := s.Terraform.Output(\"service_id\")\n\n\ts.Layer0.ScaleService(serviceID, 3)\n\ttestutils.WaitFor(t, time.Second*10, time.Minute*5, func() bool {\n\t\tlog.Debugf(\"Waiting for service to scale up\")\n\t\tservice := s.Layer0.GetService(serviceID)\n\t\treturn service.RunningCount == 3\n\t})\n\n\ts.Layer0.ScaleService(serviceID, 1)\n\ttestutils.WaitFor(t, time.Second*10, time.Minute*5, func() bool {\n\t\tlog.Debugf(\"Waiting for service to scale down\")\n\t\tservice := s.Layer0.GetService(serviceID)\n\t\treturn service.RunningCount == 1\n\t})\n}", "func applyScaleMeta(meta *runapi.ObjectMeta, scaleType string, scaleValue int) {\n\tif scaleValue > 0 {\n\t\tmeta.Annotations[\"autoscaling.knative.dev\"+scaleType] = strconv.Itoa(scaleValue)\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 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 (m *AzureManagedControlPlane) validateScaleDownDelayAfterDelete() field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif ptr.Deref(m.Spec.AutoScalerProfile.ScaleDownDelayAfterDelete, \"\") != \"\" {\n\t\tif !rScaleDownDelayAfterDelete.MatchString(ptr.Deref(m.Spec.AutoScalerProfile.ScaleDownDelayAfterDelete, \"\")) {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"Spec\", \"AutoscalerProfile\", \"ScaleDownDelayAfterDelete\"), ptr.Deref(m.Spec.AutoScalerProfile.ScaleDownDelayAfterDelete, \"\"), \"invalid value\"))\n\t\t}\n\t}\n\treturn allErrs\n}", "func (ec *experimentContext) removeScaleDownDelay(rs *appsv1.ReplicaSet) (bool, error) {\n\tctx := context.TODO()\n\trsIsUpdated := false\n\tif !replicasetutil.HasScaleDownDeadline(rs) {\n\t\treturn rsIsUpdated, nil\n\t}\n\tpatch := fmt.Sprintf(removeScaleDownAtAnnotationsPatch, v1alpha1.DefaultReplicaSetScaleDownDeadlineAnnotationKey)\n\t_, err := ec.kubeclientset.AppsV1().ReplicaSets(rs.Namespace).Patch(ctx, rs.Name, patchtypes.JSONPatchType, []byte(patch), metav1.PatchOptions{})\n\tif err == nil {\n\t\tec.log.Infof(\"Removed '%s' annotation from RS '%s'\", v1alpha1.DefaultReplicaSetScaleDownDeadlineAnnotationKey, rs.Name)\n\t\trsIsUpdated = true\n\t}\n\treturn rsIsUpdated, err\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 removeDisabledPods(dataDir, containerRuntimeEndpoint string, disabledItems map[string]bool, clusterReset bool) error {\n\tterminatePods := false\n\texecPath := binDir(dataDir)\n\tmanifestDir := podManifestsDir(dataDir)\n\n\t// no need to clean up static pods if this is a clean install (bin or manifests dirs missing)\n\tfor _, path := range []string{execPath, manifestDir} {\n\t\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t// ensure etcd and the apiserver are terminated if doing a cluster-reset, and force pod\n\t// termination even if there are no manifests on disk\n\tif clusterReset {\n\t\tdisabledItems[\"etcd\"] = true\n\t\tdisabledItems[\"kube-apiserver\"] = true\n\t\tterminatePods = true\n\t}\n\n\t// check to see if there are manifests for any disabled components. If there are no manifests for\n\t// disabled components, and termination wasn't forced by cluster-reset, termination is skipped.\n\tfor component, disabled := range disabledItems {\n\t\tif disabled {\n\t\t\tmanifestName := filepath.Join(manifestDir, component+\".yaml\")\n\t\t\tif _, err := os.Stat(manifestName); err == nil {\n\t\t\t\tterminatePods = true\n\t\t\t}\n\t\t}\n\t}\n\n\tif terminatePods {\n\t\tlogrus.Infof(\"Static pod cleanup in progress\")\n\t\t// delete manifests for disabled items\n\t\tfor component, disabled := range disabledItems {\n\t\t\tif disabled {\n\t\t\t\tmanifestName := filepath.Join(manifestDir, component+\".yaml\")\n\t\t\t\tif err := os.RemoveAll(manifestName); err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"unable to delete %s manifest\", component)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tctx, cancel := context.WithTimeout(context.Background(), (5 * time.Minute))\n\t\tdefer cancel()\n\n\t\tcontainerdErr := make(chan error)\n\n\t\t// start containerd, if necessary. The command will be terminated automatically when the context is cancelled.\n\t\tif containerRuntimeEndpoint == \"\" {\n\t\t\tcontainerdCmd := exec.CommandContext(ctx, filepath.Join(execPath, \"containerd\"))\n\t\t\tgo startContainerd(ctx, dataDir, containerdErr, containerdCmd)\n\t\t}\n\t\t// terminate any running containers from the disabled items list\n\t\tgo terminateRunningContainers(ctx, containerRuntimeEndpoint, disabledItems, containerdErr)\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase err := <-containerdErr:\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrap(err, \"temporary containerd process exited unexpectedly\")\n\t\t\t\t}\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn errors.New(\"static pod cleanup timed out\")\n\t\t\t}\n\t\t\tlogrus.Info(\"Static pod cleanup completed successfully\")\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *podManager) teardown(req *cniserver.PodRequest) error {\n\tdefer metrics.PodOperationsLatency.WithLabelValues(metrics.PodOperationTeardown).Observe(metrics.SinceInMicroseconds(time.Now()))\n\n\terrList := []error{}\n\n\tif err := m.ovs.TearDownPod(req.SandboxID); err != nil {\n\t\terrList = append(errList, err)\n\t}\n\n\tif err := m.ipamDel(req.SandboxID); err != nil {\n\t\terrList = append(errList, err)\n\t}\n\n\tif len(errList) > 0 {\n\t\treturn kerrors.NewAggregate(errList)\n\t}\n\n\tklog.Infof(\"CNI_DEL %s/%s\", req.PodNamespace, req.PodName)\n\treturn nil\n}", "func TestMilpaToK8sPod(t *testing.T) {\n\ti64 := int64(rand.Intn(math.MaxInt64))\n\tnode, ip := fakeInstanceProvider()\n\tmilpaPod := api.NewPod()\n\tmilpaPod.Namespace = rand.String(16)\n\tmilpaPod.Name = util.WithNamespace(milpaPod.Namespace, rand.String(16))\n\tmilpaPod.Spec = api.PodSpec{\n\t\tSpot: api.PodSpot{\n\t\t\tPolicy: api.SpotNever,\n\t\t},\n\t\tPhase: api.PodRunning,\n\t\tRestartPolicy: api.RestartPolicyOnFailure,\n\t\tUnits: []api.Unit{\n\t\t\t{\n\t\t\t\tName: rand.String(8),\n\t\t\t\tImage: fmt.Sprintf(\"elotl/%s:latest\", rand.String(8)),\n\t\t\t\tCommand: []string{\n\t\t\t\t\t\"unit-1-cmd\",\n\t\t\t\t},\n\t\t\t\tArgs: []string{\n\t\t\t\t\t\"-a\",\n\t\t\t\t\t\"--bb\",\n\t\t\t\t\t\"ccc\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tInitUnits: []api.Unit{\n\t\t\t{\n\t\t\t\tName: rand.String(8),\n\t\t\t\tImage: fmt.Sprintf(\"elotl/%s:latest\", rand.String(8)),\n\t\t\t\tCommand: []string{\n\t\t\t\t\t\"initunit-1-cmd\",\n\t\t\t\t},\n\t\t\t\tArgs: []string{\n\t\t\t\t\t\"--init\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tVolumes: []api.Volume{\n\t\t\t{\n\t\t\t\tName: rand.String(16),\n\t\t\t\tVolumeSource: api.VolumeSource{\n\t\t\t\t\tEmptyDir: &api.EmptyDir{\n\t\t\t\t\t\tMedium: api.StorageMediumMemory,\n\t\t\t\t\t\tSizeLimit: int64(rand.Intn(math.MaxInt64)),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tSecurityContext: &api.PodSecurityContext{\n\t\t\tNamespaceOptions: &api.NamespaceOption{\n\t\t\t\tNetwork: api.NamespaceModeNode,\n\t\t\t\tPid: api.NamespaceModeNode,\n\t\t\t\tIpc: api.NamespaceModeContainer,\n\t\t\t},\n\t\t\tRunAsUser: &i64,\n\t\t\tRunAsGroup: &i64,\n\t\t\tSupplementalGroups: []int64{\n\t\t\t\tint64(rand.Intn(math.MaxInt64)),\n\t\t\t},\n\t\t\tSysctls: []api.Sysctl{\n\t\t\t\t{\n\t\t\t\t\tName: rand.String(16),\n\t\t\t\t\tValue: rand.String(16),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: rand.String(16),\n\t\t\t\t\tValue: rand.String(16),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: rand.String(16),\n\t\t\t\t\tValue: rand.String(16),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tpod, err := milpaToK8sPod(node, ip, milpaPod)\n\tassert.NoError(t, err)\n\tassert.NotNil(t, pod)\n\tassert.Equal(t, len(milpaPod.Spec.Units), len(pod.Spec.Containers))\n\tfor _, unit := range milpaPod.Spec.Units {\n\t\tcontainer := unitToContainer(unit, nil)\n\t\tassert.Contains(t, pod.Spec.Containers, container)\n\t}\n\tassert.Equal(t, len(milpaPod.Spec.InitUnits), len(pod.Spec.InitContainers))\n\tfor _, unit := range milpaPod.Spec.InitUnits {\n\t\tcontainer := unitToContainer(unit, nil)\n\t\tassert.Contains(t, pod.Spec.InitContainers, container)\n\t}\n\tassert.Equal(t, len(milpaPod.Spec.Volumes), len(pod.Spec.Volumes))\n\tfor _, vol := range milpaPod.Spec.Volumes {\n\t\tvolume := milpaToK8sVolume(vol)\n\t\tassert.Contains(t, pod.Spec.Volumes, *volume)\n\t}\n\tassert.NotNil(t, pod.Spec.SecurityContext)\n\tassert.Equal(\n\t\tt,\n\t\tmilpaPod.Spec.SecurityContext.RunAsUser,\n\t\tpod.Spec.SecurityContext.RunAsUser)\n\tassert.Equal(\n\t\tt,\n\t\tmilpaPod.Spec.SecurityContext.RunAsGroup,\n\t\tpod.Spec.SecurityContext.RunAsGroup)\n\tassert.ElementsMatch(\n\t\tt,\n\t\tmilpaPod.Spec.SecurityContext.SupplementalGroups,\n\t\tpod.Spec.SecurityContext.SupplementalGroups)\n\tassert.Equal(\n\t\tt,\n\t\tlen(milpaPod.Spec.SecurityContext.Sysctls),\n\t\tlen(pod.Spec.SecurityContext.Sysctls))\n\tfor _, sysctl := range milpaPod.Spec.SecurityContext.Sysctls {\n\t\tsc := v1.Sysctl{\n\t\t\tName: sysctl.Name,\n\t\t\tValue: sysctl.Value,\n\t\t}\n\t\tassert.Contains(t, pod.Spec.SecurityContext.Sysctls, sc)\n\t}\n\tassert.Equal(t, len(milpaPod.Spec.Volumes), len(pod.Spec.Volumes))\n\tfor _, volume := range milpaPod.Spec.Volumes {\n\t\tfound := false\n\t\tfor _, vol := range pod.Spec.Volumes {\n\t\t\tif vol.Name == volume.Name {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tassert.True(t, found, \"volume %q is missing in k8s pod\", volume.Name)\n\t}\n\tmPod, err := k8sToMilpaPod(pod)\n\tassert.NoError(t, err)\n\tassert.NotNil(t, mPod)\n\tremoveVolume(mPod, resolvconfVolumeName)\n\tremoveVolume(mPod, etchostsVolumeName)\n\tassert.Equal(t, milpaPod.TypeMeta, mPod.TypeMeta)\n\tassert.Equal(t, milpaPod.ObjectMeta, mPod.ObjectMeta)\n\tassert.Equal(t, milpaPod.Spec, mPod.Spec)\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 (m *AzureManagedControlPlane) validateScaleDownTime(scaleDownValue *string, fieldName string) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif ptr.Deref(scaleDownValue, \"\") != \"\" {\n\t\tif !rScaleDownTime.MatchString(ptr.Deref(scaleDownValue, \"\")) {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"Spec\", \"AutoscalerProfile\", fieldName), ptr.Deref(scaleDownValue, \"\"), \"invalid value\"))\n\t\t}\n\t}\n\treturn allErrs\n}", "func (o KubernetesClusterAutoScalerProfilePtrOutput) ScaleDownUnready() 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.ScaleDownUnready\n\t}).(pulumi.StringPtrOutput)\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 (encoder *encoder) ScaleDown(pt *Plaintext, ptRt *PlaintextRingT) {\n\tencoder.scaler.DivByQOverTRounded(pt.value, ptRt.value)\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 PodAutoscalerChaosInDeployment(experimentsDetails *experimentTypes.ExperimentDetails, clients clients.ClientSets, appsUnderTest []experimentTypes.ApplicationUnderTest, resultDetails *types.ResultDetails, eventsDetails *types.EventDetails, chaosDetails *types.ChaosDetails) error {\n\n\t// Scale Application\n\tretryErr := retries.RetryOnConflict(retries.DefaultRetry, func() error {\n\t\tfor _, app := range appsUnderTest {\n\t\t\t// Retrieve the latest version of Deployment before attempting update\n\t\t\t// RetryOnConflict uses exponential backoff to avoid exhausting the apiserver\n\t\t\tappUnderTest, err := appsv1DeploymentClient.Get(app.AppName, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Errorf(\"Failed to get latest version of Application Deployment, err: %v\", err)\n\t\t\t}\n\t\t\t// modifying the replica count\n\t\t\tappUnderTest.Spec.Replicas = int32Ptr(int32(experimentsDetails.Replicas))\n\t\t\tlog.Infof(\"Updating deployment %s to number of replicas %d\", appUnderTest.ObjectMeta.Name, experimentsDetails.Replicas)\n\t\t\t_, err = appsv1DeploymentClient.Update(appUnderTest)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tif retryErr != nil {\n\t\treturn errors.Errorf(\"Unable to scale the deployment, err: %v\", retryErr)\n\t}\n\tlog.Info(\"Application Started Scaling\")\n\n\terr = DeploymentStatusCheck(experimentsDetails, clients, appsUnderTest, resultDetails, eventsDetails, chaosDetails)\n\tif err != nil {\n\t\treturn errors.Errorf(\"Status Check failed, err: %v\", err)\n\t}\n\n\treturn nil\n}", "func (obj *GenericMeasure) UnPublish(ctx context.Context) error {\n\terr := obj.RPC(ctx, \"UnPublish\", nil)\n\treturn err\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 (o KubernetesClusterAutoScalerProfileOutput) ScaleDownUtilizationThreshold() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v KubernetesClusterAutoScalerProfile) *string { return v.ScaleDownUtilizationThreshold }).(pulumi.StringPtrOutput)\n}", "func (c *Controller) onUpdate(oldObj, newObj interface{}) {\n\toldcluster := oldObj.(*crv1.Pgcluster)\n\tnewcluster := newObj.(*crv1.Pgcluster)\n\n\tlog.Debugf(\"pgcluster onUpdate for cluster %s (namespace %s)\", newcluster.ObjectMeta.Namespace,\n\t\tnewcluster.ObjectMeta.Name)\n\n\t// if the status of the pgcluster shows that it has been bootstrapped, then proceed with\n\t// creating the cluster (i.e. the cluster deployment, services, etc.)\n\tif newcluster.Status.State == crv1.PgclusterStateBootstrapped {\n\t\tclusteroperator.AddClusterBase(c.Client, newcluster, newcluster.GetNamespace())\n\t\treturn\n\t}\n\n\t// if the 'shutdown' parameter in the pgcluster update shows that the cluster should be either\n\t// shutdown or started but its current status does not properly reflect that it is, then\n\t// proceed with the logic needed to either shutdown or start the cluster\n\tif newcluster.Spec.Shutdown && newcluster.Status.State != crv1.PgclusterStateShutdown {\n\t\tclusteroperator.ShutdownCluster(c.Client, *newcluster)\n\t} else if !newcluster.Spec.Shutdown &&\n\t\tnewcluster.Status.State == crv1.PgclusterStateShutdown {\n\t\tclusteroperator.StartupCluster(c.Client, *newcluster)\n\t}\n\n\t// check to see if the \"autofail\" label on the pgcluster CR has been changed from either true to false, or from\n\t// false to true. If it has been changed to false, autofail will then be disabled in the pg cluster. If has\n\t// been changed to true, autofail will then be enabled in the pg cluster\n\tif newcluster.ObjectMeta.Labels[config.LABEL_AUTOFAIL] != \"\" {\n\t\tautofailEnabledOld, err := strconv.ParseBool(oldcluster.ObjectMeta.Labels[config.LABEL_AUTOFAIL])\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t\tautofailEnabledNew, err := strconv.ParseBool(newcluster.ObjectMeta.Labels[config.LABEL_AUTOFAIL])\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t\tif autofailEnabledNew != autofailEnabledOld {\n\t\t\tutil.ToggleAutoFailover(c.Client, autofailEnabledNew,\n\t\t\t\tnewcluster.ObjectMeta.Labels[config.LABEL_PGHA_SCOPE],\n\t\t\t\tnewcluster.ObjectMeta.Namespace)\n\t\t}\n\n\t}\n\n\t// handle standby being enabled and disabled for the cluster\n\tif oldcluster.Spec.Standby && !newcluster.Spec.Standby {\n\t\tif err := clusteroperator.DisableStandby(c.Client, *newcluster); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t} else if !oldcluster.Spec.Standby && newcluster.Spec.Standby {\n\t\tif err := clusteroperator.EnableStandby(c.Client, *newcluster); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// see if any of the resource values have changed, and if so, update them\n\tif !reflect.DeepEqual(oldcluster.Spec.Resources, newcluster.Spec.Resources) ||\n\t\t!reflect.DeepEqual(oldcluster.Spec.Limits, newcluster.Spec.Limits) {\n\t\tif err := clusteroperator.UpdateResources(c.Client, c.Client.Config, newcluster); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// see if any of the pgBackRest repository resource values have changed, and\n\t// if so, update them\n\tif !reflect.DeepEqual(oldcluster.Spec.BackrestResources, newcluster.Spec.BackrestResources) ||\n\t\t!reflect.DeepEqual(oldcluster.Spec.BackrestLimits, newcluster.Spec.BackrestLimits) {\n\t\tif err := backrestoperator.UpdateResources(c.Client, newcluster); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// see if any of the pgBouncer values have changed, and if so, update the\n\t// pgBouncer deployment\n\tif !reflect.DeepEqual(oldcluster.Spec.PgBouncer, newcluster.Spec.PgBouncer) {\n\t\tif err := updatePgBouncer(c, oldcluster, newcluster); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// if we are not in a standby state, check to see if the tablespaces have\n\t// differed, and if so, add the additional volumes to the primary and replicas\n\tif !reflect.DeepEqual(oldcluster.Spec.TablespaceMounts, newcluster.Spec.TablespaceMounts) {\n\t\tif err := updateTablespaces(c, oldcluster, newcluster); err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\t}\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 RegisterScaleUp(nodesCount int, gpuResourceName, gpuType string) {\n\tscaleUpCount.Add(float64(nodesCount))\n\tif gpuType != gpu.MetricsNoGPU {\n\t\tgpuScaleUpCount.WithLabelValues(gpuResourceName, gpuType).Add(float64(nodesCount))\n\t}\n}", "func (o KubernetesClusterDefaultNodePoolPtrOutput) ScaleDownMode() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *KubernetesClusterDefaultNodePool) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ScaleDownMode\n\t}).(pulumi.StringPtrOutput)\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 RegisterSkippedScaleDownCPU() {\n\tskippedScaleEventsCount.WithLabelValues(DirectionScaleDown, CpuResourceLimit).Add(1.0)\n}", "func addKubeSystemPdbs(ctx context.Context, f *framework.Framework) error {\n\tginkgo.By(\"Create PodDisruptionBudgets for kube-system components, so they can be migrated if required\")\n\n\tvar newPdbs []string\n\tcleanup := func(ctx context.Context) {\n\t\tvar finalErr error\n\t\tfor _, newPdbName := range newPdbs {\n\t\t\tginkgo.By(fmt.Sprintf(\"Delete PodDisruptionBudget %v\", newPdbName))\n\t\t\terr := f.ClientSet.PolicyV1().PodDisruptionBudgets(\"kube-system\").Delete(ctx, newPdbName, metav1.DeleteOptions{})\n\t\t\tif err != nil {\n\t\t\t\t// log error, but attempt to remove other pdbs\n\t\t\t\tklog.Errorf(\"Failed to delete PodDisruptionBudget %v, err: %v\", newPdbName, err)\n\t\t\t\tfinalErr = err\n\t\t\t}\n\t\t}\n\t\tif finalErr != nil {\n\t\t\tframework.Failf(\"Error during PodDisruptionBudget cleanup: %v\", finalErr)\n\t\t}\n\t}\n\tginkgo.DeferCleanup(cleanup)\n\n\ttype pdbInfo struct {\n\t\tlabel string\n\t\tminAvailable int\n\t}\n\tpdbsToAdd := []pdbInfo{\n\t\t{label: \"kube-dns\", minAvailable: 1},\n\t\t{label: \"kube-dns-autoscaler\", minAvailable: 0},\n\t\t{label: \"metrics-server\", minAvailable: 0},\n\t\t{label: \"kubernetes-dashboard\", minAvailable: 0},\n\t\t{label: \"glbc\", minAvailable: 0},\n\t}\n\tfor _, pdbData := range pdbsToAdd {\n\t\tginkgo.By(fmt.Sprintf(\"Create PodDisruptionBudget for %v\", pdbData.label))\n\t\tlabelMap := map[string]string{\"k8s-app\": pdbData.label}\n\t\tpdbName := fmt.Sprintf(\"test-pdb-for-%v\", pdbData.label)\n\t\tminAvailable := intstr.FromInt32(int32(pdbData.minAvailable))\n\t\tpdb := &policyv1.PodDisruptionBudget{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: pdbName,\n\t\t\t\tNamespace: \"kube-system\",\n\t\t\t},\n\t\t\tSpec: policyv1.PodDisruptionBudgetSpec{\n\t\t\t\tSelector: &metav1.LabelSelector{MatchLabels: labelMap},\n\t\t\t\tMinAvailable: &minAvailable,\n\t\t\t},\n\t\t}\n\t\t_, err := f.ClientSet.PolicyV1().PodDisruptionBudgets(\"kube-system\").Create(ctx, pdb, metav1.CreateOptions{})\n\t\tnewPdbs = append(newPdbs, pdbName)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func TestPrometheusScaler(t *testing.T) {\n\t// Create kubernetes resources\n\tkc := GetKubernetesClient(t)\n\tprometheus.Install(t, kc, prometheusServerName, testNamespace)\n\n\t// Create kubernetes resources for testing\n\tdata, templates := getTemplateData()\n\tKubectlApplyMultipleWithTemplate(t, data, templates)\n\tassert.True(t, WaitForDeploymentReplicaReadyCount(t, kc, monitoredAppName, testNamespace, 1, 60, 3),\n\t\t\"replica count should be %d after 3 minutes\", minReplicaCount)\n\tassert.True(t, WaitForDeploymentReplicaReadyCount(t, kc, deploymentName, testNamespace, minReplicaCount, 60, 3),\n\t\t\"replica count should be %d after 3 minutes\", minReplicaCount)\n\n\ttestActivation(t, kc, data)\n\ttestScaleOut(t, kc, data)\n\ttestScaleIn(t, kc)\n\n\t// cleanup\n\tKubectlDeleteMultipleWithTemplate(t, data, templates)\n\tprometheus.Uninstall(t, prometheusServerName, testNamespace)\n}", "func (c *Controller) clusterAction(admin submarine.AdminInterface, cluster *rapi.SubmarineCluster, infos *submarine.ClusterInfos) (bool, error) {\n\tglog.Info(\"clusterAction()\")\n\tvar err error\n\t/* run sanity check if needed\n\tneedSanity, err := sanitycheck.RunSanityChecks(admin, &c.config.submarine, c.podControl, cluster, infos, true)\n\tif err != nil {\n\t\tglog.Errorf(\"[clusterAction] cluster %s/%s, an error occurs during sanitycheck: %v \", cluster.Namespace, cluster.Name, err)\n\t\treturn false, err\n\t}\n\tif needSanity {\n\t\tglog.V(3).Infof(\"[clusterAction] run sanitycheck cluster: %s/%s\", cluster.Namespace, cluster.Name)\n\t\treturn sanitycheck.RunSanityChecks(admin, &c.config.submarine, c.podControl, cluster, infos, false)\n\t}*/\n\n\t// Start more pods in needed\n\tif needMorePods(cluster) {\n\t\tif setScalingCondition(&cluster.Status, true) {\n\t\t\tif cluster, err = c.updateHandler(cluster); err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\t\tpod, err2 := c.podControl.CreatePod(cluster)\n\t\tif err2 != nil {\n\t\t\tglog.Errorf(\"[clusterAction] unable to create a pod associated to the SubmarineCluster: %s/%s, err: %v\", cluster.Namespace, cluster.Name, err2)\n\t\t\treturn false, err2\n\t\t}\n\n\t\tglog.V(3).Infof(\"[clusterAction]create a Pod %s/%s\", pod.Namespace, pod.Name)\n\t\treturn true, nil\n\t}\n\tif setScalingCondition(&cluster.Status, false) {\n\t\tif cluster, err = c.updateHandler(cluster); err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\t// Reconfigure the Cluster if needed\n\thasChanged, err := c.applyConfiguration(admin, cluster)\n\tif err != nil {\n\t\tglog.Errorf(\"[clusterAction] cluster %s/%s, an error occurs: %v \", cluster.Namespace, cluster.Name, err)\n\t\treturn false, err\n\t}\n\n\tif hasChanged {\n\t\tglog.V(6).Infof(\"[clusterAction] cluster has changed cluster: %s/%s\", cluster.Namespace, cluster.Name)\n\t\treturn true, nil\n\t}\n\n\tglog.Infof(\"[clusterAction] cluster hasn't changed cluster: %s/%s\", cluster.Namespace, cluster.Name)\n\treturn false, nil\n}", "func (c *Controller) applyConfiguration(admin submarine.AdminInterface, cluster *rapi.SubmarineCluster) (bool, error) {\n\tglog.Info(\"applyConfiguration START\")\n\tdefer glog.Info(\"applyConfiguration STOP\")\n\n\tasChanged := false\n\n\t// expected replication factor and number of master nodes\n\tcReplicaFactor := *cluster.Spec.ReplicationFactor\n\tcNbMaster := *cluster.Spec.NumberOfMaster\n\t// Adapt, convert CR to structure in submarine package\n\trCluster, nodes, err := newSubmarineCluster(admin, cluster)\n\tif err != nil {\n\t\tglog.Errorf(\"Unable to create the SubmarineCluster view, error:%v\", err)\n\t\treturn false, err\n\t}\n\t// PodTemplate changes require rolling updates\n\tif needRollingUpdate(cluster) {\n\t\tif setRollingUpdateCondition(&cluster.Status, true) {\n\t\t\tif cluster, err = c.updateHandler(cluster); err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\n\t\tglog.Info(\"applyConfiguration needRollingUpdate\")\n\t\treturn c.manageRollingUpdate(admin, cluster, rCluster, nodes)\n\t}\n\tif setRollingUpdateCondition(&cluster.Status, false) {\n\t\tif cluster, err = c.updateHandler(cluster); err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\t// if the number of Pods is greater than expected\n\tif needLessPods(cluster) {\n\t\tif setRebalancingCondition(&cluster.Status, true) {\n\t\t\tif cluster, err = c.updateHandler(cluster); err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\t\tglog.Info(\"applyConfiguration needLessPods\")\n\t\t// Configure Submarine cluster\n\t\treturn c.managePodScaleDown(admin, cluster, rCluster, nodes)\n\t}\n\t// If it is not a rolling update, modify the Condition\n\tif setRebalancingCondition(&cluster.Status, false) {\n\t\tif cluster, err = c.updateHandler(cluster); err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\tclusterStatus := &cluster.Status.Cluster\n\tif (clusterStatus.NbPods - clusterStatus.NbSubmarineRunning) != 0 {\n\t\tglog.V(3).Infof(\"All pods not ready wait to be ready, nbPods: %d, nbPodsReady: %d\", clusterStatus.NbPods, clusterStatus.NbSubmarineRunning)\n\t\treturn false, err\n\t}\n\n\t// First, we define the new masters\n\t// Select the desired number of Masters and assign Hashslots to each Master. The Master will be distributed to different K8S nodes as much as possible\n\t// Set the cluster status to Calculating Rebalancing\n\tnewMasters, curMasters, allMaster, err := clustering.DispatchMasters(rCluster, nodes, cNbMaster, admin)\n\tif err != nil {\n\t\tglog.Errorf(\"Cannot dispatch slots to masters: %v\", err)\n\t\trCluster.Status = rapi.ClusterStatusError\n\t\treturn false, err\n\t}\n\t// If the number of new and old masters is not the same\n\tif len(newMasters) != len(curMasters) {\n\t\tasChanged = true\n\t}\n\n\t// Second select Node that is already a slave\n\tcurrentSlaveNodes := nodes.FilterByFunc(submarine.IsSlave)\n\n\t//New slaves are slaves which is currently a master with no slots\n\tnewSlave := nodes.FilterByFunc(func(nodeA *submarine.Node) bool {\n\t\tfor _, nodeB := range newMasters {\n\t\t\tif nodeA.ID == nodeB.ID {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tfor _, nodeB := range currentSlaveNodes {\n\t\t\tif nodeA.ID == nodeB.ID {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n\n\t// Depending on whether we scale up or down, we will dispatch slaves before/after the dispatch of slots\n\tif cNbMaster < int32(len(curMasters)) {\n\t\t// this happens usually after a scale down of the cluster\n\t\t// we should dispatch slots before dispatching slaves\n\t\tif err := clustering.DispatchSlotToNewMasters(rCluster, admin, newMasters, curMasters, allMaster); err != nil {\n\t\t\tglog.Error(\"Unable to dispatch slot on new master, err:\", err)\n\t\t\treturn false, err\n\t\t}\n\n\t\t// assign master/slave roles\n\t\tnewSubmarineSlavesByMaster, bestEffort := clustering.PlaceSlaves(rCluster, newMasters, currentSlaveNodes, newSlave, cReplicaFactor)\n\t\tif bestEffort {\n\t\t\trCluster.NodesPlacement = rapi.NodesPlacementInfoBestEffort\n\t\t}\n\n\t\tif err := clustering.AttachingSlavesToMaster(rCluster, admin, newSubmarineSlavesByMaster); err != nil {\n\t\t\tglog.Error(\"Unable to dispatch slave on new master, err:\", err)\n\t\t\treturn false, err\n\t\t}\n\t} else {\n\t\t// We are scaling up the nbmaster or the nbmaster doesn't change.\n\t\t// assign master/slave roles\n\t\tnewSubmarineSlavesByMaster, bestEffort := clustering.PlaceSlaves(rCluster, newMasters, currentSlaveNodes, newSlave, cReplicaFactor)\n\t\tif bestEffort {\n\t\t\trCluster.NodesPlacement = rapi.NodesPlacementInfoBestEffort\n\t\t}\n\n\t\tif err := clustering.AttachingSlavesToMaster(rCluster, admin, newSubmarineSlavesByMaster); err != nil {\n\t\t\tglog.Error(\"Unable to dispatch slave on new master, err:\", err)\n\t\t\treturn false, err\n\t\t}\n\n\t\tif err := clustering.DispatchSlotToNewMasters(rCluster, admin, newMasters, curMasters, allMaster); err != nil {\n\t\t\tglog.Error(\"Unable to dispatch slot on new master, err:\", err)\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\tglog.V(4).Infof(\"new nodes status: \\n %v\", nodes)\n\n\t// Set the cluster status\n\trCluster.Status = rapi.ClusterStatusOK\n\t// wait a bit for the cluster to propagate configuration to reduce warning logs because of temporary inconsistency\n\ttime.Sleep(1 * time.Second)\n\treturn asChanged, nil\n}", "func (c *Cluster) reconcileSize() error {\n\t// Grab an up-to-date list of pods that are currently running.\n\t// Pending pods may be ignored safely as we have previously made sure no pods are in pending state.\n\tpods, _, _, err := c.pollPods()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Grab the current and desired size of the NATS cluster.\n\tcurrentSize := len(pods)\n\tdesiredSize := c.cluster.Spec.Size\n\n\tif currentSize > desiredSize {\n\t\t// Report that we are scaling the cluster down.\n\t\tc.cluster.Status.AppendScalingDownCondition(currentSize, desiredSize)\n\t\t// Remove extra pods as required in order to meet the desired size.\n\t\t// As we remove each pod, we must update the config secret so that routes are re-computed.\n\t\tfor idx := currentSize - 1; idx >= desiredSize; idx-- {\n\t\t\tif err := c.tryGracefulPodDeletion(pods[idx]); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := c.updateConfigSecret(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tif currentSize < desiredSize {\n\t\t// Report that we are scaling the cluster up.\n\t\tc.cluster.Status.AppendScalingUpCondition(currentSize, desiredSize)\n\t\t// Create pods as required in order to meet the desired size.\n\t\t// As we create each pod, we must update the config secret so that routes are re-computed.\n\t\tfor idx := currentSize; idx < desiredSize; idx++ {\n\t\t\tif _, err := c.createPod(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := c.updateConfigSecret(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// Update the reported size before returning.\n\tc.cluster.Status.SetSize(desiredSize)\n\treturn nil\n}", "func performScalingOnStatefulSetAndVerifyPvNodeAffinity(ctx context.Context, client clientset.Interface,\n\tscaleUpReplicaCount int32, scaleDownReplicaCount int32, statefulset *appsv1.StatefulSet,\n\tparallelStatefulSetCreation bool, namespace string,\n\tallowedTopologies []v1.TopologySelectorLabelRequirement, stsScaleUp bool, stsScaleDown bool,\n\tverifyTopologyAffinity bool) error {\n\n\tif stsScaleDown {\n\t\tframework.Logf(\"Scale down statefulset replica\")\n\t\terr := scaleDownStatefulSetPod(ctx, client, statefulset, namespace, scaleDownReplicaCount,\n\t\t\tparallelStatefulSetCreation, true)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error scaling down statefulset: %v\", err)\n\t\t}\n\t}\n\n\tif stsScaleUp {\n\t\tframework.Logf(\"Scale up statefulset replica\")\n\t\terr := scaleUpStatefulSetPod(ctx, client, statefulset, namespace, scaleUpReplicaCount,\n\t\t\tparallelStatefulSetCreation, true)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error scaling up statefulset: %v\", err)\n\t\t}\n\t}\n\n\tif verifyTopologyAffinity {\n\t\tframework.Logf(\"Verify PV node affinity and that the PODS are running on appropriate node\")\n\t\terr := verifyPVnodeAffinityAndPODnodedetailsForStatefulsetsLevel5(ctx, client, statefulset,\n\t\t\tnamespace, allowedTopologies, parallelStatefulSetCreation, true)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error verifying PV node affinity and POD node details: %v\", err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func stopDeployment(ctx context.Context, clientset kubernetes.Interface, controllerResource *piraeusv1.LinstorController, log logr.Logger) error {\n\tmeta := getObjectMeta(controllerResource, \"%s-controller\")\n\n\t_, err := clientset.AppsV1().Deployments(meta.Namespace).UpdateScale(ctx, meta.Name, &autoscalingv1.Scale{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: meta.Name,\n\t\t\tNamespace: meta.Namespace,\n\t\t},\n\t\tSpec: autoscalingv1.ScaleSpec{Replicas: 0},\n\t}, metav1.UpdateOptions{})\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// No deployment, nothing to stop\n\t\t\treturn nil\n\t\t}\n\n\t\treturn fmt.Errorf(\"failed to update controller scale: %w\", err)\n\t}\n\n\tlog.V(DEBUG).Info(\"wait for pods to terminate\")\n\n\tpods, err := clientset.CoreV1().Pods(meta.Namespace).List(ctx, metav1.ListOptions{\n\t\tLabelSelector: metav1.FormatLabelSelector(&metav1.LabelSelector{MatchLabels: meta.Labels}),\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to list pods: %w\", err)\n\t}\n\n\tpodsWatch, err := clientset.CoreV1().Pods(meta.Namespace).Watch(ctx, metav1.ListOptions{\n\t\tLabelSelector: metav1.FormatLabelSelector(&metav1.LabelSelector{MatchLabels: meta.Labels}),\n\t\tResourceVersion: pods.ResourceVersion,\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to set up watch for pods: %w\", err)\n\t}\n\n\tdefer podsWatch.Stop()\n\n\tcount := len(pods.Items)\n\n\tfor {\n\t\tlog.V(DEBUG).Info(\"watch remaining pods\", \"count\", count)\n\n\t\tif count == 0 {\n\t\t\tlog.V(DEBUG).Info(\"all pods terminated\")\n\n\t\t\treturn nil\n\t\t}\n\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn fmt.Errorf(\"error while waiting for pods to terminate: %w\", ctx.Err())\n\t\tcase ev := <-podsWatch.ResultChan():\n\t\t\tif ev.Type == watch.Deleted {\n\t\t\t\tcount--\n\t\t\t} else if ev.Type == watch.Added {\n\t\t\t\tcount++\n\t\t\t}\n\t\t}\n\t}\n}", "func (m *podMetrics) Destroy() {\n}", "func (m *kubeGenericRuntimeManager) doBackOff(pod *v1.Pod, container *v1.Container, podStatus *kubecontainer.PodStatus, backOff *flowcontrol.Backoff) (bool, string, error) {\n\tvar cStatus *kubecontainer.Status\n\tfor _, c := range podStatus.ContainerStatuses {\n\t\tif c.Name == container.Name && c.State == kubecontainer.ContainerStateExited {\n\t\t\tcStatus = c\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif cStatus == nil {\n\t\treturn false, \"\", nil\n\t}\n\n\tklog.V(3).InfoS(\"Checking backoff for container in pod\", \"containerName\", container.Name, \"pod\", klog.KObj(pod))\n\t// Use the finished time of the latest exited container as the start point to calculate whether to do back-off.\n\tts := cStatus.FinishedAt\n\t// backOff requires a unique key to identify the container.\n\tkey := getStableKey(pod, container)\n\tif backOff.IsInBackOffSince(key, ts) {\n\t\tif containerRef, err := kubecontainer.GenerateContainerRef(pod, container); err == nil {\n\t\t\tm.recorder.Eventf(containerRef, v1.EventTypeWarning, events.BackOffStartContainer,\n\t\t\t\tfmt.Sprintf(\"Back-off restarting failed container %s in pod %s\", container.Name, format.Pod(pod)))\n\t\t}\n\t\terr := fmt.Errorf(\"back-off %s restarting failed container=%s pod=%s\", backOff.Get(key), container.Name, format.Pod(pod))\n\t\tklog.V(3).InfoS(\"Back-off restarting failed container\", \"err\", err.Error())\n\t\treturn true, err.Error(), kubecontainer.ErrCrashLoopBackOff\n\t}\n\n\tbackOff.Next(key, ts)\n\treturn false, \"\", nil\n}", "func TestScaleForLongRunningWorkersTakingMinutesToProcess(t *testing.T) {\n\tc := desiredWorkerTester{\n\t\tqueueName: \"q\",\n\t\tqueueMessages: 100,\n\t\ttargetMessagesPerWorker: 10,\n\t\tcurrentWorkers: 0,\n\t\tidleWorkers: 0,\n\t\tminWorkers: 0,\n\t\tmaxWorkers: 500,\n\t\tmaxDisruption: \"0%\", // partial scale down is not allowed\n\t}\n\n\t// first loop should returns 10 desired workers\n\tc.test(t, 10)\n\n\t// many loops till the queueMessages does not drop should return\n\t// the same number of desired workers, 10\n\t// queueMessages = backlog(or visible) + reserved(or not visible)\n\tc.currentWorkers = 10\n\tc.test(t, 10)\n\n\t// third loop, say backlog reduced since some messages got consumed\n\t// it will still return 10 workers since max Disruption is not set\n\tc.queueMessages = 50\n\tc.test(t, 10)\n\n\t// fourth loop, say you enabled max disruption, so\n\t// now it should scale down to half the workers\n\tc.maxDisruption = \"100%\"\n\tc.test(t, 5)\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 verifyVolumeMetadataOnStatefulsets(client clientset.Interface, ctx context.Context, namespace string,\n\tstatefulset *appsv1.StatefulSet, replicas int32, allowedTopologyHAMap map[string][]string,\n\tcategories []string, storagePolicyName string, nodeList *v1.NodeList, f *framework.Framework) {\n\t// Waiting for pods status to be Ready\n\tfss.WaitForStatusReadyReplicas(client, statefulset, replicas)\n\tgomega.Expect(fss.CheckMount(client, statefulset, mountPath)).NotTo(gomega.HaveOccurred())\n\tssPodsBeforeScaleDown := fss.GetPodList(client, statefulset)\n\tgomega.Expect(ssPodsBeforeScaleDown.Items).NotTo(gomega.BeEmpty(),\n\t\tfmt.Sprintf(\"Unable to get list of Pods from the Statefulset: %v\", statefulset.Name))\n\tgomega.Expect(len(ssPodsBeforeScaleDown.Items) == int(replicas)).To(gomega.BeTrue(),\n\t\t\"Number of Pods in the statefulset should match with number of replicas\")\n\n\tginkgo.By(\"Verify GV PV and SV PV has has required PV node affinity details\")\n\tginkgo.By(\"Verify SV PVC has TKG HA annotations set\")\n\t// Get the list of Volumes attached to Pods before scale down\n\tfor _, sspod := range ssPodsBeforeScaleDown.Items {\n\t\tpod, err := client.CoreV1().Pods(namespace).Get(ctx, sspod.Name, metav1.GetOptions{})\n\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\tfor _, volumespec := range sspod.Spec.Volumes {\n\t\t\tif volumespec.PersistentVolumeClaim != nil {\n\t\t\t\tpvcName := volumespec.PersistentVolumeClaim.ClaimName\n\t\t\t\tpv := getPvFromClaim(client, statefulset.Namespace, pvcName)\n\t\t\t\tpvclaim, err := client.CoreV1().PersistentVolumeClaims(namespace).Get(ctx,\n\t\t\t\t\tpvcName, metav1.GetOptions{})\n\t\t\t\tgomega.Expect(pvclaim).NotTo(gomega.BeNil())\n\t\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t\t\tvolHandle := getVolumeIDFromSupervisorCluster(pv.Spec.CSI.VolumeHandle)\n\t\t\t\tgomega.Expect(volHandle).NotTo(gomega.BeEmpty())\n\t\t\t\tsvcPVCName := pv.Spec.CSI.VolumeHandle\n\n\t\t\t\tsvcPVC := getPVCFromSupervisorCluster(svcPVCName)\n\t\t\t\tgomega.Expect(*svcPVC.Spec.StorageClassName == storagePolicyName).To(\n\t\t\t\t\tgomega.BeTrue(), \"SV Pvc storageclass does not match with SV storageclass\")\n\t\t\t\tframework.Logf(\"GC PVC's storageclass matches SVC PVC's storageclass\")\n\n\t\t\t\tverifyAnnotationsAndNodeAffinity(allowedTopologyHAMap, categories, pod,\n\t\t\t\t\tnodeList, svcPVC, pv, svcPVCName)\n\n\t\t\t\t// Verify the attached volume match the one in CNS cache\n\t\t\t\terr = waitAndVerifyCnsVolumeMetadata4GCVol(volHandle, svcPVCName, pvclaim,\n\t\t\t\t\tpv, pod)\n\t\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t\t}\n\t\t}\n\t}\n\n\treplicas = 5\n\tframework.Logf(fmt.Sprintf(\"Scaling up statefulset: %v to number of Replica: %v\",\n\t\tstatefulset.Name, replicas))\n\t_, scaleupErr := fss.Scale(client, statefulset, replicas)\n\tgomega.Expect(scaleupErr).NotTo(gomega.HaveOccurred())\n\n\tfss.WaitForStatusReplicas(client, statefulset, replicas)\n\tfss.WaitForStatusReadyReplicas(client, statefulset, replicas)\n\tssPodsAfterScaleUp := fss.GetPodList(client, statefulset)\n\tgomega.Expect(ssPodsAfterScaleUp.Items).NotTo(gomega.BeEmpty(),\n\t\tfmt.Sprintf(\"Unable to get list of Pods from the Statefulset: %v\", statefulset.Name))\n\tgomega.Expect(len(ssPodsAfterScaleUp.Items) == int(replicas)).To(gomega.BeTrue(),\n\t\t\"Number of Pods in the statefulset %s, %v, should match with number of replicas %v\",\n\t\tstatefulset.Name, ssPodsAfterScaleUp.Size(), replicas,\n\t)\n\n\t// Get the list of Volumes attached to Pods before scale down\n\tfor _, sspod := range ssPodsBeforeScaleDown.Items {\n\t\tpod, err := client.CoreV1().Pods(namespace).Get(ctx, sspod.Name, metav1.GetOptions{})\n\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\tfor _, volumespec := range sspod.Spec.Volumes {\n\t\t\tif volumespec.PersistentVolumeClaim != nil {\n\t\t\t\tpvcName := volumespec.PersistentVolumeClaim.ClaimName\n\t\t\t\tpv := getPvFromClaim(client, statefulset.Namespace, pvcName)\n\t\t\t\tpvclaim, err := client.CoreV1().PersistentVolumeClaims(namespace).Get(ctx,\n\t\t\t\t\tpvcName, metav1.GetOptions{})\n\t\t\t\tgomega.Expect(pvclaim).NotTo(gomega.BeNil())\n\t\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\n\t\t\t\tvolHandle := getVolumeIDFromSupervisorCluster(pv.Spec.CSI.VolumeHandle)\n\t\t\t\tgomega.Expect(volHandle).NotTo(gomega.BeEmpty())\n\t\t\t\tsvcPVCName := pv.Spec.CSI.VolumeHandle\n\t\t\t\tsvcPVC := getPVCFromSupervisorCluster(svcPVCName)\n\n\t\t\t\tverifyAnnotationsAndNodeAffinity(allowedTopologyHAMap, categories, pod,\n\t\t\t\t\tnodeList, svcPVC, pv, svcPVCName)\n\n\t\t\t\tframework.Logf(fmt.Sprintf(\"Verify volume: %s is attached to the node: %s\",\n\t\t\t\t\tpv.Spec.CSI.VolumeHandle, sspod.Spec.NodeName))\n\t\t\t\tvar vmUUID string\n\t\t\t\tctx, cancel := context.WithCancel(context.Background())\n\t\t\t\tdefer cancel()\n\t\t\t\tvmUUID, err = getVMUUIDFromNodeName(pod.Spec.NodeName)\n\t\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t\t\tverifyCRDInSupervisorWithWait(ctx, f, pod.Spec.NodeName+\"-\"+svcPVCName,\n\t\t\t\t\tcrdCNSNodeVMAttachment, crdVersion, crdGroup, true)\n\n\t\t\t\tisDiskAttached, err := e2eVSphere.isVolumeAttachedToVM(client, volHandle, vmUUID)\n\t\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t\t\tgomega.Expect(isDiskAttached).To(gomega.BeTrue(), \"Disk is not attached to the node\")\n\t\t\t\tframework.Logf(\"After scale up, verify the attached volumes match those in CNS Cache\")\n\t\t\t\terr = waitAndVerifyCnsVolumeMetadata4GCVol(volHandle, svcPVCName, pvclaim,\n\t\t\t\t\tpv, pod)\n\t\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t\t}\n\t\t}\n\t}\n\n}", "func (r *Resources) runPodFinalizers(ctx context.Context, p *v1.Pod, memberStatus api.MemberStatus, updateMember func(api.MemberStatus) error) (util.Interval, error) {\n\tlog := r.log.With().Str(\"pod-name\", p.GetName()).Logger()\n\tvar removalList []string\n\tfor _, f := range p.ObjectMeta.GetFinalizers() {\n\t\tswitch f {\n\t\tcase constants.FinalizerPodAgencyServing:\n\t\t\tlog.Debug().Msg(\"Inspecting agency-serving finalizer\")\n\t\t\tif err := r.inspectFinalizerPodAgencyServing(ctx, log, p, memberStatus, updateMember); err == nil {\n\t\t\t\tremovalList = append(removalList, f)\n\t\t\t} else {\n\t\t\t\tlog.Debug().Err(err).Str(\"finalizer\", f).Msg(\"Cannot remove finalizer yet\")\n\t\t\t}\n\t\tcase constants.FinalizerPodDrainDBServer:\n\t\t\tlog.Debug().Msg(\"Inspecting drain dbserver finalizer\")\n\t\t\tif err := r.inspectFinalizerPodDrainDBServer(ctx, log, p, memberStatus, updateMember); err == nil {\n\t\t\t\tremovalList = append(removalList, f)\n\t\t\t} else {\n\t\t\t\tlog.Debug().Err(err).Str(\"finalizer\", f).Msg(\"Cannot remove Pod finalizer yet\")\n\t\t\t}\n\t\t}\n\t}\n\t// Remove finalizers (if needed)\n\tif len(removalList) > 0 {\n\t\tkubecli := r.context.GetKubeCli()\n\t\tignoreNotFound := false\n\t\tif err := k8sutil.RemovePodFinalizers(log, kubecli, p, removalList, ignoreNotFound); err != nil {\n\t\t\tlog.Debug().Err(err).Msg(\"Failed to update pod (to remove finalizers)\")\n\t\t\treturn 0, maskAny(err)\n\t\t}\n\t\tlog.Debug().Strs(\"finalizers\", removalList).Msg(\"Removed finalizer(s) from Pod\")\n\t\t// Let's do the next inspection quickly, since things may have changed now.\n\t\treturn podFinalizerRemovedInterval, nil\n\t}\n\t// Check again at given interval\n\treturn recheckPodFinalizerInterval, nil\n}", "func UpdateClusterSafeToAutoscale(safe bool) {\n\tif safe {\n\t\tclusterSafeToAutoscale.Set(1)\n\t} else {\n\t\tclusterSafeToAutoscale.Set(0)\n\t}\n}" ]
[ "0.7220987", "0.6654861", "0.64811045", "0.64686966", "0.61882216", "0.6067729", "0.6003641", "0.5984935", "0.5909963", "0.5801375", "0.5781897", "0.5721228", "0.56992275", "0.568317", "0.5678845", "0.5672439", "0.564906", "0.56047493", "0.5596159", "0.55896974", "0.557707", "0.55640465", "0.5556739", "0.55011123", "0.55002457", "0.55001485", "0.5474478", "0.5473516", "0.5461836", "0.54429704", "0.54412776", "0.543261", "0.5427092", "0.54185665", "0.5412437", "0.5397555", "0.5368403", "0.534478", "0.5341107", "0.5332433", "0.53202844", "0.5312886", "0.5311961", "0.5308575", "0.5293115", "0.52913153", "0.52805954", "0.5249492", "0.522771", "0.5201409", "0.5184967", "0.5183538", "0.517068", "0.5166147", "0.51645714", "0.5163256", "0.51609457", "0.5160473", "0.51515687", "0.5141939", "0.51285625", "0.51223755", "0.51179355", "0.5116858", "0.51025164", "0.50946826", "0.5091264", "0.50843036", "0.5060657", "0.50583375", "0.5055821", "0.50491047", "0.5038372", "0.5030165", "0.5007777", "0.5006124", "0.5004697", "0.50020754", "0.49854404", "0.49745336", "0.49647546", "0.49638", "0.4962897", "0.49622017", "0.49578226", "0.49468458", "0.4940963", "0.493442", "0.49163866", "0.4914221", "0.4912319", "0.49076244", "0.4901048", "0.48974642", "0.48872128", "0.48845845", "0.4879391", "0.48792374", "0.48776913", "0.48459825" ]
0.84669495
0
Lock is a noop used by copylocks checker from `go vet`.
func (*noCopy) Lock() {}
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*NoCopy) Lock() {}", "func (p Pin) Lock() {\n\tp.Port().Lock(Pin0 << p.index())\n}", "func (tl Noop) Lock(_ types.JobID, _ time.Duration, targets []*target.Target) error {\n\tlog.Infof(\"Locked %d targets by doing nothing\", len(targets))\n\treturn nil\n}", "func (p *PreemptiveLocker) Lock(ctx context.Context) (_ <-chan interface{}, err error) {\n\tspan, ctx := p.startSpanFromContext(ctx, \"lock\")\n\tdefer func() {\n\t\tspan.Finish(tracer.WithError(err))\n\t}()\n\tif len(p.id) != 0 {\n\t\treturn nil, errors.New(\"Lock() called again.\")\n\t}\n\tid, err := uuid.NewRandom()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error getting random id\")\n\t}\n\treturn p.lockWithID(ctx, fmt.Sprintf(\"%d-%s\", time.Now().UTC().Unix(), id.String()))\n}", "func (*dir) Lock(pid, locktype, flags int, start, length uint64, client string) error {\n\treturn nil\n}", "func (l *Lockbox) Lock() error {\n\tl.Locked = true\n\treturn nil\n}", "func (_LockProxy *LockProxyTransactor) Lock(opts *bind.TransactOpts, sourceAssetHash common.Address, toChainId uint64, toAddress []byte, amount *big.Int) (*types.Transaction, error) {\n\treturn _LockProxy.contract.Transact(opts, \"lock\", sourceAssetHash, toChainId, toAddress, amount)\n}", "func (l *Locker) Lock() {\n\tif err := l.LockWithErr(); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (lock *ALock) Lock() {\n\tslot := atomic.AddInt32(&lock.next, 1) - 1\n\tfor !lock.Flags[slot%lock.nThreads] {\n\t}\n\tatomic.StoreInt32(&lock.slot, slot)\n\tlock.Flags[slot%lock.nThreads] = false\n}", "func (il *internalLocker) Lock(ctx context.Context) error {\n\tif err := il.mu.Lock(ctx); err != nil {\n\t\tlog.Logger.Error(err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Lock() {\n\tlock.Lock()\n}", "func (*S) Lock() {}", "func Lock(lock bool) *LockOption {\n\treturn &LockOption{lock}\n}", "func TestGetLock(t *testing.T) {\n\tlockfile := lockOrFail(t)\n\tdefer removeTestLock(lockfile)\n}", "func (l *Lock) Lock(ctx context.Context, d time.Duration) (time.Duration, error) {\n\tif d < time.Millisecond {\n\t\td = time.Millisecond\n\t}\n\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\n\tconn, err := l.Pool.GetContext(ctx)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif l.token == nil {\n\t\tl.token = randomToken()\n\t}\n\n\tdefer conn.Close()\n\treturn parseLockReply(lockScript.Do(conn, l.Key, l.token, dtoms(d)))\n}", "func Lock() {\n\tmutex.Lock()\n}", "func (_LockProxy *LockProxyTransactorSession) Lock(sourceAssetHash common.Address, toChainId uint64, toAddress []byte, amount *big.Int) (*types.Transaction, error) {\n\treturn _LockProxy.Contract.Lock(&_LockProxy.TransactOpts, sourceAssetHash, toChainId, toAddress, amount)\n}", "func (c *CheckedLock) Lock() {\n\tc.lock.Lock()\n\tc.locked = true\n}", "func (_LockProxy *LockProxySession) Lock(sourceAssetHash common.Address, toChainId uint64, toAddress []byte, amount *big.Int) (*types.Transaction, error) {\n\treturn _LockProxy.Contract.Lock(&_LockProxy.TransactOpts, sourceAssetHash, toChainId, toAddress, amount)\n}", "func (l *Locker) Lock() {\n\tfor {\n\t\tif l.locker == 0 && atomic.CompareAndSwapInt32(&l.locker, 0, -1) {\n\t\t\treturn\n\t\t} else {\n\t\t\truntime.Gosched()\n\t\t}\n\t}\n}", "func (l *NullPathLocker) Lock(lockPath string) (pathlock.Unlocker, error) {\n\treturn l, nil\n}", "func (*Item) Lock() {}", "func (service *LockServiceMock) Lock(resourceID string) bool {\n\treturn service.defaultValue\n}", "func Test_BlockedLock(t *testing.T) {\n\tkey := \"Test_BlockedLock\"\n\tconn, err := redigo.Dial(\"tcp\", RedisHost)\n\n\tif err != nil {\n\t\tt.Error(fmt.Sprintf(\"redigo.Dial failure [%s]\", err))\n\t}\n\n\tlock1 := New(conn, key, 2001, 2000)\n\n\tstatus, err := lock1.Lock()\n\tdefer lock1.UnlockIfLocked()\n\n\tif err != nil {\n\t\tt.Error(fmt.Sprintf(\"lock operation failed [%s]\", err))\n\t}\n\n\tif !status {\n\t\tt.Error(\"lock acquisition failed\")\n\t}\n\n\tlock2 := New(conn, key, 1000)\n\n\tstatus, err = lock2.Lock()\n\tdefer lock2.UnlockIfLocked()\n\n\tif err != nil {\n\t\tt.Error(fmt.Sprintf(\"lock operation failed [%s]\", err))\n\t}\n\n\tif status {\n\t\tt.Error(\"lock acquisition succeeded\")\n\t}\n}", "func (d *Dam) Lock() {\n\td.freeze.Lock()\n}", "func (f *volatileFile) Lock(lock C.int) C.int {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\n\tswitch lock {\n\tcase C.SQLITE_LOCK_NONE:\n\t\tf.none++\n\tcase C.SQLITE_LOCK_SHARED:\n\t\tf.shared++\n\tcase C.SQLITE_LOCK_RESERVED:\n\t\tf.reserved++\n\tcase C.SQLITE_LOCK_PENDING:\n\t\tf.pending++\n\tcase C.SQLITE_LOCK_EXCLUSIVE:\n\t\tf.exclusive++\n\tdefault:\n\t\treturn C.SQLITE_ERROR\n\t}\n\n\treturn C.SQLITE_OK\n}", "func Test_Lock(t *testing.T) {\n\tkey := \"Test_Lock\"\n\tconn, err := redigo.Dial(\"tcp\", RedisHost)\n\n\tif err != nil {\n\t\tt.Error(fmt.Sprintf(\"redigo.Dial failure [%s]\", err))\n\t}\n\n\tlock := New(conn, key)\n\n\tstatus, err := lock.Lock()\n\tdefer lock.UnlockIfLocked()\n\n\tif err != nil {\n\t\tt.Error(fmt.Sprintf(\"lock operation failed [%s]\", err))\n\t}\n\n\tif !status {\n\t\tt.Error(\"lock acquisition failed\")\n\t}\n}", "func NewLock() Lock {\n\treturn Lock{ch: make(chan struct{}, 1)}\n}", "func (s *KVS) TestLock() {\n\tlockReq, err := acomm.NewRequest(acomm.RequestOptions{\n\t\tTask: \"kv-lock\",\n\t\tArgs: LockArgs{\n\t\t\tKey: s.PrefixKey(\"some-lock\"),\n\t\t\tTTL: 1 * time.Second,\n\t\t},\n\t})\n\ts.Require().NoError(err)\n\n\t// acquire lock\n\tres, streamURL, err := s.KV.lock(lockReq)\n\ts.Require().NoError(err, \"should be able to acquire lock\")\n\ts.Require().Nil(streamURL)\n\ts.Require().NotNil(res)\n\n\tlock := res.(Cookie)\n\n\tres, streamURL, err = s.KV.lock(lockReq)\n\ts.Require().Error(err, \"should not be able to acquire an acquired lock\")\n\ts.Require().Nil(streamURL)\n\ts.Require().Nil(res)\n\n\t// unlocking\n\tunlockReq, err := acomm.NewRequest(acomm.RequestOptions{\n\t\tTask: \"kv-unlock\",\n\t\tArgs: lock,\n\t})\n\tres, streamURL, err = s.KV.unlock(unlockReq)\n\ts.Require().NoError(err, \"unlocking should not fail\")\n\ts.Require().Nil(streamURL)\n\ts.Require().Nil(res)\n\n\tres, streamURL, err = s.KV.unlock(unlockReq)\n\ts.Require().Error(err, \"unlocking lost lock should fail\")\n\ts.Require().Nil(streamURL)\n\ts.Require().Nil(res)\n\n\tres, streamURL, err = s.KV.lock(lockReq)\n\ts.Require().NoError(err, \"acquiring an unlocked lock should pass\")\n\ts.Require().Nil(streamURL)\n\ts.Require().NotNil(res)\n\n\tlock = res.(Cookie)\n\n\trenewReq, err := acomm.NewRequest(acomm.RequestOptions{\n\t\tTask: \"kv-renew\",\n\t\tArgs: lock,\n\t})\n\tfor i := 0; i < 5; i++ {\n\t\tres, streamURL, err = s.KV.renew(renewReq)\n\t\ts.Require().NoError(err, \"renewing a lock should pass\")\n\t\ts.Require().Nil(streamURL)\n\t\ts.Require().Nil(res)\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\n\ttime.Sleep(3 * time.Second)\n\tres, streamURL, err = s.KV.renew(renewReq)\n\ts.Require().Error(err, \"renewing an expired lock should fail\")\n\ts.Require().Nil(streamURL)\n\ts.Require().Nil(res)\n\n\t// consul's default lock-delay\n\t// see lock-delay at https://www.consul.io/docs/internals/sessions.html\n\ttime.Sleep(15 * time.Second)\n\n\tres, streamURL, err = s.KV.lock(lockReq)\n\ts.Require().NoError(err, \"should be able to acquire previously expired lock\")\n\ts.Require().Nil(streamURL)\n\ts.Require().NotNil(res)\n}", "func (l *Lock) Lock() {\n\tl.ch <- struct{}{}\n}", "func (tm *TabletManager) lock(ctx context.Context) error {\n\treturn tm.actionSema.Acquire(ctx, 1)\n}", "func (m *MutexSafe) lock() {\n\tm.Mutex.Lock()\n}", "func (r *Locking) Lock() (Result, func() (Result, error), error) {\n\tlockstatus, err := r.create()\n\tif err != nil {\n\t\treturn Result{}, nil, err\n\t}\n\t// build the unlock logic\n\tvar unlock func() (Result, error)\n\tif r.IsLockForever {\n\t\tunlock = func() (Result, error) {\n\t\t\t// this is a noop if this lock is meant\n\t\t\t// to be present forever\n\t\t\treturn Result{\n\t\t\t\tPhase: \"Passed\",\n\t\t\t\tMessage: \"Will not unlock: Locked forever\",\n\t\t\t}, nil\n\t\t}\n\t} else {\n\t\t// this is a one time lock that should be removed\n\t\tunlock = r.delete\n\t}\n\treturn lockstatus, unlock, nil\n}", "func (r *Locking) MustUnlock() (Result, error) {\n\treturn r.delete()\n}", "func (mfs *MinFS) Lock(path string) error {\n\tmfs.m.Lock()\n\tdefer mfs.m.Unlock()\n\n\tmfs.locks[path] = true\n\treturn nil\n}", "func (f *file) Lock() error {\n\treturn nil\n}", "func Lock() {\n\treg.Write(TZASC_LOCKDOWN_RANGE, 0xffffffff)\n\treg.Write(TZASC_LOCKDOWN_SELECT, 0xffffffff)\n\treg.Set(GPR1_TZASC1_BOOT_LOCK, 23)\n}", "func InheritLock(overrides ILockOverrides) *Lock {\n\treturn &Lock{\n\t\tOverrides: overrides,\n\t\tretryTimeout: 100,\n\t}\n}", "func (n *nsLockMap) lock(ctx context.Context, volume, path string, lockSource, opsID string, readLock bool, timeout time.Duration) (locked bool) {\n\tvar nsLk *nsLock\n\n\tn.lockMapMutex.Lock()\n\tparam := nsParam{volume, path}\n\tnsLk, found := n.lockMap[param]\n\tif !found {\n\t\tn.lockMap[param] = &nsLock{\n\t\t\tLRWMutex: lsync.NewLRWMutex(ctx),\n\t\t\tref: 1,\n\t\t}\n\t\tnsLk = n.lockMap[param]\n\t} else {\n\t\t// Update ref count here to avoid multiple races.\n\t\tnsLk.ref++\n\t}\n\tn.lockMapMutex.Unlock()\n\n\t// Locking here will block (until timeout).\n\tif readLock {\n\t\tlocked = nsLk.GetRLock(opsID, lockSource, timeout)\n\t} else {\n\t\tlocked = nsLk.GetLock(opsID, lockSource, timeout)\n\t}\n\n\tif !locked { // We failed to get the lock\n\n\t\t// Decrement ref count since we failed to get the lock\n\t\tn.lockMapMutex.Lock()\n\t\tnsLk.ref--\n\t\tif nsLk.ref == 0 {\n\t\t\t// Remove from the map if there are no more references.\n\t\t\tdelete(n.lockMap, param)\n\t\t}\n\t\tn.lockMapMutex.Unlock()\n\t}\n\treturn\n}", "func Lock(client *gophercloud.ServiceClient, id string) (r LockResult) {\n\t_, r.Err = client.Post(actionURL(client, id), map[string]interface{}{\"lock\": nil}, nil, nil)\n\treturn\n}", "func (l *FileLock) ExclusiveLock() error {\n\treturn syscall.Flock(l.fd, syscall.LOCK_EX)\n}", "func (s *BasePlSqlParserListener) EnterLock_mode(ctx *Lock_modeContext) {}", "func (f *File) Lock() error {\n\treturn nil\n}", "func (nc *NexusConn) Lock(lock string) (bool, error) {\n\tpar := ei.M{\n\t\t\"lock\": lock,\n\t}\n\tres, err := nc.Exec(\"sync.lock\", par)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn ei.N(res).M(\"ok\").BoolZ(), nil\n}", "func (t *trivial) Lock() bool {\n\tlockResult := false\n\tselect {\n\tcase <-t.c:\n\t\tlockResult = true\n\tdefault:\n\t}\n\treturn lockResult\n}", "func (wt *Wallet) Lock() {\n\twt.lockRequests <- struct{}{}\n}", "func Lock(client *gophercloud.ServiceClient, id string) (r LockResult) {\n\t_, r.Err = client.Post(extensions.ActionURL(client, id), map[string]interface{}{\"lock\": nil}, nil, nil)\n\treturn\n}", "func (w *Wallet) Lock() {\n\tw.lockRequests <- struct{}{}\n}", "func (l *fileLock) tryLock() (Unlocker, error) {\n\tl.mu.Lock()\n\terr := syscall.Flock(l.fd, syscall.LOCK_EX|syscall.LOCK_NB)\n\tswitch err {\n\tcase syscall.EWOULDBLOCK:\n\t\tl.mu.Unlock()\n\t\treturn nopUnlocker{}, nil\n\tcase nil:\n\t\treturn l, nil\n\tdefault:\n\t\tl.mu.Unlock()\n\t\treturn nil, err\n\t}\n}", "func testNonNilTimeoutLock(ctx context.Context, t *testing.T, w *Wallet) {\n\ttimeChan := make(chan time.Time)\n\terr := w.Unlock(ctx, testPrivPass, timeChan)\n\tif err != nil {\n\t\tt.Fatal(\"failed to unlock wallet\")\n\t}\n\ttimeChan <- time.Time{}\n\ttime.Sleep(100 * time.Millisecond) // Allow time for lock in background\n\tif !w.Locked() {\n\t\tt.Fatal(\"wallet should have locked after timeout\")\n\t}\n}", "func (r *Radix) lock() {\n\tif r.ts {\n\t\tr.mu.Lock()\n\t}\n}", "func Lock(ctx context.Context, cli api.LocksClient, id string) error {\n\t_, err := cli.Aquire(ctx, &api.AquireRequest{Id: id})\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo func() {\n\t\tticker := time.NewTicker(renewInterval)\n\t\tdefer ticker.Stop()\n\t\tif err != nil {\n\t\t\tlogrus.Error(err)\n\t\t\treturn\n\t\t}\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\t_, err = cli.Release(context.Background(), &api.ReleaseRequest{Id: id})\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogrus.Error(err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase <-ticker.C:\n\t\t\t\t_, err = cli.Hold(ctx, &api.HoldRequest{Id: id})\n\t\t\t}\n\t\t}\n\t}()\n\treturn nil\n}", "func (m *RWMutex) Lock() {\n\tlocking.AddGLock(genericMarkIndex, -1)\n\tm.mu.Lock()\n}", "func (s *sched) lock(t Task) (bool, error) {\n\treturn s.cache.SetNX(prefixLock+t.GetID(), \"locking\", t.GetTimeout())\n}", "func (l *fingerprintLocker) Lock(fp model.Fingerprint) {\n\tl.fpMtxs[hashFP(fp)%l.numFpMtxs].Lock()\n}", "func (s ClosedDoorState) Lock(door *Door) (DoorState, error) {\n\tdoor.LockCount++\n\treturn LockedDoorState{}, nil\n}", "func (l *lockServer) Lock(args *LockArgs, reply *bool) error {\n\tl.mutex.Lock()\n\tdefer l.mutex.Unlock()\n\tif err := l.verifyArgs(args); err != nil {\n\t\treturn err\n\t}\n\t_, *reply = l.lockMap[args.Name]\n\tif !*reply { // No locks held on the given name, so claim write lock\n\t\tl.lockMap[args.Name] = []lockRequesterInfo{{writer: true, node: args.Node, rpcPath: args.RPCPath, uid: args.UID, timestamp: time.Now(), timeLastCheck: time.Now()}}\n\t}\n\t*reply = !*reply // Negate *reply to return true when lock is granted or false otherwise\n\treturn nil\n}", "func (l *Lock) Lock(ctx context.Context) (err error) {\n\tvar lc <-chan struct{}\n\n\tif l.lock, err = l.client.Consul().LockOpts(&api.LockOptions{\n\t\tKey: l.config.Key,\n\t\tLockWaitTime: l.wait,\n\t\tSessionTTL: l.ttl,\n\t}); err != nil {\n\t\treturn\n\t}\n\n\tl.stop = make(chan struct{})\n\n\tif l.lock == nil {\n\t\tl.setHasLock(false)\n\t\terr = fmt.Errorf(\"node %s no lock manager\", l.id)\n\t\treturn\n\t}\n\n\tif lc, err = l.lock.Lock(l.stop); err != nil {\n\t\tl.setHasLock(false)\n\t\terr = lock.ErrLockFailed\n\t\treturn\n\t}\n\n\tl.stop = nil\n\tl.setHasLock(true)\n\n\tselect {\n\tcase <-l.cc:\n\n\t\tl.setHasLock(false)\n\t\terr = lock.ErrLockClosed\n\t\treturn\n\tcase <-lc:\n\t\tl.setHasLock(false)\n\t\terr = lock.ErrLockFailed\n\t\treturn\n\t}\n}", "func (btc *ExchangeWallet) Lock() error {\n\treturn btc.wallet.Lock()\n}", "func (r *RedisDL) lock(ctx context.Context) error {\n\tr.m.Lock()\n\tdefer r.m.Unlock()\n\ttoken, err := randToken()\n\tif err != nil {\n\t\treturn err\n\t}\n\tretry := time.NewTimer(r.opt.LockTimeout)\n\tatts := r.opt.RetryCount + 1\n\tfor {\n\t\tif err := r.storeToken(token); err == nil {\n\t\t\tr.currentToken = token\n\t\t\treturn nil\n\t\t}\n\t\tif atts--; atts <= 0 {\n\t\t\treturn fmt.Errorf(\"unable to generate token\")\n\t\t}\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tcase <-retry.C:\n\t\t}\n\t}\n}", "func (wp *WPLock) Lock() {\n\n\twp.waitingLock.Lock()\n\tif atomic.CompareAndSwapInt32(&wp.waiting, 0, 1) {\n\t\twp.writeLock.Lock()\n\t} else {\n\t\tatomic.AddInt32(&wp.waiting, 1)\n\t}\n\twp.waitingLock.Unlock()\n\n\twp.lock.Lock()\n}", "func (m *mutex) TryLock(ctx context.Context) error {\n\treturn (*semaphore.Weighted)(m).Acquire(ctx, 1)\n}", "func (rw *RWMutex) Lock() {\n\trw.RWMutex.Lock()\n\tatomic.StoreInt32(&rw.wLocked, 1)\n}", "func (s *EtcdV3) NewLock(key string, options *store.LockOptions) (store.Locker, error) {\n\treturn nil, errors.New(\"not implemented\")\n}", "func (w *wlockMap) lock(ino uint64) {\n\tw.Lock()\n\tr := w.inodeLocks[ino]\n\tw.Unlock()\n\t// this can take a long time - execute outside the wlockMap lock\n\tr.Lock()\n}", "func (f *Flock) Lock() error {\n\treturn f.lock(&f.l, writeLock)\n}", "func (el *Lock) Lock(d time.Duration) error {\n\tfor {\n\t\topts := &SetOptions{TTL: d, IfNotExist: true}\n\t\t_, err := el.Set(el.key(), el.Item, opts)\n\t\tif eerr, ok := err.(*NodeExistError); !ok {\n\t\t\treturn eerr\n\t\t}\n\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\n\t\ttime.Sleep(lockRetryTimeout)\n\t}\n\n\treturn nil\n}", "func (m mysqlDialect) Lock(ctx context.Context, tx Queryer, tableName string) error {\n\tlockID := m.advisoryLockID(tableName)\n\tquery := fmt.Sprintf(`SELECT GET_LOCK('%s', 10)`, lockID)\n\t_, err := tx.ExecContext(ctx, query)\n\treturn err\n}", "func flockLock(l *L, fd *os.File) error {\n\t// Use \"flock()\" to get a lock on the file.\n\t//\n\tlockcmd := unix.F_SETLK\n\tlockstr := unix.Flock_t{\n\t\tType: unix.F_WRLCK, Start: 0, Len: 0, Whence: 1,\n\t}\n\n\tif l.Shared {\n\t\tlockstr.Type = unix.F_RDLCK\n\t}\n\n\tif err := unix.FcntlFlock(fd.Fd(), lockcmd, &lockstr); err != nil {\n\t\tif errno, ok := err.(unix.Errno); ok {\n\t\t\tswitch errno {\n\t\t\tcase unix.EWOULDBLOCK:\n\t\t\t\t// Someone else holds the lock on this file.\n\t\t\t\treturn ErrLockHeld\n\t\t\tdefault:\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}", "func (r *RedisDL) Lock(ctx context.Context) error {\n\treturn r.lock(ctx)\n}", "func (r *Request) Lock(ctx context.Context, token string) error {\n\tif _, ok := r.wLocks[token]; ok {\n\t\treturn nil\n\t}\n\n\terr := r.m.Lock(ctx, token)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.wLocks[token] = struct{}{}\n\n\treturn nil\n}", "func (m *Mutex) Lock() {\n\tm.in <- struct{}{}\n}", "func (mdl *Model) Lock() {\n\tmdl.locked = true\n}", "func (self *Map) lock() {\n\tif self.atomic == nil {\n\t\tself.atomic = new(sync.Mutex)\n\t}\n\n\tself.atomic.Lock()\n}", "func (lt *LockTimeout) TryLock() int {\n\tbrv := atomic.CompareAndSwapInt32(&lt.frontLock, 0, 1)\n\tif brv {\n\t\treturn 1\n\t}\n\treturn 0\n}", "func (r GopassRepo) lockState(payload []byte) error { return nil }", "func (r *ByteRange) Lock() error {\n\treturn r.flock(unix.F_WRLCK)\n}", "func (l etcdLocker) Lock(ctx context.Context, oo ...Option) (Lock, error) {\n\treturn newEtcdLock(ctx, l.client, l.opts.withOptions(oo...))\n}", "func lock(filename string) (*flock.Flock, error) {\n\tfileLock := flock.NewFlock(filename)\n\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\n\tlocked, err := fileLock.TryLockContext(ctx, 100*time.Millisecond)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !locked {\n\t\treturn nil, errors.New(\"could not lock\")\n\t}\n\n\treturn fileLock, nil\n}", "func (w *xcWallet) Lock(timeout time.Duration) error {\n\ta, is := w.Wallet.(asset.Authenticator)\n\tif w.isDisabled() || !is { // wallet is disabled and is locked or it's not an authenticator.\n\t\treturn nil\n\t}\n\tif w.parent != nil {\n\t\treturn w.parent.Lock(timeout)\n\t}\n\tw.mtx.Lock()\n\tif !w.hookedUp {\n\t\tw.mtx.Unlock()\n\t\treturn errWalletNotConnected\n\t}\n\tif len(w.encPass) == 0 {\n\t\tw.mtx.Unlock()\n\t\treturn nil\n\t}\n\tw.pw.Clear()\n\tw.pw = nil\n\tw.mtx.Unlock() // end critical section before actual wallet request\n\n\treturn runWithTimeout(a.Lock, timeout)\n}", "func (obj *Field) Lock(ctx context.Context) (bool, error) {\n\tresult := &struct {\n\t\tReturn bool `json:\"qReturn\"`\n\t}{}\n\terr := obj.RPC(ctx, \"Lock\", result)\n\treturn result.Return, err\n}", "func New() Lock {\n\treturn &lock{sem: make(chan int, 1)}\n}", "func (f *Flock) Lock() error {\n\treturn f.lock(&f.l, winLockfileExclusiveLock)\n}", "func (tracker *tracker) Lock(node *Node) {\n\ttracker.mutex.Lock()\n\tmutex := tracker.locks[node]\n\tif mutex == nil {\n\t\tmutex = &sync.Mutex{}\n\t\ttracker.locks[node] = mutex\n\t}\n\ttracker.mutex.Unlock()\n\tmutex.Lock()\n}", "func mainLock(ctx *cli.Context) error {\n\tconsole.SetColor(\"Mode\", color.New(color.FgCyan, color.Bold))\n\tconsole.SetColor(\"Validity\", color.New(color.FgYellow))\n\n\t// Parse encryption keys per command.\n\t_, err := getEncKeys(ctx)\n\tfatalIf(err, \"Unable to parse encryption keys.\")\n\n\t// lock specific flags.\n\tclearLock := ctx.Bool(\"clear\")\n\n\targs := ctx.Args()\n\n\tvar urlStr string\n\tvar mode *minio.RetentionMode\n\tvar validity *uint\n\tvar unit *minio.ValidityUnit\n\n\tswitch l := len(args); l {\n\tcase 1:\n\t\turlStr = args[0]\n\n\tcase 3:\n\t\turlStr = args[0]\n\t\tif clearLock {\n\t\t\tfatalIf(probe.NewError(errors.New(\"invalid argument\")), \"clear flag must be passed with target alone\")\n\t\t}\n\n\t\tm := minio.RetentionMode(strings.ToUpper(args[1]))\n\t\tif !m.IsValid() {\n\t\t\tfatalIf(probe.NewError(errors.New(\"invalid argument\")), \"invalid retention mode '%v'\", m)\n\t\t}\n\n\t\tmode = &m\n\n\t\tvalidityStr := args[2]\n\t\tunitStr := string(validityStr[len(validityStr)-1])\n\n\t\tvalidityStr = validityStr[:len(validityStr)-1]\n\t\tui64, err := strconv.ParseUint(validityStr, 10, 64)\n\t\tif err != nil {\n\t\t\tfatalIf(probe.NewError(errors.New(\"invalid argument\")), \"invalid validity '%v'\", args[2])\n\t\t}\n\t\tu := uint(ui64)\n\t\tvalidity = &u\n\n\t\tswitch unitStr {\n\t\tcase \"d\", \"D\":\n\t\t\td := minio.Days\n\t\t\tunit = &d\n\t\tcase \"y\", \"Y\":\n\t\t\ty := minio.Years\n\t\t\tunit = &y\n\t\tdefault:\n\t\t\tfatalIf(probe.NewError(errors.New(\"invalid argument\")), \"invalid validity format '%v'\", args[2])\n\t\t}\n\tdefault:\n\t\tcli.ShowCommandHelpAndExit(ctx, \"lock\", 1)\n\t}\n\n\treturn lock(urlStr, mode, validity, unit, clearLock)\n}", "func (heap *SkewHeap) lock() { heap.mutex.Lock() }", "func (rw *RWLock) Lock() error {\n\treturn rw.LockWithCtx(nil)\n}", "func (g *glock) Lock() context.Context {\n\tvar (\n\t\tkv goku.KV\n\t\terr error\n\t)\n\n\tg.mt.Lock()\n\tg.waiting = true\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tg.cancel = cancel\n\n\tfor {\n\t\tfor {\n\t\t\tkv, err = g.gok.Get(ctx, g.key)\n\t\t\tif errors.Is(err, goku.ErrNotFound) {\n\t\t\t\t// First set so there's no key\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif strings.HasPrefix(string(kv.Value), \"locked\") {\n\t\t\t\tg.awaitRetry()\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t// Case for fist time trying to acquire lock.\n\t\tif err != nil {\n\t\t\terr = g.gok.Set(ctx, g.key, []byte(\"locked_\"+g.processID),\n\t\t\t\tgoku.WithCreateOnly(),\n\t\t\t\tgoku.WithExpiresAt(time.Now().Add(time.Second*20)))\n\t\t} else {\n\t\t\terr = g.gok.Set(ctx, g.key, []byte(\"locked_\"+g.processID),\n\t\t\t\tgoku.WithPrevVersion(kv.Version),\n\t\t\t\tgoku.WithExpiresAt(time.Now().Add(time.Second*20)))\n\t\t}\n\n\t\tif err != nil {\n\t\t\t// retry\n\t\t\tcontinue\n\t\t}\n\n\t\t// ensure the lock is ours\n\t\tkv, err = g.gok.Get(ctx, g.key)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Sanity check, paranoid\n\t\tif string(kv.Value) != \"locked_\"+g.processID {\n\t\t\tcontinue\n\t\t}\n\n\t\tg.locked = true\n\t\tgo g.keepAlive(ctx)\n\t\treturn ctx\n\t}\n}", "func (in *ActionVpsSetMaintenanceInput) SetLock(value bool) *ActionVpsSetMaintenanceInput {\n\tin.Lock = value\n\n\tif in._selectedParameters == nil {\n\t\tin._selectedParameters = make(map[string]interface{})\n\t}\n\n\tin._selectedParameters[\"Lock\"] = nil\n\treturn in\n}", "func (l *Lock) TryLock() bool {\n\tselect {\n\tcase l.ch <- struct{}{}:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (c *Client) NewLock(key string, options *store.LockOptions) (store.Locker, error) {\n\treturn nil, errNotImplemented\n}", "func New() target.Locker {\n\treturn &Noop{}\n}", "func (p *Player) lock() {\n\tp.chLock <- struct{}{}\n}", "func (channelTree *ChannelTree) Lock() {\n\tchannelTree.mutex.Lock()\n}", "func (k *Kluster) Lock(name string) (lockfile.Lockfile, error) {\n\tif name == \"\" {\n\t\tname = k.Name\n\t}\n\tf := filepath.Join(k.Dir(), \".\"+name)\n\treturn lockFile(f)\n}", "func (defaultFS) Lock(name string) (io.Closer, error) {\n\tp, err := windows.UTF16PtrFromString(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfd, err := windows.CreateFile(p,\n\t\twindows.GENERIC_READ|windows.GENERIC_WRITE,\n\t\t0, nil, windows.CREATE_ALWAYS,\n\t\twindows.FILE_ATTRIBUTE_NORMAL,\n\t\t0,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn lockCloser{fd: fd}, nil\n}", "func (*CPIO9PFID) Lock(pid int, locktype p9.LockType, flags p9.LockFlags, start, length uint64, client string) (p9.LockStatus, error) {\n\treturn p9.LockStatus(0), nil\n}", "func (t *TrudyPipe) Lock() {\n\tt.userMutex.Lock()\n}", "func (s *SharedState) lock() *SharedState {\n s.mutex.Lock()\n return s\n}", "func (m *SHMLockManager) AllocateLock() (Locker, error) {\n\treturn nil, fmt.Errorf(\"not supported\")\n}" ]
[ "0.80031097", "0.7108842", "0.7057957", "0.7014114", "0.68878496", "0.6848324", "0.684109", "0.68210536", "0.6815423", "0.6760319", "0.6752995", "0.6706289", "0.6677526", "0.6667062", "0.66536474", "0.66485286", "0.6593813", "0.6591521", "0.65862215", "0.65466106", "0.6540568", "0.6539419", "0.6538904", "0.6531736", "0.6525149", "0.6523585", "0.65184134", "0.6517733", "0.646362", "0.6462369", "0.6445941", "0.6439636", "0.6439293", "0.643049", "0.64204055", "0.64140517", "0.64067763", "0.63831484", "0.6375688", "0.6372737", "0.6371001", "0.6348295", "0.63306516", "0.63267606", "0.63206786", "0.6319392", "0.62996984", "0.62727004", "0.62603813", "0.62579244", "0.62535065", "0.6239165", "0.62381274", "0.6233082", "0.62320817", "0.6229569", "0.6215469", "0.6212522", "0.61967814", "0.6195853", "0.61935556", "0.61841124", "0.6168473", "0.6168279", "0.61613524", "0.6157282", "0.61565083", "0.6152209", "0.61491346", "0.61328584", "0.61319524", "0.61272645", "0.61222625", "0.61192304", "0.61021394", "0.60884887", "0.60870767", "0.6086721", "0.60820496", "0.6075875", "0.6074362", "0.6072164", "0.6067413", "0.60633975", "0.6056163", "0.605501", "0.60474926", "0.60414183", "0.60309803", "0.60299426", "0.6029733", "0.6026266", "0.6023223", "0.60120255", "0.6002601", "0.5999683", "0.5978591", "0.59751123", "0.59748197", "0.5973271" ]
0.78249574
1
NewAdapter returns a new Adapter that can be used to orchestrate and obtain information from Amazon Web Services. Before returning there is a discovery process for VPC and EC2 details. It tries to find the Auto Scaling Group and Security Group that should be used for newly created Load Balancers. If any of those critical steps fail an appropriate error is returned.
func NewAdapter() (adapter *Adapter, err error) { p := configProvider() adapter = &Adapter{ ec2: ec2.New(p), ec2metadata: ec2metadata.New(p), autoscaling: autoscaling.New(p), acm: acm.New(p), iam: iam.New(p), cloudformation: cloudformation.New(p), healthCheckPath: DefaultHealthCheckPath, healthCheckPort: DefaultHealthCheckPort, healthCheckInterval: DefaultHealthCheckInterval, creationTimeout: DefaultCreationTimeout, stackTTL: DefaultStackTTL, } adapter.manifest, err = buildManifest(adapter) if err != nil { return nil, err } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewAdapter(g *gce.Cloud) NetworkEndpointGroupCloud {\n\treturn &cloudProviderAdapter{\n\t\tc: g,\n\t\tnetworkURL: g.NetworkURL(),\n\t\tsubnetworkURL: g.SubnetworkURL(),\n\t}\n}", "func NewAdapter() Adapter {\n\treturn createAdapter()\n}", "func NewAdapter() Adapter {\n\treturn createAdapter()\n}", "func NewAdapter() Adapter {\n\treturn createAdapter()\n}", "func NewAdapter() Adapter {\n\treturn createAdapter()\n}", "func NewAdapter() Adapter {\n\treturn createAdapter()\n}", "func NewAdapter(b *AdapterBuilder) (a *Adapter) {\n\t// allocate default adapter\n\ta = &Adapter{\n\t\tbeforeErr: doNothing,\n\t\tafterErr: doNothing,\n\t\tinternalHandler: defaultInternalServerErrorHandler,\n\t\twrapInternal: b.WrapInternal,\n\t}\n\n\t// check for nil arguments\n\tif b.AfterError != nil {\n\t\ta.afterErr = b.AfterError\n\t}\n\tif b.BeforeError != nil {\n\t\ta.beforeErr = b.BeforeError\n\t}\n\tif b.InternalHandler != nil {\n\t\ta.internalHandler = b.InternalHandler\n\t}\n\n\t// return adapter that is safe to use and will\n\t// not panic because of nil function pointers\n\treturn\n}", "func NewAdapter(config *aws.Config, ds string) *Adapter {\n\ta := &Adapter{}\n\ta.Config = config\n\ta.DataSourceName = ds\n\ta.Service = dynamodb.New(session.New(config), a.Config)\n\ta.DB = dynamo.New(session.New(), a.Config)\n\treturn a\n}", "func New(opts []Options, mode BalanceMode) *Balancer {\n\tif len(opts) == 0 {\n\t\topts = []Options{\n\t\t\tOptions{Addr: \"127.0.0.1:4150\"},\n\t\t}\n\t}\n\n\tbalancer := &Balancer{\n\t\tselector: make(pool, len(opts)),\n\t\tmode: mode,\n\t}\n\tfor i := 0; i < len(opts); i++ {\n\t\tbalancer.selector[i] = newNsqBackend(&opts[i])\n\t}\n\treturn balancer\n}", "func NewAdapter() Adapter {\n\tbuilder := NewBuilder()\n\treturn createAdapter(builder)\n}", "func NewAdapter(name string, opt Options) (Adapter, error) {\n\tadapter, ok := adapters[name]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"cache: unknown adapter '%s'(forgot to import?)\", name)\n\t}\n\treturn adapter, adapter.StartAndGC(opt)\n}", "func New(adapterContext common.AdapterContext, client kclient.Client) Adapter {\n\n\tcompAdapter := component.New(adapterContext, client)\n\n\treturn Adapter{\n\t\tcomponentAdapter: compAdapter,\n\t}\n}", "func newAdapter(config *AdapterConfig) (adapters.ListChecker, error) {\n\tvar u *url.URL\n\tvar err error\n\tif u, err = url.Parse(config.ProviderURL); err != nil {\n\t\t// bogus URL format\n\t\treturn nil, err\n\t}\n\n\ta := adapter{\n\t\tbackend: u,\n\t\tclosing: make(chan bool),\n\t\trefreshInterval: config.RefreshInterval,\n\t\tttl: config.TimeToLive,\n\t}\n\n\t// install an empty list\n\ta.setList([]*net.IPNet{})\n\n\t// load up the list synchronously so we're ready to accept traffic immediately\n\ta.refreshList()\n\n\t// crank up the async list refresher\n\tgo a.listRefresher()\n\n\treturn &a, nil\n}", "func NewAdapter(t mockConstructorTestingTNewAdapter) *Adapter {\n\tmock := &Adapter{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewAdapter(cfg AdapterConfig, logger *zap.Logger) *Adapter {\n\thookLogger := logger.Named(\"hook-adapter\")\n\tsupervisorLogger := hookLogger.Named(\"supervisor\")\n\ta := &Adapter{\n\t\tSupervisor: suture.New(\"hook-adapter\", suture.Spec{\n\t\t\tLog: func(line string) {\n\t\t\t\tsupervisorLogger.Info(line)\n\t\t\t},\n\t\t}),\n\t}\n\n\tscanTicker := time.NewTicker(1 * time.Second)\n\tscanner := process.NewScanner(\n\t\tcfg.HookConfig.FFXIVProcess,\n\t\tscanTicker.C,\n\t\tcfg.ProcessEnumerator,\n\t\t10,\n\t\thookLogger,\n\t)\n\n\tstreamSupervisorLogger := hookLogger.Named(\"stream-supervisor\")\n\tstreamSupervisor := suture.New(\"stream-supervisor\", suture.Spec{\n\t\tLog: func(line string) {\n\t\t\tstreamSupervisorLogger.Info(line)\n\t\t},\n\t})\n\n\tstreamBuilder := func(streamID uint32) Stream {\n\t\treturn NewStream(streamID, cfg, hookLogger)\n\t}\n\n\tmanager := NewManager(\n\t\tcfg,\n\t\tscanner.ProcessAddEventListener(),\n\t\tscanner.ProcessRemoveEventListener(),\n\t\tstreamBuilder,\n\t\tstreamSupervisor,\n\t\thookLogger,\n\t)\n\n\ta.Add(scanner)\n\ta.Add(streamSupervisor)\n\ta.Add(manager)\n\n\treturn a\n}", "func NewCloudwatchAdapter(route *router.Route) (router.LogAdapter, error) {\n\tdockerHost := `unix:///var/run/docker.sock`\n\tif envVal := os.Getenv(`DOCKER_HOST`); envVal != \"\" {\n\t\tdockerHost = envVal\n\t}\n\tclient, err := docker.NewClient(dockerHost)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tec2info, err := NewEC2Info(route) // get info from EC2\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tadapter := CloudwatchAdapter{\n\t\tRoute: route,\n\t\tOsHost: hostname,\n\t\tEc2Instance: ec2info.InstanceID,\n\t\tEc2Region: ec2info.Region,\n\t\tclient: client,\n\t\tgroupnames: map[string]string{},\n\t\tstreamnames: map[string]string{},\n\t}\n\tadapter.batcher = NewCloudwatchBatcher(&adapter)\n\treturn &adapter, nil\n}", "func (a *APILoadBalancers) New() (types.Resource, error) {\n\tif err := a.Validate(); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to validate API Load balancers configuration: %w\", err)\n\t}\n\n\tcc := &container.Containers{\n\t\tPreviousState: a.State,\n\t\tDesiredState: make(container.ContainersState),\n\t}\n\n\tfor i, lb := range a.APILoadBalancers {\n\t\tlb := lb\n\t\ta.propagateInstance(&lb)\n\n\t\tlbx, _ := lb.New()\n\t\tlbxHcc, _ := lbx.ToHostConfiguredContainer()\n\n\t\tcc.DesiredState[strconv.Itoa(i)] = lbxHcc\n\t}\n\n\tc, _ := cc.New()\n\n\treturn &apiLoadBalancers{\n\t\tcontainers: c,\n\t}, nil\n}", "func NewAdapter(ctx context.Context, conf Config) (*BotAdapter, error) {\n\n\tclient, err := rt.NewClient(conf.ServerURL, conf.Debug)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgen := NewRandID()\n\n\treturn newAdapter(ctx, client, conf, gen)\n}", "func newDiscoveryTool(\n\tregions []string,\n\tproject string,\n\tlg telegraf.Logger,\n\tcredential auth.Credential,\n\trateLimit int,\n\tdiscoveryInterval time.Duration,\n) (*discoveryTool, error) {\n\tvar (\n\t\tdscReq = map[string]discoveryRequest{}\n\t\tcli = map[string]aliyunSdkClient{}\n\t\tresponseRootKey string\n\t\tresponseObjectIDKey string\n\t\terr error\n\t\tnoDiscoverySupportErr = fmt.Errorf(\"no discovery support for project %q\", project)\n\t)\n\n\tif len(regions) == 0 {\n\t\tregions = aliyunRegionList\n\t\tlg.Infof(\"'regions' is not provided! Discovery data will be queried across %d regions:\\n%s\",\n\t\t\tlen(aliyunRegionList), strings.Join(aliyunRegionList, \",\"))\n\t}\n\n\tif rateLimit == 0 { //Can be a rounding case\n\t\trateLimit = 1\n\t}\n\n\tfor _, region := range regions {\n\t\tswitch project {\n\t\tcase \"acs_ecs_dashboard\":\n\t\t\tdscReq[region] = ecs.CreateDescribeInstancesRequest()\n\t\t\tresponseRootKey = \"Instances\"\n\t\t\tresponseObjectIDKey = \"InstanceId\"\n\t\tcase \"acs_rds_dashboard\":\n\t\t\tdscReq[region] = rds.CreateDescribeDBInstancesRequest()\n\t\t\tresponseRootKey = \"Items\"\n\t\t\tresponseObjectIDKey = \"DBInstanceId\"\n\t\tcase \"acs_slb_dashboard\":\n\t\t\tdscReq[region] = slb.CreateDescribeLoadBalancersRequest()\n\t\t\tresponseRootKey = \"LoadBalancers\"\n\t\t\tresponseObjectIDKey = \"LoadBalancerId\"\n\t\tcase \"acs_memcache\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_ocs\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_oss\":\n\t\t\t// oss is really complicated and its' own format\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_vpc_eip\":\n\t\t\tdscReq[region] = vpc.CreateDescribeEipAddressesRequest()\n\t\t\tresponseRootKey = \"EipAddresses\"\n\t\t\tresponseObjectIDKey = \"AllocationId\"\n\t\tcase \"acs_kvstore\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_mns_new\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_cdn\":\n\t\t\t//API replies are in its own format.\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_polardb\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_gdb\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_ads\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_mongodb\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_express_connect\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_fc\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_nat_gateway\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_sls_dashboard\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_containerservice_dashboard\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_vpn\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_bandwidth_package\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_cen\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_ens\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_opensearch\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_scdn\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_drds\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_iot\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_directmail\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_elasticsearch\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_ess_dashboard\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_streamcompute\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_global_acceleration\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_hitsdb\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_kafka\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_openad\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_pcdn\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_dcdn\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_petadata\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_videolive\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_hybriddb\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_adb\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_mps\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_maxcompute_prepay\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_hdfs\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_ddh\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_hbr\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_hdr\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_cds\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"project %q is not recognized by discovery\", project)\n\t\t}\n\n\t\tcli[region], err = sdk.NewClientWithOptions(region, sdk.NewConfig(), credential)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif len(dscReq) == 0 || len(cli) == 0 {\n\t\treturn nil, fmt.Errorf(\"can't build discovery request for project: %q, regions: %v\", project, regions)\n\t}\n\n\treturn &discoveryTool{\n\t\treq: dscReq,\n\t\tcli: cli,\n\t\trespRootKey: responseRootKey,\n\t\trespObjectIDKey: responseObjectIDKey,\n\t\trateLimit: rateLimit,\n\t\tinterval: discoveryInterval,\n\t\treqDefaultPageSize: 20,\n\t\tdataChan: make(chan map[string]interface{}, 1),\n\t\tlg: lg,\n\t}, nil\n}", "func NewAdapter(opts ...AdapterOptions) (cache.Adapter, error) {\n\ta := &Adapter{}\n\n\tfor _, opt := range opts {\n\t\tif err := opt(a); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif a.capacity <= 1 {\n\t\treturn nil, errors.New(\"memory adapter capacity is not set\")\n\t}\n\n\tif a.algorithm == \"\" {\n\t\treturn nil, errors.New(\"memory adapter caching algorithm is not set\")\n\t}\n\n\ta.mutex = sync.RWMutex{}\n\ta.store = make(map[uint64][]byte, a.capacity)\n\n\treturn a, nil\n}", "func New(ringWeight int) LoadBalancer {\n\t// TODO: Implement this!\n\tnewLB := new(loadBalancer)\n\tnewLB.sortedNames = make([]MMENode, 0)\n\tnewLB.weight = ringWeight\n\tnewLB.hashRing = NewRing()\n\tif 7 == 2 {\n\t\tfmt.Println(ringWeight)\n\t}\n\treturn newLB\n}", "func newDriverV2(options *DriverOptions) *DriverV2 {\n\tklog.Warning(\"Using DriverV2\")\n\tdriver := DriverV2{}\n\tdriver.Name = options.DriverName\n\tdriver.Version = driverVersion\n\tdriver.NodeID = options.NodeID\n\tdriver.VolumeAttachLimit = options.VolumeAttachLimit\n\tdriver.volumeLocks = volumehelper.NewVolumeLocks()\n\tdriver.perfOptimizationEnabled = options.EnablePerfOptimization\n\tdriver.cloudConfigSecretName = options.CloudConfigSecretName\n\tdriver.cloudConfigSecretNamespace = options.CloudConfigSecretNamespace\n\tdriver.customUserAgent = options.CustomUserAgent\n\tdriver.userAgentSuffix = options.UserAgentSuffix\n\tdriver.useCSIProxyGAInterface = options.UseCSIProxyGAInterface\n\tdriver.enableOtelTracing = options.EnableOtelTracing\n\tdriver.ioHandler = azureutils.NewOSIOHandler()\n\tdriver.hostUtil = hostutil.NewHostUtil()\n\n\ttopologyKey = fmt.Sprintf(\"topology.%s/zone\", driver.Name)\n\treturn &driver\n}", "func newLoadBalancer(ctx context.Context, frontend NetAddr, policy loadBalancerPolicy, backends ...NetAddr) (*LoadBalancer, error) {\n\tif ctx == nil {\n\t\treturn nil, trace.BadParameter(\"missing parameter context\")\n\t}\n\twaitCtx, waitCancel := context.WithCancel(ctx)\n\treturn &LoadBalancer{\n\t\tfrontend: frontend,\n\t\tctx: ctx,\n\t\tbackends: backends,\n\t\tpolicy: policy,\n\t\twaitCtx: waitCtx,\n\t\twaitCancel: waitCancel,\n\t\tEntry: log.WithFields(log.Fields{\n\t\t\ttrace.Component: \"loadbalancer\",\n\t\t\ttrace.ComponentFields: log.Fields{\n\t\t\t\t\"listen\": frontend.String(),\n\t\t\t},\n\t\t}),\n\t\tconnections: make(map[NetAddr]map[int64]net.Conn),\n\t}, nil\n}", "func NewAdapter(cfg Config) (AdapterInterface, error) {\n\n\terr := validateCfg(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ta := &Adapter{\n\t\tcfg: cfg,\n\t}\n\n\terr = a.initLogFile()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn a, nil\n}", "func New(asgName, policyName, region string) (*Autoscaling, error) {\n\tconfig, err := checkConfig(asgName, policyName, region)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Initialisation error: %v\", err)\n\t}\n\treturn config, nil\n}", "func NewAdapter(driverName string, masterDSNs []string, slaveDSNs []string, dbSpecified ...bool) *Adapter {\n\ta := &Adapter{}\n\ta.driverName = driverName\n\ta.masterDSNs = masterDSNs\n\ta.slaveDSNs = slaveDSNs\n\n\tif len(dbSpecified) == 0 {\n\t\ta.dbSpecified = false\n\t} else if len(dbSpecified) == 1 {\n\t\ta.dbSpecified = dbSpecified[0]\n\t} else {\n\t\tpanic(errors.New(\"invalid parameter: dbSpecified\"))\n\t}\n\n\t// Open the DB, create it if not existed.\n\ta.open()\n\n\t// Call the destructor when the object is released.\n\truntime.SetFinalizer(a, finalizer)\n\n\treturn a\n}", "func NewAdapter(db *sql.DB, tableName string) (*Adapter, error) {\n\treturn NewAdapterWithDBSchema(db, \"public\", tableName)\n}", "func NewAdapter() Adapter {\n\tstackframeBuilder := stackframe.NewBuilder()\n\tskipBuilder := stackframe.NewSkipBuilder()\n\tsaveBuilder := stackframe.NewSaveBuilder()\n\tconditionBuilder := condition.NewBuilder()\n\tpropositionBuilder := condition.NewPropositionBuilder()\n\tremainingBuilder := remaining.NewBuilder()\n\tstandardBuilder := standard.NewBuilder()\n\tvalueBuilder := value.NewBuilder()\n\tvarValueAdapter := var_value.NewAdapter()\n\tvarValueFactory := var_value.NewFactory()\n\tvarVariableBuilder := var_variable.NewBuilder()\n\tcallBuilder := call.NewBuilder()\n\tmoduleBuilder := module.NewBuilder()\n\texitBuilder := exit.NewBuilder()\n\tregistryIndexBuilder := registry.NewIndexBuilder()\n\tregistryRegisterBuilder := registry.NewRegisterBuilder()\n\tregisterFetchBuilder := registry.NewFetchBuilder()\n\tregistryBuilder := registry.NewBuilder()\n\tbuilder := NewBuilder()\n\treturn createAdapter(\n\t\tstackframeBuilder,\n\t\tskipBuilder,\n\t\tsaveBuilder,\n\t\tconditionBuilder,\n\t\tpropositionBuilder,\n\t\tremainingBuilder,\n\t\tstandardBuilder,\n\t\tvalueBuilder,\n\t\tvarValueAdapter,\n\t\tvarValueFactory,\n\t\tvarVariableBuilder,\n\t\tcallBuilder,\n\t\tmoduleBuilder,\n\t\texitBuilder,\n\t\tregistryIndexBuilder,\n\t\tregistryRegisterBuilder,\n\t\tregisterFetchBuilder,\n\t\tregistryBuilder,\n\t\tbuilder,\n\t)\n}", "func initializeAdapter(plan catalog.RDSPlan, s *config.Settings, c *catalog.Catalog) (dbAdapter, response.Response) {\n\n\tvar dbAdapter dbAdapter\n\t// For test environments, use a mock adapter.\n\tif s.Environment == \"test\" {\n\t\tdbAdapter = &mockDBAdapter{}\n\t\treturn dbAdapter, nil\n\t}\n\n\tswitch plan.Adapter {\n\tcase \"shared\":\n\t\tsetting, err := c.GetResources().RdsSettings.GetRDSSettingByPlan(plan.ID)\n\t\tif err != nil {\n\t\t\treturn nil, response.NewErrorResponse(http.StatusInternalServerError, err.Error())\n\t\t}\n\t\tif setting.DB == nil {\n\t\t\treturn nil, response.NewErrorResponse(http.StatusInternalServerError, \"An internal error occurred setting up shared databases.\")\n\t\t}\n\t\tdbAdapter = &sharedDBAdapter{\n\t\t\tSharedDbConn: setting.DB,\n\t\t}\n\tcase \"dedicated\":\n\t\tdbAdapter = &dedicatedDBAdapter{\n\t\t\tInstanceClass: plan.InstanceClass,\n\t\t\tsettings: *s,\n\t\t}\n\tdefault:\n\t\treturn nil, response.NewErrorResponse(http.StatusInternalServerError, \"Adapter not found\")\n\t}\n\n\treturn dbAdapter, nil\n}", "func NewBalancer(opts []Options) (*Balancer, error) {\n\tif len(opts) == 0 {\n\t\treturn nil, errors.New(\"invalid options\")\n\t}\n\n\t// create balancer base on given options.\n\tbalancer := &Balancer{pool: make(pool, len(opts))}\n\n\tfor i := 0; i < len(opts); i++ {\n\t\tbalancer.pool[i] = newBackend(&opts[i])\n\t}\n\n\treturn balancer, nil\n}", "func newAdapter(logw io.Writer) *adapter {\n\treturn &adapter{\n\t\tlogger: log.New(logw, \"adapter: \", log.LstdFlags),\n\t}\n}", "func New() *AwsAsg {\n\n\tcfg, err := config.LoadDefaultConfig()\n\tif err != nil {\n\t\tpanic(\"unable to load SDK config, \" + err.Error())\n\t}\n\tsvc := autoscaling.NewFromConfig(cfg)\n\treturn &AwsAsg{\n\t\tsvc: svc,\n\t}\n}", "func newNetwork(cfg *config.Network, c *ec2.EC2) (*network, error) {\n\tlog.Debug(\"Initializing AWS Network\")\n\tn := &network{\n\t\tResources: resource.NewResources(),\n\t\tNetwork: cfg,\n\t\tec2: c,\n\t}\n\n\tvpc, err := newVpc(c, n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tn.vpc = vpc\n\tn.Append(vpc)\n\n\trouteTables, err := newRouteTables(c, n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tn.routeTables = routeTables\n\tn.Append(routeTables)\n\n\tinternetGateway, err := newInternetGateway(c, n, \"public\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tn.internetGateway = internetGateway\n\tn.Append(internetGateway)\n\n\t// Load the vpc since it is needed for the caches.\n\terr = n.vpc.Load()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tn.subnetCache, err = newSubnetCache(n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tn.secgroupCache, err = newSecurityGroupCache(n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn n, nil\n}", "func newEDSBalancerImpl(cc balancer.ClientConn, enqueueState func(priorityType, balancer.State), lr load.PerClusterReporter, logger *grpclog.PrefixLogger) *edsBalancerImpl {\n\tedsImpl := &edsBalancerImpl{\n\t\tcc: cc,\n\t\tlogger: logger,\n\t\tsubBalancerBuilder: balancer.Get(roundrobin.Name),\n\t\tloadReporter: lr,\n\n\t\tenqueueChildBalancerStateUpdate: enqueueState,\n\n\t\tpriorityToLocalities: make(map[priorityType]*balancerGroupWithConfig),\n\t\tpriorityToState: make(map[priorityType]*balancer.State),\n\t\tsubConnToPriority: make(map[apis.SubConn]priorityType),\n\t}\n\t// Don't start balancer group here. Start it when handling the first EDS\n\t// response. Otherwise the balancer group will be started with round-robin,\n\t// and if users specify a different sub-balancer, all balancers in balancer\n\t// group will be closed and recreated when sub-balancer update happens.\n\treturn edsImpl\n}", "func New(hostedZoneID string, lbAdapter adapter.FrontendAdapter, retries int) controller.Updater {\n\tinitMetrics()\n\n\treturn &updater{\n\t\tr53: r53.New(hostedZoneID, retries),\n\t\tlbAdapter: lbAdapter,\n\t\tschemeToFrontendMap: make(map[string]adapter.DNSDetails),\n\t}\n}", "func NewAdapter(url string, opts ...func(*adapter)) persist.Adapter {\n\tcl, err := mongo.NewClient(options.Client().ApplyURI(url))\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ta := &adapter{client: cl, filtered: false, databaseName: \"casbin\"}\n\n\tfor _, opt := range opts {\n\t\topt(a)\n\t}\n\n\t// Open the DB, create it if not existed.\n\ta.open()\n\n\t// Call the destructor when the object is released\n\truntime.SetFinalizer(a, finalizer)\n\n\treturn a\n\n}", "func NewAdapter(conn *nats.Conn, options ...Option) *Adapter {\n\topts := defaultOptions()\n\tfor _, o := range options {\n\t\to.apply(&opts)\n\t}\n\ta := &Adapter{\n\t\tconn: conn,\n\t\treceivedNatsMsgCh: make(chan *nats.Msg, receivedNatsMsgChSize),\n\t\tpublishCh: make(chan *types.Message, opts.publishChSize),\n\t\tdeliveredCh: make(chan *types.Message, opts.deliveredChSize),\n\t\terrorCh: make(chan error, opts.errorChSize),\n\t\tdone: make(chan struct{}),\n\t\topts: opts,\n\t\tsubs: map[string]*nats.Subscription{},\n\t}\n\tconn.SetErrorHandler(a.natsErrorHandler())\n\tconn.SetDisconnectErrHandler(a.natsConnErrorHandler())\n\ta.doneWg.Add(1)\n\tgo a.run()\n\treturn a\n}", "func newReconciledAdapter() (*servingv1.Service, error) {\n\tsrc := newEventSource()\n\n\tadapter, err := adapterBuilder(adapterCfg).BuildAdapter(src, tSinkURI)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"building adapter object using provided Reconcilable: %w\", err)\n\t}\n\n\tcommon.OwnByServiceAccount(adapter, NewServiceAccount(newEventSource())())\n\n\tadapter.Status.SetConditions(apis.Conditions{{\n\t\tType: commonv1alpha1.ConditionReady,\n\t\tStatus: corev1.ConditionTrue,\n\t}})\n\tadapter.Status.URL = tAdapterURI\n\n\treturn adapter, nil\n}", "func Adapt(name plugin.Name, rpcClient rpc_client.Client) loadbalancer.L4 {\n\treturn &client{name: name, client: rpcClient}\n}", "func NewAdapter(config *Config, options ...AdapterOption) (*Adapter, error) {\n\tadapter := &Adapter{\n\t\tconfig: config,\n\t}\n\n\tfor _, opt := range options {\n\t\topt(adapter)\n\t}\n\n\t// See if a client is set by WithSlackClient option.\n\t// If not, use golack with the given configuration.\n\tif adapter.client == nil {\n\t\tif config.Token == \"\" {\n\t\t\treturn nil, errors.New(\"Slack client must be provided with WithSlackClient option or must be configurable with given *Config\")\n\t\t}\n\n\t\tgolackConfig := golack.NewConfig()\n\t\tgolackConfig.Token = config.Token\n\t\tgolackConfig.AppSecret = config.AppSecret\n\t\tgolackConfig.ListenPort = config.ListenPort\n\t\tif config.RequestTimeout != 0 {\n\t\t\tgolackConfig.RequestTimeout = config.RequestTimeout\n\t\t}\n\n\t\tadapter.client = golack.New(golackConfig)\n\t}\n\n\tif adapter.apiSpecificAdapterBuilder == nil {\n\t\treturn nil, errors.New(\"RTM or Events API configuration must be applied with WithRTMPayloadHandler or WithEventsPayloadHandler\")\n\t}\n\n\treturn adapter, nil\n}", "func NewAdapter(text string) *Adapter {\n\treturn &Adapter{text: text}\n}", "func TestNewAdapter(t *testing.T) {\n\tadapterTypes := []AdapterType{\n\t\t0,\n\t\t1,\n\t}\n\n\tfor _, at := range adapterTypes {\n\t\tadapter, err := NewAdapter(at)\n\n\t\tswitch at {\n\t\tcase Undefined:\n\t\t\tif err == nil {\n\t\t\t\tt.Errorf(\"expected to fail initialization of adaptery with type %v.\", at)\n\t\t\t}\n\t\t\tt.Log(\"OK - got error when trying to create undefined type adapter\")\n\t\t\tbreak\n\t\tcase Memory:\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"could not create adapter of type %v, err: %v\\n\", at, err)\n\t\t\t}\n\n\t\t\tswitch v := adapter.(type) {\n\t\t\tcase *MemoryAdapter:\n\t\t\t\tt.Log(\"OK - created memory adapter successfully\")\n\t\t\t\tmemApt = adapter.(*MemoryAdapter)\n\t\t\tdefault:\n\t\t\t\tt.Errorf(\"expected adapter of type MemoryAdapter when using type %v, got %v\\n\", at, v)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n}", "func newAwsAutoscalingPolicies(c *TrussleV1Client, namespace string) *awsAutoscalingPolicies {\n\treturn &awsAutoscalingPolicies{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}", "func NewAWS(zones []string, dnsfilters []string, delay time.Duration) (khostdns.DNSSetter, error) {\n\tlog.Info(\"Creating new AWS DNSSetter\")\n\tsess, err := session.NewSession(&aws.Config{Region: aws.String(\"us-east-1\")})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr53 := route53.New(sess)\n\tad := &AWSData{\n\t\tzones: zones,\n\t\tdnsfilters: khostdns.CreateDNSFilter(dnsfilters),\n\t\tdelay: delay,\n\t\tnotifyChannel: make(chan khostdns.Arecord),\n\t\thostChange: make(chan khostdns.Arecord),\n\t\tforceUpdate: make(chan bool),\n\t\tsession: sess,\n\t\tr53: r53,\n\t\trunning: false,\n\t}\n\tm, err := ad.getAWSZoneNames()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor awsZ, name := range m {\n\t\tfor _, zid := range ad.zones {\n\t\t\tif zid == awsZ {\n\t\t\t\tad.zoneNames.Store(zid, name)\n\t\t\t\tlog.Info(\"found zone, {}:{}\", awsZ, name)\n\t\t\t}\n\t\t}\n\t}\n\tad.running = true\n\n\tgo ad.loop()\n\treturn ad, nil\n}", "func New(\n\tresourcePool string,\n\tmaxIdlePeriod, maxStartingPeriod,\n\tmaxDisconnectPeriod time.Duration,\n\tminInstanceNum int,\n\tmaxInstanceNum int,\n\tdb db.DB,\n) *ScaleDecider {\n\treturn &ScaleDecider{\n\t\tmaxStartingPeriod: maxStartingPeriod,\n\t\tmaxIdlePeriod: maxIdlePeriod,\n\t\tmaxDisconnectPeriod: maxDisconnectPeriod,\n\t\tminInstanceNum: minInstanceNum,\n\t\tmaxInstanceNum: maxInstanceNum,\n\t\tinstanceSnapshot: make(map[string]*model.Instance),\n\t\tconnectedAgentSnapshot: make(map[string]sproto.AgentSummary),\n\t\tidleAgentSnapshot: make(map[string]sproto.AgentSummary),\n\t\tinstances: make(map[string]*model.Instance),\n\t\tpending: make(map[string]bool),\n\t\trecentlyLaunched: make(map[string]bool),\n\t\tstopped: make(map[string]bool),\n\t\tdisconnected: make(map[string]time.Time),\n\t\tidle: make(map[string]time.Time),\n\t\tlongDisconnected: make(map[string]bool),\n\t\tlongIdle: make(map[string]bool),\n\t\tdb: db,\n\t\tresourcePool: resourcePool,\n\t}\n}", "func NewLoadBalancer(c config.LoadBalancerConfig) *LoadBalancer {\n\tvar lb LoadBalancer\n\tif c.Hosts != nil && len(c.Hosts) > 0 {\n\t\tlb.hosts = make([]string, len(c.Hosts))\n\t\tfor i, server := range c.Hosts {\n\t\t\tlb.hosts[i] = server\n\t\t\tgloballog.WithFields(logrus.Fields{\n\t\t\t\t\"host\": server,\n\t\t\t\t\"index\": i,\n\t\t\t}).Debug(\"adding lb host\")\n\t\t}\n\t} else {\n\t\tlb.hosts = make([]string, 10)\n\t}\n\tlb.mode = c.BalanceMode\n\tlb.hostLock = new(sync.RWMutex)\n\treturn &lb\n}", "func NewAdapter(logger gomol.WrappableLogger, journaledLevels ...gomol.LogLevel) *Adapter {\n\treturn newAdapterWithClock(logger, &realClock{}, journaledLevels...)\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 newAwsServiceDiscoveryServices(c *TrussleV1Client, namespace string) *awsServiceDiscoveryServices {\n\treturn &awsServiceDiscoveryServices{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}", "func newDriver() *driver {\n\treturn &driver{\n\t\tnetworks: map[string]*bridgeNetwork{},\n\t\tportAllocator: portallocator.Get(),\n\t}\n}", "func NewBuilder() balancer.Builder {\n\treturn base.NewBalancerBuilderV2(Name, &nodePickerBuilder{}, base.Config{HealthCheck: true})\n}", "func NewAdapter(fs http.FileSystem, path string) *Adapter {\n\treturn &Adapter{fs, path}\n}", "func New(\n\tname string,\n\tkvdbName string,\n\tkvdbBase string,\n\tkvdbMachines []string,\n\tclusterID string,\n\tkvdbOptions map[string]string,\n) (AlertClient, error) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tif _, ok := instances[name]; ok {\n\t\treturn nil, ErrExist\n\t}\n\tif initFunc, exists := drivers[name]; exists {\n\t\tdriver, err := initFunc(\n\t\t\tkvdbName,\n\t\t\tkvdbBase,\n\t\t\tkvdbMachines,\n\t\t\tclusterID,\n\t\t\tkvdbOptions,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinstances[name] = driver\n\t\treturn driver, err\n\t}\n\treturn nil, ErrNotSupported\n}", "func CreateLoadBalancer(ctx context.Context, lbName, pipName string) (lb network.LoadBalancer, err error) {\n\tprobeName := \"probe\"\n\tfrontEndIPConfigName := \"fip\"\n\tbackEndAddressPoolName := \"backEndPool\"\n\tidPrefix := fmt.Sprintf(\"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/loadBalancers\", config.SubscriptionID(), config.GroupName())\n\n\tpip, err := GetPublicIP(ctx, pipName)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tlbClient := getLBClient()\n\tfuture, err := lbClient.CreateOrUpdate(ctx,\n\t\tconfig.GroupName(),\n\t\tlbName,\n\t\tnetwork.LoadBalancer{\n\t\t\tLocation: to.StringPtr(config.Location()),\n\t\t\tLoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{\n\t\t\t\tFrontendIPConfigurations: &[]network.FrontendIPConfiguration{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: &frontEndIPConfigName,\n\t\t\t\t\t\tFrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{\n\t\t\t\t\t\t\tPrivateIPAllocationMethod: network.Dynamic,\n\t\t\t\t\t\t\tPublicIPAddress: &pip,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tBackendAddressPools: &[]network.BackendAddressPool{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: &backEndAddressPoolName,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tProbes: &[]network.Probe{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: &probeName,\n\t\t\t\t\t\tProbePropertiesFormat: &network.ProbePropertiesFormat{\n\t\t\t\t\t\t\tProtocol: network.ProbeProtocolHTTP,\n\t\t\t\t\t\t\tPort: to.Int32Ptr(80),\n\t\t\t\t\t\t\tIntervalInSeconds: to.Int32Ptr(15),\n\t\t\t\t\t\t\tNumberOfProbes: to.Int32Ptr(4),\n\t\t\t\t\t\t\tRequestPath: to.StringPtr(\"healthprobe.aspx\"),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tLoadBalancingRules: &[]network.LoadBalancingRule{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: to.StringPtr(\"lbRule\"),\n\t\t\t\t\t\tLoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{\n\t\t\t\t\t\t\tProtocol: network.TransportProtocolTCP,\n\t\t\t\t\t\t\tFrontendPort: to.Int32Ptr(80),\n\t\t\t\t\t\t\tBackendPort: to.Int32Ptr(80),\n\t\t\t\t\t\t\tIdleTimeoutInMinutes: to.Int32Ptr(4),\n\t\t\t\t\t\t\tEnableFloatingIP: to.BoolPtr(false),\n\t\t\t\t\t\t\tLoadDistribution: network.Default,\n\t\t\t\t\t\t\tFrontendIPConfiguration: &network.SubResource{\n\t\t\t\t\t\t\t\tID: to.StringPtr(fmt.Sprintf(\"/%s/%s/frontendIPConfigurations/%s\", idPrefix, lbName, frontEndIPConfigName)),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tBackendAddressPool: &network.SubResource{\n\t\t\t\t\t\t\t\tID: to.StringPtr(fmt.Sprintf(\"/%s/%s/backendAddressPools/%s\", idPrefix, lbName, backEndAddressPoolName)),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tProbe: &network.SubResource{\n\t\t\t\t\t\t\t\tID: to.StringPtr(fmt.Sprintf(\"/%s/%s/probes/%s\", idPrefix, lbName, probeName)),\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\tInboundNatRules: &[]network.InboundNatRule{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: to.StringPtr(\"natRule1\"),\n\t\t\t\t\t\tInboundNatRulePropertiesFormat: &network.InboundNatRulePropertiesFormat{\n\t\t\t\t\t\t\tProtocol: network.TransportProtocolTCP,\n\t\t\t\t\t\t\tFrontendPort: to.Int32Ptr(21),\n\t\t\t\t\t\t\tBackendPort: to.Int32Ptr(22),\n\t\t\t\t\t\t\tEnableFloatingIP: to.BoolPtr(false),\n\t\t\t\t\t\t\tIdleTimeoutInMinutes: to.Int32Ptr(4),\n\t\t\t\t\t\t\tFrontendIPConfiguration: &network.SubResource{\n\t\t\t\t\t\t\t\tID: to.StringPtr(fmt.Sprintf(\"/%s/%s/frontendIPConfigurations/%s\", idPrefix, lbName, frontEndIPConfigName)),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tName: to.StringPtr(\"natRule2\"),\n\t\t\t\t\t\tInboundNatRulePropertiesFormat: &network.InboundNatRulePropertiesFormat{\n\t\t\t\t\t\t\tProtocol: network.TransportProtocolTCP,\n\t\t\t\t\t\t\tFrontendPort: to.Int32Ptr(23),\n\t\t\t\t\t\t\tBackendPort: to.Int32Ptr(22),\n\t\t\t\t\t\t\tEnableFloatingIP: to.BoolPtr(false),\n\t\t\t\t\t\t\tIdleTimeoutInMinutes: to.Int32Ptr(4),\n\t\t\t\t\t\t\tFrontendIPConfiguration: &network.SubResource{\n\t\t\t\t\t\t\t\tID: to.StringPtr(fmt.Sprintf(\"/%s/%s/frontendIPConfigurations/%s\", idPrefix, lbName, frontEndIPConfigName)),\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\n\tif err != nil {\n\t\treturn lb, fmt.Errorf(\"cannot create load balancer: %v\", err)\n\t}\n\n\terr = future.WaitForCompletion(ctx, lbClient.Client)\n\tif err != nil {\n\t\treturn lb, fmt.Errorf(\"cannot get load balancer create or update future response: %v\", err)\n\t}\n\n\treturn future.Result(lbClient)\n}", "func NewAdapter(ctx context.Context, processed adapter.EnvConfigAccessor, ceClient cloudevents.Client) adapter.Adapter {\n\tlogger := logging.FromContext(ctx)\n\tenv := processed.(*envConfig)\n\n\treturn &mongoDbAdapter{\n\t\tnamespace: env.Namespace,\n\t\tceClient: ceClient,\n\t\tceSource: env.EventSource,\n\t\tdatabase: env.Database,\n\t\tcollection: env.Collection,\n\t\tcredentialsPath: env.MongoDbCredentialsPath,\n\t\tlogger: logger,\n\t}\n}", "func newMinimumReplicasUnavailableAdapter(ctx context.Context, image string, transformer *apis.URL) runtime.Object {\n\tobj := newReceiveAdapter(ctx, image, transformer)\n\tra := obj.(*v1.Deployment)\n\tWithDeploymentMinimumReplicasUnavailable()(ra)\n\treturn obj\n}", "func New(svc iaas.Service, terraform bool) (resources.Subnet, fail.Error) {\n\tif terraform {\n\t\treturn operations.NewTerraformSubnet(svc)\n\t}\n\treturn operations.NewSubnet(svc)\n}", "func (h DefaultConfigProvider) NewDHCPBalancingAlgorithm(version int) (dhcplb.DHCPBalancingAlgorithm, error) {\n\treturn nil, nil\n}", "func New(app, account, region, stack, cluster string) InstanceGroup {\n\treturn group{\n\t\tapp: app,\n\t\taccount: account,\n\t\tregion: region,\n\t\tstack: stack,\n\t\tcluster: cluster,\n\t}\n}", "func NewBalancer(name string, handler EventHandler, configure *conf.BalancersConfiguration) (balancer *Balancer) {\n\n\tbalancer = new(Balancer)\n\tbalancer.name = name\n\tbalancer.handler = handler\n\tconfiguration := configure.GetBalancerConfiguration(name)\n\tbalancer.balancerType = configuration.BalancerType\n\tbalancer.initQueue(configuration)\n\tbalancer.aggregatorManager = initAggregatorManager(configuration.AggreagatorName, balancer, configuration.WorkAggregatorConfiguration)\n\tbalancer.poolManager = initRoutinePoolManager(name, balancer.balancerType, balancer, handler, configuration)\n\treturn balancer\n}", "func (ts *Tester) createVPC() error {\n\tif ts.cfg.VPC.ID != \"\" {\n\t\tts.lg.Info(\"querying ELBv2\", zap.String(\"vpc-id\", ts.cfg.VPC.ID))\n\t\tctx, cancel := context.WithTimeout(context.Background(), time.Minute)\n\t\toutput, err := ts.elbv2APIV2.DescribeLoadBalancers(\n\t\t\tctx,\n\t\t\t&aws_elbv2_v2.DescribeLoadBalancersInput{},\n\t\t)\n\t\tcancel()\n\t\tif err != nil {\n\t\t\tts.lg.Warn(\"failed to describe ELBv2\", zap.Error(err))\n\t\t} else {\n\t\t\tfor _, ev := range output.LoadBalancers {\n\t\t\t\tarn := aws_v2.ToString(ev.LoadBalancerArn)\n\t\t\t\tvpcID := aws_v2.ToString(ev.VpcId)\n\t\t\t\tif vpcID == ts.cfg.VPC.ID {\n\t\t\t\t\tts.lg.Warn(\"found ELBv2 for this VPC; may overlap with the other cluster\",\n\t\t\t\t\t\tzap.String(\"vpc-id\", ts.cfg.VPC.ID),\n\t\t\t\t\t\tzap.String(\"elb-arn\", arn),\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\tts.lg.Info(\"found ELBv2 for other VPCs\", zap.String(\"vpc-id\", vpcID), zap.String(\"elb-arn\", arn))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tts.lg.Info(\"querying subnet IDs for given VPC\",\n\t\t\tzap.String(\"vpc-id\", ts.cfg.VPC.ID),\n\t\t)\n\t\tctx, cancel = context.WithTimeout(context.Background(), time.Minute)\n\t\tsresp, err := ts.ec2APIV2.DescribeSubnets(\n\t\t\tctx,\n\t\t\t&aws_ec2_v2.DescribeSubnetsInput{\n\t\t\t\tFilters: []aws_ec2_v2_types.Filter{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: aws_v2.String(\"vpc-id\"),\n\t\t\t\t\t\tValues: []string{ts.cfg.VPC.ID},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t})\n\t\tcancel()\n\t\tif err != nil {\n\t\t\tts.lg.Warn(\"failed to subnets\", zap.Error(err))\n\t\t\treturn err\n\t\t}\n\n\t\tts.cfg.VPC.PublicSubnetIDs = make([]string, 0, len(sresp.Subnets))\n\t\tts.cfg.VPC.PrivateSubnetIDs = make([]string, 0, len(sresp.Subnets))\n\t\tfor _, sv := range sresp.Subnets {\n\t\t\tid := aws_v2.ToString(sv.SubnetId)\n\t\t\tnetworkTagValue := \"\"\n\t\t\tfor _, tg := range sv.Tags {\n\t\t\t\tswitch aws_v2.ToString(tg.Key) {\n\t\t\t\tcase \"Network\":\n\t\t\t\t\tnetworkTagValue = aws_v2.ToString(tg.Value)\n\t\t\t\t}\n\t\t\t\tif networkTagValue != \"\" {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tts.lg.Info(\"found subnet\",\n\t\t\t\tzap.String(\"id\", id),\n\t\t\t\tzap.String(\"availability-zone\", aws_v2.ToString(sv.AvailabilityZone)),\n\t\t\t\tzap.String(\"network-tag\", networkTagValue),\n\t\t\t)\n\t\t\tswitch networkTagValue {\n\t\t\tcase \"Public\":\n\t\t\t\tts.cfg.VPC.PublicSubnetIDs = append(ts.cfg.VPC.PublicSubnetIDs, id)\n\t\t\tcase \"Private\":\n\t\t\t\tts.cfg.VPC.PrivateSubnetIDs = append(ts.cfg.VPC.PrivateSubnetIDs, id)\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"'Network' tag not found in subnet %q\", id)\n\t\t\t}\n\t\t}\n\t\tif len(ts.cfg.VPC.PublicSubnetIDs) == 0 {\n\t\t\treturn fmt.Errorf(\"no subnet found for VPC ID %q\", ts.cfg.VPC.ID)\n\t\t}\n\n\t\tts.lg.Info(\"querying security IDs\", zap.String(\"vpc-id\", ts.cfg.VPC.ID))\n\t\tctx, cancel = context.WithTimeout(context.Background(), time.Minute)\n\t\tgresp, err := ts.ec2APIV2.DescribeSecurityGroups(\n\t\t\tctx,\n\t\t\t&aws_ec2_v2.DescribeSecurityGroupsInput{\n\t\t\t\tFilters: []aws_ec2_v2_types.Filter{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: aws_v2.String(\"vpc-id\"),\n\t\t\t\t\t\tValues: []string{ts.cfg.VPC.ID},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t})\n\t\tcancel()\n\t\tif err != nil {\n\t\t\tts.lg.Warn(\"failed to security groups\", zap.Error(err))\n\t\t\treturn err\n\t\t}\n\t\tfor _, sg := range gresp.SecurityGroups {\n\t\t\tid, name := aws_v2.ToString(sg.GroupId), aws_v2.ToString(sg.GroupName)\n\t\t\tts.lg.Info(\"found security group\", zap.String(\"id\", id), zap.String(\"name\", name))\n\t\t\tif name != \"default\" {\n\t\t\t\tts.cfg.VPC.SecurityGroupID = id\n\t\t\t}\n\t\t}\n\t\tif ts.cfg.VPC.SecurityGroupID == \"\" {\n\t\t\treturn fmt.Errorf(\"no security group found for VPC ID %q\", ts.cfg.VPC.ID)\n\t\t}\n\n\t\tts.cfg.Sync()\n\t\treturn nil\n\t}\n\tif !ts.cfg.VPC.Create {\n\t\tts.lg.Info(\"VPC.Create false; skipping creation\")\n\t\treturn nil\n\t}\n\tif ts.cfg.VPC.ID != \"\" &&\n\t\tlen(ts.cfg.VPC.PublicSubnetIDs) > 0 &&\n\t\tts.cfg.VPC.SecurityGroupID != \"\" {\n\t\tts.lg.Info(\"VPC already created; no need to create a new one\")\n\t\treturn nil\n\t}\n\n\tif err := ts._createVPC(); err != nil { // AWS::EC2::VPC\n\t\treturn err\n\t}\n\tif err := ts.modifyVPC(); err != nil {\n\t\treturn err\n\t}\n\tif err := ts.createSecurityGroups(); err != nil { // AWS::EC2::SecurityGroup\n\t\treturn err\n\t}\n\tif err := ts.associateVPCCIDRBlocks(); err != nil { // AWS::EC2::VPCCidrBlock\n\t\treturn err\n\t}\n\n\tif err := ts.createInternetGateway(); err != nil { // AWS::EC2::InternetGateway\n\t\treturn err\n\t}\n\tif err := ts.createVPCGatewayAttachment(); err != nil { // AWS::EC2::VPCGatewayAttachment\n\t\treturn err\n\t}\n\n\tif err := ts.createPublicSubnets(); err != nil { // AWS::EC2::Subnet\n\t\treturn err\n\t}\n\tif err := ts.createPublicRouteTable(); err != nil { // AWS::EC2::RouteTable\n\t\treturn err\n\t}\n\tif err := ts.createPublicRoute(); err != nil { // AWS::EC2::Route\n\t\treturn err\n\t}\n\tif err := ts.createPublicSubnetRouteTableAssociation(); err != nil { // AWS::EC2::SubnetRouteTableAssociation\n\t\treturn err\n\t}\n\n\tif err := ts.createPublicEIPs(); err != nil { // AWS::EC2::EIP\n\t\treturn err\n\t}\n\tif err := ts.createPublicNATGateways(); err != nil { // AWS::EC2::NatGateway\n\t\treturn err\n\t}\n\n\tif err := ts.createPrivateSubnets(); err != nil { // AWS::EC2::Subnet\n\t\treturn err\n\t}\n\tif err := ts.createPrivateRouteTables(); err != nil { // AWS::EC2::RouteTable\n\t\treturn err\n\t}\n\tif err := ts.createPrivateRoutes(); err != nil { // AWS::EC2::Route\n\t\treturn err\n\t}\n\tif err := ts.createPrivateSubnetRouteTableAssociation(); err != nil { // AWS::EC2::SubnetRouteTableAssociation\n\t\treturn err\n\t}\n\n\tif err := ts.createDHCPOptions(); err != nil { // AWS::EC2::DHCPOptions, AWS::EC2::VPCDHCPOptionsAssociation\n\t\treturn err\n\t}\n\n\tif err := ts.authorizeSecurityGroup(); err != nil {\n\t\treturn err\n\t}\n\n\tts.lg.Info(\"created a VPC\",\n\t\tzap.String(\"vpc-id\", ts.cfg.VPC.ID),\n\t\tzap.Strings(\"vpc-cidr-blocks\", ts.cfg.VPC.CIDRs),\n\t\tzap.Strings(\"public-subnet-ids\", ts.cfg.VPC.PublicSubnetIDs),\n\t\tzap.Strings(\"private-subnet-ids\", ts.cfg.VPC.PrivateSubnetIDs),\n\t\tzap.String(\"control-plane-security-group-id\", ts.cfg.VPC.SecurityGroupID),\n\t)\n\n\tts.cfg.Sync()\n\treturn nil\n}", "func NewL2metAdapter(route *router.Route) (router.LogAdapter, error) {\n\t// Create the client\n\ttransport := &http.Transport{}\n\ttransport.Dial = dial\n\n\tclient := &http.Client{Transport: transport}\n\n\t// Get the url\n\turl := os.Getenv(\"L2MET_URL\")\n\tif url == \"\" {\n\t\treturn nil, errors.New(\"l2met url not found\")\n\t}\n\n\t// Create the syslog RFC5424 template\n\ttmplStr := \"<{{.Priority}}>1 {{.Timestamp}} {{.Container.Config.Hostname}} {{.ContainerName}} {{.Container.State.Pid}} - - {{.Data}}\\n\"\n\ttmpl, err := template.New(\"l2met\").Parse(tmplStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &L2metAdapter{\n\t\troute: route,\n\t\tclient: client,\n\t\turl: url,\n\t\ttmpl: tmpl,\n\t}, nil\n}", "func New(logger *zap.Logger) log.Logger {\n\treturn &adapter{\n\t\tLogger: logger,\n\t}\n}", "func NewBootstrapper(ctx context.Context, h lp2phost.Host, d lp2pnet.Dialer, r lp2prouting.Routing, conf *BootstrapConfig, logger *logger.Logger) *Bootstrapper {\n\tb := &Bootstrapper{\n\t\tctx: ctx,\n\t\tconfig: conf,\n\t\thost: h,\n\t\tdialer: d,\n\t\trouting: r,\n\t\tlogger: logger,\n\t}\n\n\taddresses, err := PeerAddrsToAddrInfo(conf.Addresses)\n\tif err != nil {\n\t\tb.logger.Panic(\"couldn't parse bootstrap addresses\", \"addressed\", conf.Addresses)\n\t}\n\n\tb.bootstrapPeers = addresses\n\tb.checkConnectivity()\n\n\treturn b\n}", "func New(pg plugingetter.PluginGetter, netConfig *NetworkConfig) (networkallocator.NetworkAllocator, error) {\n\tna := &cnmNetworkAllocator{\n\t\tnetworks: make(map[string]*network),\n\t\tservices: make(map[string]struct{}),\n\t\ttasks: make(map[string]struct{}),\n\t\tnodes: make(map[string]map[string]struct{}),\n\t\tpg: pg,\n\t}\n\n\tfor ntype, i := range initializers {\n\t\tif err := i(&na.networkRegistry); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to register %q network driver: %w\", ntype, err)\n\t\t}\n\t}\n\tif err := remote.Register(&na.networkRegistry, pg); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize network driver plugins: %w\", err)\n\t}\n\n\tif err := initIPAMDrivers(&na.ipamRegistry, netConfig); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := remoteipam.Register(&na.ipamRegistry, pg); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize IPAM driver plugins: %w\", err)\n\t}\n\n\tpa, err := newPortAllocator()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tna.portAllocator = pa\n\treturn na, nil\n}", "func (adapter *EndpointsAdapter) Create(namespace string, endpoints *corev1.Endpoints) (*corev1.Endpoints, error) {\n\tendpoints, err := adapter.endpointClient.Endpoints(namespace).Create(context.TODO(), endpoints, metav1.CreateOptions{})\n\tif err == nil {\n\t\terr = adapter.EnsureEndpointSliceFromEndpoints(namespace, endpoints)\n\t}\n\treturn endpoints, err\n}", "func NewPoliciesRequestBuilder(rawUrl string, requestAdapter i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestAdapter)(*PoliciesRequestBuilder) {\n urlParams := make(map[string]string)\n urlParams[\"request-raw-url\"] = rawUrl\n return NewPoliciesRequestBuilderInternal(urlParams, requestAdapter)\n}", "func New(\n\tarmDeployer arm.Deployer,\n\taciClient aciSDK.ContainerGroupsClient,\n) service.Module {\n\treturn &module{\n\t\tserviceManager: &serviceManager{\n\t\t\tarmDeployer: armDeployer,\n\t\t\taciClient: aciClient,\n\t\t},\n\t}\n}", "func NewLoadBalancer() *LoadBalancer {\n\tlb := &LoadBalancer{\n\t\tnodes: make(map[string]*weightedNode),\n\t}\n\treturn lb\n}", "func NewBrandingRequestBuilderInternal(pathParameters map[string]string, requestAdapter i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestAdapter)(*BrandingRequestBuilder) {\n m := &BrandingRequestBuilder{\n }\n m.urlTemplate = \"{+baseurl}/organization/{organization%2Did}/branding{?%24select,%24expand}\";\n urlTplParams := make(map[string]string)\n for idx, item := range pathParameters {\n urlTplParams[idx] = item\n }\n m.pathParameters = urlTplParams;\n m.requestAdapter = requestAdapter;\n return m\n}", "func New(addr string) (*Btmgmt, error) {\n\tvar bt Btmgmt\n\n\tif addr == \"\" {\n\t\treturn &bt, nil\n\t}\n\n\tout, err := bt.Run(\"info\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tindex, err := findAddrIndex(addr, out)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, `cannot find controller index`)\n\t}\n\n\treturn &Btmgmt{index}, nil\n}", "func newAdapterInfoRegistry(infos []*adapter.Info) (*adapterInfoRegistry, error) {\n\tr := &adapterInfoRegistry{make(map[string]*AdapterMetadata), make(map[string]*TemplateMetadata)}\n\tvar resultErr error\n\tlog.Debugf(\"registering %#v\", infos)\n\n\tfor _, info := range infos {\n\t\tif old := r.GetAdapter(info.Name); old != nil {\n\t\t\t// duplicate entry found\n\t\t\tresultErr = multierror.Append(resultErr,\n\t\t\t\tfmt.Errorf(\"duplicate registration for adapter '%s' : new = %v old = %v\", info.Name, info, old))\n\t\t\tcontinue\n\t\t}\n\n\t\tcfgFds, cfgProto, err := getAdapterCfgDescriptor(info.Config)\n\t\tif err != nil {\n\t\t\tresultErr = multierror.Append(resultErr, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar tmplNames []string\n\t\ttmplNames, err = r.ingestTemplates(info.Templates)\n\t\tif err != nil {\n\t\t\tresultErr = multierror.Append(resultErr, err)\n\t\t\tcontinue\n\t\t}\n\n\t\t// empty adapter name means just the template needs to be ingested.\n\t\tif info.Name != \"\" {\n\t\t\tr.adapters[info.Name] = &AdapterMetadata{SupportedTemplates: tmplNames, Name: info.Name, ConfigDescSet: cfgFds, ConfigDescProto: cfgProto}\n\n\t\t}\n\t}\n\n\tif resultErr != nil {\n\t\tlog.Error(resultErr.Error())\n\t}\n\n\treturn r, resultErr\n}", "func (a metricsAdapter) AdaptTags(tags []string, c *workloadmeta.Container) []string {\n\treturn append(tags, \"runtime:docker\")\n}", "func NewDNSProvider(accessKeyID, secretAccessKey, hostedZoneID, region string, ambient bool, dns01Nameservers []string) (*DNSProvider, error) {\n\tif accessKeyID == \"\" && secretAccessKey == \"\" {\n\t\tif !ambient {\n\t\t\treturn nil, fmt.Errorf(\"unable to construct route53 provider: empty credentials; perhaps you meant to enable ambient credentials?\")\n\t\t}\n\t} else if accessKeyID == \"\" || secretAccessKey == \"\" {\n\t\t// It's always an error to set one of those but not the other\n\t\treturn nil, fmt.Errorf(\"unable to construct route53 provider: only one of access and secret key was provided\")\n\t}\n\n\tuseAmbientCredentials := ambient && (accessKeyID == \"\" && secretAccessKey == \"\")\n\n\tr := customRetryer{}\n\tr.NumMaxRetries = maxRetries\n\tconfig := request.WithRetryer(aws.NewConfig(), r)\n\tsessionOpts := session.Options{}\n\n\tif useAmbientCredentials {\n\t\tklog.V(5).Infof(\"using ambient credentials\")\n\t\t// Leaving credentials unset results in a default credential chain being\n\t\t// used; this chain is a reasonable default for getting ambient creds.\n\t\t// https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html#specifying-credentials\n\t} else {\n\t\tklog.V(5).Infof(\"not using ambient credentials\")\n\t\tconfig.WithCredentials(credentials.NewStaticCredentials(accessKeyID, secretAccessKey, \"\"))\n\t\t// also disable 'ambient' region sources\n\t\tsessionOpts.SharedConfigState = session.SharedConfigDisable\n\t}\n\n\t// If ambient credentials aren't permitted, always set the region, even if to\n\t// empty string, to avoid it falling back on the environment.\n\tif region != \"\" || !useAmbientCredentials {\n\t\tconfig.WithRegion(region)\n\t}\n\tsess, err := session.NewSessionWithOptions(sessionOpts)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create aws session: %s\", err)\n\t}\n\tsess.Handlers.Build.PushBack(request.WithAppendUserAgent(pkgutil.CertManagerUserAgent))\n\tclient := route53.New(sess, config)\n\n\treturn &DNSProvider{\n\t\tclient: client,\n\t\thostedZoneID: hostedZoneID,\n\t\tdns01Nameservers: dns01Nameservers,\n\t}, nil\n}", "func New(auth aws.Auth, region aws.Region) (*RDS, error) {\n\tservice, err := aws.NewService(auth, region.RDSEndpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &RDS{\n\t\tService: service,\n\t}, nil\n}", "func New(\n\tazureEnvironment azure.Environment,\n\tarmDeployer arm.Deployer,\n\tserversClient sqlSDK.ServersClient,\n\tdatabasesClient sqlSDK.DatabasesClient,\n\tfailoverGroupsClient sqlSDK.FailoverGroupsClient,\n) service.Module {\n\tcommonDatabasePairMgr := commonDatabasePairManager{\n\t\tarmDeployer: armDeployer,\n\t\tdatabasesClient: databasesClient,\n\t\tfailoverGroupsClient: failoverGroupsClient,\n\t}\n\treturn &module{\n\t\tdbmsPairRegisteredManager: &dbmsPairRegisteredManager{\n\t\t\tsqlDatabaseDNSSuffix: azureEnvironment.SQLDatabaseDNSSuffix,\n\t\t\tarmDeployer: armDeployer,\n\t\t\tserversClient: serversClient,\n\t\t},\n\t\tdatabasePairManager: &databasePairManager{\n\t\t\tcommonDatabasePairMgr,\n\t\t},\n\t\tdatabasePairRegisteredManager: &databasePairRegisteredManager{\n\t\t\tcommonDatabasePairMgr,\n\t\t},\n\t\tdatabasePairManagerForExistingPrimary: &databasePairManagerForExistingPrimary{ // nolint: lll\n\t\t\tcommonDatabasePairMgr,\n\t\t},\n\t\tdatabasePairManagerForExistingPair: &databasePairManagerForExistingPair{ // nolint: lll\n\t\t\tcommonDatabasePairMgr,\n\t\t},\n\t}\n}", "func NewMaplAdapter(port string, rulesFilename string) (Server, error) {\n\n\t//log.Println(Params)\n\n\n\tif Params.Logging{\n\t\t/* in remarks. just output to stdout and use kubectl logs...\n\t\t// setup a log outfile file\n\t\tf, err := os.OpenFile(\"log.txt\", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0777)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\tdefer f.Close()\n\t\tlog.SetOutput(f) //set output of logs to f\n\t\t*/\n\t}else{\n\t\tlog.SetOutput(ioutil.Discard) // output discarded if no log is needed\n\t}\n\t// -------------------------\n\n\tif port == \"\" {\n\t\tport = \"0\"\n\t}\n\tlistener, err := net.Listen(\"tcp\", fmt.Sprintf(\":%s\", port))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to listen on socket: %v\", err)\n\t}\n\ts := &MaplAdapter{\n\t\tlistener: listener,\n\t\trules: MAPL_engine.YamlReadRulesFromFile(rulesFilename),\n\t}\n\tlog.Printf(\"read %v rules from file \\\"%v\\\"\\n\",len(s.rules.Rules),rulesFilename)\n\tlog.Printf(\"listening on \\\"%v\\\"\\n\", s.Addr())\n\ts.server = grpc.NewServer()\n\tauthorization.RegisterHandleAuthorizationServiceServer(s.server, s)\n\n\treturn s, nil\n}", "func NewSecurityRequestBuilder(rawUrl string, requestAdapter i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestAdapter)(*SecurityRequestBuilder) {\n urlParams := make(map[string]string)\n urlParams[\"request-raw-url\"] = rawUrl\n return NewSecurityRequestBuilderInternal(urlParams, requestAdapter)\n}", "func New(auth aws.Auth, region aws.Region) *AutoScaling {\n\treturn &AutoScaling{auth, region}\n}", "func New(route *router.Route) (router.LogAdapter, error) {\n\t// test the address, but don't use this writer\n\twriter, err := gelf.NewWriter(route.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\twriter.Close()\n\n\treturn &Adapter{address: route.Address}, nil\n}", "func New(bc blockchainer.Blockchainer, capacity int) *Pool {\n\tif capacity <= 0 {\n\t\tpanic(\"invalid capacity\")\n\t}\n\n\treturn &Pool{\n\t\tverified: make(map[util.Uint256]*list.Element),\n\t\tsenders: make(map[util.Uint160]*list.List),\n\t\tsingleCap: capacity,\n\t\tchain: bc,\n\t}\n}", "func (el *ELBV2Manager) Detect(metrics []config.MetricConfig) (interface{}, error) {\n\n\tlog.WithFields(log.Fields{\n\t\t\"region\": el.awsManager.GetRegion(),\n\t\t\"resource\": \"elb_v2\",\n\t}).Info(\"starting to analyze resource\")\n\n\tel.awsManager.GetCollector().CollectStart(el.Name)\n\n\tdetectedELBV2 := []DetectedELBV2{}\n\n\tpricingRegionPrefix, err := el.awsManager.GetPricingClient().GetRegionPrefix(el.awsManager.GetRegion())\n\tif err != nil {\n\t\tlog.WithError(err).WithFields(log.Fields{\n\t\t\t\"region\": el.awsManager.GetRegion(),\n\t\t}).Error(\"Could not get pricing region prefix\")\n\t\tel.awsManager.GetCollector().CollectError(el.Name, err)\n\t\treturn detectedELBV2, err\n\t}\n\n\tinstances, err := el.describeLoadbalancers(nil, nil)\n\tif err != nil {\n\t\tel.awsManager.GetCollector().CollectError(el.Name, err)\n\t\treturn detectedELBV2, err\n\t}\n\n\tnow := time.Now()\n\n\tfor _, instance := range instances {\n\t\tvar cloudWatchNameSpace string\n\t\tvar price float64\n\t\tif loadBalancerConfig, found := loadBalancersConfig[*instance.Type]; found {\n\t\t\tcloudWatchNameSpace = loadBalancerConfig.cloudWatchNamespace\n\n\t\t\tlog.WithField(\"name\", *instance.LoadBalancerName).Debug(\"checking elbV2\")\n\n\t\t\tloadBalancerConfig.pricingfilters = append(\n\t\t\t\tloadBalancerConfig.pricingfilters, &pricing.Filter{\n\t\t\t\t\tType: awsClient.String(\"TERM_MATCH\"),\n\t\t\t\t\tField: awsClient.String(\"usagetype\"),\n\t\t\t\t\tValue: awsClient.String(fmt.Sprintf(\"%sLoadBalancerUsage\", pricingRegionPrefix)),\n\t\t\t\t})\n\t\t\tprice, _ = el.awsManager.GetPricingClient().GetPrice(el.getPricingFilterInput(loadBalancerConfig.pricingfilters), \"\", el.awsManager.GetRegion())\n\t\t}\n\t\tfor _, metric := range metrics {\n\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"name\": *instance.LoadBalancerName,\n\t\t\t\t\"metric_name\": metric.Description,\n\t\t\t}).Debug(\"check metric\")\n\n\t\t\tperiod := int64(metric.Period.Seconds())\n\n\t\t\tmetricEndTime := now.Add(time.Duration(-metric.StartTime))\n\n\t\t\tregx, _ := regexp.Compile(\".*loadbalancer/\")\n\n\t\t\telbv2Name := regx.ReplaceAllString(*instance.LoadBalancerArn, \"\")\n\n\t\t\tmetricInput := awsCloudwatch.GetMetricStatisticsInput{\n\t\t\t\tNamespace: &cloudWatchNameSpace,\n\t\t\t\tMetricName: &metric.Description,\n\t\t\t\tPeriod: &period,\n\t\t\t\tStartTime: &metricEndTime,\n\t\t\t\tEndTime: &now,\n\t\t\t\tDimensions: []*awsCloudwatch.Dimension{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: awsClient.String(\"LoadBalancer\"),\n\t\t\t\t\t\tValue: &elbv2Name,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tformulaValue, _, err := el.awsManager.GetCloudWatchClient().GetMetric(&metricInput, metric)\n\n\t\t\tif err != nil {\n\t\t\t\tlog.WithError(err).WithFields(log.Fields{\n\t\t\t\t\t\"name\": *instance.LoadBalancerName,\n\t\t\t\t\t\"metric_name\": metric.Description,\n\t\t\t\t}).Error(\"Could not get cloudwatch metric data\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\texpression, err := expression.BoolExpression(formulaValue, metric.Constraint.Value, metric.Constraint.Operator)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif expression {\n\n\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\"metric_name\": metric.Description,\n\t\t\t\t\t\"constraint_operator\": metric.Constraint.Operator,\n\t\t\t\t\t\"constraint_Value\": metric.Constraint.Value,\n\t\t\t\t\t\"formula_value\": formulaValue,\n\t\t\t\t\t\"name\": *instance.LoadBalancerName,\n\t\t\t\t\t\"region\": el.awsManager.GetRegion(),\n\t\t\t\t}).Info(\"LoadBalancer detected as unutilized resource\")\n\n\t\t\t\ttags, err := el.client.DescribeTags(&elbv2.DescribeTagsInput{\n\t\t\t\t\tResourceArns: []*string{instance.LoadBalancerArn},\n\t\t\t\t})\n\t\t\t\ttagsData := map[string]string{}\n\t\t\t\tif err == nil {\n\t\t\t\t\tfor _, tags := range tags.TagDescriptions {\n\t\t\t\t\t\tfor _, tag := range tags.Tags {\n\t\t\t\t\t\t\ttagsData[*tag.Key] = *tag.Value\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\telbv2 := DetectedELBV2{\n\t\t\t\t\tRegion: el.awsManager.GetRegion(),\n\t\t\t\t\tMetric: metric.Description,\n\t\t\t\t\tType: *instance.Type,\n\t\t\t\t\tPriceDetectedFields: collector.PriceDetectedFields{\n\t\t\t\t\t\tResourceID: *instance.LoadBalancerName,\n\t\t\t\t\t\tLaunchTime: *instance.CreatedTime,\n\t\t\t\t\t\tPricePerHour: price,\n\t\t\t\t\t\tPricePerMonth: price * collector.TotalMonthHours,\n\t\t\t\t\t\tTag: tagsData,\n\t\t\t\t\t},\n\t\t\t\t}\n\n\t\t\t\tel.awsManager.GetCollector().AddResource(collector.EventCollector{\n\t\t\t\t\tResourceName: el.Name,\n\t\t\t\t\tData: elbv2,\n\t\t\t\t})\n\n\t\t\t\tdetectedELBV2 = append(detectedELBV2, elbv2)\n\t\t\t}\n\t\t}\n\t}\n\n\tel.awsManager.GetCollector().CollectFinish(el.Name)\n\n\treturn detectedELBV2, nil\n\n}", "func NewLoadBalancer(hosts ...string) (*LoadBalancer, error) {\n\tbackends := make([]*backend, 0, len(hosts))\n\tp := pool{backends: backends}\n\tlb := LoadBalancer{\n\t\tp: p,\n\t\tdone: make(chan *backend, len(hosts)),\n\t}\n\tfor _, h := range hosts {\n\t\tu, err := url.Parse(h)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\theap.Push(&lb.p, &backend{r: httputil.NewSingleHostReverseProxy(u)})\n\t}\n\tgo lb.handleFinishes()\n\treturn &lb, nil\n}", "func New(pub mainflux.MessagePublisher, things mainflux.ThingsServiceClient) mainflux.MessagePublisher {\n\treturn &adapterService{\n\t\tpub: pub,\n\t\tthings: things,\n\t}\n}", "func (s StaticInfoExtn) NewBandwidth() (StaticInfoExtn_BandwidthInfo, error) {\n\tss, err := NewStaticInfoExtn_BandwidthInfo(s.Struct.Segment())\n\tif err != nil {\n\t\treturn StaticInfoExtn_BandwidthInfo{}, err\n\t}\n\terr = s.Struct.SetPtr(3, ss.Struct.ToPtr())\n\treturn ss, err\n}", "func New(adaptee *log.Logger) adapter.LogAdapter {\n\tadapted := &delegate{adaptee}\n\n\treturn &logAdapter{\n\t\tcommonlog.NewLogger(adapted),\n\t\tadapted,\n\t}\n}", "func NewMetricsAdapterCommand(ctx context.Context) *cobra.Command {\n\topts := options.NewOptions()\n\n\tcmd := &cobra.Command{\n\t\tUse: \"karmada-metrics-adapter\",\n\t\tLong: `The karmada-metrics-adapter is a adapter to aggregate the metrics from member clusters.`,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tif err := opts.Complete(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := opts.Validate(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := opts.Run(ctx); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t\tArgs: func(cmd *cobra.Command, args []string) error {\n\t\t\tfor _, arg := range args {\n\t\t\t\tif len(arg) > 0 {\n\t\t\t\t\treturn fmt.Errorf(\"%q does not take any arguments, got %q\", cmd.CommandPath(), args)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tfss := cliflag.NamedFlagSets{}\n\n\tgenericFlagSet := fss.FlagSet(\"generic\")\n\topts.AddFlags(genericFlagSet)\n\n\t// Set klog flags\n\tlogsFlagSet := fss.FlagSet(\"logs\")\n\tklogflag.Add(logsFlagSet)\n\n\tcmd.AddCommand(sharedcommand.NewCmdVersion(\"karmada-metrics-adapter\"))\n\tcmd.Flags().AddFlagSet(genericFlagSet)\n\tcmd.Flags().AddFlagSet(logsFlagSet)\n\n\tcols, _, _ := term.TerminalSize(cmd.OutOrStdout())\n\tsharedcli.SetUsageAndHelpFunc(cmd, fss, cols)\n\treturn cmd\n}", "func newAcceptableUsePolicies(c *AppsV1alphaClient, namespace string) *acceptableUsePolicies {\n\treturn &acceptableUsePolicies{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}", "func newTiDBGroups(c *PingcapV1alpha1Client, namespace string) *tiDBGroups {\n\treturn &tiDBGroups{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}", "func NewMetrics(registry metrics.Registry, exchanges []openrtb_ext.BidderName, disableAccountMetrics config.DisabledMetrics, syncerKeys []string, moduleStageNames map[string][]string) *Metrics {\n\tnewMetrics := NewBlankMetrics(registry, exchanges, disableAccountMetrics, moduleStageNames)\n\tnewMetrics.ConnectionCounter = metrics.GetOrRegisterCounter(\"active_connections\", registry)\n\tnewMetrics.TMaxTimeoutCounter = metrics.GetOrRegisterCounter(\"tmax_timeout\", registry)\n\tnewMetrics.ConnectionAcceptErrorMeter = metrics.GetOrRegisterMeter(\"connection_accept_errors\", registry)\n\tnewMetrics.ConnectionCloseErrorMeter = metrics.GetOrRegisterMeter(\"connection_close_errors\", registry)\n\tnewMetrics.ImpMeter = metrics.GetOrRegisterMeter(\"imps_requested\", registry)\n\n\tnewMetrics.ImpsTypeBanner = metrics.GetOrRegisterMeter(\"imp_banner\", registry)\n\tnewMetrics.ImpsTypeVideo = metrics.GetOrRegisterMeter(\"imp_video\", registry)\n\tnewMetrics.ImpsTypeAudio = metrics.GetOrRegisterMeter(\"imp_audio\", registry)\n\tnewMetrics.ImpsTypeNative = metrics.GetOrRegisterMeter(\"imp_native\", registry)\n\n\tnewMetrics.NoCookieMeter = metrics.GetOrRegisterMeter(\"no_cookie_requests\", registry)\n\tnewMetrics.AppRequestMeter = metrics.GetOrRegisterMeter(\"app_requests\", registry)\n\tnewMetrics.DebugRequestMeter = metrics.GetOrRegisterMeter(\"debug_requests\", registry)\n\tnewMetrics.RequestTimer = metrics.GetOrRegisterTimer(\"request_time\", registry)\n\tnewMetrics.DNSLookupTimer = metrics.GetOrRegisterTimer(\"dns_lookup_time\", registry)\n\tnewMetrics.TLSHandshakeTimer = metrics.GetOrRegisterTimer(\"tls_handshake_time\", registry)\n\tnewMetrics.PrebidCacheRequestTimerSuccess = metrics.GetOrRegisterTimer(\"prebid_cache_request_time.ok\", registry)\n\tnewMetrics.PrebidCacheRequestTimerError = metrics.GetOrRegisterTimer(\"prebid_cache_request_time.err\", registry)\n\tnewMetrics.StoredResponsesMeter = metrics.GetOrRegisterMeter(\"stored_responses\", registry)\n\tnewMetrics.OverheadTimer = makeOverheadTimerMetrics(registry)\n\tnewMetrics.BidderServerResponseTimer = metrics.GetOrRegisterTimer(\"bidder_server_response_time_seconds\", registry)\n\n\tfor _, dt := range StoredDataTypes() {\n\t\tfor _, ft := range StoredDataFetchTypes() {\n\t\t\ttimerName := fmt.Sprintf(\"stored_%s_fetch_time.%s\", string(dt), string(ft))\n\t\t\tnewMetrics.StoredDataFetchTimer[dt][ft] = metrics.GetOrRegisterTimer(timerName, registry)\n\t\t}\n\t\tfor _, e := range StoredDataErrors() {\n\t\t\tmeterName := fmt.Sprintf(\"stored_%s_error.%s\", string(dt), string(e))\n\t\t\tnewMetrics.StoredDataErrorMeter[dt][e] = metrics.GetOrRegisterMeter(meterName, registry)\n\t\t}\n\t}\n\n\tnewMetrics.AmpNoCookieMeter = metrics.GetOrRegisterMeter(\"amp_no_cookie_requests\", registry)\n\n\tnewMetrics.CookieSyncMeter = metrics.GetOrRegisterMeter(\"cookie_sync_requests\", registry)\n\tfor _, s := range CookieSyncStatuses() {\n\t\tnewMetrics.CookieSyncStatusMeter[s] = metrics.GetOrRegisterMeter(fmt.Sprintf(\"cookie_sync_requests.%s\", s), registry)\n\t}\n\n\tnewMetrics.SetUidMeter = metrics.GetOrRegisterMeter(\"setuid_requests\", registry)\n\tfor _, s := range SetUidStatuses() {\n\t\tnewMetrics.SetUidStatusMeter[s] = metrics.GetOrRegisterMeter(fmt.Sprintf(\"setuid_requests.%s\", s), registry)\n\t}\n\n\tfor _, syncerKey := range syncerKeys {\n\t\tnewMetrics.SyncerRequestsMeter[syncerKey] = make(map[SyncerCookieSyncStatus]metrics.Meter)\n\t\tfor _, status := range SyncerRequestStatuses() {\n\t\t\tnewMetrics.SyncerRequestsMeter[syncerKey][status] = metrics.GetOrRegisterMeter(fmt.Sprintf(\"syncer.%s.request.%s\", syncerKey, status), registry)\n\t\t}\n\n\t\tnewMetrics.SyncerSetsMeter[syncerKey] = make(map[SyncerSetUidStatus]metrics.Meter)\n\t\tfor _, status := range SyncerSetUidStatuses() {\n\t\t\tnewMetrics.SyncerSetsMeter[syncerKey][status] = metrics.GetOrRegisterMeter(fmt.Sprintf(\"syncer.%s.set.%s\", syncerKey, status), registry)\n\t\t}\n\t}\n\n\tfor _, a := range exchanges {\n\t\tregisterAdapterMetrics(registry, \"adapter\", string(a), newMetrics.AdapterMetrics[a])\n\t}\n\n\tfor typ, statusMap := range newMetrics.RequestStatuses {\n\t\tfor stat := range statusMap {\n\t\t\tstatusMap[stat] = metrics.GetOrRegisterMeter(\"requests.\"+string(stat)+\".\"+string(typ), registry)\n\t\t}\n\t}\n\n\tfor _, cacheRes := range CacheResults() {\n\t\tnewMetrics.StoredReqCacheMeter[cacheRes] = metrics.GetOrRegisterMeter(fmt.Sprintf(\"stored_request_cache_%s\", string(cacheRes)), registry)\n\t\tnewMetrics.StoredImpCacheMeter[cacheRes] = metrics.GetOrRegisterMeter(fmt.Sprintf(\"stored_imp_cache_%s\", string(cacheRes)), registry)\n\t\tnewMetrics.AccountCacheMeter[cacheRes] = metrics.GetOrRegisterMeter(fmt.Sprintf(\"account_cache_%s\", string(cacheRes)), registry)\n\t}\n\n\tnewMetrics.RequestsQueueTimer[\"video\"][true] = metrics.GetOrRegisterTimer(\"queued_requests.video.accepted\", registry)\n\tnewMetrics.RequestsQueueTimer[\"video\"][false] = metrics.GetOrRegisterTimer(\"queued_requests.video.rejected\", registry)\n\n\tnewMetrics.TimeoutNotificationSuccess = metrics.GetOrRegisterMeter(\"timeout_notification.ok\", registry)\n\tnewMetrics.TimeoutNotificationFailure = metrics.GetOrRegisterMeter(\"timeout_notification.failed\", registry)\n\n\tnewMetrics.PrivacyCCPARequest = metrics.GetOrRegisterMeter(\"privacy.request.ccpa.specified\", registry)\n\tnewMetrics.PrivacyCCPARequestOptOut = metrics.GetOrRegisterMeter(\"privacy.request.ccpa.opt-out\", registry)\n\tnewMetrics.PrivacyCOPPARequest = metrics.GetOrRegisterMeter(\"privacy.request.coppa\", registry)\n\tnewMetrics.PrivacyLMTRequest = metrics.GetOrRegisterMeter(\"privacy.request.lmt\", registry)\n\tfor _, version := range TCFVersions() {\n\t\tnewMetrics.PrivacyTCFRequestVersion[version] = metrics.GetOrRegisterMeter(fmt.Sprintf(\"privacy.request.tcf.%s\", string(version)), registry)\n\t}\n\n\tnewMetrics.AdsCertRequestsSuccess = metrics.GetOrRegisterMeter(\"ads_cert_requests.ok\", registry)\n\tnewMetrics.AdsCertRequestsFailure = metrics.GetOrRegisterMeter(\"ads_cert_requests.failed\", registry)\n\tnewMetrics.adsCertSignTimer = metrics.GetOrRegisterTimer(\"ads_cert_sign_time\", registry)\n\n\tfor module, stages := range moduleStageNames {\n\t\tregisterModuleMetrics(registry, module, stages, newMetrics.ModuleMetrics[module])\n\t}\n\n\treturn newMetrics\n}", "func newPacketAdaptor(conn net.Conn) *packetAdaptor {\n\treturn &packetAdaptor{conn, nil}\n}", "func newEndpoints() *Endpoints {\n\treturn &Endpoints{\n\t\tBackends: map[string]service.PortConfiguration{},\n\t}\n}", "func NewLoadBalancer(ctx context.Context, frontend NetAddr, backends ...NetAddr) (*LoadBalancer, error) {\n\treturn newLoadBalancer(ctx, frontend, roundRobinPolicy(), backends...)\n}", "func New(c *Config) *pool {\n\tbackends := c.Backends\n\tconnsPerBackend := c.NumConns\n\tcacheEnabled := c.EnableCache\n\tmaxRetries := c.MaxRetries\n\n\tbackendCount := int(math.Max(float64(len(backends)), float64(1)))\n\tmaxRequests := connsPerBackend * backendCount * 2\n\n\ttr := &http.Transport{\n\t\tDialContext: (&net.Dialer{\n\t\t\tTimeout: 10 * time.Second,\n\t\t\tKeepAlive: 10 * time.Second,\n\t\t}).DialContext,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\tExpectContinueTimeout: 10 * time.Second,\n\t\tResponseHeaderTimeout: 10 * time.Second,\n\t}\n\n\tclient := &http.Client{\n\t\tTimeout: 30 * time.Second,\n\t\tTransport: tr,\n\t}\n\n\tcache, err := buildCache(cacheEnabled)\n\tif err != nil {\n\t\tlog.Printf(\"Error creating cache: %v\", err)\n\t}\n\n\tconnectionPool := &pool{\n\t\tconnections: make(chan *connection.Connection, maxRequests),\n\t\thealthChecks: make(map[string]*healthcheck.HealthChecker),\n\t\tclient: client,\n\t\tconnsPerBackend: connsPerBackend,\n\t\tcache: cache,\n\t\tmaxRetries: maxRetries,\n\t}\n\n\tpoolConnections := []*connection.Connection{}\n\n\tstartup := &sync.WaitGroup{}\n\tfor _, backend := range backends {\n\t\tstartup.Add(1)\n\t\tpoolConnections = connectionPool.addBackend(poolConnections, backend, startup)\n\t}\n\n\tshuffle(poolConnections, connectionPool.connections)\n\n\tgo connectionPool.ListenForBackendChanges(startup)\n\n\treturn connectionPool\n}", "func makeBlankAdapterMetrics(disabledMetrics config.DisabledMetrics) *AdapterMetrics {\n\tblankMeter := &metrics.NilMeter{}\n\tnewAdapter := &AdapterMetrics{\n\t\tNoCookieMeter: blankMeter,\n\t\tErrorMeters: make(map[AdapterError]metrics.Meter),\n\t\tNoBidMeter: blankMeter,\n\t\tGotBidsMeter: blankMeter,\n\t\tRequestTimer: &metrics.NilTimer{},\n\t\tPriceHistogram: &metrics.NilHistogram{},\n\t\tBidsReceivedMeter: blankMeter,\n\t\tPanicMeter: blankMeter,\n\t\tMarkupMetrics: makeBlankBidMarkupMetrics(),\n\t}\n\tif !disabledMetrics.AdapterConnectionMetrics {\n\t\tnewAdapter.ConnCreated = metrics.NilCounter{}\n\t\tnewAdapter.ConnReused = metrics.NilCounter{}\n\t\tnewAdapter.ConnWaitTime = &metrics.NilTimer{}\n\t}\n\tif !disabledMetrics.AdapterGDPRRequestBlocked {\n\t\tnewAdapter.GDPRRequestBlocked = blankMeter\n\t}\n\tfor _, err := range AdapterErrors() {\n\t\tnewAdapter.ErrorMeters[err] = blankMeter\n\t}\n\treturn newAdapter\n}", "func NewLegacy(ctx context.Context, connection string, tlsInfo tls.Config) (server.Backend, error) {\n\treturn newBackend(ctx, connection, tlsInfo, true)\n}", "func newTracesExporter(params exporter.CreateSettings, cfg component.Config) (*traceExporterImp, error) {\n\texporterFactory := otlpexporter.NewFactory()\n\n\tlb, err := newLoadBalancer(params, cfg, func(ctx context.Context, endpoint string) (component.Component, error) {\n\t\toCfg := buildExporterConfig(cfg.(*Config), endpoint)\n\t\treturn exporterFactory.CreateTracesExporter(ctx, params, &oCfg)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttraceExporter := traceExporterImp{loadBalancer: lb, routingKey: traceIDRouting}\n\n\tswitch cfg.(*Config).RoutingKey {\n\tcase \"service\":\n\t\ttraceExporter.routingKey = svcRouting\n\tcase \"traceID\", \"\":\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported routing_key: %s\", cfg.(*Config).RoutingKey)\n\t}\n\treturn &traceExporter, nil\n}", "func NewPoliciesRequestBuilderInternal(pathParameters map[string]string, requestAdapter i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestAdapter)(*PoliciesRequestBuilder) {\n m := &PoliciesRequestBuilder{\n }\n m.urlTemplate = \"{+baseurl}/policies{?%24select,%24expand}\";\n urlTplParams := make(map[string]string)\n for idx, item := range pathParameters {\n urlTplParams[idx] = item\n }\n m.pathParameters = urlTplParams\n m.requestAdapter = requestAdapter\n return m\n}", "func New(endpointURL string, opts ...Option) (*VDRI, error) {\n\tvdri := &VDRI{client: &http.Client{}, accept: func(method string) bool { return true }}\n\n\tfor _, opt := range opts {\n\t\topt(vdri)\n\t}\n\n\t// Validate host\n\t_, err := url.ParseRequestURI(endpointURL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"base URL invalid: %w\", err)\n\t}\n\n\tvdri.endpointURL = endpointURL\n\n\treturn vdri, nil\n}", "func New() *Baa {\n\tb := new(Baa)\n\tb.middleware = make([]HandlerFunc, 0)\n\tb.pool = sync.Pool{\n\t\tNew: func() interface{} {\n\t\t\treturn NewContext(nil, nil, b)\n\t\t},\n\t}\n\tif Env != PROD {\n\t\tb.debug = true\n\t}\n\tb.SetDIer(NewDI())\n\tb.SetDI(\"router\", NewTree(b))\n\tb.SetDI(\"logger\", log.New(os.Stderr, \"[Baa] \", log.LstdFlags))\n\tb.SetDI(\"render\", newRender())\n\tb.SetNotFound(b.DefaultNotFoundHandler)\n\treturn b\n}" ]
[ "0.62870306", "0.60330063", "0.60330063", "0.60330063", "0.60330063", "0.60330063", "0.5953721", "0.5809309", "0.56710106", "0.5604929", "0.55235195", "0.5386451", "0.53338236", "0.5292613", "0.5190306", "0.51769847", "0.5173544", "0.5151814", "0.51018894", "0.509229", "0.5082324", "0.5054785", "0.5001413", "0.49938914", "0.49568912", "0.4944858", "0.4939145", "0.49253547", "0.49122253", "0.49113294", "0.48868793", "0.48712915", "0.48437282", "0.48166725", "0.48101622", "0.48000917", "0.47969875", "0.47869962", "0.47749823", "0.47669303", "0.47604457", "0.47391814", "0.47048855", "0.4690717", "0.46481693", "0.46388355", "0.4627935", "0.46123075", "0.46091172", "0.4589297", "0.45605472", "0.45502174", "0.45487678", "0.45290902", "0.45252168", "0.44926634", "0.44803813", "0.44737044", "0.44711488", "0.44639447", "0.44619682", "0.4458597", "0.44512504", "0.44401863", "0.44400984", "0.44310042", "0.44276792", "0.44190913", "0.44162473", "0.44159597", "0.44137856", "0.44124955", "0.4392056", "0.43820444", "0.43748087", "0.437432", "0.43741834", "0.43735924", "0.43725675", "0.43637636", "0.43526763", "0.4350096", "0.43468088", "0.4344074", "0.43267", "0.43231028", "0.43097505", "0.43089944", "0.430412", "0.4303054", "0.43020982", "0.4298811", "0.42832893", "0.42768845", "0.4267395", "0.42646095", "0.42617315", "0.4234013", "0.42306584", "0.4224927" ]
0.71556956
0
WithHealthCheckPath returns the receiver adapter after changing the health check path that will be used by the resources created by the adapter.
func (a *Adapter) WithHealthCheckPath(path string) *Adapter { a.healthCheckPath = path return a }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func WithHealthPath(path string) Option {\n\treturn func(o Options) {\n\t\to[optionWithHealthPath] = path\n\t}\n}", "func (a *Adapter) WithHealthCheckInterval(interval time.Duration) *Adapter {\n\ta.healthCheckInterval = interval\n\treturn a\n}", "func (a *Adapter) WithHealthCheckPort(port uint) *Adapter {\n\ta.healthCheckPort = port\n\treturn a\n}", "func (s *SimpleHealthCheck) Path() string {\n\treturn s.path\n}", "func (c *Config) BindPath(path string) {\n\tc.path = append(c.path, path)\n}", "func (m *monitor) withManifestPath(manifestsPath string) *monitor {\n\tm.manifestsPath = manifestsPath\n\treturn m\n}", "func InstallPathHandlerWithHealthyFunc(mux Muxer, path string, firstTimeHealthy func(), checks ...HealthChecker) {\n\tif len(checks) == 0 {\n\t\tslog.Info(\"No default health checks specified. Installing the ping handler.\")\n\t\tchecks = []HealthChecker{PingHealthzCheck}\n\t}\n\n\tslog.Info(fmt.Sprintf(\"Installing health checkers for (%v): %v\", path, formatQuoted(checkerNames(checks...)...)))\n\n\tname := strings.Split(strings.TrimPrefix(path, \"/\"), \"/\")[0]\n\tmux.Handle(path,\n\t\thandleRootHealth(name, firstTimeHealthy, checks...))\n\tfor _, check := range checks {\n\t\tmux.Handle(fmt.Sprintf(\"%s/%v\", path, check.Name()), adaptCheckToHandler(check.Check))\n\t}\n}", "func (o LookupLoadBalancerResultOutput) HealthCheckPath() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupLoadBalancerResult) *string { return v.HealthCheckPath }).(pulumi.StringPtrOutput)\n}", "func (f *staticPodFallback) withManifestPath(manifestsPath string) *staticPodFallback {\n\tf.manifestsPath = manifestsPath\n\treturn f\n}", "func (b *Builder) WithPath(path string) *Builder {\n\tb.path = HostPath(path)\n\treturn b\n}", "func WithConfigPath(path string) ClientOpt {\n\treturn clientOptFunc(func(cfg *engineconn.Config) {\n\t\tcfg.ConfigPath = path\n\t})\n}", "func (e EnumSQLBuilder) UsePath(path string) EnumSQLBuilder {\n\te.Path = path\n\treturn e\n}", "func (hc *HealthCheckArgsOrString) Path() *string {\n\tif hc.IsBasic() {\n\t\treturn aws.String(hc.Basic)\n\t}\n\treturn hc.Advanced.Path\n}", "func (options *CreateLoadBalancerMonitorOptions) SetPath(path string) *CreateLoadBalancerMonitorOptions {\n\toptions.Path = core.StringPtr(path)\n\treturn options\n}", "func (options *EditLoadBalancerMonitorOptions) SetPath(path string) *EditLoadBalancerMonitorOptions {\n\toptions.Path = core.StringPtr(path)\n\treturn options\n}", "func ForPath(db *bolt.DB, path Path) (bb *Bucketeer) {\n\tbb = &Bucketeer{\n\t\tdb: db,\n\t\tpath: path,\n\t}\n\treturn\n}", "func (c client) ConfigureHealthCheck(hc loadbalancer.HealthCheck) (loadbalancer.Result, error) {\n\t_, l4Type := c.name.GetLookupAndType()\n\treq := ConfigureHealthCheckRequest{\n\t\tType: l4Type,\n\t\tHealthCheck: hc,\n\t}\n\tresp := ConfigureHealthCheckResponse{}\n\n\tif err := c.client.Call(\"L4.ConfigureHealthCheck\", req, &resp); err != nil {\n\t\treturn nil, err\n\t}\n\treturn clientResult(resp.Result), nil\n}", "func InstallPathHandler(mux Muxer, path string, checks ...HealthChecker) {\n\tInstallPathHandlerWithHealthyFunc(mux, path, nil, checks...)\n}", "func (p artifactPath) hostPath(path string) string {\n\treturn rebasePath(path, p.mountPath, p.mountBind)\n}", "func (sb SQLBuilder) UsePath(path string) SQLBuilder {\n\tsb.Path = path\n\treturn sb\n}", "func WithMetricsURLPath(urlPath string) Option {\n\treturn wrappedOption{otlpconfig.WithMetricsURLPath(urlPath)}\n}", "func WithConfigPath(value string) OptFn {\n\treturn func(o *Opt) {\n\t\to.configPath = value\n\t}\n}", "func NewHealthCheck(opt ...Option) *HealthCheck {\n\topts := GetOpts(opt...)\n\n\th := &HealthCheck{\n\t\tstatus: &healthStatus{},\n\t}\n\tif e, ok := opts[optionWithEngine].(*gin.Engine); ok {\n\t\th.Engine = e\n\t}\n\tif path, ok := opts[optionWithHealthPath].(string); ok {\n\t\th.HealthPath = path\n\t} else {\n\t\th.HealthPath = \"/ready\"\n\t}\n\tif handler, ok := opts[optionWithHealthHandler].(gin.HandlerFunc); ok {\n\t\th.Handler = handler\n\t} else {\n\t\th.Handler = h.DefaultHealthHandler()\n\t}\n\n\tif ticker, ok := opts[optionHealthTicker].(*time.Ticker); ok {\n\t\th.metricTicker = ticker\n\t} else {\n\t\th.metricTicker = time.NewTicker(DefaultHealthTickerDuration)\n\t}\n\n\treturn h\n}", "func HandlerWithPluginPath(pluginPath string) HandlerOption {\n\treturn func(handlerOptions *handlerOptions) {\n\t\thandlerOptions.pluginPath = pluginPath\n\t}\n}", "func WithPath(path string) Option {\n\treturn func(r *RequestClient) {\n\t\tr.path = path\n\t}\n}", "func createHealthCheckRouter(ctx context.Context, l kitlog.Logger, h endpoints.HealthCheckServicer) *mux.Router {\n\trouter := mux.NewRouter().PathPrefix(prefix).Subrouter()\n\trouter.Handle(\n\t\t\"/healthcheck\",\n\t\tkithttp.NewServer(\n\t\t\th.Run,\n\t\t\tnoOpDecodeRequest,\n\t\t\tencodeHealthCheckHTTPResponse,\n\t\t)).Methods(http.MethodGet)\n\treturn router\n}", "func (*BgpFilter) PatchPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/bgp/filter/%s\", ref)\n}", "func (a *adapter) HealthCheck() (string, error) {\n\terr := a.client.checkHealthy()\n\tif err == nil {\n\t\treturn model.Healthy, nil\n\t}\n\treturn model.Unhealthy, err\n}", "func FromHealthCheckSource(ctx context.Context, gracePeriod time.Duration, retryInterval time.Duration, source Source, options ...Option) status.HealthCheckSource {\n\tchecker := &healthCheckSource{\n\t\tsource: source,\n\t\tgracePeriod: gracePeriod,\n\t\tretryInterval: retryInterval,\n\t\tcheckStates: map[health.CheckType]*checkState{},\n\t\tstartupTime: time.Now(),\n\t\tstartupGracePeriod: gracePeriod,\n\t}\n\tfor _, option := range options {\n\t\toption.apply(checker)\n\t}\n\tgo wapp.RunWithRecoveryLogging(ctx, checker.runPoll)\n\treturn checker\n}", "func (cPtr *Config) resolvePath(path string) string {\n\tif filepathPtr.IsAbs(path) {\n\t\treturn path\n\t}\n\tif cPtr.datadirectory == \"\" {\n\t\treturn \"\"\n\t}\n\t// Backwards-compatibility: ensure that data directory files created\n\t// by gbgm 1.4 are used if they exist.\n\tif cPtr.name() == \"gbgm\" && isOldGbgmResource[path] {\n\t\toldpath := \"\"\n\t\tif cPtr.Name == \"gbgm\" {\n\t\t\toldpath = filepathPtr.Join(cPtr.datadirectory, path)\n\t\t}\n\t\tif oldpath != \"\" && bgmcommon.FileExist(oldpath) {\n\t\t\t// TODO: print warning\n\t\t\treturn oldpath\n\t\t}\n\t}\n\treturn filepathPtr.Join(cPtr.instanceDir(), path)\n}", "func WithURLPath(urlPath string) Option {\n\treturn wrappedOption{oconf.WithURLPath(urlPath)}\n}", "func WithSlackClient(client SlackClient) AdapterOption {\n\treturn func(adapter *Adapter) {\n\t\tadapter.client = client\n\t}\n}", "func (rLoader *V1RouterLoader) routerHealthCheck(router *gin.Engine, handler *health.V1HealthController) {\n\tgroup := router.Group(\"v1/healthcheck\")\n\tgroup.GET(\"\", handler.HealthCheck)\n}", "func withHealthCheck(parent context.Context) context.Context {\n\treturn context.WithValue(parent, requestTypeKey{}, reqTypeHealthCheck)\n}", "func WithPath(p string) CallOption {\n\treturn &pathOpt{p: p}\n}", "func NewSimpleHealthCheck(path string) *SimpleHealthCheck {\n\treturn &SimpleHealthCheck{path: path}\n}", "func (m *PathsMutator) Path(path string, item PathItem) *PathsMutator {\n\tm.proxy.addPathItem(path, item)\n\treturn m\n}", "func (*CaHostCert) PatchPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/host_cert/%s\", ref)\n}", "func UsePath(path string, handler PathHandler) http.Handler {\n\treturn Handler(func(w http.ResponseWriter, r *http.Request) {\n\t\thandler(w, r, path)\n\t})\n}", "func InstallPathHandler(mux mux, path string, checks ...Checker) {\n\tif len(checks) == 0 {\n\t\tlog.Debug(\"No default health checks specified. Installing the ping handler.\")\n\t\tchecks = []Checker{PingHealthz}\n\t}\n\tlog.WithField(\"checkers\", checkerNames(checks...)).Debug(\"Installing healthz checkers\")\n\tmux.Handle(path, registerRootHealthzChecks(checks...))\n\tfor _, check := range checks {\n\t\tmux.Handle(fmt.Sprintf(\"%s/%v\", path, check.Name()), adaptCheckToHandler(check.Check))\n\t}\n}", "func WithChecker(c WorloadHealthChecker) ReconcilerOption {\n\treturn func(r *Reconciler) {\n\t\tif r.checkers == nil {\n\t\t\tr.checkers = make([]WorloadHealthChecker, 0)\n\t\t}\n\t\tr.checkers = append(r.checkers, c)\n\t}\n}", "func (*InterfaceBridge) PatchPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/interface/bridge/%s\", ref)\n}", "func initHealthCheck(apiRouter *mux.Router, context *Context) {\n\taddContext := func(handler contextHandlerFunc) *contextHandler {\n\t\treturn newContextHandler(context, handler)\n\t}\n\n\tpluginsRouter := apiRouter.PathPrefix(\"/health\").Subrouter()\n\tpluginsRouter.Handle(\"\", addContext(handleHealthCheck)).Methods(http.MethodGet)\n}", "func WithPath(path string) Option {\n\treturn pathOption(path)\n}", "func (s *LEAdvertisement1) Path() dbus.ObjectPath {\n\treturn s.config.objectPath\n}", "func NewHealthCheck() jrpc2.Handler {\n\treturn handler.New(func(context.Context) HealthCheckResult {\n\t\treturn HealthCheckResult{Status: \"healthy\"}\n\t})\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 NewAdapter(fs http.FileSystem, path string) *Adapter {\n\treturn &Adapter{fs, path}\n}", "func (c *HAProxyController) handlePath(namespace *Namespace, ingress *Ingress, rule *IngressRule, path *IngressPath) (reload bool, err error) {\n\treload = false\n\t// fetch Service\n\tservice, ok := namespace.Services[path.ServiceName]\n\tif !ok {\n\t\treturn reload, fmt.Errorf(\"service '%s' does not exist\", path.ServiceName)\n\t}\n\t// handle Backend\n\tbackendName, newBackend, r, err := c.handleService(namespace, ingress, rule, path, service)\n\treload = reload || r\n\tif err != nil {\n\t\treturn reload, err\n\t}\n\t// fetch Endpoints\n\tendpoints, ok := namespace.Endpoints[service.Name]\n\tif !ok {\n\t\tif service.DNS == \"\" {\n\t\t\tc.Logger.Warningf(\"No Endpoints for service '%s'\", service.Name)\n\t\t\treturn reload, nil // not an end of world scenario, just log this\n\t\t}\n\t\t//TODO: currently HAProxy will only resolve server name at startup/reload\n\t\t// This needs to be improved by using HAPorxy resolvers to have resolution at runtime\n\t\tc.Logger.Debugf(\"Configuring service '%s', of type ExternalName\", service.Name)\n\t\tendpoints = &Endpoints{\n\t\t\tNamespace: \"external\",\n\t\t\tAddresses: &EndpointIPs{\n\t\t\t\t\"external\": &EndpointIP{\n\t\t\t\t\tHAProxyName: \"external-service\",\n\t\t\t\t\tIP: service.DNS,\n\t\t\t\t\tDisabled: false,\n\t\t\t\t\tStatus: service.Status,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\t// resolve TargetPort\n\tendpoints.BackendName = backendName\n\tif err := c.setTargetPort(path, service, endpoints); err != nil {\n\t\treturn reload, err\n\t}\n\t// Handle Backend servers\n\tfor _, endpoint := range *endpoints.Addresses {\n\t\tendpoint := *endpoint\n\t\tif newBackend {\n\t\t\tendpoint.Status = ADDED\n\t\t}\n\t\tr := c.handleEndpoint(namespace, ingress, path, service, backendName, endpoint)\n\t\treload = reload || r\n\t}\n\treturn reload, nil\n}", "func (rLoader *V1RouterLoader) routerHealthCheck(router *gin.Engine, handler *health.V1HealthController) {\n\tgroup := router.Group(\"v1/check\")\n\tgroup.GET(\"\", handler.HealthCheck)\n}", "func (c *Client) appPath(path string) string {\n\treturn \"/apps/\" + c.AppId + \"/\" + path\n}", "func (b *CustomResourceColumnDefinitionApplyConfiguration) WithJSONPath(value string) *CustomResourceColumnDefinitionApplyConfiguration {\n\tb.JSONPath = &value\n\treturn b\n}", "func WithPath(path string) Option {\n\treturn func(p *Protocol) error {\n\t\tif p == nil {\n\t\t\treturn fmt.Errorf(\"http path option can not set nil protocol\")\n\t\t}\n\t\tpath = strings.TrimSpace(path)\n\t\tif len(path) == 0 {\n\t\t\treturn fmt.Errorf(\"http path option was given an invalid path: %q\", path)\n\t\t}\n\t\tp.Path = path\n\t\treturn nil\n\t}\n}", "func (c *clientHandler) SetPath(path string) {\n\tc.path = path\n}", "func (pc *PolicyConfigurator) Path() string {\n\treturn endpoint\n}", "func (c *scaleClient) apiPathFor(groupVer schema.GroupVersion) string {\n\t// we need to set the API path based on GroupVersion (defaulting to the legacy path if none is set)\n\t// TODO: we \"cheat\" here since the API path really only depends on group ATM, but this should\n\t// *probably* take GroupVersionResource and not GroupVersionKind.\n\tapiPath := c.apiPathResolverFunc(groupVer.WithKind(\"\"))\n\tif apiPath == \"\" {\n\t\tapiPath = \"/api\"\n\t}\n\n\treturn restclient.DefaultVersionedAPIPath(apiPath, groupVer)\n}", "func (resource *ResourcesData) SetHealthCheck(appName string, healthCheckType string, healthCheckHTTPEndpoint string, invocationTimeout int, process string) (err error) {\n\tif healthCheckType == \"\" {\n\t\treturn nil\n\t}\n\n\targs := []string{\"v3-set-health-check\", appName}\n\n\tif healthCheckType == \"http\" && healthCheckHTTPEndpoint != \"\" {\n\t\targs = append(args, healthCheckType, \"--endpoint\", healthCheckHTTPEndpoint)\n\t\tif invocationTimeout >= 0 {\n\t\t\targs = append(args, \"--invocation-timeout\", strconv.Itoa(invocationTimeout))\n\t\t}\n\t} else if process != \"\" && healthCheckType == \"process\" {\n\t\targs = append(args, healthCheckType, \"--process\", process)\n\t} else if healthCheckType == \"port\" {\n\t\targs = append(args, healthCheckType)\n\t}\n\n\terr = resource.Executor.Execute(args)\n\tif err != nil {\n\t\treturn errors.Wrap(err, fmt.Sprintf(\"could not set healthcheck with type: %s - endpoint: %s - invocationTimeout %v\", healthCheckType, healthCheckHTTPEndpoint, invocationTimeout))\n\t}\n\treturn nil\n}", "func (f *staticPodFallback) withStaticPodResourcesPath(staticPodResourcesPath string) *staticPodFallback {\n\tf.staticPodResourcesPath = staticPodResourcesPath\n\treturn f\n}", "func (*CaHostKeyCert) PatchPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/host_key_cert/%s\", ref)\n}", "func (Adapter MockPage) GetPath() string {\n\treturn Adapter.FakePath\n}", "func (m *Win32LobAppFileSystemDetection) SetPath(value *string)() {\n err := m.GetBackingStore().Set(\"path\", value)\n if err != nil {\n panic(err)\n }\n}", "func (tb TableSQLBuilder) UsePath(path string) TableSQLBuilder {\n\ttb.Path = path\n\treturn tb\n}", "func NewPather(provider topology.Provider, headerV2 bool) Pather {\n\tvar pather Pather = LegacyPather{TopoProvider: provider}\n\tif headerV2 {\n\t\tpather = PatherV2{\n\t\t\tUnderlayNextHop: func(ifID uint16) (*net.UDPAddr, bool) {\n\t\t\t\treturn provider.Get().UnderlayNextHop2(common.IFIDType(ifID))\n\t\t\t},\n\t\t}\n\t}\n\treturn pather\n}", "func (*InterfaceVlan) PatchPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/interface/vlan/%s\", ref)\n}", "func SetPath(newpath string) {\n\tpath = newpath\n}", "func BOSHPath(path string) Option {\n\treturn func(c *CLI) error {\n\t\tc.boshPath = path\n\t\treturn nil\n\t}\n}", "func (s *ClusterHealthService) FilterPath(filterPath ...string) *ClusterHealthService {\n\ts.filterPath = filterPath\n\treturn s\n}", "func (c *Config) AtPath(path ...string) ConfigElement {\n\tdata := (*configData)(atomic.LoadPointer(&c.data))\n\treturn &JSONElement{c, data, data.body.GetPath(path...)}\n}", "func (m *ItemSitesSiteItemRequestBuilder) GetByPathWithPath(path *string)(*ItemSitesItemGetByPathWithPathRequestBuilder) {\n return NewItemSitesItemGetByPathWithPathRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter, path)\n}", "func NewHealthCheck(rt *permissions.Runtime) operations.HealthCheckHandler {\n\treturn &healthCheck{}\n}", "func (h *ProxyHealth) SetHealthCheck(check func(addr *url.URL) bool, period time.Duration) {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\n\th.stop()\n\th.check = check\n\th.period = period\n\th.cancel = make(chan struct{})\n\th.isAvailable = h.check(h.origin)\n\th.run()\n}", "func (b *BgpFilter) GetPath() string { return fmt.Sprintf(\"/api/objects/bgp/filter/%s\", b.Reference) }", "func HealthCheckFilter(req typhon.Request, svc typhon.Service) typhon.Response {\n\tif matchesHealthCheckPath(req) {\n\t\treturn req.Response(&healthCheckResponse{OK: true})\n\t}\n\n\treturn svc(req)\n}", "func (s *ServerImpl) RegisterHealthcheckEndpoint(path string, handler func(w http.ResponseWriter, r *http.Request)) {\n\ts.healthcheckEndpoint = path\n\ts.healthcheckHandler = handler\n\ts.Router.Path(path).Name(path).Methods(\"GET\").HandlerFunc(s.handleFuncHealthcheck)\n}", "func (m *GroupPolicyDefinition) SetCategoryPath(value *string)() {\n err := m.GetBackingStore().Set(\"categoryPath\", value)\n if err != nil {\n panic(err)\n }\n}", "func (e *CachedEnforcer) InitWithAdapter(modelPath string, adapter persist.Adapter) error {\n\tif e.autoClear {\n\t\tdefer e.InvalidateCache()\n\t}\n\treturn e.base.InitWithAdapter(modelPath, adapter)\n}", "func NewHealthCheck(rt *app.Runtime) operations.HealthCheckHandler {\n\treturn &healthCheck{}\n}", "func (p Path) Apply(conf *Config) {\n\tconf.Path = string(p)\n}", "func (a *AdminPolicyStatus1) Path() dbus.ObjectPath {\n\treturn a.client.Config.Path\n}", "func WithPath(path string) Preparer {\n\treturn func(r *http.Request) *http.Request {\n\t\tr.URL.Path = path\n\t\treturn r\n\t}\n}", "func addWatcher(appID string, path string) (*fsnotify.Watcher, error) {\n\tpath, err := checkPath(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfilelist, err := getFilelist(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = messaging.RegisterClient(appID, path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = sendFilelist(filelist)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twatcher, err := fsnotify.NewWatcher()\n\n\tif err != nil {\n\t\tlog.Error(\"Failed to initalise watcher: \", err)\n\t\treturn nil, err\n\t}\n\n\tgo dirWatcher(watcher)\n\n\terr = watcher.Add(path)\n\n\tif err != nil {\n\t\tlog.Error(\"Error adding watcher for path \", path, \": \", err)\n\t\treturn nil, err\n\t}\n\n\tlog.Info(\"Started watching \", path, \" for changes\")\n\tlisten(path)\n\treturn watcher, err\n}", "func (_m *requestHeaderMapUpdatable) SetPath(path string) {\n\t_m.Called(path)\n}", "func (c *Client) SetPath(path string) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tc.path = path\n}", "func expandHealthCheck(c *Client, f *HealthCheck) (map[string]interface{}, error) {\n\tm := make(map[string]interface{})\n\tif v := f.CheckIntervalSec; !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"checkIntervalSec\"] = v\n\t}\n\tif v := f.Description; !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"description\"] = v\n\t}\n\tif v := f.HealthyThreshold; !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"healthyThreshold\"] = v\n\t}\n\tif v, err := expandHealthCheckHttp2HealthCheck(c, f.Http2HealthCheck); err != nil {\n\t\treturn nil, fmt.Errorf(\"error expanding Http2HealthCheck into http2HealthCheck: %w\", err)\n\t} else if !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"http2HealthCheck\"] = v\n\t}\n\tif v, err := expandHealthCheckHttpHealthCheck(c, f.HttpHealthCheck); err != nil {\n\t\treturn nil, fmt.Errorf(\"error expanding HttpHealthCheck into httpHealthCheck: %w\", err)\n\t} else if !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"httpHealthCheck\"] = v\n\t}\n\tif v, err := expandHealthCheckHttpsHealthCheck(c, f.HttpsHealthCheck); err != nil {\n\t\treturn nil, fmt.Errorf(\"error expanding HttpsHealthCheck into httpsHealthCheck: %w\", err)\n\t} else if !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"httpsHealthCheck\"] = v\n\t}\n\tif v := f.Name; !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"name\"] = v\n\t}\n\tif v, err := expandHealthCheckSslHealthCheck(c, f.SslHealthCheck); err != nil {\n\t\treturn nil, fmt.Errorf(\"error expanding SslHealthCheck into sslHealthCheck: %w\", err)\n\t} else if !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"sslHealthCheck\"] = v\n\t}\n\tif v, err := expandHealthCheckTcpHealthCheck(c, f.TcpHealthCheck); err != nil {\n\t\treturn nil, fmt.Errorf(\"error expanding TcpHealthCheck into tcpHealthCheck: %w\", err)\n\t} else if !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"tcpHealthCheck\"] = v\n\t}\n\tif v := f.Type; !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"type\"] = v\n\t}\n\tif v := f.UnhealthyThreshold; !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"unhealthyThreshold\"] = v\n\t}\n\tif v := f.TimeoutSec; !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"timeoutSec\"] = v\n\t}\n\tif v, err := dcl.EmptyValue(); err != nil {\n\t\treturn nil, fmt.Errorf(\"error expanding Region into region: %w\", err)\n\t} else if !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"region\"] = v\n\t}\n\tif v, err := dcl.EmptyValue(); err != nil {\n\t\treturn nil, fmt.Errorf(\"error expanding Project into project: %w\", err)\n\t} else if !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"project\"] = v\n\t}\n\tif v := f.SelfLink; !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"selfLink\"] = v\n\t}\n\tif v, err := dcl.EmptyValue(); err != nil {\n\t\treturn nil, fmt.Errorf(\"error expanding Location into location: %w\", err)\n\t} else if !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"location\"] = v\n\t}\n\n\treturn m, nil\n}", "func (c *Container) healthCheckLogPath() string {\n\treturn filepath.Join(filepath.Dir(c.state.RunDir), \"healthcheck.log\")\n}", "func (c *Container) healthCheckLogPath() string {\n\treturn filepath.Join(filepath.Dir(c.state.RunDir), \"healthcheck.log\")\n}", "func (o *UpdateLoadBalancerRequest) SetHealthCheck(v HealthCheck) {\n\to.HealthCheck = &v\n}", "func (aw *alfredWatcher) AddWatch(path string) error {\n if aw.Size() >= MAX_PATH_PER_WATCHER {\n return errors.New(\"Watch path full for this watcher.\")\n }\n err := aw.watcher.AddWatch(path, inotify.IN_ISDIR|inotify.IN_CLOSE_WRITE|inotify.IN_CREATE|inotify.IN_DELETE|inotify.IN_MODIFY|inotify.IN_MOVE)\n //err := aw.watcher.Watch(path)\n if err == nil {\n aw.list[path] = inotify.IN_ISDIR | inotify.IN_CLOSE_WRITE | inotify.IN_CREATE | inotify.IN_DELETE | inotify.IN_MODIFY | inotify.IN_MOVE\n }\n return err\n}", "func NewHealthCheckSource(ctx context.Context, gracePeriod time.Duration, retryInterval time.Duration, checkType health.CheckType, poll func() error, options ...Option) status.HealthCheckSource {\n\treturn FromHealthCheckSource(ctx, gracePeriod, retryInterval, newDefaultHealthCheckSource(checkType, poll), options...)\n}", "func (*InterfaceEthernet) PatchPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/interface/ethernet/%s\", ref)\n}", "func (a *BaseAdapter) ApplyPathPrefix(path string) string {\n\treturn fmt.Sprintf(\"%s%s\", *a.pathPrefix, strings.TrimPrefix(path, string(os.PathSeparator)))\n}", "func (b *Builder) WithPath(filePath string) *Builder {\n\tb.path = filePath\n\treturn b\n}", "func (l *HostIPListener) Path() string {\n\treturn path.Join(\"/hosts\", l.hostid, \"ips\")\n}", "func upgradePath(path *pb.Path) *pb.Path {\n\tif path != nil && len(path.Elem) == 0 {\n\t\tvar elems []*pb.PathElem\n\t\tfor _, element := range path.Element {\n\t\t\tn, keys, _ := parseElement(element)\n\t\t\telems = append(elems, &pb.PathElem{Name: n, Key: keys})\n\t\t}\n\t\tpath.Elem = elems\n\t\tpath.Element = nil\n\t}\n\treturn path\n}", "func (d *discovery) SetHealthChecker(h HealthChecker) {\n\td.healthCheckerLock.Lock()\n\tdefer d.healthCheckerLock.Unlock()\n\td.healthChecker = h\n}", "func (client IotHubResourceClient) GetEndpointHealthResponder(resp *http.Response) (result EndpointHealthDataListResult, 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 (_m *Knapsack) EnrollSecretPath() string {\n\tret := _m.Called()\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func() string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func setupWithPath(path string) (client *Client, mux *http.ServeMux, serverURL string, teardown func()) {\n\t// mux is the HTTP request multiplexer used with the test server.\n\tmux = http.NewServeMux()\n\n\tapiHandler := http.NewServeMux()\n\tapiHandler.Handle(baseURLPath+\"/\", http.StripPrefix(baseURLPath, mux))\n\tapiHandler.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n\t\tfmt.Fprintln(os.Stderr, \"\\t\"+req.URL.String())\n\t\tfmt.Fprintln(os.Stderr)\n\t})\n\n\t// server is a test HTTP server used to provide mock API responses.\n\tserver := httptest.NewServer(apiHandler)\n\n\t// client is the backlog client being tested and is\n\t// configured to use test server.\n\tclient = New(\n\t\t\"test-token\",\n\t\tserver.URL+path,\n\t\tOptionHTTPClient(&http.Client{}),\n\t\tOptionDebug(false),\n\t\tOptionLog(log.New(os.Stderr, \"kenzo0107/backlog\", log.LstdFlags|log.Lshortfile)),\n\t)\n\n\treturn client, mux, server.URL, server.Close\n}", "func (o IopingSpecVolumeVolumeSourceOutput) HostPath() IopingSpecVolumeVolumeSourceHostPathPtrOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSource) *IopingSpecVolumeVolumeSourceHostPath { return v.HostPath }).(IopingSpecVolumeVolumeSourceHostPathPtrOutput)\n}", "func (*CaVerificationCa) PatchPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/verification_ca/%s\", ref)\n}" ]
[ "0.56311184", "0.54221565", "0.53355366", "0.5065387", "0.5011958", "0.5011295", "0.49516243", "0.49430206", "0.47376975", "0.4716614", "0.4532915", "0.4531635", "0.4468667", "0.4417027", "0.4402186", "0.44014338", "0.4387692", "0.43710768", "0.43495873", "0.43489194", "0.4318213", "0.42823744", "0.42594266", "0.42170084", "0.42115", "0.42087618", "0.4207503", "0.41823706", "0.41648307", "0.41646627", "0.4158321", "0.41531175", "0.41468996", "0.41371152", "0.41269827", "0.41260993", "0.41254643", "0.41236457", "0.41110918", "0.41047603", "0.40980098", "0.4096229", "0.40767518", "0.4056652", "0.4050018", "0.40403333", "0.4039148", "0.40372935", "0.4036944", "0.4035166", "0.40245044", "0.40238702", "0.4023583", "0.4016856", "0.40051338", "0.39923692", "0.39899316", "0.3987966", "0.39847764", "0.39831436", "0.39792556", "0.39762843", "0.39431497", "0.39409882", "0.38995263", "0.38984492", "0.3898246", "0.38964602", "0.38945088", "0.3893646", "0.38888958", "0.38869083", "0.3886208", "0.38828418", "0.38807738", "0.3878378", "0.38724852", "0.38721654", "0.3862617", "0.38609406", "0.38573882", "0.38520306", "0.38489425", "0.38422653", "0.38399565", "0.38399565", "0.38337696", "0.38230202", "0.38225853", "0.3822422", "0.3820415", "0.38072947", "0.38021523", "0.38008642", "0.38008028", "0.37985858", "0.37947035", "0.37943345", "0.37879258", "0.37851658" ]
0.7927095
0
WithHealthCheckPort returns the receiver adapter after changing the health check port that will be used by the resources created by the adapter
func (a *Adapter) WithHealthCheckPort(port uint) *Adapter { a.healthCheckPort = port return a }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func HealthPort(port uint) Option {\n\treturn optionFunc(func(r *runtime) {\n\t\tr.hPort = port\n\t})\n}", "func (o SSLHealthCheckResponseOutput) Port() pulumi.IntOutput {\n\treturn o.ApplyT(func(v SSLHealthCheckResponse) int { return v.Port }).(pulumi.IntOutput)\n}", "func (o HTTPHealthCheckResponseOutput) Port() pulumi.IntOutput {\n\treturn o.ApplyT(func(v HTTPHealthCheckResponse) int { return v.Port }).(pulumi.IntOutput)\n}", "func (o HTTPSHealthCheckResponseOutput) Port() pulumi.IntOutput {\n\treturn o.ApplyT(func(v HTTPSHealthCheckResponse) int { return v.Port }).(pulumi.IntOutput)\n}", "func (o HTTP2HealthCheckOutput) Port() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v HTTP2HealthCheck) *int { return v.Port }).(pulumi.IntPtrOutput)\n}", "func (o HTTP2HealthCheckResponseOutput) Port() pulumi.IntOutput {\n\treturn o.ApplyT(func(v HTTP2HealthCheckResponse) int { return v.Port }).(pulumi.IntOutput)\n}", "func (o TCPHealthCheckResponseOutput) Port() pulumi.IntOutput {\n\treturn o.ApplyT(func(v TCPHealthCheckResponse) int { return v.Port }).(pulumi.IntOutput)\n}", "func (o SSLHealthCheckOutput) Port() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v SSLHealthCheck) *int { return v.Port }).(pulumi.IntPtrOutput)\n}", "func (o TCPHealthCheckOutput) Port() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v TCPHealthCheck) *int { return v.Port }).(pulumi.IntPtrOutput)\n}", "func (o HTTP2HealthCheckPtrOutput) Port() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *HTTP2HealthCheck) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Port\n\t}).(pulumi.IntPtrOutput)\n}", "func (o AppTemplateContainerReadinessProbeOutput) Port() pulumi.IntOutput {\n\treturn o.ApplyT(func(v AppTemplateContainerReadinessProbe) int { return v.Port }).(pulumi.IntOutput)\n}", "func (o HTTPSHealthCheckTypeOutput) Port() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v HTTPSHealthCheckType) *int { return v.Port }).(pulumi.IntPtrOutput)\n}", "func WithPort(port int) Option {\n\treturn func(c *config) {\n\t\tc.options.Collector.Port = port\n\t\tc.options.SystemMetrics.Endpoint.Port = port\n\t}\n}", "func (o GetAppTemplateContainerReadinessProbeOutput) Port() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GetAppTemplateContainerReadinessProbe) int { return v.Port }).(pulumi.IntOutput)\n}", "func (o SSLHealthCheckPtrOutput) Port() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *SSLHealthCheck) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Port\n\t}).(pulumi.IntPtrOutput)\n}", "func (o AppTemplateContainerLivenessProbeOutput) Port() pulumi.IntOutput {\n\treturn o.ApplyT(func(v AppTemplateContainerLivenessProbe) int { return v.Port }).(pulumi.IntOutput)\n}", "func (o GetAppTemplateContainerLivenessProbeOutput) Port() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GetAppTemplateContainerLivenessProbe) int { return v.Port }).(pulumi.IntOutput)\n}", "func (o HTTPHealthCheckTypeOutput) Port() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v HTTPHealthCheckType) *int { return v.Port }).(pulumi.IntPtrOutput)\n}", "func (o TCPHealthCheckPtrOutput) Port() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *TCPHealthCheck) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Port\n\t}).(pulumi.IntPtrOutput)\n}", "func (self *holder) GetPort() int {\n\treturn self.port\n}", "func NewHealthOnPort(port int) *Health {\n\thealthMux := http.NewServeMux()\n\thealthMux.HandleFunc(\"/healthz\", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, \"OK\") })\n\tserver := &http.Server{Addr: \":\" + strconv.Itoa(port), Handler: healthMux}\n\tinterrupts.ListenAndServe(server, 5*time.Second)\n\treturn &Health{\n\t\thealthMux: healthMux,\n\t}\n}", "func (o BuildStrategySpecBuildStepsLivenessProbeHttpGetOutput) Port() BuildStrategySpecBuildStepsLivenessProbeHttpGetPortOutput {\n\treturn o.ApplyT(func(v BuildStrategySpecBuildStepsLivenessProbeHttpGet) BuildStrategySpecBuildStepsLivenessProbeHttpGetPort {\n\t\treturn v.Port\n\t}).(BuildStrategySpecBuildStepsLivenessProbeHttpGetPortOutput)\n}", "func (o BuildStrategySpecBuildStepsReadinessProbeTcpSocketOutput) Port() BuildStrategySpecBuildStepsReadinessProbeTcpSocketPortOutput {\n\treturn o.ApplyT(func(v BuildStrategySpecBuildStepsReadinessProbeTcpSocket) BuildStrategySpecBuildStepsReadinessProbeTcpSocketPort {\n\t\treturn v.Port\n\t}).(BuildStrategySpecBuildStepsReadinessProbeTcpSocketPortOutput)\n}", "func (o GRPCHealthCheckResponseOutput) Port() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GRPCHealthCheckResponse) int { return v.Port }).(pulumi.IntOutput)\n}", "func (o BuildStrategySpecBuildStepsLivenessProbeTcpSocketOutput) Port() BuildStrategySpecBuildStepsLivenessProbeTcpSocketPortOutput {\n\treturn o.ApplyT(func(v BuildStrategySpecBuildStepsLivenessProbeTcpSocket) BuildStrategySpecBuildStepsLivenessProbeTcpSocketPort {\n\t\treturn v.Port\n\t}).(BuildStrategySpecBuildStepsLivenessProbeTcpSocketPortOutput)\n}", "func (o HTTP2HealthCheckResponsePtrOutput) Port() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *HTTP2HealthCheckResponse) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Port\n\t}).(pulumi.IntPtrOutput)\n}", "func (o SSLHealthCheckResponsePtrOutput) Port() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *SSLHealthCheckResponse) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Port\n\t}).(pulumi.IntPtrOutput)\n}", "func freeport(t *testing.T) (port int, addr string) {\n\tl, err := net.ListenTCP(\"tcp\", &net.TCPAddr{IP: net.ParseIP(\"127.0.0.1\")})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer l.Close()\n\ta := l.Addr().(*net.TCPAddr)\n\tport = a.Port\n\treturn port, a.String()\n}", "func (o TCPHealthCheckResponsePtrOutput) Port() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *TCPHealthCheckResponse) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Port\n\t}).(pulumi.IntPtrOutput)\n}", "func (o HTTPHealthCheckResponsePtrOutput) Port() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *HTTPHealthCheckResponse) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Port\n\t}).(pulumi.IntPtrOutput)\n}", "func (o HTTPSHealthCheckResponsePtrOutput) Port() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *HTTPSHealthCheckResponse) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Port\n\t}).(pulumi.IntPtrOutput)\n}", "func (o BuildStrategySpecBuildStepsReadinessProbeHttpGetOutput) Port() BuildStrategySpecBuildStepsReadinessProbeHttpGetPortOutput {\n\treturn o.ApplyT(func(v BuildStrategySpecBuildStepsReadinessProbeHttpGet) BuildStrategySpecBuildStepsReadinessProbeHttpGetPort {\n\t\treturn v.Port\n\t}).(BuildStrategySpecBuildStepsReadinessProbeHttpGetPortOutput)\n}", "func (k Keeper) BindPort(ctx sdk.Context, portID string) error {\n\t// Set the portID into our store so we can retrieve it later\n\tstore := ctx.KVStore(k.storeKey)\n\tstore.Set([]byte(\"consuming\"), []byte(portID))\n\n\tcap := k.PortKeeper.BindPort(ctx, portID)\n\treturn k.ScopedKeeper.ClaimCapability(ctx, cap, porttypes.PortPath(portID))\n}", "func (o HTTPSHealthCheckTypePtrOutput) Port() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *HTTPSHealthCheckType) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Port\n\t}).(pulumi.IntPtrOutput)\n}", "func (o ClusterBuildStrategySpecBuildStepsLivenessProbeHttpGetOutput) Port() ClusterBuildStrategySpecBuildStepsLivenessProbeHttpGetPortOutput {\n\treturn o.ApplyT(func(v ClusterBuildStrategySpecBuildStepsLivenessProbeHttpGet) ClusterBuildStrategySpecBuildStepsLivenessProbeHttpGetPort {\n\t\treturn v.Port\n\t}).(ClusterBuildStrategySpecBuildStepsLivenessProbeHttpGetPortOutput)\n}", "func withPort(host string) string {\n\tif _, _, err := net.SplitHostPort(host); err != nil {\n\t\treturn net.JoinHostPort(host, \"443\")\n\t}\n\treturn host\n}", "func withPort(host string) string {\n\tif _, _, err := net.SplitHostPort(host); err != nil {\n\t\treturn net.JoinHostPort(host, \"443\")\n\t}\n\treturn host\n}", "func freeport() (port int, addr string) {\n\tl, err := net.ListenTCP(\"tcp\", &net.TCPAddr{IP: net.ParseIP(\"127.0.0.1\")})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer l.Close()\n\ta := l.Addr().(*net.TCPAddr)\n\tport = a.Port\n\treturn port, a.String()\n}", "func (m *Modifier) UsePort(port int) {\n\tm.port = port\n\tm.remove = false\n\tm.defaultForScheme = false\n}", "func (h *Host) Port() uint16 {\n}", "func (o HTTPHealthCheckTypePtrOutput) Port() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *HTTPHealthCheckType) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Port\n\t}).(pulumi.IntPtrOutput)\n}", "func (ctx *Context) Port() int {\r\n\tparts := strings.Split(ctx.R.Host, \":\")\r\n\tif len(parts) == 2 {\r\n\t\tport, _ := strconv.Atoi(parts[1])\r\n\t\treturn port\r\n\t}\r\n\treturn 80\r\n}", "func WithPort(p int) Option {\n\treturn func(o *options) {\n\t\to.port = p\n\t}\n}", "func (o GroupContainerReadinessProbeHttpGetOutput) Port() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v GroupContainerReadinessProbeHttpGet) *int { return v.Port }).(pulumi.IntPtrOutput)\n}", "func (o BuildStrategySpecBuildStepsStartupProbeTcpSocketOutput) Port() BuildStrategySpecBuildStepsStartupProbeTcpSocketPortOutput {\n\treturn o.ApplyT(func(v BuildStrategySpecBuildStepsStartupProbeTcpSocket) BuildStrategySpecBuildStepsStartupProbeTcpSocketPort {\n\t\treturn v.Port\n\t}).(BuildStrategySpecBuildStepsStartupProbeTcpSocketPortOutput)\n}", "func (o ServerGroupHealthCheckOutput) HealthCheckConnectPort() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v ServerGroupHealthCheck) *int { return v.HealthCheckConnectPort }).(pulumi.IntPtrOutput)\n}", "func (o GetServerGroupsGroupHealthCheckOutput) HealthCheckConnectPort() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GetServerGroupsGroupHealthCheck) int { return v.HealthCheckConnectPort }).(pulumi.IntOutput)\n}", "func (o ClusterBuildStrategySpecBuildStepsReadinessProbeHttpGetOutput) Port() ClusterBuildStrategySpecBuildStepsReadinessProbeHttpGetPortOutput {\n\treturn o.ApplyT(func(v ClusterBuildStrategySpecBuildStepsReadinessProbeHttpGet) ClusterBuildStrategySpecBuildStepsReadinessProbeHttpGetPort {\n\t\treturn v.Port\n\t}).(ClusterBuildStrategySpecBuildStepsReadinessProbeHttpGetPortOutput)\n}", "func (c *Client) UsePort(port int) error {\n\t_, err := c.ExecCmd(NewCmd(\"use\").WithArgs(NewArg(\"port\", port)))\n\treturn err\n}", "func (o BuildStrategySpecBuildStepsStartupProbeHttpGetOutput) Port() BuildStrategySpecBuildStepsStartupProbeHttpGetPortOutput {\n\treturn o.ApplyT(func(v BuildStrategySpecBuildStepsStartupProbeHttpGet) BuildStrategySpecBuildStepsStartupProbeHttpGetPort {\n\t\treturn v.Port\n\t}).(BuildStrategySpecBuildStepsStartupProbeHttpGetPortOutput)\n}", "func (b *BluetoothAdapter) Port() string { return b.portName }", "func (o ClusterBuildStrategySpecBuildStepsLivenessProbeTcpSocketOutput) Port() ClusterBuildStrategySpecBuildStepsLivenessProbeTcpSocketPortOutput {\n\treturn o.ApplyT(func(v ClusterBuildStrategySpecBuildStepsLivenessProbeTcpSocket) ClusterBuildStrategySpecBuildStepsLivenessProbeTcpSocketPort {\n\t\treturn v.Port\n\t}).(ClusterBuildStrategySpecBuildStepsLivenessProbeTcpSocketPortOutput)\n}", "func (h *Host) SetPort(p uint16) {\n}", "func (o ClusterBuildStrategySpecBuildStepsReadinessProbeTcpSocketOutput) Port() ClusterBuildStrategySpecBuildStepsReadinessProbeTcpSocketPortOutput {\n\treturn o.ApplyT(func(v ClusterBuildStrategySpecBuildStepsReadinessProbeTcpSocket) ClusterBuildStrategySpecBuildStepsReadinessProbeTcpSocketPort {\n\t\treturn v.Port\n\t}).(ClusterBuildStrategySpecBuildStepsReadinessProbeTcpSocketPortOutput)\n}", "func (b *BrokerInfo) Port() int32 {\n\treturn b.port\n}", "func (o AppTemplateContainerStartupProbeOutput) Port() pulumi.IntOutput {\n\treturn o.ApplyT(func(v AppTemplateContainerStartupProbe) int { return v.Port }).(pulumi.IntOutput)\n}", "func (h *HttpReceiver) initializeReceiverPort() error {\n\t// Try 5 random ports before giving up.\n\tretryCount := 0\n\tfor (retryCount < maxPortRetries) {\n\t\tcurrPort := generateRandomPort(minReceiverPort, maxReceiverPort)\n\t\tcurrBindPortStr := \":\" + strconv.Itoa(currPort)\n\n\t\t// Check if port is already in use.\n\t\tif ln, err := net.Listen(\"tcp\", currBindPortStr); err != nil {\n\t\t\toutput.VerbosePrint(fmt.Sprintf(\"[-] Error trying to use random port %d: %s\", currPort, err.Error()))\n\t\t} else {\n\t\t\th.port = currPort\n\t\t\th.bindPortStr = currBindPortStr\n\t\t\treturn ln.Close()\n\t\t}\n\t}\n\treturn errors.New(fmt.Sprintf(\"Failed to find available port %d consecutive times.\", maxPortRetries))\n}", "func (a AdminAPI) GetPort() int {\n\treturn a.Port\n}", "func CheckPort(protocol CheckPortProtocol, address string, port, timeout int, invert bool, metricName string) (string, int) {\n\tconst checkName = \"CheckPort\"\n\tvar retCode int\n\tvar msg, desc, nagiosOutput, retText, retDesc string\n\n\tif protocol.String() == \"unknown\" {\n\t\tdesc = fmt.Sprintf(\"Unknown protocol value of %d\", protocol)\n\t\tretText = statusTextCritical\n\t\tretCode = statusCodeCritical\n\t} else if metricName == \"\" {\n\t\tdesc = \"Empty metric name\"\n\t\tretText = statusTextCritical\n\t\tretCode = statusCodeCritical\n\t} else if address == \"\" {\n\t\tdesc = \"Empty address\"\n\t\tretText = statusTextCritical\n\t\tretCode = statusCodeCritical\n\t} else {\n\t\tretText, retCode, retDesc = checkPort(protocol, address, port, timeout, invert)\n\t\tdesc = fmt.Sprintf(\"port %d on %s using %s\", port, address, protocol)\n\t\tif retDesc != \"\" {\n\t\t\tdesc = desc + fmt.Sprintf(\" (%s)\", retDesc)\n\t\t}\n\t}\n\n\tnagiosOutput = fmt.Sprintf(\"%s=%d\", metricName, retCode)\n\tmsg, _ = resultMessage(checkName, retText, desc, nagiosOutput)\n\n\treturn msg, retCode\n}", "func (o GetAppTemplateContainerStartupProbeOutput) Port() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GetAppTemplateContainerStartupProbe) int { return v.Port }).(pulumi.IntOutput)\n}", "func (o GroupContainerLivenessProbeHttpGetOutput) Port() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v GroupContainerLivenessProbeHttpGet) *int { return v.Port }).(pulumi.IntPtrOutput)\n}", "func (pe NoopFirewallClient) ExposePort(port int32) error {\n\treturn nil\n}", "func Port() int {\n\treturn appConfig.appPort\n}", "func (o ListenerOutput) ListenerPort() pulumi.IntOutput {\n\treturn o.ApplyT(func(v *Listener) pulumi.IntOutput { return v.ListenerPort }).(pulumi.IntOutput)\n}", "func (k Keeper) BindPort(ctx sdk.Context, portID string) error {\n\tcap := k.portKeeper.BindPort(ctx, portID)\n\treturn k.ClaimCapability(ctx, cap, host.PortPath(portID))\n}", "func (o BuildStrategySpecBuildStepsLivenessProbeTcpSocketPtrOutput) Port() BuildStrategySpecBuildStepsLivenessProbeTcpSocketPortPtrOutput {\n\treturn o.ApplyT(func(v *BuildStrategySpecBuildStepsLivenessProbeTcpSocket) *BuildStrategySpecBuildStepsLivenessProbeTcpSocketPort {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Port\n\t}).(BuildStrategySpecBuildStepsLivenessProbeTcpSocketPortPtrOutput)\n}", "func freePort() (uint16, error) {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tl, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer l.Close()\n\n\treturn uint16(l.Addr().(*net.TCPAddr).Port), nil\n}", "func freePort() (uint16, error) {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tl, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer l.Close()\n\n\treturn uint16(l.Addr().(*net.TCPAddr).Port), nil\n}", "func (o InstanceListenerEndpointOutput) Port() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v InstanceListenerEndpoint) *int { return v.Port }).(pulumi.IntPtrOutput)\n}", "func (c *Config) Port(port uint16) *Config {\n\tc.GetContext().Port = port\n\treturn c\n}", "func (mds *metadataService) Port() int {\n\treturn mds.listener.Addr().(*net.TCPAddr).Port\n}", "func WithPort(port int) Option {\n\treturn func(o *P) {\n\t\to.Port = port\n\t}\n}", "func (info *endpointsInfo) Port() (int, error) {\n\treturn int(info.port), nil\n}", "func (o BuildStrategySpecBuildStepsLivenessProbeHttpGetPtrOutput) Port() BuildStrategySpecBuildStepsLivenessProbeHttpGetPortPtrOutput {\n\treturn o.ApplyT(func(v *BuildStrategySpecBuildStepsLivenessProbeHttpGet) *BuildStrategySpecBuildStepsLivenessProbeHttpGetPort {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Port\n\t}).(BuildStrategySpecBuildStepsLivenessProbeHttpGetPortPtrOutput)\n}", "func (o BuildStrategySpecBuildStepsReadinessProbeTcpSocketPtrOutput) Port() BuildStrategySpecBuildStepsReadinessProbeTcpSocketPortPtrOutput {\n\treturn o.ApplyT(func(v *BuildStrategySpecBuildStepsReadinessProbeTcpSocket) *BuildStrategySpecBuildStepsReadinessProbeTcpSocketPort {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Port\n\t}).(BuildStrategySpecBuildStepsReadinessProbeTcpSocketPortPtrOutput)\n}", "func (o *IamLdapProviderAllOf) GetPort() int64 {\n\tif o == nil || o.Port == nil {\n\t\tvar ret int64\n\t\treturn ret\n\t}\n\treturn *o.Port\n}", "func (rp *ResolverPool) Port() int {\n\treturn 0\n}", "func (rp *ResolverPool) Port() int {\n\treturn 0\n}", "func (info *BaseEndpointInfo) Port() (int, error) {\n\treturn utilproxy.PortPart(info.Endpoint)\n}", "func (o GRPCHealthCheckResponsePtrOutput) Port() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *GRPCHealthCheckResponse) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Port\n\t}).(pulumi.IntPtrOutput)\n}", "func (o GetListenersListenerOutput) ListenerPort() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GetListenersListener) int { return v.ListenerPort }).(pulumi.IntOutput)\n}", "func (a QueryArg) GetPort(port int) uint16 {\n\tif a.ImpliedPort {\n\t\treturn uint16(port)\n\t}\n\treturn a.Port\n}", "func (o SecurityGroupRuleOutput) FromPort() pulumi.IntOutput {\n\treturn o.ApplyT(func(v *SecurityGroupRule) pulumi.IntOutput { return v.FromPort }).(pulumi.IntOutput)\n}", "func Port(port int) func(*Proxy) {\n\treturn func(r *Proxy) {\n\t\tr.port = port\n\t}\n}", "func (c *config) WithPort(port int) Config {\n\tc.port = port\n\treturn c\n}", "func (k Keeper) BindPort(ctx sdk.Context, portID string) error {\n\t_, ok := k.scopedKeeper.GetCapability(ctx, host.PortPath(portID))\n\tif ok {\n\t\treturn fmt.Errorf(\"port %s is already bound\", portID)\n\t}\n\tcap := k.portKeeper.BindPort(ctx, portID)\n\treturn k.ClaimCapability(ctx, cap, host.PortPath(portID))\n}", "func (o ClusterBuildStrategySpecBuildStepsStartupProbeHttpGetOutput) Port() ClusterBuildStrategySpecBuildStepsStartupProbeHttpGetPortOutput {\n\treturn o.ApplyT(func(v ClusterBuildStrategySpecBuildStepsStartupProbeHttpGet) ClusterBuildStrategySpecBuildStepsStartupProbeHttpGetPort {\n\t\treturn v.Port\n\t}).(ClusterBuildStrategySpecBuildStepsStartupProbeHttpGetPortOutput)\n}", "func (ctx *Context) HostWithPort() string {\r\n\tif ctx.R.Host != \"\" {\r\n\t\tif strings.Contains(ctx.R.Host, \":\") {\r\n\t\t\treturn ctx.R.Host\r\n\t\t}\r\n\t\treturn ctx.R.Host + \":80\"\r\n\t}\r\n\treturn \"localhost:80\"\r\n}", "func (c *Client) Port(p int) *Client {\n\tc.port = p\n\treturn c\n}", "func (p PandaproxyAPI) GetPort() int {\n\treturn p.Port\n}", "func Port() string {\n\treturn strconv.Itoa(app.Port)\n}", "func (o BuildStrategySpecBuildStepsReadinessProbeHttpGetPtrOutput) Port() BuildStrategySpecBuildStepsReadinessProbeHttpGetPortPtrOutput {\n\treturn o.ApplyT(func(v *BuildStrategySpecBuildStepsReadinessProbeHttpGet) *BuildStrategySpecBuildStepsReadinessProbeHttpGetPort {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Port\n\t}).(BuildStrategySpecBuildStepsReadinessProbeHttpGetPortPtrOutput)\n}", "func (o ServerGroupHealthCheckPtrOutput) HealthCheckConnectPort() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *ServerGroupHealthCheck) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.HealthCheckConnectPort\n\t}).(pulumi.IntPtrOutput)\n}", "func (o *LdapProvider) GetPort() int32 {\n\tif o == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\n\treturn o.Port\n}", "func (o ClusterBuildStrategySpecBuildStepsStartupProbeTcpSocketOutput) Port() ClusterBuildStrategySpecBuildStepsStartupProbeTcpSocketPortOutput {\n\treturn o.ApplyT(func(v ClusterBuildStrategySpecBuildStepsStartupProbeTcpSocket) ClusterBuildStrategySpecBuildStepsStartupProbeTcpSocketPort {\n\t\treturn v.Port\n\t}).(ClusterBuildStrategySpecBuildStepsStartupProbeTcpSocketPortOutput)\n}", "func MetricsPort(port uint) Option {\n\treturn optionFunc(func(r *runtime) {\n\t\tr.mPort = port\n\t})\n}", "func (o HTTP2HealthCheckOutput) PortSpecification() HTTP2HealthCheckPortSpecificationPtrOutput {\n\treturn o.ApplyT(func(v HTTP2HealthCheck) *HTTP2HealthCheckPortSpecification { return v.PortSpecification }).(HTTP2HealthCheckPortSpecificationPtrOutput)\n}", "func (g *GRPC) Port() int {\n\treturn g.lis.Addr().(*net.TCPAddr).Port\n}", "func GetPort() string {\n\treturn fmt.Sprintf(\":%d\", viper.GetInt(port))\n}", "func (cc ClusterConfig) Port(name string) uint32 {\n\tif name == cc.ID {\n\t\treturn uint32(cc.GatewayPort)\n\t}\n\tfor _, peer := range cc.WatchedPeers {\n\t\tif name == peer.ID {\n\t\t\treturn uint32(peer.GatewayPort)\n\t\t}\n\t}\n\treturn 8080 // dummy value for unknown clusters\n}" ]
[ "0.5946382", "0.5838031", "0.57817173", "0.5774734", "0.5774415", "0.574717", "0.5694374", "0.5687079", "0.56020105", "0.55426747", "0.54782814", "0.5443749", "0.54404604", "0.54351515", "0.5432953", "0.54073334", "0.5406503", "0.5379687", "0.5363278", "0.53539973", "0.5336573", "0.5313063", "0.5301213", "0.52885306", "0.5277937", "0.52733403", "0.52580553", "0.5239345", "0.52340233", "0.523164", "0.52263343", "0.519589", "0.5186571", "0.51721334", "0.5155926", "0.51544523", "0.51544523", "0.5143111", "0.5133118", "0.5124422", "0.5118093", "0.5112241", "0.5111284", "0.5099585", "0.50910383", "0.5090823", "0.508303", "0.5067778", "0.5059155", "0.5039102", "0.5035301", "0.5034713", "0.5031558", "0.5028477", "0.5025436", "0.50237393", "0.5022409", "0.5018713", "0.49976334", "0.4989351", "0.49763957", "0.49739072", "0.49709603", "0.49673477", "0.4958041", "0.49501282", "0.49497503", "0.49497503", "0.49479258", "0.49465433", "0.49375015", "0.4935164", "0.49350765", "0.49337196", "0.49335268", "0.49312174", "0.49308735", "0.49308735", "0.49150437", "0.48966333", "0.48959312", "0.48822284", "0.48798048", "0.4871035", "0.48698083", "0.48680943", "0.4856492", "0.48521215", "0.4844756", "0.48439407", "0.48423734", "0.48257366", "0.4819409", "0.48173994", "0.48108906", "0.47972697", "0.47967225", "0.47945186", "0.47914493", "0.47829404" ]
0.70723397
0
WithHealthCheckInterval returns the receiver adapter after changing the health check interval that will be used by the resources created by the adapter
func (a *Adapter) WithHealthCheckInterval(interval time.Duration) *Adapter { a.healthCheckInterval = interval return a }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *monitor) withProbeInterval(probeInterval time.Duration) *monitor {\n\tm.probeInterval = probeInterval\n\treturn m\n}", "func (o ServerGroupHealthCheckOutput) HealthCheckInterval() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v ServerGroupHealthCheck) *int { return v.HealthCheckInterval }).(pulumi.IntPtrOutput)\n}", "func (o GetServerGroupsGroupHealthCheckOutput) HealthCheckInterval() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GetServerGroupsGroupHealthCheck) int { return v.HealthCheckInterval }).(pulumi.IntOutput)\n}", "func (e *LifecycleEvent) SetHeartbeatInterval(interval int64) { e.heartbeatInterval = interval }", "func (o ServerGroupHealthCheckPtrOutput) HealthCheckInterval() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *ServerGroupHealthCheck) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.HealthCheckInterval\n\t}).(pulumi.IntPtrOutput)\n}", "func (a *Adapter) WithHealthCheckPath(path string) *Adapter {\n\ta.healthCheckPath = path\n\treturn a\n}", "func (a *Adapter) WithHealthCheckPort(port uint) *Adapter {\n\ta.healthCheckPort = port\n\treturn a\n}", "func (jm *JobManager) HeartbeatInterval() time.Duration {\n\treturn jm.heartbeatInterval\n}", "func WithInterval(interval time.Duration) BuilderOption {\n\treturn func(b *builder) error {\n\t\tb.checkInterval = interval\n\t\treturn nil\n\t}\n}", "func (c *configuration) HeartbeatIntervalInSecond() int {\n\treturn c.HeartbeatIntervalSecond\n}", "func WithPollInterval(after time.Duration) ReconcilerOption {\n\treturn func(r *Reconciler) {\n\t\tr.pollInterval = after\n\t}\n}", "func (a *adapter) HealthCheck() (string, error) {\n\terr := a.client.checkHealthy()\n\tif err == nil {\n\t\treturn model.Healthy, nil\n\t}\n\treturn model.Unhealthy, err\n}", "func (g *Gateway) heartbeatInterval() time.Duration {\n\tthreshold := g.HeartbeatOfflineThreshold\n\tif threshold <= 0 {\n\t\tthreshold = time.Duration(db.DefaultOfflineThreshold) * time.Second\n\t}\n\n\treturn threshold / 2\n}", "func (p *Poller) WithInterval(interval time.Duration) *Poller {\n\tif interval > 0 {\n\t\tp.interval = interval\n\t}\n\n\treturn p\n}", "func (r *ManagedServicePollRequest) Interval(value time.Duration) *ManagedServicePollRequest {\n\tr.interval = value\n\treturn r\n}", "func BufferHeartbeatInterval(Interval int) int {\n\tbuffer := math.Ceil(float64(Interval) * 0.05)\n\tbuffer = math.Min(buffer, 5)\n\treturn Interval + int(buffer)\n}", "func WithInterval(interval int) Option {\n\treturn func(c *config) {\n\t\tc.Interval = interval\n\t}\n}", "func WithInterval(interval int) Option {\n\treturn func(c *config) {\n\t\tc.Interval = interval\n\t}\n}", "func monitoringExporter(ctx context.Context, getRsc ResourceAvailable, refreshInterval time.Duration, logger *log.Logger) {\n\n\tlastRefresh := time.Now()\n\n\tresourceMonitor.Do(func() {\n\t\trefresh := time.NewTicker(30 * time.Second)\n\t\tdefer refresh.Stop()\n\n\t\tlastMsg := \"\"\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-refresh.C:\n\t\t\t\tmsg := getRsc.FetchMachineResources().String()\n\t\t\t\tif lastMsg != msg || time.Since(lastRefresh) > time.Duration(20*time.Minute) {\n\t\t\t\t\tlastRefresh = time.Now()\n\t\t\t\t\tlogger.Info(\"capacity\", \"available\", msg)\n\t\t\t\t\tlastMsg = msg\n\t\t\t\t}\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t})\n\n\trefresh := time.NewTicker(refreshInterval)\n\tdefer refresh.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-refresh.C:\n\t\t\t// The function will update our resource consumption gauges for the\n\t\t\t// host we are running on\n\t\t\tupdateGauges(getRsc.FetchMachineResources())\n\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func (r *ClusterPollRequest) Interval(value time.Duration) *ClusterPollRequest {\n\tr.interval = value\n\treturn r\n}", "func (a adapter) HealthCheck() (model.HealthStatus, error) {\n\tvar err error\n\tif a.registry.Credential == nil ||\n\t\tlen(a.registry.Credential.AccessKey) == 0 || len(a.registry.Credential.AccessSecret) == 0 {\n\t\tlog.Errorf(\"no credential to ping registry %s\", a.registry.URL)\n\t\treturn model.Unhealthy, nil\n\t}\n\tif err = a.PingGet(); err != nil {\n\t\tlog.Errorf(\"failed to ping registry %s: %v\", a.registry.URL, err)\n\t\treturn model.Unhealthy, nil\n\t}\n\treturn model.Healthy, nil\n}", "func NewHealthCheck(opt ...Option) *HealthCheck {\n\topts := GetOpts(opt...)\n\n\th := &HealthCheck{\n\t\tstatus: &healthStatus{},\n\t}\n\tif e, ok := opts[optionWithEngine].(*gin.Engine); ok {\n\t\th.Engine = e\n\t}\n\tif path, ok := opts[optionWithHealthPath].(string); ok {\n\t\th.HealthPath = path\n\t} else {\n\t\th.HealthPath = \"/ready\"\n\t}\n\tif handler, ok := opts[optionWithHealthHandler].(gin.HandlerFunc); ok {\n\t\th.Handler = handler\n\t} else {\n\t\th.Handler = h.DefaultHealthHandler()\n\t}\n\n\tif ticker, ok := opts[optionHealthTicker].(*time.Ticker); ok {\n\t\th.metricTicker = ticker\n\t} else {\n\t\th.metricTicker = time.NewTicker(DefaultHealthTickerDuration)\n\t}\n\n\treturn h\n}", "func (b *BuntBackend) Interval(interval time.Duration) *BuntBackend {\n\tb.interval = interval\n\treturn b\n}", "func (c *connAttrs) PingInterval() time.Duration {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\treturn c._pingInterval\n}", "func WithPollingInterval(d time.Duration) AggregatorOption {\n\treturn func(a *Aggregator) {\n\t\ta.pollingInterval = d\n\t}\n}", "func WithProbeInterval(d time.Duration) Option {\n\treturn withProbeInterval(d)\n}", "func (throttler *Throttler) refreshMySQLInventory(ctx context.Context) error {\n\n\t// distribute the query/threshold from the throttler down to the cluster settings and from there to the probes\n\tmetricsQuery := throttler.GetMetricsQuery()\n\tmetricsThreshold := throttler.MetricsThreshold.Load()\n\taddInstanceKey := func(tablet *topodatapb.Tablet, tabletHost string, tabletPort int, key *mysql.InstanceKey, clusterName string, clusterSettings *config.MySQLClusterConfigurationSettings, probes *mysql.Probes) {\n\t\tfor _, ignore := range clusterSettings.IgnoreHosts {\n\t\t\tif strings.Contains(key.StringCode(), ignore) {\n\t\t\t\tlog.Infof(\"Throttler: instance key ignored: %+v\", key)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif !key.IsValid() && !key.IsSelf() {\n\t\t\tlog.Infof(\"Throttler: read invalid instance key: [%+v] for cluster %+v\", key, clusterName)\n\t\t\treturn\n\t\t}\n\n\t\tprobe := &mysql.Probe{\n\t\t\tKey: *key,\n\t\t\tTablet: tablet,\n\t\t\tTabletHost: tabletHost,\n\t\t\tTabletPort: tabletPort,\n\t\t\tMetricQuery: clusterSettings.MetricQuery,\n\t\t\tCacheMillis: clusterSettings.CacheMillis,\n\t\t}\n\t\t(*probes)[*key] = probe\n\t}\n\n\tfor clusterName, clusterSettings := range config.Settings().Stores.MySQL.Clusters {\n\t\tclusterName := clusterName\n\t\tclusterSettings := clusterSettings\n\t\tclusterSettings.MetricQuery = metricsQuery\n\t\tclusterSettings.ThrottleThreshold.Store(metricsThreshold)\n\t\t// config may dynamically change, but internal structure (config.Settings().Stores.MySQL.Clusters in our case)\n\t\t// is immutable and can only be _replaced_. Hence, it's safe to read in a goroutine:\n\t\tgo func() {\n\t\t\tthrottler.mysqlClusterThresholds.Set(clusterName, math.Float64frombits(clusterSettings.ThrottleThreshold.Load()), cache.DefaultExpiration)\n\t\t\tclusterProbes := &mysql.ClusterProbes{\n\t\t\t\tClusterName: clusterName,\n\t\t\t\tIgnoreHostsCount: clusterSettings.IgnoreHostsCount,\n\t\t\t\tInstanceProbes: mysql.NewProbes(),\n\t\t\t}\n\n\t\t\tif clusterName == selfStoreName {\n\t\t\t\t// special case: just looking at this tablet's MySQL server\n\t\t\t\t// We will probe this \"cluster\" (of one server) is a special way.\n\t\t\t\taddInstanceKey(nil, \"\", 0, mysql.SelfInstanceKey, clusterName, clusterSettings, clusterProbes.InstanceProbes)\n\t\t\t\tthrottler.mysqlClusterProbesChan <- clusterProbes\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif !throttler.isLeader.Load() {\n\t\t\t\t// not the leader (primary tablet)? Then no more work for us.\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// The primary tablet is also in charge of collecting the shard's metrics\n\t\t\terr := func() error {\n\t\t\t\ttabletAliases, err := throttler.ts.FindAllTabletAliasesInShard(ctx, throttler.keyspace, throttler.shard)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfor _, tabletAlias := range tabletAliases {\n\t\t\t\t\ttablet, err := throttler.ts.GetTablet(ctx, tabletAlias)\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 throttler.throttleTabletTypesMap[tablet.Type] {\n\t\t\t\t\t\tkey := mysql.InstanceKey{Hostname: tablet.MysqlHostname, Port: int(tablet.MysqlPort)}\n\t\t\t\t\t\taddInstanceKey(tablet.Tablet, tablet.Hostname, int(tablet.PortMap[\"vt\"]), &key, clusterName, clusterSettings, clusterProbes.InstanceProbes)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthrottler.mysqlClusterProbesChan <- clusterProbes\n\t\t\t\treturn nil\n\t\t\t}()\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"refreshMySQLInventory: %+v\", err)\n\t\t\t}\n\t\t}()\n\t}\n\treturn nil\n}", "func (h ZmqBUF) SweepInterval() time.Duration {\n\ti, _ := strconv.Atoi(h.sweepinterval)\n\treturn time.Second * time.Duration(i)\n}", "func NewHealthCheck() jrpc2.Handler {\n\treturn handler.New(func(context.Context) HealthCheckResult {\n\t\treturn HealthCheckResult{Status: \"healthy\"}\n\t})\n}", "func handleHealthCheck(m *MicroService, d *net.Dialer) bool {\r\n\tchange := false\r\n\tfor i, inst := range m.Instances {\r\n\t\t_, err := d.Dial(\"tcp\", inst.Host)\r\n\t\tif err != nil {\r\n\t\t\tif !m.isBlacklisted(i) {\r\n\t\t\t\tm.blackList(i, true)\r\n\t\t\t\tlogInfo(\"Instance: \" + inst.Host + \" is now marked as DOWN\")\r\n\t\t\t\tchange = true\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tif m.isBlacklisted(i) {\r\n\t\t\t\tm.blackList(i, false)\r\n\t\t\t\tlogInfo(\"Instance: \" + inst.Host + \" is now marked as UP\")\r\n\t\t\t\tchange = true\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn change\r\n}", "func (o NotificationEndpointGrpcSettingsResponseOutput) ResendInterval() DurationResponseOutput {\n\treturn o.ApplyT(func(v NotificationEndpointGrpcSettingsResponse) DurationResponse { return v.ResendInterval }).(DurationResponseOutput)\n}", "func startPeriodicHealthCheck(m *MicroService, interval time.Duration, d *net.Dialer) {\r\n\tticker := time.NewTicker(interval)\r\n\tdefer ticker.Stop()\r\n\tfor t := range ticker.C {\r\n\t\tlogVerbose(\"Checking health of Service:\", m.Route, \" ---tick:\", t)\r\n\t\thandleHealthCheck(m, d)\r\n\t}\r\n}", "func (c *ClusterScalingScheduleCollector) Interval() time.Duration {\n\treturn c.interval\n}", "func delayedHealthCheck(check healthz.HealthChecker, clock clock.Clock, delay time.Duration) healthz.HealthChecker {\n\treturn delayedHealthzCheck{\n\t\tcheck,\n\t\tclock.Now().Add(delay),\n\t\tclock,\n\t}\n}", "func (c *Clock) AfterHeartbeatInterval() <-chan chan struct{} {\n\treturn newClockChan(c.HeartbeatInterval)\n}", "func NewBackendHealthCheck(options Options) *BackendHealthCheck {\n\treturn &BackendHealthCheck{\n\t\tOptions: options,\n\t\trequestTimeout: 5 * time.Second,\n\t}\n}", "func diffHealthCheck(c *Client, desired, actual *HealthCheck, opts ...dcl.ApplyOption) ([]healthCheckDiff, 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 []healthCheckDiff\n\tif !reflect.DeepEqual(desired.CheckIntervalSec, actual.CheckIntervalSec) {\n\t\tc.Config.Logger.Infof(\"Detected diff in CheckIntervalSec.\\nDESIRED: %v\\nACTUAL: %v\", desired.CheckIntervalSec, actual.CheckIntervalSec)\n\n\t\tdiffs = append(diffs, healthCheckDiff{\n\t\t\tUpdateOp: &updateHealthCheckUpdateOperation{},\n\t\t\tFieldName: \"CheckIntervalSec\",\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, healthCheckDiff{\n\t\t\tUpdateOp: &updateHealthCheckUpdateOperation{},\n\t\t\tFieldName: \"Description\",\n\t\t})\n\n\t}\n\tif !reflect.DeepEqual(desired.HealthyThreshold, actual.HealthyThreshold) {\n\t\tc.Config.Logger.Infof(\"Detected diff in HealthyThreshold.\\nDESIRED: %v\\nACTUAL: %v\", desired.HealthyThreshold, actual.HealthyThreshold)\n\n\t\tdiffs = append(diffs, healthCheckDiff{\n\t\t\tUpdateOp: &updateHealthCheckUpdateOperation{},\n\t\t\tFieldName: \"HealthyThreshold\",\n\t\t})\n\n\t}\n\tif compareHealthCheckHttp2HealthCheck(c, desired.Http2HealthCheck, actual.Http2HealthCheck) {\n\t\tc.Config.Logger.Infof(\"Detected diff in Http2HealthCheck.\\nDESIRED: %v\\nACTUAL: %v\", desired.Http2HealthCheck, actual.Http2HealthCheck)\n\n\t\tdiffs = append(diffs, healthCheckDiff{\n\t\t\tUpdateOp: &updateHealthCheckUpdateOperation{},\n\t\t\tFieldName: \"Http2HealthCheck\",\n\t\t})\n\n\t}\n\tif compareHealthCheckHttpHealthCheck(c, desired.HttpHealthCheck, actual.HttpHealthCheck) {\n\t\tc.Config.Logger.Infof(\"Detected diff in HttpHealthCheck.\\nDESIRED: %v\\nACTUAL: %v\", desired.HttpHealthCheck, actual.HttpHealthCheck)\n\n\t\tdiffs = append(diffs, healthCheckDiff{\n\t\t\tUpdateOp: &updateHealthCheckUpdateOperation{},\n\t\t\tFieldName: \"HttpHealthCheck\",\n\t\t})\n\n\t}\n\tif compareHealthCheckHttpsHealthCheck(c, desired.HttpsHealthCheck, actual.HttpsHealthCheck) {\n\t\tc.Config.Logger.Infof(\"Detected diff in HttpsHealthCheck.\\nDESIRED: %v\\nACTUAL: %v\", desired.HttpsHealthCheck, actual.HttpsHealthCheck)\n\n\t\tdiffs = append(diffs, healthCheckDiff{\n\t\t\tUpdateOp: &updateHealthCheckUpdateOperation{},\n\t\t\tFieldName: \"HttpsHealthCheck\",\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, healthCheckDiff{\n\t\t\tUpdateOp: &updateHealthCheckUpdateOperation{},\n\t\t\tFieldName: \"Name\",\n\t\t})\n\n\t}\n\tif compareHealthCheckSslHealthCheck(c, desired.SslHealthCheck, actual.SslHealthCheck) {\n\t\tc.Config.Logger.Infof(\"Detected diff in SslHealthCheck.\\nDESIRED: %v\\nACTUAL: %v\", desired.SslHealthCheck, actual.SslHealthCheck)\n\n\t\tdiffs = append(diffs, healthCheckDiff{\n\t\t\tUpdateOp: &updateHealthCheckUpdateOperation{},\n\t\t\tFieldName: \"SslHealthCheck\",\n\t\t})\n\n\t}\n\tif compareHealthCheckTcpHealthCheck(c, desired.TcpHealthCheck, actual.TcpHealthCheck) {\n\t\tc.Config.Logger.Infof(\"Detected diff in TcpHealthCheck.\\nDESIRED: %v\\nACTUAL: %v\", desired.TcpHealthCheck, actual.TcpHealthCheck)\n\n\t\tdiffs = append(diffs, healthCheckDiff{\n\t\t\tUpdateOp: &updateHealthCheckUpdateOperation{},\n\t\t\tFieldName: \"TcpHealthCheck\",\n\t\t})\n\n\t}\n\tif !reflect.DeepEqual(desired.Type, actual.Type) {\n\t\tc.Config.Logger.Infof(\"Detected diff in Type.\\nDESIRED: %v\\nACTUAL: %v\", desired.Type, actual.Type)\n\n\t\tdiffs = append(diffs, healthCheckDiff{\n\t\t\tUpdateOp: &updateHealthCheckUpdateOperation{},\n\t\t\tFieldName: \"Type\",\n\t\t})\n\n\t}\n\tif !reflect.DeepEqual(desired.UnhealthyThreshold, actual.UnhealthyThreshold) {\n\t\tc.Config.Logger.Infof(\"Detected diff in UnhealthyThreshold.\\nDESIRED: %v\\nACTUAL: %v\", desired.UnhealthyThreshold, actual.UnhealthyThreshold)\n\n\t\tdiffs = append(diffs, healthCheckDiff{\n\t\t\tUpdateOp: &updateHealthCheckUpdateOperation{},\n\t\t\tFieldName: \"UnhealthyThreshold\",\n\t\t})\n\n\t}\n\tif !reflect.DeepEqual(desired.TimeoutSec, actual.TimeoutSec) {\n\t\tc.Config.Logger.Infof(\"Detected diff in TimeoutSec.\\nDESIRED: %v\\nACTUAL: %v\", desired.TimeoutSec, actual.TimeoutSec)\n\n\t\tdiffs = append(diffs, healthCheckDiff{\n\t\t\tUpdateOp: &updateHealthCheckUpdateOperation{},\n\t\t\tFieldName: \"TimeoutSec\",\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 []healthCheckDiff\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 (m *Module) RefreshInterval(interval time.Duration) *Module {\n\tm.scheduler.Every(interval)\n\treturn m\n}", "func (hc *LegacyHealthCheckImpl) checkConn(hcc *legacyHealthCheckConn, name string) {\n\tdefer hc.connsWG.Done()\n\tdefer hc.finalizeConn(hcc)\n\n\t// Initial notification for downstream about the tablet existence.\n\thc.updateHealth(hcc.tabletStats.Copy(), hcc.conn)\n\thc.initialUpdatesWG.Done()\n\n\tretryDelay := hc.retryDelay\n\tfor {\n\t\tstreamCtx, streamCancel := context.WithCancel(hcc.ctx)\n\n\t\t// Setup a watcher that restarts the timer every time an update is received.\n\t\t// If a timeout occurs for a serving tablet, we make it non-serving and send\n\t\t// a status update. The stream is also terminated so it can be retried.\n\t\t// servingStatus feeds into the serving var, which keeps track of the serving\n\t\t// status transmitted by the tablet.\n\t\tservingStatus := make(chan bool, 1)\n\t\t// timedout is accessed atomically because there could be a race\n\t\t// between the goroutine that sets it and the check for its value\n\t\t// later.\n\t\ttimedout := sync2.NewAtomicBool(false)\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-servingStatus:\n\t\t\t\t\tcontinue\n\t\t\t\tcase <-time.After(hc.healthCheckTimeout):\n\t\t\t\t\ttimedout.Set(true)\n\t\t\t\t\tstreamCancel()\n\t\t\t\t\treturn\n\t\t\t\tcase <-streamCtx.Done():\n\t\t\t\t\t// If the stream is done, stop watching.\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\t// Read stream health responses.\n\t\thcc.stream(streamCtx, hc, func(shr *querypb.StreamHealthResponse) error {\n\t\t\t// We received a message. Reset the back-off.\n\t\t\tretryDelay = hc.retryDelay\n\t\t\t// Don't block on send to avoid deadlocks.\n\t\t\tselect {\n\t\t\tcase servingStatus <- shr.Serving:\n\t\t\tdefault:\n\t\t\t}\n\t\t\treturn hcc.processResponse(hc, shr)\n\t\t})\n\n\t\t// streamCancel to make sure the watcher goroutine terminates.\n\t\tstreamCancel()\n\n\t\t// If there was a timeout send an error. We do this after stream has returned.\n\t\t// This will ensure that this update prevails over any previous message that\n\t\t// stream could have sent.\n\t\tif timedout.Get() {\n\t\t\thcc.tabletStats.LastError = fmt.Errorf(\"healthcheck timed out (latest %v)\", hcc.lastResponseTimestamp)\n\t\t\thcc.setServingState(false, hcc.tabletStats.LastError.Error())\n\t\t\thc.updateHealth(hcc.tabletStats.Copy(), hcc.conn)\n\t\t\thcErrorCounters.Add([]string{hcc.tabletStats.Target.Keyspace, hcc.tabletStats.Target.Shard, topoproto.TabletTypeLString(hcc.tabletStats.Target.TabletType)}, 1)\n\t\t}\n\n\t\t// Streaming RPC failed e.g. because vttablet was restarted or took too long.\n\t\t// Sleep until the next retry is up or the context is done/canceled.\n\t\tselect {\n\t\tcase <-hcc.ctx.Done():\n\t\t\treturn\n\t\tcase <-time.After(retryDelay):\n\t\t\t// Exponentially back-off to prevent tight-loop.\n\t\t\tretryDelay *= 2\n\t\t\t// Limit the retry delay backoff to the health check timeout\n\t\t\tif retryDelay > hc.healthCheckTimeout {\n\t\t\t\tretryDelay = hc.healthCheckTimeout\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *ScalingScheduleCollector) Interval() time.Duration {\n\treturn c.interval\n}", "func (c *ClientOptions) SetHeartbeatInterval(d time.Duration) *ClientOptions {\n\tc.HeartbeatInterval = &d\n\treturn c\n}", "func NewHealthCheck(rt *app.Runtime) operations.HealthCheckHandler {\n\treturn &healthCheck{}\n}", "func (o NotificationEndpointGrpcSettingsOutput) ResendInterval() DurationPtrOutput {\n\treturn o.ApplyT(func(v NotificationEndpointGrpcSettings) *Duration { return v.ResendInterval }).(DurationPtrOutput)\n}", "func GetHealthCheck() *HealthCheck {\n\tonce.Do(func() {\n\t\tsingleton = newHealthCheck()\n\t})\n\treturn singleton\n}", "func (lbu *LoadBalanceUpdate) AddCheckInterval(i int) *LoadBalanceUpdate {\n\tlbu.mutation.AddCheckInterval(i)\n\treturn lbu\n}", "func (o NotificationEndpointGrpcSettingsPtrOutput) ResendInterval() DurationPtrOutput {\n\treturn o.ApplyT(func(v *NotificationEndpointGrpcSettings) *Duration {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ResendInterval\n\t}).(DurationPtrOutput)\n}", "func (o NotificationEndpointGrpcSettingsResponsePtrOutput) ResendInterval() DurationResponsePtrOutput {\n\treturn o.ApplyT(func(v *NotificationEndpointGrpcSettingsResponse) *DurationResponse {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.ResendInterval\n\t}).(DurationResponsePtrOutput)\n}", "func Interval(interval time.Duration) DefaultBackoffPolicyOption {\n\treturn func(dbp *DefaultBackoffPolicy) {\n\t\tdbp.Interval = interval\n\t\tdbp.MinWaitTime = 1 * interval\n\t\tdbp.MaxWaitTime = 30 * interval\n\t}\n}", "func (_SimpleSavingsWallet *SimpleSavingsWalletCaller) HeartbeatTimeout(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _SimpleSavingsWallet.contract.Call(opts, out, \"heartbeatTimeout\")\n\treturn *ret0, err\n}", "func RefreshInterval(interval time.Duration) {\n\tconstruct()\n\tupdater.Every(interval)\n}", "func JobPollingInterval(d time.Duration) WorkerOption {\n\treturn func(worker *Worker) {\n\t\tworker.jobPollingInterval = d\n\t}\n}", "func (ds *MqttDatasource) CheckHealth(ctx context.Context, req *backend.CheckHealthRequest) (*backend.CheckHealthResult, error) {\n\n\tinstance, err := ds.getInstance(req.PluginContext)\n\tif err != nil {\n\t\treturn &backend.CheckHealthResult{\n\t\t\tStatus: backend.HealthStatusError,\n\t\t\tMessage: err.Error(),\n\t\t}, nil\n\t}\n\n\tsettings, err := instance.Settings()\n\tif err != nil {\n\t\tlog.DefaultLogger.Error(\"CheckHealth\", err.Error())\n\t\treturn nil, err\n\t}\n\n\tlog.DefaultLogger.Info(\"CheckHealth\", \"PluginContext\", req.PluginContext, \"Settings\", settings)\n\n\tif ds.mqttClient.IsSameConnection(&settings) {\n\t\tds.mqttClient.Disconnect()\n\t}\n\tds.mqttClient = mqtt.NewMqttClient(&settings)\n\terr = ds.mqttClient.Connect()\n\tif err != nil {\n\t\treturn &backend.CheckHealthResult{\n\t\t\tStatus: backend.HealthStatusError,\n\t\t\tMessage: err.Error(),\n\t\t}, nil\n\t}\n\n\treturn &backend.CheckHealthResult{\n\t\tStatus: backend.HealthStatusOk,\n\t\tMessage: \"Mqtt client is working\",\n\t}, nil\n}", "func (c *Config) GetCheckInterval() int {\n\treturn c.CheckInterval\n}", "func GetHeartbeat(cfg *HeartbeatConfig) (*Heartbeat, error) {\n\tonce.Do(func() {\n\t\theartbeat = &Heartbeat{\n\t\t\tlock: make(chan struct{}, 1), // with buffer 1, no recursion supported\n\t\t\tcfg: cfg,\n\t\t\tschema: filter.DMHeartbeatSchema,\n\t\t\ttable: filter.DMHeartbeatTable,\n\t\t\tslavesTs: make(map[string]float64),\n\t\t\tlogger: log.With(zap.String(\"component\", \"heartbeat\")),\n\t\t}\n\t})\n\tif err := heartbeat.cfg.Equal(cfg); err != nil {\n\t\treturn nil, terror.Annotate(err, \"heartbeat config is different from previous used\")\n\t}\n\treturn heartbeat, nil\n}", "func (o AiFeatureStoreEntityTypeMonitoringConfigSnapshotAnalysisOutput) MonitoringInterval() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v AiFeatureStoreEntityTypeMonitoringConfigSnapshotAnalysis) *string { return v.MonitoringInterval }).(pulumi.StringPtrOutput)\n}", "func (options *CreateLoadBalancerMonitorOptions) SetInterval(interval int64) *CreateLoadBalancerMonitorOptions {\n\toptions.Interval = core.Int64Ptr(interval)\n\treturn options\n}", "func SetInterval(t time.Duration) Setting {\n\treturn func(cf *fetcherSetting) {\n\t\tcf.interval = t\n\t}\n}", "func WithInterval(t time.Duration) WorkerOption {\n\treturn func(w *workerOptions) {\n\t\tw.interval = t\n\t}\n}", "func (lbuo *LoadBalanceUpdateOne) AddCheckInterval(i int) *LoadBalanceUpdateOne {\n\tlbuo.mutation.AddCheckInterval(i)\n\treturn lbuo\n}", "func (client IotHubResourceClient) GetEndpointHealthSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func newHeartbeat(conn webwire.Socket, errLog *log.Logger) heartbeat {\n\treturn heartbeat{\n\t\tresetChan: make(chan struct{}, 1),\n\t\tstopChan: make(chan struct{}, 1),\n\t\tlock: sync.Mutex{},\n\t\tconn: conn,\n\t\terrLog: errLog,\n\t}\n}", "func withInterval(node *Interval) intervalOption {\n\treturn func(m *IntervalMutation) {\n\t\tm.oldValue = func(context.Context) (*Interval, error) {\n\t\t\treturn node, nil\n\t\t}\n\t\tm.id = &node.ID\n\t}\n}", "func newAdapter(config *AdapterConfig) (adapters.ListChecker, error) {\n\tvar u *url.URL\n\tvar err error\n\tif u, err = url.Parse(config.ProviderURL); err != nil {\n\t\t// bogus URL format\n\t\treturn nil, err\n\t}\n\n\ta := adapter{\n\t\tbackend: u,\n\t\tclosing: make(chan bool),\n\t\trefreshInterval: config.RefreshInterval,\n\t\tttl: config.TimeToLive,\n\t}\n\n\t// install an empty list\n\ta.setList([]*net.IPNet{})\n\n\t// load up the list synchronously so we're ready to accept traffic immediately\n\ta.refreshList()\n\n\t// crank up the async list refresher\n\tgo a.listRefresher()\n\n\treturn &a, nil\n}", "func WithRefreshInterval(value time.Duration) coptions.Opt {\n\treturn func(p coptions.Params) {\n\t\tif setter, ok := p.(refreshIntervalSetter); ok {\n\t\t\tsetter.SetChConfigRefreshInterval(value)\n\t\t}\n\t}\n}", "func getConfiguration(monitor models.Monitor) Configuration {\n\n\tproviderConfig, _ := monitor.Config.(*endpointmonitorv1alpha1.AppInsightsConfig)\n\n\tvar config Configuration\n\n\t// ExpectedStatusCode is configurable via Config, Default value 200\n\tif providerConfig != nil && providerConfig.StatusCode > 0 {\n\t\tconfig.expectedStatusCode = providerConfig.StatusCode\n\t} else {\n\t\tconfig.expectedStatusCode = AppInsightsStatusCodeDefaultValue\n\t}\n\n\t// isRetryEnabled is configurable via config, Default value true\n\tif providerConfig != nil {\n\t\tconfig.isRetryEnabled = providerConfig.RetryEnable\n\t} else {\n\t\tconfig.isRetryEnabled = AppInsightsRetryEnabledDefaultValue\n\t}\n\n\t// frequency is configurable via config, Default value 300\n\tif providerConfig != nil && providerConfig.StatusCode > 0 {\n\t\tconfig.frequency = int32(providerConfig.StatusCode)\n\t} else {\n\t\tconfig.frequency = AppInsightsFrequencyDefaultValue\n\t}\n\n\treturn config\n}", "func (jm *JobManager) WithHeartbeatInterval(interval time.Duration) *JobManager {\n\tjm.schedulerWorker.WithInterval(interval)\n\tjm.killHangingTasksWorker.WithInterval(interval)\n\tjm.heartbeatInterval = interval\n\treturn jm\n}", "func expandHealthCheck(c *Client, f *HealthCheck) (map[string]interface{}, error) {\n\tm := make(map[string]interface{})\n\tif v := f.CheckIntervalSec; !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"checkIntervalSec\"] = v\n\t}\n\tif v := f.Description; !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"description\"] = v\n\t}\n\tif v := f.HealthyThreshold; !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"healthyThreshold\"] = v\n\t}\n\tif v, err := expandHealthCheckHttp2HealthCheck(c, f.Http2HealthCheck); err != nil {\n\t\treturn nil, fmt.Errorf(\"error expanding Http2HealthCheck into http2HealthCheck: %w\", err)\n\t} else if !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"http2HealthCheck\"] = v\n\t}\n\tif v, err := expandHealthCheckHttpHealthCheck(c, f.HttpHealthCheck); err != nil {\n\t\treturn nil, fmt.Errorf(\"error expanding HttpHealthCheck into httpHealthCheck: %w\", err)\n\t} else if !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"httpHealthCheck\"] = v\n\t}\n\tif v, err := expandHealthCheckHttpsHealthCheck(c, f.HttpsHealthCheck); err != nil {\n\t\treturn nil, fmt.Errorf(\"error expanding HttpsHealthCheck into httpsHealthCheck: %w\", err)\n\t} else if !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"httpsHealthCheck\"] = v\n\t}\n\tif v := f.Name; !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"name\"] = v\n\t}\n\tif v, err := expandHealthCheckSslHealthCheck(c, f.SslHealthCheck); err != nil {\n\t\treturn nil, fmt.Errorf(\"error expanding SslHealthCheck into sslHealthCheck: %w\", err)\n\t} else if !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"sslHealthCheck\"] = v\n\t}\n\tif v, err := expandHealthCheckTcpHealthCheck(c, f.TcpHealthCheck); err != nil {\n\t\treturn nil, fmt.Errorf(\"error expanding TcpHealthCheck into tcpHealthCheck: %w\", err)\n\t} else if !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"tcpHealthCheck\"] = v\n\t}\n\tif v := f.Type; !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"type\"] = v\n\t}\n\tif v := f.UnhealthyThreshold; !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"unhealthyThreshold\"] = v\n\t}\n\tif v := f.TimeoutSec; !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"timeoutSec\"] = v\n\t}\n\tif v, err := dcl.EmptyValue(); err != nil {\n\t\treturn nil, fmt.Errorf(\"error expanding Region into region: %w\", err)\n\t} else if !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"region\"] = v\n\t}\n\tif v, err := dcl.EmptyValue(); err != nil {\n\t\treturn nil, fmt.Errorf(\"error expanding Project into project: %w\", err)\n\t} else if !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"project\"] = v\n\t}\n\tif v := f.SelfLink; !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"selfLink\"] = v\n\t}\n\tif v, err := dcl.EmptyValue(); err != nil {\n\t\treturn nil, fmt.Errorf(\"error expanding Location into location: %w\", err)\n\t} else if !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"location\"] = v\n\t}\n\n\treturn m, nil\n}", "func NewHealthCheck(rt *permissions.Runtime) operations.HealthCheckHandler {\n\treturn &healthCheck{}\n}", "func (a *SpecConfig) getAlertContainer() (*components.Container, error) {\n\timage := a.alert.Spec.AlertImage\n\tif image == \"\" {\n\t\timage = GetImageTag(a.alert.Spec.Version, \"blackduck-alert\")\n\t}\n\tcontainer, err := components.NewContainer(horizonapi.ContainerConfig{\n\t\tName: \"alert\",\n\t\tImage: image,\n\t\tPullPolicy: horizonapi.PullAlways,\n\t\tMinMem: a.alert.Spec.AlertMemory,\n\t\tMaxMem: a.alert.Spec.AlertMemory,\n\t})\n\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tcontainer.AddPort(horizonapi.PortConfig{\n\t\tContainerPort: *a.alert.Spec.Port,\n\t\tProtocol: horizonapi.ProtocolTCP,\n\t})\n\n\terr = container.AddVolumeMount(horizonapi.VolumeMountConfig{\n\t\tName: \"dir-alert\",\n\t\tMountPath: \"/opt/blackduck/alert/alert-config\",\n\t})\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tcontainer.AddEnv(horizonapi.EnvConfig{\n\t\tType: horizonapi.EnvFromConfigMap,\n\t\tFromName: utils.GetResourceName(a.alert.Name, util.AlertName, \"blackduck-config\"),\n\t})\n\n\tcontainer.AddEnv(horizonapi.EnvConfig{\n\t\tType: horizonapi.EnvFromSecret,\n\t\tFromName: utils.GetResourceName(a.alert.Name, util.AlertName, \"secret\"),\n\t})\n\n\tcontainer.AddLivenessProbe(horizonapi.ProbeConfig{\n\t\tActionConfig: horizonapi.ActionConfig{\n\t\t\tType: horizonapi.ActionTypeCommand,\n\t\t\tCommand: []string{\"/usr/local/bin/docker-healthcheck.sh\", \"https://localhost:8443/alert/api/about\"},\n\t\t},\n\t\tDelay: 240,\n\t\tTimeout: 10,\n\t\tInterval: 30,\n\t\tMinCountFailure: 5,\n\t})\n\n\treturn container, nil\n}", "func CleanupInterval(interval time.Duration) Option {\n\treturn func(lc *loadingCache) error {\n\t\tlc.cleanupInterval = interval\n\t\treturn nil\n\t}\n}", "func (check *HealthCheck) CheckHealth(brokerUpdates chan<- Update, clusterUpdates chan<- Update, stop <-chan struct{}) {\n\tmanageTopic := !check.config.NoTopicCreation\n\terr := check.connect(manageTopic, stop)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer check.close(manageTopic)\n\n\tcheck.randSrc = rand.NewSource(time.Now().UnixNano())\n\n\tlog.Info(\"starting health check loop\")\n\tticker := time.NewTicker(check.config.CheckInterval)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tbrokerStatus := check.checkBrokerHealth()\n\n\t\t\tdata, err := json.Marshal(brokerStatus)\n\t\t\tif err != nil {\n\t\t\t\tlog.Warn(\"Error while marshaling broker status: %s\", err.Error())\n\t\t\t\tdata = simpleStatus(brokerStatus.Status)\n\t\t\t}\n\n\t\t\tbrokerUpdates <- Update{brokerStatus.Status, data}\n\n\t\t\tif brokerStatus.Status == unhealthy {\n\t\t\t\tclusterUpdates <- Update{red, simpleStatus(red)}\n\t\t\t\tlog.Info(\"closing connection and reconnecting\")\n\t\t\t\terr := check.reconnect(stop)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Info(\"error while reconnecting:\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tlog.Info(\"reconnected\")\n\t\t\t} else {\n\t\t\t\tclusterStatus := check.checkClusterHealth()\n\t\t\t\tdata, err := json.Marshal(clusterStatus)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Warn(\"Error while marshaling cluster status: %s\", err.Error())\n\t\t\t\t\tdata = simpleStatus(clusterStatus.Status)\n\t\t\t\t}\n\n\t\t\t\tclusterUpdates <- Update{clusterStatus.Status, data}\n\t\t\t}\n\t\tcase <-stop:\n\t\t\treturn\n\t\t}\n\t}\n}", "func WithHeartbeatInterval(fn func(time.Duration) time.Duration) ServerOption {\n\treturn func(cfg *serverConfig) {\n\t\tcfg.heartbeatInterval = fn(cfg.heartbeatInterval)\n\t}\n}", "func (c *Check) Interval() time.Duration { return 0 }", "func (ml *ManagedListener) UpdateEndpointsWithBackoff() {\n\tvar ServicePrefix = fmt.Sprintf(\"Service %-32.32s\", ml.Key)\n\n\tTry := func() (err error) {\n\t\tdefer ml.Monitor()()\n\t\tml.UpdateEndpoints()\n\t\tif !ml.canListen() {\n\t\t\terr = fmt.Errorf(\"%s !canListen %v:%v\",\n\t\t\t\tServicePrefix,\n\t\t\t\tml.IPs,\n\t\t\t\tml.Port,\n\t\t\t)\n\t\t}\n\t\treturn\n\t}\n\n\tExpBackoff := ConfigureBackoff(5*time.Second, 1*time.Minute, 3*time.Minute, ml.Canceled)\n\n\tNotify := func(err error, t time.Duration) {\n\t\tlog.Printf(\"%v started %s elapsed %s break after %s\",\n\t\t\terr,\n\t\t\tExpBackoff.StartTime().Format(\"15.04.999\"),\n\t\t\tDurationString(ExpBackoff.GetElapsedTime()),\n\t\t\tDurationString(ExpBackoff.MaxElapsedTime))\n\t}\n\n\tvar err error\n\tfor {\n\t\tif err = backoff.RetryNotify(Try, ExpBackoff, Notify); err != nil {\n\t\t\tlog.Printf(\"%s accept retry timeout: %v\\n\", ServicePrefix, err)\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n}", "func (m *ItemListsItemItemsListItemItemRequestBuilder) GetActivitiesByInterval()(*ItemListsItemItemsItemGetActivitiesByIntervalRequestBuilder) {\n return NewItemListsItemItemsItemGetActivitiesByIntervalRequestBuilderInternal(m.pathParameters, m.requestAdapter)\n}", "func (o *NetworkLoadBalancerForwardingRuleTargetHealthCheck) SetCheckInterval(v int32) {\n\n\to.CheckInterval = &v\n\n}", "func (in *HealthService) GetWorkloadHealth(ctx context.Context, namespace, cluster, workload, rateInterval string, queryTime time.Time, w *models.Workload) (models.WorkloadHealth, error) {\n\tvar end observability.EndFunc\n\t_, end = observability.StartSpan(ctx, \"GetWorkloadHealth\",\n\t\tobservability.Attribute(\"package\", \"business\"),\n\t\tobservability.Attribute(\"namespace\", namespace),\n\t\tobservability.Attribute(\"workload\", workload),\n\t\tobservability.Attribute(\"rateInterval\", rateInterval),\n\t\tobservability.Attribute(\"queryTime\", queryTime),\n\t)\n\tdefer end()\n\n\t// Perf: do not bother fetching request rate if workload has no sidecar\n\tif !w.IstioSidecar && !w.IsGateway() {\n\t\treturn models.WorkloadHealth{\n\t\t\tWorkloadStatus: w.CastWorkloadStatus(),\n\t\t\tRequests: models.NewEmptyRequestHealth(),\n\t\t}, nil\n\t}\n\n\t// Add Telemetry info\n\trate, err := in.getWorkloadRequestsHealth(namespace, cluster, workload, rateInterval, queryTime, w)\n\treturn models.WorkloadHealth{\n\t\tWorkloadStatus: w.CastWorkloadStatus(),\n\t\tRequests: rate,\n\t}, err\n}", "func (c *Client) Health(ctx context.Context) (err error) {\n\t_, err = c.HealthEndpoint(ctx, nil)\n\treturn\n}", "func (r *RegisterMonitor) heartbeat() {\n\t// Trigger the health check passing. We don't need to retry this\n\t// since we do a couple tries within the TTL period.\n\tif err := r.Client.Agent().PassTTL(r.checkID(), \"\"); err != nil {\n\t\tif !strings.Contains(err.Error(), \"does not have associated\") {\n\t\t\tr.Logger.Printf(\"[WARN] proxy: heartbeat failed: %s\", err)\n\t\t}\n\t}\n}", "func MergeHealthcheckConfig(a, b Healthcheck) Healthcheck {\n\tresult := b\n\tif result.Interval == \"\" {\n\t\tresult.Interval = a.Interval\n\t}\n\tif result.Timeout == \"\" {\n\t\tresult.Timeout = a.Timeout\n\t}\n\tif len(result.Rules) == 0 {\n\t\tresult.Rules = a.Rules\n\t}\n\treturn result\n}", "func (o RouterBgpResponseOutput) KeepaliveInterval() pulumi.IntOutput {\n\treturn o.ApplyT(func(v RouterBgpResponse) int { return v.KeepaliveInterval }).(pulumi.IntOutput)\n}", "func (o AiFeatureStoreEntityTypeMonitoringConfigSnapshotAnalysisPtrOutput) MonitoringInterval() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *AiFeatureStoreEntityTypeMonitoringConfigSnapshotAnalysis) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.MonitoringInterval\n\t}).(pulumi.StringPtrOutput)\n}", "func (e *ExternalServiceList) GetHealthCheck(cfg *config.Config, buildTime, gitCommit, version string) (healthcheck.HealthCheck, error) {\n\n\t// Create healthcheck object with versionInfo\n\tversionInfo, err := healthcheck.NewVersionInfo(buildTime, gitCommit, version)\n\tif err != nil {\n\t\treturn healthcheck.HealthCheck{}, err\n\t}\n\thc := healthcheck.New(versionInfo, cfg.HealthCheckCriticalTimeout, cfg.HealthCheckInterval)\n\n\te.HealthCheck = true\n\n\treturn hc, nil\n}", "func (c client) ConfigureHealthCheck(hc loadbalancer.HealthCheck) (loadbalancer.Result, error) {\n\t_, l4Type := c.name.GetLookupAndType()\n\treq := ConfigureHealthCheckRequest{\n\t\tType: l4Type,\n\t\tHealthCheck: hc,\n\t}\n\tresp := ConfigureHealthCheckResponse{}\n\n\tif err := c.client.Call(\"L4.ConfigureHealthCheck\", req, &resp); err != nil {\n\t\treturn nil, err\n\t}\n\treturn clientResult(resp.Result), nil\n}", "func (client IotHubResourceClient) GetEndpointHealthResponder(resp *http.Response) (result EndpointHealthDataListResult, 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 stdlib) RetryInterval(time.Duration) {}", "func (c *Connection) healthCheck() {\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(healthCheckTime):\n\t\t\tif !c.Retrying {\n\t\t\t\t// capture current rmq host\n\t\t\t\toldHost := c.Config.Host\n\n\t\t\t\tif err := c.validateHost(); err != nil {\n\t\t\t\t\tkillService(\"failed to validate rmq host: \", err)\n\t\t\t\t}\n\n\t\t\t\t// this means new host was assigned meanwhile (in c.validateHost())\n\t\t\t\tif oldHost != c.Config.Host {\n\t\t\t\t\tif err := c.recreateConn(); err != nil {\n\t\t\t\t\t\tkillService(\"failed to recreate rmq connection: \", err)\n\t\t\t\t\t}\n\n\t\t\t\t\tlog.Println(\"rmq connected to new host: \", c.Config.Host)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func writeHealth(ctx context.Context, t *text.Text, delay time.Duration, connectionSignal chan string) {\n\treconnect := false\n\thealth := gjson.Get(getFromRPC(\"health\"), \"result\")\n\tt.Reset()\n\tif health.Exists() {\n\t\tt.Write(\"🟢 good\")\n\t} else {\n\t\tt.Write(\"🔴 no connection\")\n\t}\n\n\tticker := time.NewTicker(delay)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\thealth := gjson.Get(getFromRPC(\"health\"), \"result\")\n\t\t\tif health.Exists() {\n\t\t\t\tt.Write(\"🟢 good\")\n\t\t\t\tif reconnect == true {\n\t\t\t\t\tconnectionSignal <- \"reconnect\"\n\t\t\t\t\tconnectionSignal <- \"reconnect\"\n\t\t\t\t\tconnectionSignal <- \"reconnect\"\n\t\t\t\t\treconnect = false\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tt.Write(\"🔴 no connection\")\n\t\t\t\tif reconnect == false {\n\t\t\t\t\tconnectionSignal <- \"no_connection\"\n\t\t\t\t\tconnectionSignal <- \"no_connection\"\n\t\t\t\t\tconnectionSignal <- \"no_connection\"\n\t\t\t\t\treconnect = true\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func getContainersHealthCheck(cc v3.ComponentContainer) (livenesshandler corev1.Handler, readinesshandler corev1.Handler) {\n\t//log.Debugf(\"Container info is %v\", cc)\n\t//if !reflect.DeepEqual(cc.LivenessProbe, v3.HealthProbe{}) {\n\tif cc.LivenessProbe != nil {\n\t\tif cc.LivenessProbe.Exec != nil {\n\t\t\tif len(cc.LivenessProbe.Exec.Command) != 0 {\n\t\t\t\tvar commandlist []string\n\t\t\t\tfor _, i := range cc.LivenessProbe.Exec.Command {\n\t\t\t\t\tlist := strings.Split(i, \" \")\n\t\t\t\t\tcommandlist = append(commandlist, list...)\n\t\t\t\t}\n\t\t\t\tlivenesshandler = corev1.Handler{\n\t\t\t\t\tExec: &corev1.ExecAction{\n\t\t\t\t\t\tCommand: commandlist,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t} else if cc.LivenessProbe.HTTPGet != nil {\n\t\t\tif cc.LivenessProbe.HTTPGet.Path != \"\" && cc.LivenessProbe.HTTPGet.Port > 0 {\n\t\t\t\tlivenesshandler = corev1.Handler{\n\t\t\t\t\tHTTPGet: &corev1.HTTPGetAction{\n\t\t\t\t\t\tPath: cc.LivenessProbe.HTTPGet.Path,\n\t\t\t\t\t\tPort: intstr.IntOrString{\n\t\t\t\t\t\t\tType: intstr.Int,\n\t\t\t\t\t\t\tIntVal: int32(cc.LivenessProbe.HTTPGet.Port),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t} else if cc.LivenessProbe.TCPSocket != nil {\n\t\t\tif cc.LivenessProbe.TCPSocket.Port > 0 {\n\t\t\t\tlivenesshandler = corev1.Handler{\n\t\t\t\t\tTCPSocket: &corev1.TCPSocketAction{\n\t\t\t\t\t\tPort: intstr.IntOrString{\n\t\t\t\t\t\t\tIntVal: int32(cc.LivenessProbe.TCPSocket.Port),\n\t\t\t\t\t\t\tType: intstr.Int,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlivenesshandler = corev1.Handler{}\n\t\t}\n\t}\n\t//if !reflect.DeepEqual(cc.ReadinessProbe, v3.HealthProbe{}) {\n\tif cc.ReadinessProbe != nil {\n\t\tif cc.ReadinessProbe.Exec != nil {\n\t\t\tif len(cc.ReadinessProbe.Exec.Command) != 0 {\n\t\t\t\tvar commandlist []string\n\t\t\t\tfor _, i := range cc.ReadinessProbe.Exec.Command {\n\t\t\t\t\tlist := strings.Split(i, \" \")\n\t\t\t\t\tcommandlist = append(commandlist, list...)\n\t\t\t\t}\n\t\t\t\treadinesshandler = corev1.Handler{\n\t\t\t\t\tExec: &corev1.ExecAction{\n\t\t\t\t\t\tCommand: commandlist,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t} else if cc.ReadinessProbe.HTTPGet != nil {\n\t\t\tif cc.ReadinessProbe.HTTPGet.Path != \"\" && cc.ReadinessProbe.HTTPGet.Port > 0 {\n\t\t\t\treadinesshandler = corev1.Handler{\n\t\t\t\t\tHTTPGet: &corev1.HTTPGetAction{\n\t\t\t\t\t\tPath: cc.ReadinessProbe.HTTPGet.Path,\n\t\t\t\t\t\tPort: intstr.IntOrString{\n\t\t\t\t\t\t\tType: intstr.Int,\n\t\t\t\t\t\t\tIntVal: int32(cc.ReadinessProbe.HTTPGet.Port),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t} else if cc.ReadinessProbe.TCPSocket != nil {\n\t\t\tif cc.ReadinessProbe.TCPSocket.Port > 0 {\n\t\t\t\treadinesshandler = corev1.Handler{\n\t\t\t\t\tTCPSocket: &corev1.TCPSocketAction{\n\t\t\t\t\t\tPort: intstr.IntOrString{\n\t\t\t\t\t\t\tIntVal: int32(cc.ReadinessProbe.TCPSocket.Port),\n\t\t\t\t\t\t\tType: intstr.Int,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treadinesshandler = corev1.Handler{}\n\t\t}\n\t}\n\treturn\n}", "func WithHttpPollInterval(duration time.Duration) RPCOption {\n\treturn func(cfg *rpcConfig) error {\n\t\tcfg.httpPollInterval = duration\n\t\treturn nil\n\t}\n}", "func WithBootTimeRefreshInterval(bootTimeRefreshInterval time.Duration) Option {\n\treturn func(p Probe) {}\n}", "func (h *allocHealthWatcherHook) init() error {\n\t// No need to watch health as it's already set\n\tif h.healthSetter.HasHealth() {\n\t\th.logger.Trace(\"not watching; already has health set\")\n\t\treturn nil\n\t}\n\n\ttg := h.alloc.Job.LookupTaskGroup(h.alloc.TaskGroup)\n\tif tg == nil {\n\t\treturn fmt.Errorf(\"task group %q does not exist in job %q\", h.alloc.TaskGroup, h.alloc.Job.ID)\n\t}\n\n\th.isDeploy = h.alloc.DeploymentID != \"\"\n\n\t// No need to watch allocs for deployments that rely on operators\n\t// manually setting health\n\tif h.isDeploy && (tg.Update.IsEmpty() || tg.Update.HealthCheck == structs.UpdateStrategyHealthCheck_Manual) {\n\t\treturn nil\n\t}\n\n\t// Define the deadline, health method, min healthy time from the\n\t// deployment if this is a deployment; otherwise from the migration\n\t// strategy.\n\tdeadline, useChecks, minHealthyTime := getHealthParams(time.Now(), tg, h.isDeploy)\n\n\t// Create a context that is canceled when the tracker should shutdown.\n\tctx := context.Background()\n\tctx, h.cancelFn = context.WithCancel(ctx)\n\n\th.logger.Trace(\"watching\", \"deadline\", deadline, \"checks\", useChecks, \"min_healthy_time\", minHealthyTime)\n\t// Create a new tracker, start it, and watch for health results.\n\ttracker := allochealth.NewTracker(\n\t\tctx, h.logger, h.alloc, h.listener, h.consul, h.checkStore, minHealthyTime, useChecks,\n\t)\n\ttracker.Start()\n\n\t// Create a new done chan and start watching for health updates\n\th.watchDone = make(chan struct{})\n\tgo h.watchHealth(ctx, deadline, tracker, h.watchDone)\n\treturn nil\n}", "func flattenHttpsHealthCheck(c *Client, i interface{}) *HttpsHealthCheck {\n\tm, ok := i.(map[string]interface{})\n\tif !ok {\n\t\treturn nil\n\t}\n\tif len(m) == 0 {\n\t\treturn nil\n\t}\n\n\tr := &HttpsHealthCheck{}\n\tr.CheckIntervalSec = dcl.FlattenInteger(m[\"checkIntervalSec\"])\n\tif _, ok := m[\"checkIntervalSec\"]; !ok {\n\t\tc.Config.Logger.Info(\"Using default value for checkIntervalSec\")\n\t\tr.CheckIntervalSec = dcl.Int64(5)\n\t}\n\tr.Description = dcl.FlattenString(m[\"description\"])\n\tr.HealthyThreshold = dcl.FlattenInteger(m[\"healthyThreshold\"])\n\tif _, ok := m[\"healthyThreshold\"]; !ok {\n\t\tc.Config.Logger.Info(\"Using default value for healthyThreshold\")\n\t\tr.HealthyThreshold = dcl.Int64(2)\n\t}\n\tr.Host = dcl.FlattenString(m[\"host\"])\n\tr.Name = dcl.FlattenString(m[\"name\"])\n\tr.Port = dcl.FlattenInteger(m[\"port\"])\n\tif _, ok := m[\"port\"]; !ok {\n\t\tc.Config.Logger.Info(\"Using default value for port\")\n\t\tr.Port = dcl.Int64(443)\n\t}\n\tr.RequestPath = dcl.FlattenString(m[\"requestPath\"])\n\tif _, ok := m[\"requestPath\"]; !ok {\n\t\tc.Config.Logger.Info(\"Using default value for requestPath\")\n\t\tr.RequestPath = dcl.String(\"/\")\n\t}\n\tr.TimeoutSec = dcl.FlattenInteger(m[\"timeoutSec\"])\n\tif _, ok := m[\"timeoutSec\"]; !ok {\n\t\tc.Config.Logger.Info(\"Using default value for timeoutSec\")\n\t\tr.TimeoutSec = dcl.Int64(5)\n\t}\n\tr.UnhealthyThreshold = dcl.FlattenInteger(m[\"unhealthyThreshold\"])\n\tif _, ok := m[\"unhealthyThreshold\"]; !ok {\n\t\tc.Config.Logger.Info(\"Using default value for unhealthyThreshold\")\n\t\tr.UnhealthyThreshold = dcl.Int64(2)\n\t}\n\tr.Project = dcl.FlattenString(m[\"project\"])\n\tr.SelfLink = dcl.FlattenString(m[\"selfLink\"])\n\tr.CreationTimestamp = dcl.FlattenString(m[\"creationTimestamp\"])\n\n\treturn r\n}", "func (o *NetworkLoadBalancerForwardingRuleTargetHealthCheck) GetCheckInterval() *int32 {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\treturn o.CheckInterval\n\n}", "func (options *EditLoadBalancerMonitorOptions) SetInterval(interval int64) *EditLoadBalancerMonitorOptions {\n\toptions.Interval = core.Int64Ptr(interval)\n\treturn options\n}", "func (c *connAttrs) SetPingInterval(d time.Duration) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tc._pingInterval = d\n}", "func GetMetricAlerts() MetricAlerts {\n\tonce.Do(func() {\n\t\tviper.Set(\"metricAlerts\", metricAlerts)\n\t})\n\n\ttmp := viper.Get(\"metricAlerts\")\n\tma, ok := tmp.(MetricAlerts)\n\tif !ok {\n\t\tlog.Println(\"Error casting metricAlerts from Viper\")\n\t}\n\n\treturn ma\n}", "func (hc *LegacyHealthCheckImpl) AddTablet(tablet *topodatapb.Tablet, name string) {\n\tctx, cancelFunc := context.WithCancel(context.Background())\n\tkey := TabletToMapKey(tablet)\n\thcc := &legacyHealthCheckConn{\n\t\tctx: ctx,\n\t\ttabletStats: LegacyTabletStats{\n\t\t\tKey: key,\n\t\t\tTablet: tablet,\n\t\t\tName: name,\n\t\t\tTarget: &querypb.Target{},\n\t\t\tUp: true,\n\t\t},\n\t}\n\thc.mu.Lock()\n\tif hc.addrToHealth == nil {\n\t\t// already closed.\n\t\thc.mu.Unlock()\n\t\tcancelFunc()\n\t\treturn\n\t}\n\tif th, ok := hc.addrToHealth[key]; ok {\n\t\t// Something already exists at this key.\n\t\t// If it's the same tablet, something is wrong.\n\t\tif topoproto.TabletAliasEqual(th.latestTabletStats.Tablet.Alias, tablet.Alias) {\n\t\t\thc.mu.Unlock()\n\t\t\tlog.Warningf(\"refusing to add duplicate tablet %v for %v: %+v\", name, tablet.Alias.Cell, tablet)\n\t\t\tcancelFunc()\n\t\t\treturn\n\t\t}\n\t\t// If it's a different tablet, then we trust this new tablet that claims\n\t\t// it has taken over the host:port that the old tablet used to be on.\n\t\t// Remove the old tablet to clear the way.\n\t\thc.deleteConnLocked(key, th)\n\t}\n\thc.addrToHealth[key] = &legacyTabletHealth{\n\t\tcancelFunc: cancelFunc,\n\t\tlatestTabletStats: hcc.tabletStats,\n\t}\n\thc.initialUpdatesWG.Add(1)\n\thc.connsWG.Add(1)\n\thc.mu.Unlock()\n\n\tgo hc.checkConn(hcc, name)\n}", "func New(config HealthCheckConfig) *HealthCheck {\n\treturn &HealthCheck{\n\t\tbroker: &kafkaBrokerConnection{},\n\t\tzookeeper: &zkConnection{},\n\t\trandSrc: rand.NewSource(time.Now().UnixNano()),\n\t\tconfig: config,\n\t}\n}", "func (ac *addrConn) startHealthCheck(ctx context.Context) {\n\tvar healthcheckManagingState bool\n\tdefer func() {\n\t\tif !healthcheckManagingState {\n\t\t\t// todo (read code)\n\t\t\t// 连接 就绪!!!\n\t\t\tac.updateConnectivityState(connectivity.Ready, nil)\n\t\t}\n\t}()\n\n\tif ac.cc.dopts.disableHealthCheck {\n\t\treturn\n\t}\n\thealthCheckConfig := ac.cc.healthCheckConfig()\n\tif healthCheckConfig == nil {\n\t\treturn\n\t}\n\tif !ac.scopts.HealthCheckEnabled {\n\t\treturn\n\t}\n\thealthCheckFunc := ac.cc.dopts.healthCheckFunc\n\tif healthCheckFunc == nil {\n\t\t// The health package is not imported to set health check function.\n\t\t//\n\t\t// TODO: add a link to the health check doc in the error message.\n\t\tchannelz.Error(logger, ac.channelzID, \"Health check is requested but health check function is not set.\")\n\t\treturn\n\t}\n\n\thealthcheckManagingState = true\n\n\t// Set up the health check helper functions.\n\tcurrentTr := ac.transport\n\tnewStream := func(method string) (interface{}, error) {\n\t\tac.mu.Lock()\n\t\tif ac.transport != currentTr {\n\t\t\tac.mu.Unlock()\n\t\t\treturn nil, status.Error(codes.Canceled, \"the provided transport is no longer valid to use\")\n\t\t}\n\t\tac.mu.Unlock()\n\t\treturn newNonRetryClientStream(ctx, &StreamDesc{ServerStreams: true}, method, currentTr, ac)\n\t}\n\n\tsetConnectivityState := func(s connectivity.State, lastErr error) {\n\t\tac.mu.Lock()\n\t\tdefer ac.mu.Unlock()\n\t\tif ac.transport != currentTr {\n\t\t\treturn\n\t\t}\n\t\tac.updateConnectivityState(s, lastErr)\n\t}\n\n\t// Start the health checking stream.\n\t// 开始健康检查\n\tgo func() {\n\t\terr := ac.cc.dopts.healthCheckFunc(ctx, newStream, setConnectivityState, healthCheckConfig.ServiceName)\n\t\tif err != nil {\n\t\t\tif status.Code(err) == codes.Unimplemented {\n\t\t\t\tchannelz.Error(logger, ac.channelzID, \"Subchannel health check is unimplemented at server side, thus health check is disabled\")\n\t\t\t} else {\n\t\t\t\tchannelz.Errorf(logger, ac.channelzID, \"HealthCheckFunc exits with unexpected error %v\", err)\n\t\t\t}\n\t\t}\n\t}()\n}" ]
[ "0.53278637", "0.53035617", "0.5293944", "0.52465594", "0.50903225", "0.507159", "0.50312275", "0.5020901", "0.50069153", "0.49919906", "0.49600998", "0.49336693", "0.49049205", "0.4866939", "0.4840432", "0.46657336", "0.46649086", "0.46649086", "0.46628025", "0.46599445", "0.46590328", "0.46242118", "0.46219116", "0.46178687", "0.46010834", "0.45979926", "0.45623615", "0.4514922", "0.45144582", "0.45055804", "0.45010024", "0.44627705", "0.4457356", "0.44550872", "0.44490716", "0.44376376", "0.4433534", "0.44322404", "0.44279516", "0.44257015", "0.442408", "0.44234872", "0.44221407", "0.4383947", "0.43664467", "0.43563285", "0.43354762", "0.4331656", "0.43301862", "0.43284473", "0.43056288", "0.42886448", "0.42842343", "0.42728516", "0.42708984", "0.42680624", "0.4265365", "0.4263165", "0.42626685", "0.42614284", "0.4258955", "0.42575598", "0.4257139", "0.42519784", "0.42506284", "0.42491025", "0.42467004", "0.42443055", "0.42403838", "0.42388514", "0.42347625", "0.4231071", "0.42276672", "0.42124182", "0.42107922", "0.42106", "0.42088893", "0.41958725", "0.41957706", "0.419397", "0.4191576", "0.41904932", "0.41885838", "0.41860142", "0.4184479", "0.4183654", "0.41722205", "0.41680247", "0.4154033", "0.41481826", "0.41424632", "0.41401085", "0.41384393", "0.41383314", "0.4135047", "0.41322002", "0.41218433", "0.41146305", "0.4113349", "0.4107317" ]
0.73375005
0
WithCreationTimeout returns the receiver adapter after changing the creation timeout that is used as the max wait time for the creation of all the required AWS resources for a given Ingress
func (a *Adapter) WithCreationTimeout(interval time.Duration) *Adapter { a.creationTimeout = interval return a }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func WithTimeout(t time.Duration) apiOption {\n\treturn func(m *Management) {\n\t\tm.timeout = t\n\t}\n}", "func createFromResources(dp *v1alpha1.EdgeDataplane, da *v1alpha1.EdgeTraceabilityAgent) (*APIGatewayConfiguration, error) {\n\n\tcfg := &APIGatewayConfiguration{\n\t\tHost: dp.Spec.ApiGatewayManager.Host,\n\t\tPort: int(dp.Spec.ApiGatewayManager.Port),\n\t\tEnableAPICalls: da.Spec.Config.ProcessHeaders,\n\t\tPollInterval: 1 * time.Minute,\n\t}\n\n\tif dp.Spec.ApiGatewayManager.PollInterval != \"\" {\n\t\tresCfgPollInterval, err := time.ParseDuration(dp.Spec.ApiGatewayManager.PollInterval)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcfg.PollInterval = resCfgPollInterval\n\t}\n\treturn cfg, nil\n}", "func (o *IgroupInitiatorCreateParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (o *GetCreationTasksParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func createSecret(ingressType ingress.CallType, cn, ns string, ic IngressCredential) *v1.Secret {\n\tif ingressType == ingress.Mtls {\n\t\treturn &v1.Secret{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: cn,\n\t\t\t\tNamespace: ns,\n\t\t\t},\n\t\t\tData: map[string][]byte{\n\t\t\t\tgenericScrtCert: []byte(ic.ServerCert),\n\t\t\t\tgenericScrtKey: []byte(ic.PrivateKey),\n\t\t\t\tgenericScrtCaCert: []byte(ic.CaCert),\n\t\t\t},\n\t\t}\n\t}\n\treturn &v1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cn,\n\t\t\tNamespace: ns,\n\t\t},\n\t\tData: map[string][]byte{\n\t\t\ttlsScrtCert: []byte(ic.ServerCert),\n\t\t\ttlsScrtKey: []byte(ic.PrivateKey),\n\t\t},\n\t}\n}", "func CreateContextWithTimeout(r *protoTypes.Request) (context.Context, context.CancelFunc) {\n\tctx := context.Background()\n\tcancel := *new(context.CancelFunc)\n\n\tif IsEven(r) {\n\n\t\tfmt.Println(\"Request\", r.Id, \"timeout is\", evenTimeout)\n\t\tctx, cancel = context.WithTimeout(ctx, time.Duration(evenTimeout)*time.Second)\n\n\t} else {\n\n\t\tfmt.Println(\"Request\", r.Id, \"timeout is\", oddTimeout)\n\t\tctx, cancel = context.WithTimeout(ctx, time.Duration(oddTimeout)*time.Second)\n\n\t}\n\tfmt.Println(\"Time.Now == \", time.Now())\n\treturn ctx, cancel\n}", "func CreateIngressKubeSecret(t *testing.T, ctx framework.TestContext, credNames []string,\n\tingressType ingress.CallType, ingressCred IngressCredential) {\n\t// Get namespace for ingress gateway pod.\n\tistioCfg := istio.DefaultConfigOrFail(t, ctx)\n\tsystemNS := namespace.ClaimOrFail(t, ctx, istioCfg.SystemNamespace)\n\n\tif len(credNames) == 0 {\n\t\tt.Log(\"no credential names are specified, skip creating ingress secret\")\n\t\treturn\n\t}\n\t// Create Kubernetes secret for ingress gateway\n\tkubeAccessor := ctx.Environment().(*kube.Environment).Accessor\n\tfor _, cn := range credNames {\n\t\tsecret := createSecret(ingressType, cn, systemNS.Name(), ingressCred)\n\t\terr := kubeAccessor.CreateSecret(systemNS.Name(), secret)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to create secret (error: %s)\", err)\n\t\t}\n\t}\n\t// Check if Kubernetes secret is ready\n\tmaxRetryNumber := 5\n\tcheckRetryInterval := time.Second * 1\n\tfor _, cn := range credNames {\n\t\tt.Logf(\"Check ingress Kubernetes secret %s:%s...\", systemNS.Name(), cn)\n\t\tfor i := 0; i < maxRetryNumber; i++ {\n\t\t\t_, err := kubeAccessor.GetSecret(systemNS.Name()).Get(cn, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\ttime.Sleep(checkRetryInterval)\n\t\t\t} else {\n\t\t\t\tt.Logf(\"Secret %s:%s is ready.\", systemNS.Name(), cn)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}", "func IngressObjectWrapper(create IngressCreator) ObjectCreator {\n\treturn func(existing runtime.Object) (runtime.Object, error) {\n\t\tif existing != nil {\n\t\t\treturn create(existing.(*extensionsv1beta1.Ingress))\n\t\t}\n\t\treturn create(&extensionsv1beta1.Ingress{})\n\t}\n}", "func (o *CreateRoutingInstanceUsingPOSTParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func Timeout(timeout time.Duration, timeoutFunction OnTimeout) crOption {\n\treturn func(cr *ConsumerRegistration) *ConsumerRegistration {\n\t\tcr.timeout = timeout\n\t\tcr.onTimeout = timeoutFunction\n\t\treturn cr\n\t}\n}", "func (e *enqueForSelectingEgressIPAMNode) Create(evt event.CreateEvent, q workqueue.RateLimitingInterface) {\n\tnode, ok := evt.Object.(*corev1.Node)\n\tif !ok {\n\t\tlog.Info(\"unable convert event object to node,\", \"event\", evt)\n\t\treturn\n\t}\n\tegressIPAMs, err := e.r.getAllEgressIPAM()\n\tif err != nil {\n\t\tlog.Error(err, \"unable to get all EgressIPAM resources\")\n\t\treturn\n\t}\n\tfor _, egressIPAM := range egressIPAMs {\n\t\tif matches, _ := matchesNode(&egressIPAM, node); matches {\n\t\t\tq.Add(reconcile.Request{NamespacedName: types.NamespacedName{\n\t\t\t\tName: egressIPAM.GetName(),\n\t\t\t}})\n\t\t}\n\t}\n}", "func (o *EmployeeEntitlementGrantEntitlementsByTemplateGrantEntitlementsByTemplateParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (o *CapacityPoolGetParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func WithTimeout(ctx context.Context) (context.Context, context.CancelFunc) {\n\treturn context.WithTimeout(ctx, RetryAttempts*RetryInterval)\n}", "func NewTransport(opts *ClientOptions) *aws.Config {\n\tcfg := aws.NewConfig().WithHTTPClient(httputil.DefaultRestClient(opts.Debug))\n\tretryer := &transportRetryer{\n\t\tMaxTries: 3,\n\t}\n\tif opts.Log != nil {\n\t\tretryer.Log = opts.Log.New(\"transport\")\n\t}\n\treturn request.WithRetryer(cfg, retryer)\n}", "func (o GetAppTemplateContainerLivenessProbeOutput) Timeout() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GetAppTemplateContainerLivenessProbe) int { return v.Timeout }).(pulumi.IntOutput)\n}", "func resourceAwsRoute53ZoneAssociationCreate(d *schema.ResourceData, meta interface{}) error {\n\tr53 := meta.(*AWSClient).r53conn\n\n\treq := &route53.AssociateVPCWithHostedZoneInput{\n\t\tHostedZoneId: aws.String(d.Get(\"zone_id\").(string)),\n\t\tVPC: &route53.VPC{\n\t\t\tVPCId: aws.String(d.Get(\"vpc_id\").(string)),\n\t\t\tVPCRegion: aws.String(meta.(*AWSClient).region),\n\t\t},\n\t\tComment: aws.String(\"Managed by Terraform\"),\n\t}\n\tif w := d.Get(\"vpc_region\"); w != \"\" {\n\t\treq.VPC.VPCRegion = aws.String(w.(string))\n\t}\n\n\tlog.Printf(\"[DEBUG] Associating Route53 Private Zone %s with VPC %s with region %s\", *req.HostedZoneId, *req.VPC.VPCId, *req.VPC.VPCRegion)\n\tvar err error\n\tresp, err := r53.AssociateVPCWithHostedZone(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Store association id\n\td.SetId(fmt.Sprintf(\"%s:%s\", *req.HostedZoneId, *req.VPC.VPCId))\n\td.Set(\"vpc_region\", req.VPC.VPCRegion)\n\n\t// Wait until we are done initializing\n\twait := resource.StateChangeConf{\n\t\tDelay: 30 * time.Second,\n\t\tPending: []string{\"PENDING\"},\n\t\tTarget: []string{\"INSYNC\"},\n\t\tTimeout: 10 * time.Minute,\n\t\tMinTimeout: 2 * time.Second,\n\t\tRefresh: func() (result interface{}, state string, err error) {\n\t\t\tchangeRequest := &route53.GetChangeInput{\n\t\t\t\tId: aws.String(cleanChangeID(*resp.ChangeInfo.Id)),\n\t\t\t}\n\t\t\treturn resourceAwsGoRoute53Wait(getSubProvider(d, meta).(*AWSClient).r53conn, changeRequest)\n\t\t},\n\t}\n\t_, err = wait.WaitForState()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func makeDeploymentOptionsForIngestionBT(instance Instance, internal bool) DeploymentOptions {\n\treturn DeploymentOptions{\n\t\tinternal: internal,\n\t\tconfigMapName: fmt.Sprintf(\"gold-%s-ingestion-config-bt\", instance),\n\t\tconfigMapTemplate: \"golden/k8s-config-templates/ingest-config-template.json5\",\n\t}\n}", "func NewTimeout(cfg configs.Config) Middleware {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tctx, cancel := context.WithTimeout(\n\t\t\t\tcontext.Background(),\n\t\t\t\ttime.Duration(cfg.MaxSlowTimeout)*time.Millisecond,\n\t\t\t)\n\t\t\tdefer cancel()\n\n\t\t\tr = r.WithContext(ctx)\n\t\t\tdone := make(chan struct{})\n\t\t\tgo func() {\n\t\t\t\th.ServeHTTP(w, r)\n\t\t\t\tclose(done)\n\t\t\t}()\n\n\t\t\tselect {\n\t\t\tcase <-done:\n\t\t\tcase <-ctx.Done():\n\t\t\t\tresp := api.ErrorResponseBody{\n\t\t\t\t\tError: api.ErrorTooLongTimeout,\n\t\t\t\t}\n\t\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\t\t_ = json.NewEncoder(w).Encode(resp)\n\t\t\t}\n\t\t})\n\t}\n}", "func (o *GetIPLoadbalancingServiceNameTaskParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func NewTimeout(parameters ...wparams.ParamStorer) Error {\n\treturn newGenericError(nil, DefaultTimeout, wparams.NewParamStorer(parameters...))\n}", "func (o *CreateAccessPolicyParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (o *IgroupInitiatorCreateParams) WithTimeout(timeout time.Duration) *IgroupInitiatorCreateParams {\n\to.SetTimeout(timeout)\n\treturn o\n}", "func (o *AutoscaleStopInstancesByCrnParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func TestAllocRunner_TaskFailed_KillTG(t *testing.T) {\n\tci.Parallel(t)\n\n\talloc := mock.Alloc()\n\ttr := alloc.AllocatedResources.Tasks[alloc.Job.TaskGroups[0].Tasks[0].Name]\n\talloc.Job.TaskGroups[0].RestartPolicy.Attempts = 0\n\talloc.Job.TaskGroups[0].Tasks[0].RestartPolicy.Attempts = 0\n\n\t// Create two tasks in the task group\n\ttask := alloc.Job.TaskGroups[0].Tasks[0]\n\ttask.Name = \"task1\"\n\ttask.Driver = \"mock_driver\"\n\ttask.KillTimeout = 10 * time.Millisecond\n\ttask.Config = map[string]interface{}{\n\t\t\"run_for\": \"10s\",\n\t}\n\t// Set a service with check\n\ttask.Services = []*structs.Service{\n\t\t{\n\t\t\tName: \"fakservice\",\n\t\t\tPortLabel: \"http\",\n\t\t\tProvider: structs.ServiceProviderConsul,\n\t\t\tChecks: []*structs.ServiceCheck{\n\t\t\t\t{\n\t\t\t\t\tName: \"fakecheck\",\n\t\t\t\t\tType: structs.ServiceCheckScript,\n\t\t\t\t\tCommand: \"true\",\n\t\t\t\t\tInterval: 30 * time.Second,\n\t\t\t\t\tTimeout: 5 * time.Second,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\ttask2 := alloc.Job.TaskGroups[0].Tasks[0].Copy()\n\ttask2.Name = \"task 2\"\n\ttask2.Driver = \"mock_driver\"\n\ttask2.Config = map[string]interface{}{\n\t\t\"start_error\": \"fail task please\",\n\t}\n\talloc.Job.TaskGroups[0].Tasks = append(alloc.Job.TaskGroups[0].Tasks, task2)\n\talloc.AllocatedResources.Tasks[task.Name] = tr\n\talloc.AllocatedResources.Tasks[task2.Name] = tr\n\n\t// Make the alloc be part of a deployment\n\talloc.DeploymentID = uuid.Generate()\n\talloc.Job.TaskGroups[0].Update = structs.DefaultUpdateStrategy.Copy()\n\talloc.Job.TaskGroups[0].Update.HealthCheck = structs.UpdateStrategyHealthCheck_Checks\n\talloc.Job.TaskGroups[0].Update.MaxParallel = 1\n\talloc.Job.TaskGroups[0].Update.MinHealthyTime = 10 * time.Millisecond\n\talloc.Job.TaskGroups[0].Update.HealthyDeadline = 2 * time.Second\n\n\tcheckHealthy := &api.AgentCheck{\n\t\tCheckID: uuid.Generate(),\n\t\tStatus: api.HealthPassing,\n\t}\n\n\tconf, cleanup := testAllocRunnerConfig(t, alloc)\n\tdefer cleanup()\n\n\tconsulClient := conf.Consul.(*regMock.ServiceRegistrationHandler)\n\tconsulClient.AllocRegistrationsFn = func(allocID string) (*serviceregistration.AllocRegistration, error) {\n\t\treturn &serviceregistration.AllocRegistration{\n\t\t\tTasks: map[string]*serviceregistration.ServiceRegistrations{\n\t\t\t\ttask.Name: {\n\t\t\t\t\tServices: map[string]*serviceregistration.ServiceRegistration{\n\t\t\t\t\t\t\"123\": {\n\t\t\t\t\t\t\tService: &api.AgentService{Service: \"fakeservice\"},\n\t\t\t\t\t\t\tChecks: []*api.AgentCheck{checkHealthy},\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}, nil\n\t}\n\n\tar, err := NewAllocRunner(conf)\n\trequire.NoError(t, err)\n\tdefer destroy(ar)\n\tgo ar.Run()\n\tupd := conf.StateUpdater.(*MockStateUpdater)\n\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tlast := upd.Last()\n\t\tif last == nil {\n\t\t\treturn false, fmt.Errorf(\"No updates\")\n\t\t}\n\t\tif last.ClientStatus != structs.AllocClientStatusFailed {\n\t\t\treturn false, fmt.Errorf(\"got status %v; want %v\", last.ClientStatus, structs.AllocClientStatusFailed)\n\t\t}\n\n\t\t// Task One should be killed\n\t\tstate1 := last.TaskStates[task.Name]\n\t\tif state1.State != structs.TaskStateDead {\n\t\t\treturn false, fmt.Errorf(\"got state %v; want %v\", state1.State, structs.TaskStateDead)\n\t\t}\n\t\tif len(state1.Events) < 2 {\n\t\t\t// At least have a received and destroyed\n\t\t\treturn false, fmt.Errorf(\"Unexpected number of events\")\n\t\t}\n\n\t\tfound := false\n\t\tfor _, e := range state1.Events {\n\t\t\tif e.Type != structs.TaskSiblingFailed {\n\t\t\t\tfound = true\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false, fmt.Errorf(\"Did not find event %v\", structs.TaskSiblingFailed)\n\t\t}\n\n\t\t// Task Two should be failed\n\t\tstate2 := last.TaskStates[task2.Name]\n\t\tif state2.State != structs.TaskStateDead {\n\t\t\treturn false, fmt.Errorf(\"got state %v; want %v\", state2.State, structs.TaskStateDead)\n\t\t}\n\t\tif !state2.Failed {\n\t\t\treturn false, fmt.Errorf(\"task2 should have failed\")\n\t\t}\n\n\t\tif !last.DeploymentStatus.HasHealth() {\n\t\t\treturn false, fmt.Errorf(\"Expected deployment health to be non nil\")\n\t\t}\n\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.Fail(t, \"err: %v\", err)\n\t})\n}", "func (r *podResourceRecommender) estimateContainerResources(s *model.AggregateContainerState,\n\tcustomClient *kubernetes.Clientset, containerName string) RecommendedContainerResources {\n\n\t// fmt.Println(\"Container Name:\", containerName)\t\n\tif (containerName == \"pwitter-front\" || containerName == \"azure-vote-front\") {\n\t\t// custom metrics\n\t\tvar metrics MetricValueList\n\t\tmetricName := \"response_time\"\n\t\terr := getMetrics(customClient, &metrics, metricName)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Cannot get metric %s from Prometheus. Reason: %+v\", metricName, err)\n\t\t}\n\t\tresponse_time := parseValue(metrics.Items[0].Value)\n\t\t// fmt.Println(\"Response time:\", response_time)\n\t\t\n\t\tmetricName = \"response_count\"\n\t\terr = getMetrics(customClient, &metrics, metricName)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Cannot get metric %s from Prometheus. Reason: %+v\", metricName, err)\n\t\t}\n\t\tresponse_count := parseValue(metrics.Items[0].Value)\n\t\t// fmt.Println(\"Response count:\", response_count)\n\n\t\trequests := response_count - old_count\n\t\told_count = response_count // new count\n\t\trespTime := response_time\n\t\n\t\treq := float64(requests / (*control_replicasNum)) // active requests + queue of requests\n\t\trt := respTime // mean of the response times\n\t\terror := (*control_sla) - rt\n\t\tke := ((*control_a)-1)/((*control_pNom)-1)*error\n\t\tui := uiOld+(1-(*control_pNom))*ke\n\t\tut := ui+ke\n\t\n\t\ttargetCore := req*(ut-(*control_a1Nom)-1000.0*(*control_a2Nom))/(1000.0*(*control_a3Nom)*((*control_a1Nom)-ut))\n\t\n\t\tapproxCore := 0.0\n\t\tif error < 0 {\n\t\t\tapproxCore = *control_coreMax\n\t\t} else {\n\t\t\tapproxCore = math.Min(math.Max(math.Abs(targetCore), *podMinCPUMillicores/1000.0), *control_coreMax)\n\t\t}\n\t\t\n\t\tapproxUt := ((1000.0*(*control_a2Nom)+(*control_a1Nom))*req+1000.0*(*control_a1Nom)*(*control_a3Nom)*approxCore)/(req+1000.0*(*control_a3Nom)*approxCore)\n\t\tuiOld = approxUt-ke\n\n\t\t// fmt.Println(\n\t\t// \t\"== Controller debug ==\",\n\t\t// \t\"\\nRequests:\", req,\n\t\t// \t\"\\nResponse time:\", rt,\n\t\t// \t\" s\\nerror:\", error,\n\t\t// \t\"\\nke:\", ke,\n\t\t// \t\"\\nui:\", ui,\n\t\t// \t\"\\nut:\", ut,\n\t\t// \t\"\\ntargetCore:\", targetCore,\n\t\t// \t\"\\napproxCore:\", approxCore,\n\t\t// \t\"\\napproxUt:\", approxUt,\n\t\t// \t\"\\nuiOld:\", uiOld)\n\t\t\n\t\tfmt.Printf(\"%.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f\\n\",\n\t\t\treq, rt, error, ke, ui, ut, targetCore, approxCore, approxUt, uiOld)\n\n\t\treturn RecommendedContainerResources{\n\t\t\tTarget: model.Resources{\n\t\t\t\tmodel.ResourceCPU: model.CPUAmountFromCores(approxCore),\n\t\t\t\tmodel.ResourceMemory: model.MemoryAmountFromBytes(*control_memory*1024*1024),\n\t\t\t},\n\t\t\tLowerBound: model.Resources{\n\t\t\t\tmodel.ResourceCPU: model.CPUAmountFromCores(*podMinCPUMillicores/1000.0),\n\t\t\t\tmodel.ResourceMemory: model.MemoryAmountFromBytes(*control_memory*1024*1024),\n\t\t\t},\n\t\t\tUpperBound: model.Resources{\n\t\t\t\tmodel.ResourceCPU: model.CPUAmountFromCores(*control_coreMax),\n\t\t\t\tmodel.ResourceMemory: model.MemoryAmountFromBytes(*control_memory*1024*1024),\n\t\t\t},\n\t\t}\n\t} else {\n\t\treturn RecommendedContainerResources{\n\t\t\tr.targetEstimator.GetResourceEstimation(s),\n\t\t\tr.lowerBoundEstimator.GetResourceEstimation(s),\n\t\t\tr.upperBoundEstimator.GetResourceEstimation(s),\n\t\t}\n\t}\n\t\n}", "func (o *StorageServiceMetricsHintsInProgressGetParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (o *CreatePolicyParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (o *BackupsCreateStatusParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func NewAutoscaleStopInstancesByCrnParamsWithTimeout(timeout time.Duration) *AutoscaleStopInstancesByCrnParams {\n\tvar (\n\t\tforcedDefault = bool(false)\n\t)\n\treturn &AutoscaleStopInstancesByCrnParams{\n\t\tForced: &forcedDefault,\n\n\t\ttimeout: timeout,\n\t}\n}", "func (o *CreateRegionSubscriptionParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (r *Request) Timeout(d time.Duration) *Request {\n\tpanic(\"TODO\")\n\treturn r\n}", "func (o *PetCreateParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (c completedConfig) New() (*NamespaceReservationServer, error) {\n\tgenericServer, err := c.GenericConfig.New(\"kubernetes-namespace-reservation\", genericapiserver.EmptyDelegate) // completion is done in Complete, no need for a second time\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts := &NamespaceReservationServer{\n\t\tGenericAPIServer: genericServer,\n\t}\n\n\tinClusterConfig, err := restclient.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, versionMap := range admissionHooksByGroupThenVersion(c.ExtraConfig.AdmissionHooks...) {\n\t\taccessor := meta.NewAccessor()\n\t\tversionInterfaces := &meta.VersionInterfaces{\n\t\t\tObjectConvertor: Scheme,\n\t\t\tMetadataAccessor: accessor,\n\t\t}\n\t\tinterfacesFor := func(version schema.GroupVersion) (*meta.VersionInterfaces, error) {\n\t\t\tif version != admissionv1alpha1.SchemeGroupVersion {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected version %v\", version)\n\t\t\t}\n\t\t\treturn versionInterfaces, nil\n\t\t}\n\t\trestMapper := meta.NewDefaultRESTMapper([]schema.GroupVersion{admissionv1alpha1.SchemeGroupVersion}, interfacesFor)\n\t\t// TODO we're going to need a later k8s.io/apiserver so that we can get discovery to list a different group version for\n\t\t// our endpoint which we'll use to back some custom storage which will consume the AdmissionReview type and give back the correct response\n\t\tapiGroupInfo := genericapiserver.APIGroupInfo{\n\t\t\tGroupMeta: apimachinery.GroupMeta{\n\t\t\t\t// filled in later\n\t\t\t\t//GroupVersion: admissionVersion,\n\t\t\t\t//GroupVersions: []schema.GroupVersion{admissionVersion},\n\n\t\t\t\tSelfLinker: runtime.SelfLinker(accessor),\n\t\t\t\tRESTMapper: restMapper,\n\t\t\t\tInterfacesFor: interfacesFor,\n\t\t\t\tInterfacesByVersion: map[schema.GroupVersion]*meta.VersionInterfaces{\n\t\t\t\t\tadmissionv1alpha1.SchemeGroupVersion: versionInterfaces,\n\t\t\t\t},\n\t\t\t},\n\t\t\tVersionedResourcesStorageMap: map[string]map[string]rest.Storage{},\n\t\t\t// TODO unhardcode this. It was hardcoded before, but we need to re-evaluate\n\t\t\tOptionsExternalVersion: &schema.GroupVersion{Version: \"v1\"},\n\t\t\tScheme: Scheme,\n\t\t\tParameterCodec: metav1.ParameterCodec,\n\t\t\tNegotiatedSerializer: Codecs,\n\t\t\tSubresourceGroupVersionKind: map[string]schema.GroupVersionKind{\n\t\t\t\t\"namespacereservations\": admissionv1alpha1.SchemeGroupVersion.WithKind(\"AdmissionReview\"),\n\t\t\t},\n\t\t}\n\n\t\tfor _, admissionHooks := range versionMap {\n\t\t\tfor i := range admissionHooks {\n\t\t\t\tadmissionHook := admissionHooks[i]\n\t\t\t\tadmissionResource, singularResourceType := admissionHook.Resource()\n\t\t\t\tadmissionVersion := admissionResource.GroupVersion()\n\n\t\t\t\trestMapper.AddSpecific(\n\t\t\t\t\tadmissionv1alpha1.SchemeGroupVersion.WithKind(\"AdmissionReview\"),\n\t\t\t\t\tadmissionResource,\n\t\t\t\t\tadmissionVersion.WithResource(singularResourceType),\n\t\t\t\t\tmeta.RESTScopeRoot)\n\n\t\t\t\t// just overwrite the groupversion with a random one. We don't really care or know.\n\t\t\t\tapiGroupInfo.GroupMeta.GroupVersions = append(apiGroupInfo.GroupMeta.GroupVersions, admissionVersion)\n\n\t\t\t\tadmissionReview := admissionreview.NewREST(admissionHook.Admit)\n\t\t\t\tv1alpha1storage := map[string]rest.Storage{\n\t\t\t\t\tadmissionResource.Resource: admissionReview,\n\t\t\t\t}\n\t\t\t\tapiGroupInfo.VersionedResourcesStorageMap[admissionVersion.Version] = v1alpha1storage\n\n\t\t\t\ts.GenericAPIServer.AddPostStartHookOrDie(\n\t\t\t\t\tfmt.Sprintf(\"%s.%s.%s-init\", admissionResource.Resource, admissionResource.Version, admissionResource.Group),\n\t\t\t\t\tfunc(context genericapiserver.PostStartHookContext) error {\n\t\t\t\t\t\treturn admissionHook.Initialize(inClusterConfig, context.StopCh)\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\t// just prefer the first one in the list for consistency\n\t\tapiGroupInfo.GroupMeta.GroupVersion = apiGroupInfo.GroupMeta.GroupVersions[0]\n\n\t\tif err := s.GenericAPIServer.InstallAPIGroup(&apiGroupInfo); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn s, nil\n}", "func WrapWithTimeout(cause error, parameters ...wparams.ParamStorer) Error {\n\treturn newGenericError(cause, DefaultTimeout, wparams.NewParamStorer(parameters...))\n}", "func NewServiceUnavailable(cause error) ServiceUnavailable { return ServiceUnavailable(cause.Error()) }", "func (p *MockProvisionerClient) Timeout() time.Duration {\n\treturn 30 * time.Second\n}", "func (r *Reconciler) createResource(ctx context.Context, resourceName string, serverClient k8sclient.Client) (runtime.Object, error) {\n\tif r.extraParams == nil {\n\t\tr.extraParams = map[string]string{}\n\t}\n\tr.extraParams[\"MonitoringKey\"] = r.Config.GetLabelSelector()\n\tr.extraParams[\"Namespace\"] = r.Config.GetOperatorNamespace()\n\n\ttemplateHelper := NewTemplateHelper(r.extraParams)\n\tresource, err := templateHelper.CreateResource(resourceName)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"createResource failed: %w\", err)\n\t}\n\n\tmetaObj, err := meta.Accessor(resource)\n\tif err == nil {\n\t\towner.AddIntegreatlyOwnerAnnotations(metaObj, r.installation)\n\t}\n\n\terr = serverClient.Create(ctx, resource)\n\tif err != nil {\n\t\tif !k8serr.IsAlreadyExists(err) {\n\t\t\treturn nil, fmt.Errorf(\"error creating resource: %w\", err)\n\t\t}\n\t}\n\n\treturn resource, nil\n}", "func (o *CreateRunbookRunCreateParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (r *NamespaceTemplateReconciler) createadditionalresources(ctx context.Context,\n\tnsName string, nstObj megav1.NamespaceTemplate, options map[string]string) error {\n\n\t// provision pods\n\tvar p v1.Pod\n\tkey := types.NamespacedName{Namespace: nsName, Name: nstObj.Spec.AddResources.Pod.Name}\n\n\tif err := r.Get(ctx, key, &p); err != nil {\n\t\tfmt.Printf(\"pod not found, creating new\\n\")\n\t\t// assume that the error is \"pod doesnt exist\". in theory, err can be due to other issues as well\n\t\tnewPod := v1.Pod{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: nsName,\n\t\t\t\tName: nstObj.Spec.AddResources.Pod.Name,\n\t\t\t\tLabels: options,\n\t\t\t},\n\t\t\tSpec: nstObj.Spec.AddResources.Pod.Spec,\n\t\t}\n\t\tfmt.Printf(\"dumping pod spec in namespace %s: %+v\\n\", nsName, newPod.Spec)\n\n\t\tif err := r.Create(ctx, &newPod); err != nil {\n\t\t\tfmt.Printf(\"unable to create pod due to %v\\n\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// provision secrets\n\tvar s v1.Secret\n\tkey = types.NamespacedName{Namespace: nsName, Name: nstObj.Spec.AddResources.Secret.Name}\n\tif err := r.Get(ctx, key, &s); err != nil {\n\t\tfmt.Printf(\"secret not found, creating new\\n\")\n\t\tsecret := &v1.Secret{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: nsName,\n\t\t\t\tName: nstObj.Spec.AddResources.Secret.Name,\n\t\t\t\tLabels: options,\n\t\t\t},\n\t\t\tData: nstObj.Spec.AddResources.Secret.Data,\n\t\t\tStringData: nstObj.Spec.AddResources.Secret.StringData,\n\t\t}\n\t\tif err := r.Create(ctx, secret); err != nil {\n\t\t\tfmt.Printf(\"unable to create secret due to %v\\n\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// provision LimitRange\n\tvar lr v1.LimitRange\n\tkey = types.NamespacedName{Namespace: nsName, Name: nstObj.Spec.AddResources.LimitRange.Name}\n\tif err := r.Get(ctx, key, &lr); err != nil {\n\t\tfmt.Printf(\"limitrange not found, creating new\\n\")\n\t\tlimitrange := &v1.LimitRange{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: nsName,\n\t\t\t\tName: nstObj.Spec.AddResources.LimitRange.Name,\n\t\t\t\tLabels: options,\n\t\t\t},\n\t\t\tSpec: nstObj.Spec.AddResources.LimitRange.Spec,\n\t\t}\n\t\tif err := r.Create(ctx, limitrange); err != nil {\n\t\t\tfmt.Printf(\"unable to create Limitrange due to %v\\n\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (o *GetIPAMsubnetsParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (o GetAppTemplateContainerStartupProbeOutput) Timeout() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GetAppTemplateContainerStartupProbe) int { return v.Timeout }).(pulumi.IntOutput)\n}", "func resourceVolterraNetworkInterfaceCreate(d *schema.ResourceData, meta interface{}) error {\n\tclient := meta.(*APIClient)\n\n\tcreateMeta := &ves_io_schema.ObjectCreateMetaType{}\n\tcreateSpec := &ves_io_schema_network_interface.CreateSpecType{}\n\tcreateReq := &ves_io_schema_network_interface.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//interface_choice\n\n\tinterfaceChoiceTypeFound := false\n\n\tif v, ok := d.GetOk(\"dedicated_interface\"); ok && !interfaceChoiceTypeFound {\n\n\t\tinterfaceChoiceTypeFound = true\n\t\tinterfaceChoiceInt := &ves_io_schema_network_interface.CreateSpecType_DedicatedInterface{}\n\t\tinterfaceChoiceInt.DedicatedInterface = &ves_io_schema_network_interface.DedicatedInterfaceType{}\n\t\tcreateSpec.InterfaceChoice = interfaceChoiceInt\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\t// device\n\n\t\t\tif v, ok := cs[\"device\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tinterfaceChoiceInt.DedicatedInterface.Device = v.(string)\n\t\t\t}\n\n\t\t\t// monitoring_choice\n\n\t\t\tmonitoringChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"monitor\"]; ok && !isIntfNil(v) && !monitoringChoiceTypeFound {\n\n\t\t\t\tmonitoringChoiceTypeFound = true\n\t\t\t\t_ = v\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"monitor_disabled\"]; ok && !isIntfNil(v) && !monitoringChoiceTypeFound {\n\n\t\t\t\tmonitoringChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tmonitoringChoiceInt := &ves_io_schema_network_interface.DedicatedInterfaceType_MonitorDisabled{}\n\t\t\t\t\tmonitoringChoiceInt.MonitorDisabled = &ves_io_schema.Empty{}\n\t\t\t\t\tinterfaceChoiceInt.DedicatedInterface.MonitoringChoice = monitoringChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// mtu\n\n\t\t\tif v, ok := cs[\"mtu\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tinterfaceChoiceInt.DedicatedInterface.Mtu = uint32(v.(int))\n\t\t\t}\n\n\t\t\t// node_choice\n\n\t\t\tnodeChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"cluster\"]; ok && !isIntfNil(v) && !nodeChoiceTypeFound {\n\n\t\t\t\tnodeChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tnodeChoiceInt := &ves_io_schema_network_interface.DedicatedInterfaceType_Cluster{}\n\t\t\t\t\tnodeChoiceInt.Cluster = &ves_io_schema.Empty{}\n\t\t\t\t\tinterfaceChoiceInt.DedicatedInterface.NodeChoice = nodeChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"node\"]; ok && !isIntfNil(v) && !nodeChoiceTypeFound {\n\n\t\t\t\tnodeChoiceTypeFound = true\n\t\t\t\tnodeChoiceInt := &ves_io_schema_network_interface.DedicatedInterfaceType_Node{}\n\n\t\t\t\tinterfaceChoiceInt.DedicatedInterface.NodeChoice = nodeChoiceInt\n\n\t\t\t\tnodeChoiceInt.Node = v.(string)\n\n\t\t\t}\n\n\t\t\t// primary_choice\n\n\t\t\tprimaryChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"is_primary\"]; ok && !isIntfNil(v) && !primaryChoiceTypeFound {\n\n\t\t\t\tprimaryChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tprimaryChoiceInt := &ves_io_schema_network_interface.DedicatedInterfaceType_IsPrimary{}\n\t\t\t\t\tprimaryChoiceInt.IsPrimary = &ves_io_schema.Empty{}\n\t\t\t\t\tinterfaceChoiceInt.DedicatedInterface.PrimaryChoice = primaryChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"not_primary\"]; ok && !isIntfNil(v) && !primaryChoiceTypeFound {\n\n\t\t\t\tprimaryChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tprimaryChoiceInt := &ves_io_schema_network_interface.DedicatedInterfaceType_NotPrimary{}\n\t\t\t\t\tprimaryChoiceInt.NotPrimary = &ves_io_schema.Empty{}\n\t\t\t\t\tinterfaceChoiceInt.DedicatedInterface.PrimaryChoice = primaryChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// priority\n\n\t\t\tif v, ok := cs[\"priority\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tinterfaceChoiceInt.DedicatedInterface.Priority = uint32(v.(int))\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tif v, ok := d.GetOk(\"dedicated_management_interface\"); ok && !interfaceChoiceTypeFound {\n\n\t\tinterfaceChoiceTypeFound = true\n\t\tinterfaceChoiceInt := &ves_io_schema_network_interface.CreateSpecType_DedicatedManagementInterface{}\n\t\tinterfaceChoiceInt.DedicatedManagementInterface = &ves_io_schema_network_interface.DedicatedManagementInterfaceType{}\n\t\tcreateSpec.InterfaceChoice = interfaceChoiceInt\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\t// device\n\n\t\t\tif v, ok := cs[\"device\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tinterfaceChoiceInt.DedicatedManagementInterface.Device = v.(string)\n\t\t\t}\n\n\t\t\t// mtu\n\n\t\t\tif v, ok := cs[\"mtu\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tinterfaceChoiceInt.DedicatedManagementInterface.Mtu = uint32(v.(int))\n\t\t\t}\n\n\t\t\t// node_choice\n\n\t\t\tnodeChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"cluster\"]; ok && !isIntfNil(v) && !nodeChoiceTypeFound {\n\n\t\t\t\tnodeChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tnodeChoiceInt := &ves_io_schema_network_interface.DedicatedManagementInterfaceType_Cluster{}\n\t\t\t\t\tnodeChoiceInt.Cluster = &ves_io_schema.Empty{}\n\t\t\t\t\tinterfaceChoiceInt.DedicatedManagementInterface.NodeChoice = nodeChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"node\"]; ok && !isIntfNil(v) && !nodeChoiceTypeFound {\n\n\t\t\t\tnodeChoiceTypeFound = true\n\t\t\t\tnodeChoiceInt := &ves_io_schema_network_interface.DedicatedManagementInterfaceType_Node{}\n\n\t\t\t\tinterfaceChoiceInt.DedicatedManagementInterface.NodeChoice = nodeChoiceInt\n\n\t\t\t\tnodeChoiceInt.Node = v.(string)\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tif v, ok := d.GetOk(\"ethernet_interface\"); ok && !interfaceChoiceTypeFound {\n\n\t\tinterfaceChoiceTypeFound = true\n\t\tinterfaceChoiceInt := &ves_io_schema_network_interface.CreateSpecType_EthernetInterface{}\n\t\tinterfaceChoiceInt.EthernetInterface = &ves_io_schema_network_interface.EthernetInterfaceType{}\n\t\tcreateSpec.InterfaceChoice = interfaceChoiceInt\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\t// address_choice\n\n\t\t\taddressChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"dhcp_client\"]; ok && !isIntfNil(v) && !addressChoiceTypeFound {\n\n\t\t\t\taddressChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\taddressChoiceInt := &ves_io_schema_network_interface.EthernetInterfaceType_DhcpClient{}\n\t\t\t\t\taddressChoiceInt.DhcpClient = &ves_io_schema.Empty{}\n\t\t\t\t\tinterfaceChoiceInt.EthernetInterface.AddressChoice = addressChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"dhcp_server\"]; ok && !isIntfNil(v) && !addressChoiceTypeFound {\n\n\t\t\t\taddressChoiceTypeFound = true\n\t\t\t\taddressChoiceInt := &ves_io_schema_network_interface.EthernetInterfaceType_DhcpServer{}\n\t\t\t\taddressChoiceInt.DhcpServer = &ves_io_schema_network_interface.DHCPServerParametersType{}\n\t\t\t\tinterfaceChoiceInt.EthernetInterface.AddressChoice = addressChoiceInt\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\t// dhcp_networks\n\n\t\t\t\t\tif v, ok := cs[\"dhcp_networks\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\tdhcpNetworks := make([]*ves_io_schema_network_interface.DHCPNetworkType, len(sl))\n\t\t\t\t\t\taddressChoiceInt.DhcpServer.DhcpNetworks = dhcpNetworks\n\t\t\t\t\t\tfor i, set := range sl {\n\t\t\t\t\t\t\tdhcpNetworks[i] = &ves_io_schema_network_interface.DHCPNetworkType{}\n\t\t\t\t\t\t\tdhcpNetworksMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t// dns_choice\n\n\t\t\t\t\t\t\tdnsChoiceTypeFound := false\n\n\t\t\t\t\t\t\tif v, ok := dhcpNetworksMapStrToI[\"dns_address\"]; ok && !isIntfNil(v) && !dnsChoiceTypeFound {\n\n\t\t\t\t\t\t\t\tdnsChoiceTypeFound = true\n\t\t\t\t\t\t\t\tdnsChoiceInt := &ves_io_schema_network_interface.DHCPNetworkType_DnsAddress{}\n\n\t\t\t\t\t\t\t\tdhcpNetworks[i].DnsChoice = dnsChoiceInt\n\n\t\t\t\t\t\t\t\tdnsChoiceInt.DnsAddress = v.(string)\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := dhcpNetworksMapStrToI[\"same_as_dgw\"]; ok && !isIntfNil(v) && !dnsChoiceTypeFound {\n\n\t\t\t\t\t\t\t\tdnsChoiceTypeFound = true\n\n\t\t\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\t\t\tdnsChoiceInt := &ves_io_schema_network_interface.DHCPNetworkType_SameAsDgw{}\n\t\t\t\t\t\t\t\t\tdnsChoiceInt.SameAsDgw = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\t\t\tdhcpNetworks[i].DnsChoice = dnsChoiceInt\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// gateway_choice\n\n\t\t\t\t\t\t\tgatewayChoiceTypeFound := false\n\n\t\t\t\t\t\t\tif v, ok := dhcpNetworksMapStrToI[\"dgw_address\"]; ok && !isIntfNil(v) && !gatewayChoiceTypeFound {\n\n\t\t\t\t\t\t\t\tgatewayChoiceTypeFound = true\n\t\t\t\t\t\t\t\tgatewayChoiceInt := &ves_io_schema_network_interface.DHCPNetworkType_DgwAddress{}\n\n\t\t\t\t\t\t\t\tdhcpNetworks[i].GatewayChoice = gatewayChoiceInt\n\n\t\t\t\t\t\t\t\tgatewayChoiceInt.DgwAddress = v.(string)\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := dhcpNetworksMapStrToI[\"first_address\"]; ok && !isIntfNil(v) && !gatewayChoiceTypeFound {\n\n\t\t\t\t\t\t\t\tgatewayChoiceTypeFound = true\n\n\t\t\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\t\t\tgatewayChoiceInt := &ves_io_schema_network_interface.DHCPNetworkType_FirstAddress{}\n\t\t\t\t\t\t\t\t\tgatewayChoiceInt.FirstAddress = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\t\t\tdhcpNetworks[i].GatewayChoice = gatewayChoiceInt\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := dhcpNetworksMapStrToI[\"last_address\"]; ok && !isIntfNil(v) && !gatewayChoiceTypeFound {\n\n\t\t\t\t\t\t\t\tgatewayChoiceTypeFound = true\n\n\t\t\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\t\t\tgatewayChoiceInt := &ves_io_schema_network_interface.DHCPNetworkType_LastAddress{}\n\t\t\t\t\t\t\t\t\tgatewayChoiceInt.LastAddress = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\t\t\tdhcpNetworks[i].GatewayChoice = gatewayChoiceInt\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// network_prefix_choice\n\n\t\t\t\t\t\t\tnetworkPrefixChoiceTypeFound := false\n\n\t\t\t\t\t\t\tif v, ok := dhcpNetworksMapStrToI[\"network_prefix\"]; ok && !isIntfNil(v) && !networkPrefixChoiceTypeFound {\n\n\t\t\t\t\t\t\t\tnetworkPrefixChoiceTypeFound = true\n\t\t\t\t\t\t\t\tnetworkPrefixChoiceInt := &ves_io_schema_network_interface.DHCPNetworkType_NetworkPrefix{}\n\n\t\t\t\t\t\t\t\tdhcpNetworks[i].NetworkPrefixChoice = networkPrefixChoiceInt\n\n\t\t\t\t\t\t\t\tnetworkPrefixChoiceInt.NetworkPrefix = v.(string)\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := dhcpNetworksMapStrToI[\"network_prefix_allocator\"]; ok && !isIntfNil(v) && !networkPrefixChoiceTypeFound {\n\n\t\t\t\t\t\t\t\tnetworkPrefixChoiceTypeFound = true\n\t\t\t\t\t\t\t\tnetworkPrefixChoiceInt := &ves_io_schema_network_interface.DHCPNetworkType_NetworkPrefixAllocator{}\n\t\t\t\t\t\t\t\tnetworkPrefixChoiceInt.NetworkPrefixAllocator = &ves_io_schema_views.ObjectRefType{}\n\t\t\t\t\t\t\t\tdhcpNetworks[i].NetworkPrefixChoice = networkPrefixChoiceInt\n\n\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t// name\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"name\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\tnetworkPrefixChoiceInt.NetworkPrefixAllocator.Name = v.(string)\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// namespace\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"namespace\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\tnetworkPrefixChoiceInt.NetworkPrefixAllocator.Namespace = v.(string)\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// tenant\n\n\t\t\t\t\t\t\t\t\tif v, ok := cs[\"tenant\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\t\t\tnetworkPrefixChoiceInt.NetworkPrefixAllocator.Tenant = v.(string)\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// pool_settings\n\n\t\t\t\t\t\t\tif v, ok := dhcpNetworksMapStrToI[\"pool_settings\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\tdhcpNetworks[i].PoolSettings = ves_io_schema_network_interface.DHCPPoolSettingType(ves_io_schema_network_interface.DHCPPoolSettingType_value[v.(string)])\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// pools\n\n\t\t\t\t\t\t\tif v, ok := dhcpNetworksMapStrToI[\"pools\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\t\t\tpools := make([]*ves_io_schema_network_interface.DHCPPoolType, len(sl))\n\t\t\t\t\t\t\t\tdhcpNetworks[i].Pools = pools\n\t\t\t\t\t\t\t\tfor i, set := range sl {\n\t\t\t\t\t\t\t\t\tpools[i] = &ves_io_schema_network_interface.DHCPPoolType{}\n\t\t\t\t\t\t\t\t\tpoolsMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t// end_ip\n\n\t\t\t\t\t\t\t\t\tif w, ok := poolsMapStrToI[\"end_ip\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\t\t\tpools[i].EndIp = w.(string)\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// exclude\n\n\t\t\t\t\t\t\t\t\tif w, ok := poolsMapStrToI[\"exclude\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\t\t\tpools[i].Exclude = w.(bool)\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// start_ip\n\n\t\t\t\t\t\t\t\t\tif w, ok := poolsMapStrToI[\"start_ip\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\t\t\tpools[i].StartIp = w.(string)\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\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\t// dhcp_option82_tag\n\n\t\t\t\t\tif v, ok := cs[\"dhcp_option82_tag\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\taddressChoiceInt.DhcpServer.DhcpOption82Tag = v.(string)\n\t\t\t\t\t}\n\n\t\t\t\t\t// fixed_ip_map\n\n\t\t\t\t\tif v, ok := cs[\"fixed_ip_map\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tms := map[string]string{}\n\t\t\t\t\t\tfor k, v := range v.(map[string]interface{}) {\n\t\t\t\t\t\t\tms[k] = v.(string)\n\t\t\t\t\t\t}\n\t\t\t\t\t\taddressChoiceInt.DhcpServer.FixedIpMap = ms\n\t\t\t\t\t}\n\n\t\t\t\t\t// interfaces_addressing_choice\n\n\t\t\t\t\tinterfacesAddressingChoiceTypeFound := false\n\n\t\t\t\t\tif v, ok := cs[\"automatic_from_end\"]; ok && !isIntfNil(v) && !interfacesAddressingChoiceTypeFound {\n\n\t\t\t\t\t\tinterfacesAddressingChoiceTypeFound = true\n\n\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\tinterfacesAddressingChoiceInt := &ves_io_schema_network_interface.DHCPServerParametersType_AutomaticFromEnd{}\n\t\t\t\t\t\t\tinterfacesAddressingChoiceInt.AutomaticFromEnd = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\taddressChoiceInt.DhcpServer.InterfacesAddressingChoice = interfacesAddressingChoiceInt\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"automatic_from_start\"]; ok && !isIntfNil(v) && !interfacesAddressingChoiceTypeFound {\n\n\t\t\t\t\t\tinterfacesAddressingChoiceTypeFound = true\n\n\t\t\t\t\t\tif v.(bool) {\n\t\t\t\t\t\t\tinterfacesAddressingChoiceInt := &ves_io_schema_network_interface.DHCPServerParametersType_AutomaticFromStart{}\n\t\t\t\t\t\t\tinterfacesAddressingChoiceInt.AutomaticFromStart = &ves_io_schema.Empty{}\n\t\t\t\t\t\t\taddressChoiceInt.DhcpServer.InterfacesAddressingChoice = interfacesAddressingChoiceInt\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"interface_ip_map\"]; ok && !isIntfNil(v) && !interfacesAddressingChoiceTypeFound {\n\n\t\t\t\t\t\tinterfacesAddressingChoiceTypeFound = true\n\t\t\t\t\t\tinterfacesAddressingChoiceInt := &ves_io_schema_network_interface.DHCPServerParametersType_InterfaceIpMap{}\n\t\t\t\t\t\tinterfacesAddressingChoiceInt.InterfaceIpMap = &ves_io_schema_network_interface.DHCPInterfaceIPType{}\n\t\t\t\t\t\taddressChoiceInt.DhcpServer.InterfacesAddressingChoice = interfacesAddressingChoiceInt\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\t// interface_ip_map\n\n\t\t\t\t\t\t\tif v, ok := cs[\"interface_ip_map\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\tms := map[string]string{}\n\t\t\t\t\t\t\t\tfor k, v := range v.(map[string]interface{}) {\n\t\t\t\t\t\t\t\t\tms[k] = v.(string)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tinterfacesAddressingChoiceInt.InterfaceIpMap.InterfaceIpMap = ms\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[\"static_ip\"]; ok && !isIntfNil(v) && !addressChoiceTypeFound {\n\n\t\t\t\taddressChoiceTypeFound = true\n\t\t\t\taddressChoiceInt := &ves_io_schema_network_interface.EthernetInterfaceType_StaticIp{}\n\t\t\t\taddressChoiceInt.StaticIp = &ves_io_schema_network_interface.StaticIPParametersType{}\n\t\t\t\tinterfaceChoiceInt.EthernetInterface.AddressChoice = addressChoiceInt\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\t// network_prefix_choice\n\n\t\t\t\t\tnetworkPrefixChoiceTypeFound := false\n\n\t\t\t\t\tif v, ok := cs[\"cluster_static_ip\"]; ok && !isIntfNil(v) && !networkPrefixChoiceTypeFound {\n\n\t\t\t\t\t\tnetworkPrefixChoiceTypeFound = true\n\t\t\t\t\t\tnetworkPrefixChoiceInt := &ves_io_schema_network_interface.StaticIPParametersType_ClusterStaticIp{}\n\t\t\t\t\t\tnetworkPrefixChoiceInt.ClusterStaticIp = &ves_io_schema_network_interface.StaticIpParametersClusterType{}\n\t\t\t\t\t\taddressChoiceInt.StaticIp.NetworkPrefixChoice = networkPrefixChoiceInt\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\t// interface_ip_map\n\n\t\t\t\t\t\t\tif v, ok := cs[\"interface_ip_map\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\tinterfaceIpMap := make(map[string]*ves_io_schema_network_interface.StaticIpParametersNodeType)\n\t\t\t\t\t\t\t\tnetworkPrefixChoiceInt.ClusterStaticIp.InterfaceIpMap = interfaceIpMap\n\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\tinterfaceIpMapMapStrToI := set.(map[string]interface{})\n\t\t\t\t\t\t\t\t\tkey, ok := interfaceIpMapMapStrToI[\"name\"]\n\t\t\t\t\t\t\t\t\tif ok && !isIntfNil(key) {\n\t\t\t\t\t\t\t\t\t\tinterfaceIpMap[key.(string)] = &ves_io_schema_network_interface.StaticIpParametersNodeType{}\n\t\t\t\t\t\t\t\t\t\tval, _ := interfaceIpMapMapStrToI[\"value\"]\n\n\t\t\t\t\t\t\t\t\t\tinterfaceIpMapVals := val.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\tfor _, intVal := range interfaceIpMapVals {\n\n\t\t\t\t\t\t\t\t\t\t\tinterfaceIpMapStaticMap := intVal.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\tif w, ok := interfaceIpMapStaticMap[\"default_gw\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\t\t\t\t\tinterfaceIpMap[key.(string)].DefaultGw = w.(string)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tif w, ok := interfaceIpMapStaticMap[\"dns_server\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\t\t\t\t\tinterfaceIpMap[key.(string)].DnsServer = w.(string)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tif w, ok := interfaceIpMapStaticMap[\"ip_address\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\t\t\t\t\tinterfaceIpMap[key.(string)].IpAddress = w.(string)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t// break after one loop\n\t\t\t\t\t\t\t\t\t\t\tbreak\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\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[\"fleet_static_ip\"]; ok && !isIntfNil(v) && !networkPrefixChoiceTypeFound {\n\n\t\t\t\t\t\tnetworkPrefixChoiceTypeFound = true\n\t\t\t\t\t\tnetworkPrefixChoiceInt := &ves_io_schema_network_interface.StaticIPParametersType_FleetStaticIp{}\n\t\t\t\t\t\tnetworkPrefixChoiceInt.FleetStaticIp = &ves_io_schema_network_interface.StaticIpParametersFleetType{}\n\t\t\t\t\t\taddressChoiceInt.StaticIp.NetworkPrefixChoice = networkPrefixChoiceInt\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\t// default_gw\n\n\t\t\t\t\t\t\tif v, ok := cs[\"default_gw\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\tnetworkPrefixChoiceInt.FleetStaticIp.DefaultGw = v.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// dns_server\n\n\t\t\t\t\t\t\tif v, ok := cs[\"dns_server\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\tnetworkPrefixChoiceInt.FleetStaticIp.DnsServer = v.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// network_prefix_allocator\n\n\t\t\t\t\t\t\tif v, ok := cs[\"network_prefix_allocator\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\tnetworkPrefixAllocatorInt := &ves_io_schema_views.ObjectRefType{}\n\t\t\t\t\t\t\t\tnetworkPrefixChoiceInt.FleetStaticIp.NetworkPrefixAllocator = networkPrefixAllocatorInt\n\n\t\t\t\t\t\t\t\tnpaMapToStrVal := v.(map[string]interface{})\n\t\t\t\t\t\t\t\tif val, ok := npaMapToStrVal[\"name\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\t\tnetworkPrefixAllocatorInt.Name = val.(string)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif val, ok := npaMapToStrVal[\"namespace\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\t\tnetworkPrefixAllocatorInt.Namespace = val.(string)\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif val, ok := npaMapToStrVal[\"tenant\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\t\tnetworkPrefixAllocatorInt.Tenant = val.(string)\n\t\t\t\t\t\t\t\t}\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 := cs[\"node_static_ip\"]; ok && !isIntfNil(v) && !networkPrefixChoiceTypeFound {\n\n\t\t\t\t\t\tnetworkPrefixChoiceTypeFound = true\n\t\t\t\t\t\tnetworkPrefixChoiceInt := &ves_io_schema_network_interface.StaticIPParametersType_NodeStaticIp{}\n\t\t\t\t\t\tnetworkPrefixChoiceInt.NodeStaticIp = &ves_io_schema_network_interface.StaticIpParametersNodeType{}\n\t\t\t\t\t\taddressChoiceInt.StaticIp.NetworkPrefixChoice = networkPrefixChoiceInt\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\t// default_gw\n\n\t\t\t\t\t\t\tif v, ok := cs[\"default_gw\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\tnetworkPrefixChoiceInt.NodeStaticIp.DefaultGw = v.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// dns_server\n\n\t\t\t\t\t\t\tif v, ok := cs[\"dns_server\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\tnetworkPrefixChoiceInt.NodeStaticIp.DnsServer = v.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// ip_address\n\n\t\t\t\t\t\t\tif v, ok := cs[\"ip_address\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\tnetworkPrefixChoiceInt.NodeStaticIp.IpAddress = v.(string)\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\t// device\n\n\t\t\tif v, ok := cs[\"device\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tinterfaceChoiceInt.EthernetInterface.Device = v.(string)\n\t\t\t}\n\n\t\t\t// monitoring_choice\n\n\t\t\tmonitoringChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"monitor\"]; ok && !isIntfNil(v) && !monitoringChoiceTypeFound {\n\n\t\t\t\tmonitoringChoiceTypeFound = true\n\t\t\t\t_ = v\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"monitor_disabled\"]; ok && !isIntfNil(v) && !monitoringChoiceTypeFound {\n\n\t\t\t\tmonitoringChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tmonitoringChoiceInt := &ves_io_schema_network_interface.EthernetInterfaceType_MonitorDisabled{}\n\t\t\t\t\tmonitoringChoiceInt.MonitorDisabled = &ves_io_schema.Empty{}\n\t\t\t\t\tinterfaceChoiceInt.EthernetInterface.MonitoringChoice = monitoringChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// mtu\n\n\t\t\tif v, ok := cs[\"mtu\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tinterfaceChoiceInt.EthernetInterface.Mtu = uint32(v.(int))\n\t\t\t}\n\n\t\t\t// network_choice\n\n\t\t\tnetworkChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"inside_network\"]; ok && !isIntfNil(v) && !networkChoiceTypeFound {\n\n\t\t\t\tnetworkChoiceTypeFound = true\n\t\t\t\tnetworkChoiceInt := &ves_io_schema_network_interface.EthernetInterfaceType_InsideNetwork{}\n\t\t\t\tnetworkChoiceInt.InsideNetwork = &ves_io_schema_views.ObjectRefType{}\n\t\t\t\tinterfaceChoiceInt.EthernetInterface.NetworkChoice = networkChoiceInt\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\t// name\n\n\t\t\t\t\tif v, ok := cs[\"name\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tnetworkChoiceInt.InsideNetwork.Name = v.(string)\n\t\t\t\t\t}\n\n\t\t\t\t\t// namespace\n\n\t\t\t\t\tif v, ok := cs[\"namespace\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tnetworkChoiceInt.InsideNetwork.Namespace = v.(string)\n\t\t\t\t\t}\n\n\t\t\t\t\t// tenant\n\n\t\t\t\t\tif v, ok := cs[\"tenant\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tnetworkChoiceInt.InsideNetwork.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[\"site_local_inside_network\"]; ok && !isIntfNil(v) && !networkChoiceTypeFound {\n\n\t\t\t\tnetworkChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tnetworkChoiceInt := &ves_io_schema_network_interface.EthernetInterfaceType_SiteLocalInsideNetwork{}\n\t\t\t\t\tnetworkChoiceInt.SiteLocalInsideNetwork = &ves_io_schema.Empty{}\n\t\t\t\t\tinterfaceChoiceInt.EthernetInterface.NetworkChoice = networkChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"site_local_network\"]; ok && !isIntfNil(v) && !networkChoiceTypeFound {\n\n\t\t\t\tnetworkChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tnetworkChoiceInt := &ves_io_schema_network_interface.EthernetInterfaceType_SiteLocalNetwork{}\n\t\t\t\t\tnetworkChoiceInt.SiteLocalNetwork = &ves_io_schema.Empty{}\n\t\t\t\t\tinterfaceChoiceInt.EthernetInterface.NetworkChoice = networkChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"storage_network\"]; ok && !isIntfNil(v) && !networkChoiceTypeFound {\n\n\t\t\t\tnetworkChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tnetworkChoiceInt := &ves_io_schema_network_interface.EthernetInterfaceType_StorageNetwork{}\n\t\t\t\t\tnetworkChoiceInt.StorageNetwork = &ves_io_schema.Empty{}\n\t\t\t\t\tinterfaceChoiceInt.EthernetInterface.NetworkChoice = networkChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// node_choice\n\n\t\t\tnodeChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"cluster\"]; ok && !isIntfNil(v) && !nodeChoiceTypeFound {\n\n\t\t\t\tnodeChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tnodeChoiceInt := &ves_io_schema_network_interface.EthernetInterfaceType_Cluster{}\n\t\t\t\t\tnodeChoiceInt.Cluster = &ves_io_schema.Empty{}\n\t\t\t\t\tinterfaceChoiceInt.EthernetInterface.NodeChoice = nodeChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"node\"]; ok && !isIntfNil(v) && !nodeChoiceTypeFound {\n\n\t\t\t\tnodeChoiceTypeFound = true\n\t\t\t\tnodeChoiceInt := &ves_io_schema_network_interface.EthernetInterfaceType_Node{}\n\n\t\t\t\tinterfaceChoiceInt.EthernetInterface.NodeChoice = nodeChoiceInt\n\n\t\t\t\tnodeChoiceInt.Node = v.(string)\n\n\t\t\t}\n\n\t\t\t// primary_choice\n\n\t\t\tprimaryChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"is_primary\"]; ok && !isIntfNil(v) && !primaryChoiceTypeFound {\n\n\t\t\t\tprimaryChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tprimaryChoiceInt := &ves_io_schema_network_interface.EthernetInterfaceType_IsPrimary{}\n\t\t\t\t\tprimaryChoiceInt.IsPrimary = &ves_io_schema.Empty{}\n\t\t\t\t\tinterfaceChoiceInt.EthernetInterface.PrimaryChoice = primaryChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"not_primary\"]; ok && !isIntfNil(v) && !primaryChoiceTypeFound {\n\n\t\t\t\tprimaryChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tprimaryChoiceInt := &ves_io_schema_network_interface.EthernetInterfaceType_NotPrimary{}\n\t\t\t\t\tprimaryChoiceInt.NotPrimary = &ves_io_schema.Empty{}\n\t\t\t\t\tinterfaceChoiceInt.EthernetInterface.PrimaryChoice = primaryChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// priority\n\n\t\t\tif v, ok := cs[\"priority\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tinterfaceChoiceInt.EthernetInterface.Priority = uint32(v.(int))\n\t\t\t}\n\n\t\t\t// vlan_choice\n\n\t\t\tvlanChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"untagged\"]; ok && !isIntfNil(v) && !vlanChoiceTypeFound {\n\n\t\t\t\tvlanChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tvlanChoiceInt := &ves_io_schema_network_interface.EthernetInterfaceType_Untagged{}\n\t\t\t\t\tvlanChoiceInt.Untagged = &ves_io_schema.Empty{}\n\t\t\t\t\tinterfaceChoiceInt.EthernetInterface.VlanChoice = vlanChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"vlan_id\"]; ok && !isIntfNil(v) && !vlanChoiceTypeFound {\n\n\t\t\t\tvlanChoiceTypeFound = true\n\t\t\t\tvlanChoiceInt := &ves_io_schema_network_interface.EthernetInterfaceType_VlanId{}\n\n\t\t\t\tinterfaceChoiceInt.EthernetInterface.VlanChoice = vlanChoiceInt\n\n\t\t\t\tvlanChoiceInt.VlanId =\n\t\t\t\t\tuint32(v.(int))\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tif v, ok := d.GetOk(\"legacy_interface\"); ok && !interfaceChoiceTypeFound {\n\n\t\tinterfaceChoiceTypeFound = true\n\t\tinterfaceChoiceInt := &ves_io_schema_network_interface.CreateSpecType_LegacyInterface{}\n\t\tinterfaceChoiceInt.LegacyInterface = &ves_io_schema_network_interface.LegacyInterfaceType{}\n\t\tcreateSpec.InterfaceChoice = interfaceChoiceInt\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\t// DHCP_server\n\n\t\t\tif v, ok := cs[\"dhcp_server\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tinterfaceChoiceInt.LegacyInterface.DHCPServer = ves_io_schema_network_interface.NetworkInterfaceDHCPServer(ves_io_schema_network_interface.NetworkInterfaceDHCPServer_value[v.(string)])\n\n\t\t\t}\n\n\t\t\t// DNS_server\n\n\t\t\tif v, ok := cs[\"dns_server\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tdnsServer := &ves_io_schema_network_interface.NetworkInterfaceDNS{}\n\t\t\t\tinterfaceChoiceInt.LegacyInterface.DNSServer = dnsServer\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tdnsServerMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t// dns_mode\n\n\t\t\t\t\tif v, ok := dnsServerMapStrToI[\"dns_mode\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tdnsServer.DnsMode = ves_io_schema_network_interface.NetworkInterfaceDNSMode(ves_io_schema_network_interface.NetworkInterfaceDNSMode_value[v.(string)])\n\n\t\t\t\t\t}\n\n\t\t\t\t\t// dns_server\n\n\t\t\t\t\tif v, ok := dnsServerMapStrToI[\"dns_server\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\tdnsServerIpv4s := make([]*ves_io_schema.Ipv4AddressType, len(sl))\n\t\t\t\t\t\tdnsServer.DnsServer = dnsServerIpv4s\n\t\t\t\t\t\tfor i, set := range sl {\n\t\t\t\t\t\t\tdnsServerIpv4s[i] = &ves_io_schema.Ipv4AddressType{}\n\t\t\t\t\t\t\tdnsServerMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t// addr\n\n\t\t\t\t\t\t\tif w, ok := dnsServerMapStrToI[\"addr\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\tdnsServerIpv4s[i].Addr = w.(string)\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\t// address_allocator\n\n\t\t\tif v, ok := cs[\"address_allocator\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.([]interface{})\n\t\t\t\taddressAllocatorInt := make([]*ves_io_schema.ObjectRefType, len(sl))\n\t\t\t\tinterfaceChoiceInt.LegacyInterface.AddressAllocator = addressAllocatorInt\n\t\t\t\tfor i, ps := range sl {\n\n\t\t\t\t\taaMapToStrVal := ps.(map[string]interface{})\n\t\t\t\t\taddressAllocatorInt[i] = &ves_io_schema.ObjectRefType{}\n\n\t\t\t\t\taddressAllocatorInt[i].Kind = \"address_allocator\"\n\n\t\t\t\t\tif v, ok := aaMapToStrVal[\"name\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\taddressAllocatorInt[i].Name = v.(string)\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := aaMapToStrVal[\"namespace\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\taddressAllocatorInt[i].Namespace = v.(string)\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := aaMapToStrVal[\"tenant\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\taddressAllocatorInt[i].Tenant = v.(string)\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := aaMapToStrVal[\"uid\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\taddressAllocatorInt[i].Uid = v.(string)\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// default_gateway\n\n\t\t\tif v, ok := cs[\"default_gateway\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tdefaultGateway := &ves_io_schema_network_interface.NetworkInterfaceDFGW{}\n\t\t\t\tinterfaceChoiceInt.LegacyInterface.DefaultGateway = defaultGateway\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tdefaultGatewayMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t// default_gateway_address\n\n\t\t\t\t\tif v, ok := defaultGatewayMapStrToI[\"default_gateway_address\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tdefaultGatewayAddress := &ves_io_schema.Ipv4AddressType{}\n\t\t\t\t\t\tdefaultGateway.DefaultGatewayAddress = defaultGatewayAddress\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tdefaultGatewayAddressMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\t// addr\n\n\t\t\t\t\t\t\tif w, ok := defaultGatewayAddressMapStrToI[\"addr\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\tdefaultGatewayAddress.Addr = w.(string)\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\t// default_gateway_mode\n\n\t\t\t\t\tif v, ok := defaultGatewayMapStrToI[\"default_gateway_mode\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tdefaultGateway.DefaultGatewayMode = ves_io_schema_network_interface.NetworkInterfaceGatewayMode(ves_io_schema_network_interface.NetworkInterfaceGatewayMode_value[v.(string)])\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// device_name\n\n\t\t\tif v, ok := cs[\"device_name\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tinterfaceChoiceInt.LegacyInterface.DeviceName = v.(string)\n\t\t\t}\n\n\t\t\t// dhcp_address\n\n\t\t\tif v, ok := cs[\"dhcp_address\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tinterfaceChoiceInt.LegacyInterface.DhcpAddress = ves_io_schema_network_interface.NetworkInterfaceDHCP(ves_io_schema_network_interface.NetworkInterfaceDHCP_value[v.(string)])\n\n\t\t\t}\n\n\t\t\t// monitoring_choice\n\n\t\t\tmonitoringChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"monitor\"]; ok && !isIntfNil(v) && !monitoringChoiceTypeFound {\n\n\t\t\t\tmonitoringChoiceTypeFound = true\n\t\t\t\t_ = v\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"monitor_disabled\"]; ok && !isIntfNil(v) && !monitoringChoiceTypeFound {\n\n\t\t\t\tmonitoringChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tmonitoringChoiceInt := &ves_io_schema_network_interface.LegacyInterfaceType_MonitorDisabled{}\n\t\t\t\t\tmonitoringChoiceInt.MonitorDisabled = &ves_io_schema.Empty{}\n\t\t\t\t\tinterfaceChoiceInt.LegacyInterface.MonitoringChoice = monitoringChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// mtu\n\n\t\t\tif v, ok := cs[\"mtu\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tinterfaceChoiceInt.LegacyInterface.Mtu = uint32(v.(int))\n\t\t\t}\n\n\t\t\t// priority\n\n\t\t\tif v, ok := cs[\"priority\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tinterfaceChoiceInt.LegacyInterface.Priority = uint32(v.(int))\n\t\t\t}\n\n\t\t\t// static_addresses\n\n\t\t\tif v, ok := cs[\"static_addresses\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.([]interface{})\n\t\t\t\tstaticAddresses := make([]*ves_io_schema.Ipv4SubnetType, len(sl))\n\t\t\t\tinterfaceChoiceInt.LegacyInterface.StaticAddresses = staticAddresses\n\t\t\t\tfor i, set := range sl {\n\t\t\t\t\tstaticAddresses[i] = &ves_io_schema.Ipv4SubnetType{}\n\t\t\t\t\tstaticAddressesMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t// plen\n\n\t\t\t\t\tif w, ok := staticAddressesMapStrToI[\"plen\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\tstaticAddresses[i].Plen = uint32(w.(int))\n\t\t\t\t\t}\n\n\t\t\t\t\t// prefix\n\n\t\t\t\t\tif w, ok := staticAddressesMapStrToI[\"prefix\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\tstaticAddresses[i].Prefix = w.(string)\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// tunnel\n\n\t\t\tif v, ok := cs[\"tunnel\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\ttunnel := &ves_io_schema_network_interface.NetworkInterfaceTunnel{}\n\t\t\t\tinterfaceChoiceInt.LegacyInterface.Tunnel = tunnel\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\ttunnelMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t// tunnel\n\n\t\t\t\t\tif v, ok := tunnelMapStrToI[\"tunnel\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\ttunnelInt := make([]*ves_io_schema.ObjectRefType, len(sl))\n\t\t\t\t\t\ttunnel.Tunnel = tunnelInt\n\t\t\t\t\t\tfor i, ps := range sl {\n\n\t\t\t\t\t\t\ttMapToStrVal := ps.(map[string]interface{})\n\t\t\t\t\t\t\ttunnelInt[i] = &ves_io_schema.ObjectRefType{}\n\n\t\t\t\t\t\t\ttunnelInt[i].Kind = \"tunnel\"\n\n\t\t\t\t\t\t\tif v, ok := tMapToStrVal[\"name\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\ttunnelInt[i].Name = v.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := tMapToStrVal[\"namespace\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\ttunnelInt[i].Namespace = v.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := tMapToStrVal[\"tenant\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\ttunnelInt[i].Tenant = v.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := tMapToStrVal[\"uid\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\ttunnelInt[i].Uid = v.(string)\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\t// type\n\n\t\t\tif v, ok := cs[\"type\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tinterfaceChoiceInt.LegacyInterface.Type = ves_io_schema_network_interface.NetworkInterfaceType(ves_io_schema_network_interface.NetworkInterfaceType_value[v.(string)])\n\n\t\t\t}\n\n\t\t\t// virtual_network\n\n\t\t\tif v, ok := cs[\"virtual_network\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.([]interface{})\n\t\t\t\tvirtualNetworkInt := make([]*ves_io_schema.ObjectRefType, len(sl))\n\t\t\t\tinterfaceChoiceInt.LegacyInterface.VirtualNetwork = virtualNetworkInt\n\t\t\t\tfor i, ps := range sl {\n\n\t\t\t\t\tvnMapToStrVal := ps.(map[string]interface{})\n\t\t\t\t\tvirtualNetworkInt[i] = &ves_io_schema.ObjectRefType{}\n\n\t\t\t\t\tvirtualNetworkInt[i].Kind = \"virtual_network\"\n\n\t\t\t\t\tif v, ok := vnMapToStrVal[\"name\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\tvirtualNetworkInt[i].Name = v.(string)\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := vnMapToStrVal[\"namespace\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\tvirtualNetworkInt[i].Namespace = v.(string)\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := vnMapToStrVal[\"tenant\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\tvirtualNetworkInt[i].Tenant = v.(string)\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := vnMapToStrVal[\"uid\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\tvirtualNetworkInt[i].Uid = v.(string)\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// vlan_tag\n\n\t\t\tif v, ok := cs[\"vlan_tag\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tinterfaceChoiceInt.LegacyInterface.VlanTag = uint32(v.(int))\n\t\t\t}\n\n\t\t\t// vlan_tagging\n\n\t\t\tif v, ok := cs[\"vlan_tagging\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tinterfaceChoiceInt.LegacyInterface.VlanTagging = ves_io_schema_network_interface.NetworkInterfaceVLANTagging(ves_io_schema_network_interface.NetworkInterfaceVLANTagging_value[v.(string)])\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tif v, ok := d.GetOk(\"tunnel_interface\"); ok && !interfaceChoiceTypeFound {\n\n\t\tinterfaceChoiceTypeFound = true\n\t\tinterfaceChoiceInt := &ves_io_schema_network_interface.CreateSpecType_TunnelInterface{}\n\t\tinterfaceChoiceInt.TunnelInterface = &ves_io_schema_network_interface.TunnelInterfaceType{}\n\t\tcreateSpec.InterfaceChoice = interfaceChoiceInt\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\t// mtu\n\n\t\t\tif v, ok := cs[\"mtu\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tinterfaceChoiceInt.TunnelInterface.Mtu = uint32(v.(int))\n\t\t\t}\n\n\t\t\t// network_choice\n\n\t\t\tnetworkChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"inside_network\"]; ok && !isIntfNil(v) && !networkChoiceTypeFound {\n\n\t\t\t\tnetworkChoiceTypeFound = true\n\t\t\t\tnetworkChoiceInt := &ves_io_schema_network_interface.TunnelInterfaceType_InsideNetwork{}\n\t\t\t\tnetworkChoiceInt.InsideNetwork = &ves_io_schema_views.ObjectRefType{}\n\t\t\t\tinterfaceChoiceInt.TunnelInterface.NetworkChoice = networkChoiceInt\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\t// name\n\n\t\t\t\t\tif v, ok := cs[\"name\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tnetworkChoiceInt.InsideNetwork.Name = v.(string)\n\t\t\t\t\t}\n\n\t\t\t\t\t// namespace\n\n\t\t\t\t\tif v, ok := cs[\"namespace\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tnetworkChoiceInt.InsideNetwork.Namespace = v.(string)\n\t\t\t\t\t}\n\n\t\t\t\t\t// tenant\n\n\t\t\t\t\tif v, ok := cs[\"tenant\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tnetworkChoiceInt.InsideNetwork.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[\"site_local_inside_network\"]; ok && !isIntfNil(v) && !networkChoiceTypeFound {\n\n\t\t\t\tnetworkChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tnetworkChoiceInt := &ves_io_schema_network_interface.TunnelInterfaceType_SiteLocalInsideNetwork{}\n\t\t\t\t\tnetworkChoiceInt.SiteLocalInsideNetwork = &ves_io_schema.Empty{}\n\t\t\t\t\tinterfaceChoiceInt.TunnelInterface.NetworkChoice = networkChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"site_local_network\"]; ok && !isIntfNil(v) && !networkChoiceTypeFound {\n\n\t\t\t\tnetworkChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tnetworkChoiceInt := &ves_io_schema_network_interface.TunnelInterfaceType_SiteLocalNetwork{}\n\t\t\t\t\tnetworkChoiceInt.SiteLocalNetwork = &ves_io_schema.Empty{}\n\t\t\t\t\tinterfaceChoiceInt.TunnelInterface.NetworkChoice = networkChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// node_choice\n\n\t\t\tnodeChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"cluster\"]; ok && !isIntfNil(v) && !nodeChoiceTypeFound {\n\n\t\t\t\tnodeChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tnodeChoiceInt := &ves_io_schema_network_interface.TunnelInterfaceType_Cluster{}\n\t\t\t\t\tnodeChoiceInt.Cluster = &ves_io_schema.Empty{}\n\t\t\t\t\tinterfaceChoiceInt.TunnelInterface.NodeChoice = nodeChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"node\"]; ok && !isIntfNil(v) && !nodeChoiceTypeFound {\n\n\t\t\t\tnodeChoiceTypeFound = true\n\t\t\t\tnodeChoiceInt := &ves_io_schema_network_interface.TunnelInterfaceType_Node{}\n\n\t\t\t\tinterfaceChoiceInt.TunnelInterface.NodeChoice = nodeChoiceInt\n\n\t\t\t\tnodeChoiceInt.Node = v.(string)\n\n\t\t\t}\n\n\t\t\t// priority\n\n\t\t\tif v, ok := cs[\"priority\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tinterfaceChoiceInt.TunnelInterface.Priority = uint32(v.(int))\n\t\t\t}\n\n\t\t\t// static_ip\n\n\t\t\tif v, ok := cs[\"static_ip\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tstaticIp := &ves_io_schema_network_interface.StaticIPParametersType{}\n\t\t\t\tinterfaceChoiceInt.TunnelInterface.StaticIp = staticIp\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tstaticIpMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t// network_prefix_choice\n\n\t\t\t\t\tnetworkPrefixChoiceTypeFound := false\n\n\t\t\t\t\tif v, ok := staticIpMapStrToI[\"cluster_static_ip\"]; ok && !isIntfNil(v) && !networkPrefixChoiceTypeFound {\n\n\t\t\t\t\t\tnetworkPrefixChoiceTypeFound = true\n\t\t\t\t\t\tnetworkPrefixChoiceInt := &ves_io_schema_network_interface.StaticIPParametersType_ClusterStaticIp{}\n\t\t\t\t\t\tnetworkPrefixChoiceInt.ClusterStaticIp = &ves_io_schema_network_interface.StaticIpParametersClusterType{}\n\t\t\t\t\t\tstaticIp.NetworkPrefixChoice = networkPrefixChoiceInt\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\t// interface_ip_map\n\n\t\t\t\t\t\t\tif v, ok := cs[\"interface_ip_map\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\t\t\tinterfaceIpMap := make(map[string]*ves_io_schema_network_interface.StaticIpParametersNodeType)\n\t\t\t\t\t\t\t\tnetworkPrefixChoiceInt.ClusterStaticIp.InterfaceIpMap = interfaceIpMap\n\t\t\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\t\t\tinterfaceIpMapMapStrToI := set.(map[string]interface{})\n\t\t\t\t\t\t\t\t\tkey, ok := interfaceIpMapMapStrToI[\"name\"]\n\t\t\t\t\t\t\t\t\tif ok && !isIntfNil(key) {\n\t\t\t\t\t\t\t\t\t\tinterfaceIpMap[key.(string)] = &ves_io_schema_network_interface.StaticIpParametersNodeType{}\n\t\t\t\t\t\t\t\t\t\tval, _ := interfaceIpMapMapStrToI[\"value\"]\n\n\t\t\t\t\t\t\t\t\t\tinterfaceIpMapVals := val.(*schema.Set).List()\n\t\t\t\t\t\t\t\t\t\tfor _, intVal := range interfaceIpMapVals {\n\n\t\t\t\t\t\t\t\t\t\t\tinterfaceIpMapStaticMap := intVal.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\t\t\tif w, ok := interfaceIpMapStaticMap[\"default_gw\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\t\t\t\t\tinterfaceIpMap[key.(string)].DefaultGw = w.(string)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tif w, ok := interfaceIpMapStaticMap[\"dns_server\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\t\t\t\t\tinterfaceIpMap[key.(string)].DnsServer = w.(string)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tif w, ok := interfaceIpMapStaticMap[\"ip_address\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\t\t\t\t\tinterfaceIpMap[key.(string)].IpAddress = w.(string)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t// break after one loop\n\t\t\t\t\t\t\t\t\t\t\tbreak\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\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 := staticIpMapStrToI[\"fleet_static_ip\"]; ok && !isIntfNil(v) && !networkPrefixChoiceTypeFound {\n\n\t\t\t\t\t\tnetworkPrefixChoiceTypeFound = true\n\t\t\t\t\t\tnetworkPrefixChoiceInt := &ves_io_schema_network_interface.StaticIPParametersType_FleetStaticIp{}\n\t\t\t\t\t\tnetworkPrefixChoiceInt.FleetStaticIp = &ves_io_schema_network_interface.StaticIpParametersFleetType{}\n\t\t\t\t\t\tstaticIp.NetworkPrefixChoice = networkPrefixChoiceInt\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\t// default_gw\n\n\t\t\t\t\t\t\tif v, ok := cs[\"default_gw\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\tnetworkPrefixChoiceInt.FleetStaticIp.DefaultGw = v.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// dns_server\n\n\t\t\t\t\t\t\tif v, ok := cs[\"dns_server\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\tnetworkPrefixChoiceInt.FleetStaticIp.DnsServer = v.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// network_prefix_allocator\n\n\t\t\t\t\t\t\tif v, ok := cs[\"network_prefix_allocator\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\tnetworkPrefixAllocatorInt := &ves_io_schema_views.ObjectRefType{}\n\t\t\t\t\t\t\t\tnetworkPrefixChoiceInt.FleetStaticIp.NetworkPrefixAllocator = networkPrefixAllocatorInt\n\n\t\t\t\t\t\t\t\tnpaMapToStrVal := v.(map[string]interface{})\n\t\t\t\t\t\t\t\tif val, ok := npaMapToStrVal[\"name\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\t\tnetworkPrefixAllocatorInt.Name = val.(string)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif val, ok := npaMapToStrVal[\"namespace\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\t\tnetworkPrefixAllocatorInt.Namespace = val.(string)\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif val, ok := npaMapToStrVal[\"tenant\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\t\tnetworkPrefixAllocatorInt.Tenant = val.(string)\n\t\t\t\t\t\t\t\t}\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 := staticIpMapStrToI[\"node_static_ip\"]; ok && !isIntfNil(v) && !networkPrefixChoiceTypeFound {\n\n\t\t\t\t\t\tnetworkPrefixChoiceTypeFound = true\n\t\t\t\t\t\tnetworkPrefixChoiceInt := &ves_io_schema_network_interface.StaticIPParametersType_NodeStaticIp{}\n\t\t\t\t\t\tnetworkPrefixChoiceInt.NodeStaticIp = &ves_io_schema_network_interface.StaticIpParametersNodeType{}\n\t\t\t\t\t\tstaticIp.NetworkPrefixChoice = networkPrefixChoiceInt\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\t// default_gw\n\n\t\t\t\t\t\t\tif v, ok := cs[\"default_gw\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\tnetworkPrefixChoiceInt.NodeStaticIp.DefaultGw = v.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// dns_server\n\n\t\t\t\t\t\t\tif v, ok := cs[\"dns_server\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\tnetworkPrefixChoiceInt.NodeStaticIp.DnsServer = v.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// ip_address\n\n\t\t\t\t\t\t\tif v, ok := cs[\"ip_address\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\tnetworkPrefixChoiceInt.NodeStaticIp.IpAddress = v.(string)\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\t// tunnel\n\n\t\t\tif v, ok := cs[\"tunnel\"]; ok && !isIntfNil(v) {\n\n\t\t\t\ttunnelInt := &ves_io_schema_views.ObjectRefType{}\n\t\t\t\tinterfaceChoiceInt.TunnelInterface.Tunnel = tunnelInt\n\n\t\t\t\ttMapToStrVal := v.(map[string]interface{})\n\t\t\t\tif val, ok := tMapToStrVal[\"name\"]; ok && !isIntfNil(v) {\n\t\t\t\t\ttunnelInt.Name = val.(string)\n\t\t\t\t}\n\t\t\t\tif val, ok := tMapToStrVal[\"namespace\"]; ok && !isIntfNil(v) {\n\t\t\t\t\ttunnelInt.Namespace = val.(string)\n\t\t\t\t}\n\n\t\t\t\tif val, ok := tMapToStrVal[\"tenant\"]; ok && !isIntfNil(v) {\n\t\t\t\t\ttunnelInt.Tenant = val.(string)\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tlog.Printf(\"[DEBUG] Creating Volterra NetworkInterface object with struct: %+v\", createReq)\n\n\tcreateNetworkInterfaceResp, err := client.CreateObject(context.Background(), ves_io_schema_network_interface.ObjectType, createReq)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating NetworkInterface: %s\", err)\n\t}\n\td.SetId(createNetworkInterfaceResp.GetObjSystemMetadata().GetUid())\n\n\treturn resourceVolterraNetworkInterfaceRead(d, meta)\n}", "func (o *ValidateCreateServiceRequestNamingParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (o *CreateListParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func AddTimeout() {}", "func configureRequestTimeout() {\n\trequestTimeout = defaultRequestTimeout\n\n\tif v := os.Getenv(registryClientTimeoutEnvName); v != \"\" {\n\t\ttimeout, err := strconv.Atoi(v)\n\t\tif err == nil && timeout > 0 {\n\t\t\trequestTimeout = time.Duration(timeout) * time.Second\n\t\t}\n\t}\n}", "func ExampleVirtualMachineScaleSetsClient_BeginCreateOrUpdate_createOrUpdateAScaleSetWithCapacityReservation() {\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\tclientFactory, err := armcompute.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpoller, err := clientFactory.NewVirtualMachineScaleSetsClient().BeginCreateOrUpdate(ctx, \"myResourceGroup\", \"{vmss-name}\", armcompute.VirtualMachineScaleSet{\n\t\tLocation: to.Ptr(\"westus\"),\n\t\tProperties: &armcompute.VirtualMachineScaleSetProperties{\n\t\t\tOverprovision: to.Ptr(true),\n\t\t\tUpgradePolicy: &armcompute.UpgradePolicy{\n\t\t\t\tMode: to.Ptr(armcompute.UpgradeModeManual),\n\t\t\t},\n\t\t\tVirtualMachineProfile: &armcompute.VirtualMachineScaleSetVMProfile{\n\t\t\t\tCapacityReservation: &armcompute.CapacityReservationProfile{\n\t\t\t\t\tCapacityReservationGroup: &armcompute.SubResource{\n\t\t\t\t\t\tID: to.Ptr(\"subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/CapacityReservationGroups/{crgName}\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tNetworkProfile: &armcompute.VirtualMachineScaleSetNetworkProfile{\n\t\t\t\t\tNetworkInterfaceConfigurations: []*armcompute.VirtualMachineScaleSetNetworkConfiguration{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: to.Ptr(\"{vmss-name}\"),\n\t\t\t\t\t\t\tProperties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{\n\t\t\t\t\t\t\t\tEnableIPForwarding: to.Ptr(true),\n\t\t\t\t\t\t\t\tIPConfigurations: []*armcompute.VirtualMachineScaleSetIPConfiguration{\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tName: to.Ptr(\"{vmss-name}\"),\n\t\t\t\t\t\t\t\t\t\tProperties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{\n\t\t\t\t\t\t\t\t\t\t\tSubnet: &armcompute.APIEntityReference{\n\t\t\t\t\t\t\t\t\t\t\t\tID: to.Ptr(\"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/{existing-virtual-network-name}/subnets/{existing-subnet-name}\"),\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\t\t\t\t\t\t\t\tPrimary: to.Ptr(true),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t\tOSProfile: &armcompute.VirtualMachineScaleSetOSProfile{\n\t\t\t\t\tAdminPassword: to.Ptr(\"{your-password}\"),\n\t\t\t\t\tAdminUsername: to.Ptr(\"{your-username}\"),\n\t\t\t\t\tComputerNamePrefix: to.Ptr(\"{vmss-name}\"),\n\t\t\t\t},\n\t\t\t\tStorageProfile: &armcompute.VirtualMachineScaleSetStorageProfile{\n\t\t\t\t\tImageReference: &armcompute.ImageReference{\n\t\t\t\t\t\tOffer: to.Ptr(\"WindowsServer\"),\n\t\t\t\t\t\tPublisher: to.Ptr(\"MicrosoftWindowsServer\"),\n\t\t\t\t\t\tSKU: to.Ptr(\"2016-Datacenter\"),\n\t\t\t\t\t\tVersion: to.Ptr(\"latest\"),\n\t\t\t\t\t},\n\t\t\t\t\tOSDisk: &armcompute.VirtualMachineScaleSetOSDisk{\n\t\t\t\t\t\tCaching: to.Ptr(armcompute.CachingTypesReadWrite),\n\t\t\t\t\t\tCreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),\n\t\t\t\t\t\tManagedDisk: &armcompute.VirtualMachineScaleSetManagedDiskParameters{\n\t\t\t\t\t\t\tStorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),\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\tSKU: &armcompute.SKU{\n\t\t\tName: to.Ptr(\"Standard_DS1_v2\"),\n\t\t\tCapacity: to.Ptr[int64](3),\n\t\t\tTier: to.Ptr(\"Standard\"),\n\t\t},\n\t}, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\tres, err := poller.PollUntilDone(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to pull the result: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.VirtualMachineScaleSet = armcompute.VirtualMachineScaleSet{\n\t// \tName: to.Ptr(\"{vmss-name}\"),\n\t// \tType: to.Ptr(\"Microsoft.Compute/virtualMachineScaleSets\"),\n\t// \tID: to.Ptr(\"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachineScaleSets/{vmss-name}\"),\n\t// \tLocation: to.Ptr(\"westus\"),\n\t// \tProperties: &armcompute.VirtualMachineScaleSetProperties{\n\t// \t\tOverprovision: to.Ptr(true),\n\t// \t\tProvisioningState: to.Ptr(\"Succeeded\"),\n\t// \t\tSinglePlacementGroup: to.Ptr(true),\n\t// \t\tUniqueID: to.Ptr(\"d053ec5a-8da6-495f-ab13-38216503c6d7\"),\n\t// \t\tUpgradePolicy: &armcompute.UpgradePolicy{\n\t// \t\t\tMode: to.Ptr(armcompute.UpgradeModeManual),\n\t// \t\t},\n\t// \t\tVirtualMachineProfile: &armcompute.VirtualMachineScaleSetVMProfile{\n\t// \t\t\tCapacityReservation: &armcompute.CapacityReservationProfile{\n\t// \t\t\t\tCapacityReservationGroup: &armcompute.SubResource{\n\t// \t\t\t\t\tID: to.Ptr(\"subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/CapacityReservationGroups/{crgName}\"),\n\t// \t\t\t\t},\n\t// \t\t\t},\n\t// \t\t\tNetworkProfile: &armcompute.VirtualMachineScaleSetNetworkProfile{\n\t// \t\t\t\tNetworkInterfaceConfigurations: []*armcompute.VirtualMachineScaleSetNetworkConfiguration{\n\t// \t\t\t\t\t{\n\t// \t\t\t\t\t\tName: to.Ptr(\"{vmss-name}\"),\n\t// \t\t\t\t\t\tProperties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{\n\t// \t\t\t\t\t\t\tDNSSettings: &armcompute.VirtualMachineScaleSetNetworkConfigurationDNSSettings{\n\t// \t\t\t\t\t\t\t\tDNSServers: []*string{\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\tEnableAcceleratedNetworking: to.Ptr(false),\n\t// \t\t\t\t\t\t\tEnableIPForwarding: to.Ptr(true),\n\t// \t\t\t\t\t\t\tIPConfigurations: []*armcompute.VirtualMachineScaleSetIPConfiguration{\n\t// \t\t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\t\tName: to.Ptr(\"{vmss-name}\"),\n\t// \t\t\t\t\t\t\t\t\tProperties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{\n\t// \t\t\t\t\t\t\t\t\t\tPrivateIPAddressVersion: to.Ptr(armcompute.IPVersionIPv4),\n\t// \t\t\t\t\t\t\t\t\t\tSubnet: &armcompute.APIEntityReference{\n\t// \t\t\t\t\t\t\t\t\t\t\tID: to.Ptr(\"/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/nsgExistingVnet/subnets/nsgExistingSubnet\"),\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}},\n\t// \t\t\t\t\t\t\tPrimary: to.Ptr(true),\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t}},\n\t// \t\t\t},\n\t// \t\t\tOSProfile: &armcompute.VirtualMachineScaleSetOSProfile{\n\t// \t\t\t\tAdminUsername: to.Ptr(\"{your-username}\"),\n\t// \t\t\t\tComputerNamePrefix: to.Ptr(\"{vmss-name}\"),\n\t// \t\t\t\tSecrets: []*armcompute.VaultSecretGroup{\n\t// \t\t\t\t},\n\t// \t\t\t\tWindowsConfiguration: &armcompute.WindowsConfiguration{\n\t// \t\t\t\t\tEnableAutomaticUpdates: to.Ptr(true),\n\t// \t\t\t\t\tProvisionVMAgent: to.Ptr(true),\n\t// \t\t\t\t},\n\t// \t\t\t},\n\t// \t\t\tStorageProfile: &armcompute.VirtualMachineScaleSetStorageProfile{\n\t// \t\t\t\tImageReference: &armcompute.ImageReference{\n\t// \t\t\t\t\tOffer: to.Ptr(\"WindowsServer\"),\n\t// \t\t\t\t\tPublisher: to.Ptr(\"MicrosoftWindowsServer\"),\n\t// \t\t\t\t\tSKU: to.Ptr(\"2016-Datacenter\"),\n\t// \t\t\t\t\tVersion: to.Ptr(\"latest\"),\n\t// \t\t\t\t},\n\t// \t\t\t\tOSDisk: &armcompute.VirtualMachineScaleSetOSDisk{\n\t// \t\t\t\t\tCaching: to.Ptr(armcompute.CachingTypesReadWrite),\n\t// \t\t\t\t\tCreateOption: to.Ptr(armcompute.DiskCreateOptionTypesFromImage),\n\t// \t\t\t\t\tManagedDisk: &armcompute.VirtualMachineScaleSetManagedDiskParameters{\n\t// \t\t\t\t\t\tStorageAccountType: to.Ptr(armcompute.StorageAccountTypesStandardLRS),\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// \tSKU: &armcompute.SKU{\n\t// \t\tName: to.Ptr(\"Standard_DS1_v2\"),\n\t// \t\tCapacity: to.Ptr[int64](3),\n\t// \t\tTier: to.Ptr(\"Standard\"),\n\t// \t},\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 WithPoolTimeout(timeout time.Duration) OptsFunc {\n\treturn func(o *redis.Options) {\n\t\to.PoolTimeout = timeout\n\t}\n}", "func (o *CreateDashboardRenderTaskParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (o *IndicatorCreateV1Params) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func ExampleVirtualNetworkTapsClient_BeginCreateOrUpdate() {\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\tclientFactory, err := armnetwork.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpoller, err := clientFactory.NewVirtualNetworkTapsClient().BeginCreateOrUpdate(ctx, \"rg1\", \"test-vtap\", armnetwork.VirtualNetworkTap{\n\t\tLocation: to.Ptr(\"centraluseuap\"),\n\t\tProperties: &armnetwork.VirtualNetworkTapPropertiesFormat{\n\t\t\tDestinationNetworkInterfaceIPConfiguration: &armnetwork.InterfaceIPConfiguration{\n\t\t\t\tID: to.Ptr(\"/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/networkInterfaces/testNetworkInterface/ipConfigurations/ipconfig1\"),\n\t\t\t},\n\t\t},\n\t}, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\tres, err := poller.PollUntilDone(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to pull the result: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.VirtualNetworkTap = armnetwork.VirtualNetworkTap{\n\t// \tName: to.Ptr(\"testvtap\"),\n\t// \tType: to.Ptr(\"Microsoft.Network/virtualNetworkTaps\"),\n\t// \tID: to.Ptr(\"/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/virtualNetworkTaps/testvtap\"),\n\t// \tLocation: to.Ptr(\"centraluseuap\"),\n\t// \tEtag: to.Ptr(\"etag\"),\n\t// \tProperties: &armnetwork.VirtualNetworkTapPropertiesFormat{\n\t// \t\tDestinationNetworkInterfaceIPConfiguration: &armnetwork.InterfaceIPConfiguration{\n\t// \t\t\tID: to.Ptr(\"/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/networkInterfaces/testNetworkInterface/ipConfigurations/testIPConfig1\"),\n\t// \t\t},\n\t// \t\tDestinationPort: to.Ptr[int32](4789),\n\t// \t\tNetworkInterfaceTapConfigurations: []*armnetwork.InterfaceTapConfiguration{\n\t// \t\t\t{\n\t// \t\t\t\tID: to.Ptr(\"/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/networkInterfaces/testNetworkInterface2/tapConfigurations/testtapConfiguration\"),\n\t// \t\t}},\n\t// \t\tProvisioningState: to.Ptr(armnetwork.ProvisioningStateSucceeded),\n\t// \t\tResourceGUID: to.Ptr(\"6A7C139D-8B8D-499B-B7CB-4F3F02A8A44F\"),\n\t// \t},\n\t// }\n}", "func (o *CreateScheduledPlanParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (o *AddOrUpdateNodePoolConfigItemParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (o *CreateInstantPaymentParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func AddPunchHoleTimeout() {}", "func TestNewThrottler2(t *testing.T) {\n\ttestThrottler := &Throttler{transport: http.DefaultTransport,\n\t\tmapMethods: map[string]struct{}{\"DELETE\": {}, \"GET\": {}, \"POST\": {}, \"PUT\": {}},\n\t\tlimiter: rate.NewLimiter(rate.Every(time.Minute/(time.Duration(60))), 1),\n\t\tgoodPrefix: new([]string),\n\t\tbadPrefix: new([]string),\n\t\twaitLimit: true}\n\tgetThrottler := NewThrottler(http.DefaultTransport,\n\t\t&[]string{\"GET\", \"POST\", \"PUT\", \"DELETE\"},\n\t\ttime.Minute, 60,\n\t\tnil, nil,\n\t\ttrue)\n\tif !reflect.DeepEqual(testThrottler, getThrottler) {\n\t\tt.Error(\n\t\t\t\"message\", \"the problem is in creating a new throttler\",\n\t\t)\n\t}\n\ttestThrottler.waitLimit = false\n\tif reflect.DeepEqual(testThrottler, getThrottler) {\n\t\tt.Error(\n\t\t\t\"message\", \"the problem is in creating a new throttler\",\n\t\t)\n\t}\n}", "func WithTimeout(t time.Duration) Option {\n\treturn func(c *Client) { c.httpClient.Timeout = t }\n}", "func (o *CreateCognitoIDPParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func newReconciler(mgr manager.Manager, opts options.AddOptions, licenseAPIReady *utils.ReadyFlag) reconcile.Reconciler {\n\tr := &ReconcileEgressGateway{\n\t\tclient: mgr.GetClient(),\n\t\tscheme: mgr.GetScheme(),\n\t\tprovider: opts.DetectedProvider,\n\t\tstatus: status.New(mgr.GetClient(), \"egressgateway\", opts.KubernetesVersion),\n\t\tclusterDomain: opts.ClusterDomain,\n\t\tlicenseAPIReady: licenseAPIReady,\n\t\tusePSP: opts.UsePSP,\n\t}\n\tr.status.Run(opts.ShutdownContext)\n\treturn r\n}", "func (o *GetInterceptionitemsParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (p *Poller) createRuntime(runtimeKeyValues [][]*RuntimeKeyValue, ttl *time.Duration) ([]gcpTypes.ResourceWithTTL, int) {\n\tisUsed := func(usedKeys map[string]bool, keyValues []*RuntimeKeyValue) bool {\n\t\tfor _, kv := range keyValues {\n\t\t\tif val, ok := usedKeys[kv.Key]; ok && val {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\tupdateIsUsed := func(usedKeys map[string]bool, keyValues []*RuntimeKeyValue) {\n\t\tfor _, kv := range keyValues {\n\t\t\tusedKeys[kv.Key] = true\n\t\t}\n\t}\n\n\tappliedKeValueSetsCount := 0\n\tusedKeyValues := make([]*RuntimeKeyValue, 0)\n\tusedKeys := make(map[string]bool)\n\tfor _, kvs := range runtimeKeyValues {\n\t\tif isUsed(usedKeys, kvs) {\n\t\t\t// Skip if there is an overlap between already processed keys and\n\t\t\t// keys that are being currently evaluated.\n\t\t\tcontinue\n\t\t}\n\n\t\tappliedKeValueSetsCount += 1\n\t\tupdateIsUsed(usedKeys, kvs)\n\t\tusedKeyValues = append(usedKeyValues, kvs...)\n\t}\n\n\tvar fieldsMap = map[string]*pstruct.Value{}\n\tfor _, kv := range usedKeyValues {\n\t\tfieldsMap[kv.Key] = &pstruct.Value{\n\t\t\tKind: &pstruct.Value_NumberValue{\n\t\t\t\tNumberValue: float64(kv.Value),\n\t\t\t},\n\t\t}\n\t}\n\n\t// We only want to set a TTL for non-empty layers. This ensures that we don't spam clients with heartbeat responses\n\t// unless they have an active runtime override.\n\tvar resourceTTL *time.Duration\n\tif len(usedKeyValues) > 0 {\n\t\tresourceTTL = ttl\n\t}\n\n\treturn []gcpTypes.ResourceWithTTL{{\n\t\tResource: &gcpRuntimeServiceV3.Runtime{\n\t\t\tName: p.rtdsConfig.layerName,\n\t\t\tLayer: &pstruct.Struct{\n\t\t\t\tFields: fieldsMap,\n\t\t\t},\n\t\t},\n\t\tTTL: resourceTTL,\n\t}}, appliedKeValueSetsCount\n}", "func (o *CreateLifecycleParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func Timeout(t time.Duration) ClientOpt {\n\treturn func(c *Client) {\n\t\tc.HTTPClient.Timeout = t\n\t}\n}", "func WithPerRetryTimeout(timeout time.Duration) *CallOption {\n\treturn &CallOption{apply: func(o *options) {\n\t\to.perCallTimeout = timeout\n\t}}\n}", "func WithTimeout(timeout time.Duration) ClientOption {\n\treturn withTimeout{timeout}\n}", "func (o GetAppTemplateContainerReadinessProbeOutput) Timeout() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GetAppTemplateContainerReadinessProbe) int { return v.Timeout }).(pulumi.IntOutput)\n}", "func (o *CloudTargetCreateParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (o *GetDeploymentByIDV3UsingGETParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func TestAllocRunner_TaskMain_KillTG(t *testing.T) {\n\tci.Parallel(t)\n\n\talloc := mock.BatchAlloc()\n\ttr := alloc.AllocatedResources.Tasks[alloc.Job.TaskGroups[0].Tasks[0].Name]\n\talloc.Job.TaskGroups[0].RestartPolicy.Attempts = 0\n\talloc.Job.TaskGroups[0].Tasks[0].RestartPolicy.Attempts = 0\n\n\t// Create four tasks in the task group\n\tprestart := alloc.Job.TaskGroups[0].Tasks[0].Copy()\n\tprestart.Name = \"prestart-sidecar\"\n\tprestart.Driver = \"mock_driver\"\n\tprestart.KillTimeout = 10 * time.Millisecond\n\tprestart.Lifecycle = &structs.TaskLifecycleConfig{\n\t\tHook: structs.TaskLifecycleHookPrestart,\n\t\tSidecar: true,\n\t}\n\n\tprestart.Config = map[string]interface{}{\n\t\t\"run_for\": \"100s\",\n\t}\n\n\tpoststart := alloc.Job.TaskGroups[0].Tasks[0].Copy()\n\tpoststart.Name = \"poststart-sidecar\"\n\tpoststart.Driver = \"mock_driver\"\n\tpoststart.KillTimeout = 10 * time.Millisecond\n\tpoststart.Lifecycle = &structs.TaskLifecycleConfig{\n\t\tHook: structs.TaskLifecycleHookPoststart,\n\t\tSidecar: true,\n\t}\n\n\tpoststart.Config = map[string]interface{}{\n\t\t\"run_for\": \"100s\",\n\t}\n\n\t// these two main tasks have the same name, is that ok?\n\tmain1 := alloc.Job.TaskGroups[0].Tasks[0].Copy()\n\tmain1.Name = \"task2\"\n\tmain1.Driver = \"mock_driver\"\n\tmain1.Config = map[string]interface{}{\n\t\t\"run_for\": \"1s\",\n\t}\n\n\tmain2 := alloc.Job.TaskGroups[0].Tasks[0].Copy()\n\tmain2.Name = \"task2\"\n\tmain2.Driver = \"mock_driver\"\n\tmain2.Config = map[string]interface{}{\n\t\t\"run_for\": \"2s\",\n\t}\n\n\talloc.Job.TaskGroups[0].Tasks = []*structs.Task{prestart, poststart, main1, main2}\n\talloc.AllocatedResources.Tasks = map[string]*structs.AllocatedTaskResources{\n\t\tprestart.Name: tr,\n\t\tpoststart.Name: tr,\n\t\tmain1.Name: tr,\n\t\tmain2.Name: tr,\n\t}\n\n\tconf, cleanup := testAllocRunnerConfig(t, alloc)\n\tdefer cleanup()\n\tar, err := NewAllocRunner(conf)\n\trequire.NoError(t, err)\n\tdefer destroy(ar)\n\tgo ar.Run()\n\n\thasTaskMainEvent := func(state *structs.TaskState) bool {\n\t\tfor _, e := range state.Events {\n\t\t\tif e.Type == structs.TaskMainDead {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\treturn false\n\t}\n\n\t// Wait for all tasks to be killed\n\tupd := conf.StateUpdater.(*MockStateUpdater)\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tlast := upd.Last()\n\t\tif last == nil {\n\t\t\treturn false, fmt.Errorf(\"No updates\")\n\t\t}\n\t\tif last.ClientStatus != structs.AllocClientStatusComplete {\n\t\t\treturn false, fmt.Errorf(\"got status %v; want %v\", last.ClientStatus, structs.AllocClientStatusComplete)\n\t\t}\n\n\t\tvar state *structs.TaskState\n\n\t\t// both sidecars should be killed because Task2 exited\n\t\tstate = last.TaskStates[prestart.Name]\n\t\tif state == nil {\n\t\t\treturn false, fmt.Errorf(\"could not find state for task %s\", prestart.Name)\n\t\t}\n\t\tif state.State != structs.TaskStateDead {\n\t\t\treturn false, fmt.Errorf(\"got state %v; want %v\", state.State, structs.TaskStateDead)\n\t\t}\n\t\tif state.FinishedAt.IsZero() || state.StartedAt.IsZero() {\n\t\t\treturn false, fmt.Errorf(\"expected to have a start and finish time\")\n\t\t}\n\t\tif len(state.Events) < 2 {\n\t\t\t// At least have a received and destroyed\n\t\t\treturn false, fmt.Errorf(\"Unexpected number of events\")\n\t\t}\n\n\t\tif !hasTaskMainEvent(state) {\n\t\t\treturn false, fmt.Errorf(\"Did not find event %v: %#+v\", structs.TaskMainDead, state.Events)\n\t\t}\n\n\t\tstate = last.TaskStates[poststart.Name]\n\t\tif state == nil {\n\t\t\treturn false, fmt.Errorf(\"could not find state for task %s\", poststart.Name)\n\t\t}\n\t\tif state.State != structs.TaskStateDead {\n\t\t\treturn false, fmt.Errorf(\"got state %v; want %v\", state.State, structs.TaskStateDead)\n\t\t}\n\t\tif state.FinishedAt.IsZero() || state.StartedAt.IsZero() {\n\t\t\treturn false, fmt.Errorf(\"expected to have a start and finish time\")\n\t\t}\n\t\tif len(state.Events) < 2 {\n\t\t\t// At least have a received and destroyed\n\t\t\treturn false, fmt.Errorf(\"Unexpected number of events\")\n\t\t}\n\n\t\tif !hasTaskMainEvent(state) {\n\t\t\treturn false, fmt.Errorf(\"Did not find event %v: %#+v\", structs.TaskMainDead, state.Events)\n\t\t}\n\n\t\t// main tasks should die naturely\n\t\tstate = last.TaskStates[main1.Name]\n\t\tif state.State != structs.TaskStateDead {\n\t\t\treturn false, fmt.Errorf(\"got state %v; want %v\", state.State, structs.TaskStateDead)\n\t\t}\n\t\tif state.FinishedAt.IsZero() || state.StartedAt.IsZero() {\n\t\t\treturn false, fmt.Errorf(\"expected to have a start and finish time\")\n\t\t}\n\t\tif hasTaskMainEvent(state) {\n\t\t\treturn false, fmt.Errorf(\"unexpected event %#+v in %v\", structs.TaskMainDead, state.Events)\n\t\t}\n\n\t\tstate = last.TaskStates[main2.Name]\n\t\tif state.State != structs.TaskStateDead {\n\t\t\treturn false, fmt.Errorf(\"got state %v; want %v\", state.State, structs.TaskStateDead)\n\t\t}\n\t\tif state.FinishedAt.IsZero() || state.StartedAt.IsZero() {\n\t\t\treturn false, fmt.Errorf(\"expected to have a start and finish time\")\n\t\t}\n\t\tif hasTaskMainEvent(state) {\n\t\t\treturn false, fmt.Errorf(\"unexpected event %v in %#+v\", structs.TaskMainDead, state.Events)\n\t\t}\n\n\t\treturn true, nil\n\t}, func(err error) {\n\t\tt.Fatalf(\"err: %v\", err)\n\t})\n}", "func createNamespace(t *testing.T, name string) *corev1.Namespace {\n\tt.Helper()\n\n\tt.Logf(\"Creating namespace %q...\", name)\n\tns := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: name}}\n\tif err := kclient.Create(context.TODO(), ns); err != nil {\n\t\tt.Fatalf(\"failed to create namespace: %v\", err)\n\t}\n\tt.Cleanup(func() {\n\t\tt.Logf(\"Dumping events in namespace %q...\", name)\n\t\tif t.Failed() {\n\t\t\tdumpEventsInNamespace(t, name)\n\t\t}\n\t\tt.Logf(\"Deleting namespace %q...\", name)\n\t\tif err := kclient.Delete(context.TODO(), ns); err != nil {\n\t\t\tt.Errorf(\"failed to delete namespace %s: %v\", ns.Name, err)\n\t\t}\n\t})\n\n\tsaName := types.NamespacedName{\n\t\tNamespace: name,\n\t\tName: \"default\",\n\t}\n\tt.Logf(\"Waiting for ServiceAccount %s to be provisioned...\", saName)\n\tif err := wait.PollImmediate(1*time.Second, 3*time.Minute, func() (bool, error) {\n\t\tvar sa corev1.ServiceAccount\n\t\tif err := kclient.Get(context.TODO(), saName, &sa); err != nil {\n\t\t\tif errors.IsNotFound(err) {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\t\tfor _, s := range sa.Secrets {\n\t\t\tif strings.Contains(s.Name, \"dockercfg\") {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t\treturn false, nil\n\t}); err != nil {\n\t\tt.Fatalf(`Timed out waiting for ServiceAccount %s to be provisioned: %v`, saName, err)\n\t}\n\n\trbName := types.NamespacedName{\n\t\tNamespace: name,\n\t\tName: \"system:image-pullers\",\n\t}\n\tt.Logf(\"Waiting for RoleBinding %s to be created...\", rbName)\n\tif err := wait.PollImmediate(1*time.Second, 3*time.Minute, func() (bool, error) {\n\t\tvar rb rbacv1.RoleBinding\n\t\tif err := kclient.Get(context.TODO(), rbName, &rb); err != nil {\n\t\t\tif errors.IsNotFound(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}); err != nil {\n\t\tt.Fatalf(`Timed out waiting for RoleBinding \"default\" to be provisioned: %v`, err)\n\t}\n\n\treturn ns\n}", "func createClients(config componentbaseconfig.ClientConnectionConfiguration,\n\ttimeout time.Duration) (clientset.Interface, clientset.Interface, clientset.Interface, error) {\n\tkubeConfig, err := clientcmd.BuildConfigFromFlags(\"\", config.Kubeconfig)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tkubeConfig.DisableCompression = true\n\tkubeConfig.AcceptContentTypes = config.AcceptContentTypes\n\tkubeConfig.ContentType = config.ContentType\n\tkubeConfig.QPS = config.QPS\n\tkubeConfig.Burst = int(config.Burst)\n\n\tclient, err := clientset.NewForConfig(restclient.AddUserAgent(kubeConfig, \"dynamic-scheduler\"))\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// shallow copy, do not modify the kubeConfig.Timeout.\n\trestConfig := *kubeConfig\n\trestConfig.Timeout = timeout\n\tleaderElectionClient, err := clientset.NewForConfig(restclient.AddUserAgent(&restConfig, \"leader-election\"))\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\teventClient, err := clientset.NewForConfig(kubeConfig)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\treturn client, leaderElectionClient, eventClient, nil\n}", "func newTimeoutResponse(id string) *Response {\n\treturn &Response{\n\t\tID: id,\n\t\tError: &HTTPResponse{\n\t\t\tRawStatus: http.StatusGatewayTimeout,\n\t\t\tRawBody: map[string]interface{}{},\n\t\t},\n\t}\n}", "func (o *IntegrationsManualHTTPSCreateParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func ConstructTimeoutQueue( workers int ) chan *packet_metadata {\n\n timeoutQueue := make(chan *packet_metadata, 1000000)\n return timeoutQueue\n}", "func DiscoveryTimeout(t time.Duration) RequestOption {\n\treturn func(o *RequestOptions) {\n\t\to.DiscoveryTimeout = t\n\t}\n}", "func (o AppTemplateContainerLivenessProbeOutput) Timeout() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v AppTemplateContainerLivenessProbe) *int { return v.Timeout }).(pulumi.IntPtrOutput)\n}", "func (o *CreatePublicIPAdressUsingPOSTParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (o *GetClientConfigV1ConfigByNameParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func IngressToGateway(key resource.VersionedKey, i *ingress.IngressSpec) resource.Entry {\n\tnamespace, name := key.FullName.InterpretAsNamespaceAndName()\n\n\tgateway := &v1alpha3.Gateway{\n\t\tSelector: model.IstioIngressWorkloadLabels,\n\t}\n\n\t// FIXME this is a temporary hack until all test templates are updated\n\t//for _, tls := range i.Spec.TLS {\n\tif len(i.TLS) > 0 {\n\t\ttls := i.TLS[0] // FIXME\n\t\t// TODO validation when multiple wildcard tls secrets are given\n\t\tif len(tls.Hosts) == 0 {\n\t\t\ttls.Hosts = []string{\"*\"}\n\t\t}\n\t\tgateway.Servers = append(gateway.Servers, &v1alpha3.Server{\n\t\t\tPort: &v1alpha3.Port{\n\t\t\t\tNumber: 443,\n\t\t\t\tProtocol: string(model.ProtocolHTTPS),\n\t\t\t\tName: fmt.Sprintf(\"https-443-i-%s-%s\", name, namespace),\n\t\t\t},\n\t\t\tHosts: tls.Hosts,\n\t\t\t// While we accept multiple certs, we expect them to be mounted in\n\t\t\t// /etc/istio/certs/namespace/secretname/tls.crt|tls.key\n\t\t\tTls: &v1alpha3.Server_TLSOptions{\n\t\t\t\tHttpsRedirect: false,\n\t\t\t\tMode: v1alpha3.Server_TLSOptions_SIMPLE,\n\t\t\t\t// TODO this is no longer valid for the new v2 stuff\n\t\t\t\tPrivateKey: path.Join(model.IngressCertsPath, model.IngressKeyFilename),\n\t\t\t\tServerCertificate: path.Join(model.IngressCertsPath, model.IngressCertFilename),\n\t\t\t\t// TODO: make sure this is mounted\n\t\t\t\tCaCertificates: path.Join(model.IngressCertsPath, model.RootCertFilename),\n\t\t\t},\n\t\t})\n\t}\n\n\tgateway.Servers = append(gateway.Servers, &v1alpha3.Server{\n\t\tPort: &v1alpha3.Port{\n\t\t\tNumber: 80,\n\t\t\tProtocol: string(model.ProtocolHTTP),\n\t\t\tName: fmt.Sprintf(\"http-80-i-%s-%s\", name, namespace),\n\t\t},\n\t\tHosts: []string{\"*\"},\n\t})\n\n\tnewName := name + \"-\" + model.IstioIngressGatewayName\n\tnewNamespace := model.IstioIngressNamespace\n\n\tgw := resource.Entry{\n\t\tID: resource.VersionedKey{\n\t\t\tKey: resource.Key{\n\t\t\t\tFullName: resource.FullNameFromNamespaceAndName(newNamespace, newName),\n\t\t\t\tTypeURL: metadata.VirtualService.TypeURL,\n\t\t\t},\n\t\t\tVersion: key.Version,\n\t\t\tCreateTime: key.CreateTime,\n\t\t},\n\t\tItem: gateway,\n\t}\n\n\treturn gw\n}", "func createRetentionSpec(queueName string, taskType queue.TaskType, status queue.TaskStatus, age time.Duration) retentionTaskSpec {\n\tspec := retentionTaskSpec{\n\t\tQueueName: queueName,\n\t\tTaskType: taskType,\n\t\tStatus: status,\n\t\tAge: age,\n\t}\n\n\t// use separate WHERE statements to make the order deterministic\n\tdeletionSQL := squirrel.Delete(TasksTable).\n\t\tWhere(squirrel.Eq{\"status\": status}).\n\t\tWhere(\n\t\t\t// note that using this comparision allows us to use the index on\n\t\t\t// finished_at, if yo use `age(now(), finished_at)`, this can not use the index\n\t\t\tfmt.Sprintf(\"finished_at <= now() - interval '%f minutes'\", age.Minutes()),\n\t\t)\n\n\tif queueName != \"\" {\n\t\tdeletionSQL = deletionSQL.Where(squirrel.Eq{\"queue\": queueName})\n\t}\n\n\tif taskType != \"\" {\n\t\tdeletionSQL = deletionSQL.Where(squirrel.Eq{\"type\": taskType})\n\t}\n\n\tspec.SQL = squirrel.DebugSqlizer(deletionSQL)\n\n\treturn spec\n}", "func (o *GetTerraformConfigurationSourcesUsingGET1Params) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func createIngress(kubeconfig string, kubeContexts []string, ing *v1beta1.Ingress) ([]string, map[string]kubeclient.Interface, error) {\n\tclients, err := kubeutils.GetClients(kubeconfig, kubeContexts)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tclusters, createErr := createIngressInClusters(ing, clients)\n\treturn clusters, clients, createErr\n}", "func (o *ActionDeploymentRequestUsingPOST2Params) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func Timeout(d time.Duration) ConfigOpt {\n\treturn func(c *Config) {\n\t\tc.transport.ResponseHeaderTimeout = d\n\t\tc.transport.TLSHandshakeTimeout = d\n\t\tc.dialer.Timeout = d\n\t}\n}", "func newTubePoolWithOptions(address string, options tubePoolOptions, connConfigData connConfig) *tubePool {\n\tif options.maxConcurrentConnAttempts <= 0 {\n\t\toptions.maxConcurrentConnAttempts = defaultTubePoolOptions.maxConcurrentConnAttempts\n\t}\n\n\tif options.dialContext == nil {\n\t\tif connConfigData.isEncrypted {\n\t\t\tdialer := &proxy.Dialer{}\n\t\t\tvar cfg tls.Config\n\t\t\tif connConfigData.skipHostnameVerification {\n\t\t\t\tcfg = tls.Config{InsecureSkipVerify: true}\n\t\t\t} else {\n\t\t\t\tcfg = tls.Config{ServerName: connConfigData.hostname}\n\t\t\t}\n\t\t\tdialer.Config = &cfg\n\t\t\toptions.dialContext = dialer.DialContext\n\t\t} else {\n\t\t\tdialer := &net.Dialer{}\n\t\t\toptions.dialContext = dialer.DialContext\n\t\t}\n\t}\n\n\treturn &tubePool{\n\t\taddress: address,\n\t\tgate: make(gate, options.maxConcurrentConnAttempts),\n\t\terrCh: make(chan error),\n\t\twaiters: make(chan tube),\n\t\ttimeout: options.timeout,\n\t\tdialContext: options.dialContext,\n\n\t\tconnConfig: connConfigData,\n\t}\n}", "func (o *CreateWidgetParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (client *GrpcClient) CreateTimer(count int32, namespace, interval, startTime string) (string, error) {\n\ttimerID, err := uuid.NewUUID()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\ttimerIDString := timerID.String()\n\taddr, shardResult := client.messenger.GetAddress(timerIDString)\n\tif !client.messenger.config.LocalConnect {\n\t\taddr = trimAddress(addr)\n\t\taddr = addr + \":\" + strconv.Itoa(client.messenger.config.RPCPort)\n\t}\n\t// shardRes := int32(shardResult)\n\tconn, err := client.Connect(addr)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer conn.Close()\n\n\tc := proto.NewActionsClient(conn)\n\tresp, err := c.Create(context.Background(), &proto.CreateJobRequest{\n\t\tTimerId: timerIDString,\n\t\tShardId: int32(shardResult),\n\t\tNameSpace: namespace,\n\t\tInterval: interval,\n\t\tCount: count,\n\t\tStartTime: startTime,\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t//fmt.Println(resp.GetTimerinfo().GetTimerID())\n\treturn resp.GetTimerinfo().GetTimerID(), nil\n}", "func (tb *timerBuilder) createActivityTimeoutTask(fireTimeOut int32, timeoutType w.TimeoutType,\n\teventID int64, baseTime *time.Time) *persistence.ActivityTimeoutTask {\n\tvar expiryTime time.Time\n\tif baseTime != nil {\n\t\texpiryTime = baseTime.Add(time.Duration(fireTimeOut) * time.Second)\n\t} else {\n\t\texpiryTime = tb.timeSource.Now().Add(time.Duration(fireTimeOut) * time.Second)\n\t}\n\n\treturn &persistence.ActivityTimeoutTask{\n\t\tVisibilityTimestamp: expiryTime,\n\t\tTimeoutType: int(timeoutType),\n\t\tEventID: eventID,\n\t}\n}", "func (o *GetClusterTemplateByNameInWorkspaceParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func testEgressToServerInCIDRBlockWithException(t *testing.T, data *TestData) {\n\tworkerNode := workerNodeName(1)\n\tserverAName, serverAIPs, cleanupFunc := createAndWaitForPod(t, data, data.createNginxPodOnNode, \"test-server-\", workerNode, testNamespace, false)\n\tdefer cleanupFunc()\n\n\tclientA, _, cleanupFunc := createAndWaitForPod(t, data, data.createBusyboxPodOnNode, \"test-client-\", workerNode, testNamespace, false)\n\tdefer cleanupFunc()\n\tvar serverAAllowCIDR string\n\tvar serverAExceptList []string\n\tvar serverAIP string\n\tif serverAIPs.ipv6 == nil {\n\t\tt.Fatal(\"server IPv6 address is empty\")\n\t}\n\t_, serverAAllowSubnet, err := net.ParseCIDR(fmt.Sprintf(\"%s/%d\", serverAIPs.ipv6.String(), 64))\n\tif err != nil {\n\t\tt.Fatalf(\"could not parse allow subnet\")\n\t}\n\tserverAAllowCIDR = serverAAllowSubnet.String()\n\tserverAExceptList = []string{fmt.Sprintf(\"%s/%d\", serverAIPs.ipv6.String(), 128)}\n\tserverAIP = serverAIPs.ipv6.String()\n\n\tif err := data.runNetcatCommandFromTestPod(clientA, testNamespace, serverAIP, 80); err != nil {\n\t\tt.Fatalf(\"%s should be able to netcat %s\", clientA, serverAName)\n\t}\n\n\tnp, err := data.createNetworkPolicy(\"deny-client-a-via-except-cidr-egress-rule\", &networkingv1.NetworkPolicySpec{\n\t\tPodSelector: metav1.LabelSelector{\n\t\t\tMatchLabels: map[string]string{\n\t\t\t\t\"antrea-e2e\": clientA,\n\t\t\t},\n\t\t},\n\t\tPolicyTypes: []networkingv1.PolicyType{networkingv1.PolicyTypeEgress},\n\t\tEgress: []networkingv1.NetworkPolicyEgressRule{\n\t\t\t{\n\t\t\t\tTo: []networkingv1.NetworkPolicyPeer{\n\t\t\t\t\t{\n\t\t\t\t\t\tIPBlock: &networkingv1.IPBlock{\n\t\t\t\t\t\t\tCIDR: serverAAllowCIDR,\n\t\t\t\t\t\t\tExcept: serverAExceptList,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tt.Fatalf(\"Error when creating network policy: %v\", err)\n\t}\n\tcleanupNP := func() {\n\t\tif err = data.deleteNetworkpolicy(np); err != nil {\n\t\t\tt.Errorf(\"Error when deleting network policy: %v\", err)\n\t\t}\n\t}\n\tdefer cleanupNP()\n\n\tif err := data.runNetcatCommandFromTestPod(clientA, testNamespace, serverAIP, 80); err == nil {\n\t\tt.Fatalf(\"%s should not be able to netcat %s\", clientA, serverAName)\n\t}\n}", "func (client PrimitiveClient) PutDurationSender(req *http.Request) (*http.Response, error) {\n return autorest.SendWithSender(client, req)\n}", "func WaitForASGDesiredCapacity(ctx context.Context, f *framework.Framework, nodes []corev1.Node, desiredCapacity int) error {\n\tvar asgNames []*string\n\tvar asgs []*autoscaling.Group\n\tvar nodeNames []*string\n\tvar instanceIDs []*string\n\n\tif len(nodes) >= desiredCapacity {\n\t\treturn nil\n\t}\n\n\tfor _, node := range nodes {\n\t\tnodeName := node.Name\n\t\tnodeNames = append(nodeNames, &nodeName)\n\t}\n\n\t// Get instance IDs\n\tfilterName := \"private-dns-name\"\n\tdescribeInstancesInput := &ec2.DescribeInstancesInput{\n\t\tFilters: []*ec2.Filter{\n\t\t\t{\n\t\t\t\tName: &filterName,\n\t\t\t\tValues: nodeNames,\n\t\t\t},\n\t\t},\n\t}\n\tinstances, 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\tif len(instances) == 0 {\n\t\treturn errors.New(\"No instances found\")\n\t}\n\n\t// Get ASGs\n\tfor _, instance := range instances {\n\t\tinstanceIDs = append(instanceIDs, instance.InstanceId)\n\t}\n\tdescribeAutoScalingInstancesInput := &autoscaling.DescribeAutoScalingInstancesInput{\n\t\tInstanceIds: instanceIDs,\n\t}\n\tasgInstanceDetails, err := f.Cloud.AutoScaling().DescribeAutoScalingInstancesAsList(aws.BackgroundContext(), describeAutoScalingInstancesInput)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, asgInstance := range asgInstanceDetails {\n\t\tasgNames = append(asgNames, asgInstance.AutoScalingGroupName)\n\t}\n\tdescribeASGsInput := &autoscaling.DescribeAutoScalingGroupsInput{\n\t\tAutoScalingGroupNames: asgNames,\n\t}\n\tasgs, err = f.Cloud.AutoScaling().DescribeAutoScalingGroupsAsList(aws.BackgroundContext(), describeASGsInput)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Debug(\"verifying desired capacity of ASGs\")\n\tcap := int64(math.Ceil(float64(desiredCapacity) / float64(len(asgs))))\n\tfor _, asg := range asgs {\n\t\tif *(asg.DesiredCapacity) < cap {\n\t\t\tlog.Debugf(\"\")\n\t\t\tmax := *(asg.MaxSize)\n\t\t\tif max < cap {\n\t\t\t\tmax = cap\n\t\t\t}\n\t\t\tlog.Debugf(\"increasing ASG desired capacity to %d\", cap)\n\t\t\tupdateAutoScalingGroupInput := &autoscaling.UpdateAutoScalingGroupInput{\n\t\t\t\tAutoScalingGroupName: asg.AutoScalingGroupName,\n\t\t\t\tDesiredCapacity: &cap,\n\t\t\t\tMaxSize: &max,\n\t\t\t}\n\t\t\t_, err := f.Cloud.AutoScaling().UpdateAutoScalingGroup(updateAutoScalingGroupInput)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// Wait for instances and nodes to be ready\n\treturn WaitForASGInstancesAndNodesReady(ctx, f, describeASGsInput)\n}", "func WithTimeout(t time.Duration) APIOption {\n\treturn newAPIOption(func(o *Options) {\n\t\to.Timeout = t\n\t})\n}", "func WithTimeout(duration time.Duration) ReconcilerOption {\n\treturn func(r *Reconciler) {\n\t\tr.timeout = duration\n\t}\n}", "func (o *AutoscaleStopInstancesByCrnParams) WithTimeout(timeout time.Duration) *AutoscaleStopInstancesByCrnParams {\n\to.SetTimeout(timeout)\n\treturn o\n}", "func Timeout(t time.Duration) RequestOption {\n\treturn func(o *RequestOptions) {\n\t\to.Timeout = t\n\t}\n}", "func (o *CreateCrossConnectParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (c *OrganizationsEnvironmentsApisRevisionsDebugsessionsCreateCall) Timeout(timeout int64) *OrganizationsEnvironmentsApisRevisionsDebugsessionsCreateCall {\n\tc.urlParams_.Set(\"timeout\", fmt.Sprint(timeout))\n\treturn c\n}" ]
[ "0.48463553", "0.4834523", "0.47509903", "0.47425815", "0.46419632", "0.45079255", "0.44784862", "0.44415823", "0.44252938", "0.44230074", "0.44079074", "0.44064182", "0.4389599", "0.438555", "0.4380319", "0.43769553", "0.43735534", "0.43591672", "0.43350774", "0.4330374", "0.43274707", "0.43243742", "0.4322683", "0.43188936", "0.42986014", "0.4296885", "0.42945436", "0.4285693", "0.42796102", "0.42783228", "0.42720506", "0.42662883", "0.42568654", "0.42445004", "0.423543", "0.42344043", "0.42230904", "0.42217353", "0.42146552", "0.42145336", "0.42118135", "0.4203383", "0.42033193", "0.41942662", "0.41913095", "0.41901574", "0.41896433", "0.41871214", "0.41851693", "0.41826636", "0.41802645", "0.4180234", "0.417915", "0.4178451", "0.41775188", "0.41764483", "0.41753232", "0.41717252", "0.416955", "0.41676196", "0.4167477", "0.4164039", "0.41586083", "0.41582066", "0.41567108", "0.4156605", "0.415636", "0.41545394", "0.41490299", "0.41490144", "0.41462588", "0.41460428", "0.41402334", "0.4132948", "0.41299984", "0.4128962", "0.4123996", "0.4120746", "0.41174513", "0.41050583", "0.41013792", "0.41001245", "0.40988222", "0.40967616", "0.40951267", "0.4092364", "0.4091458", "0.40846294", "0.40774217", "0.40756476", "0.4075051", "0.40734044", "0.40723664", "0.4069548", "0.4066875", "0.4063472", "0.4062985", "0.40566143", "0.40552726", "0.4054844" ]
0.5352167
0
WithCustomTemplate returns the receiver adapter after changing the CloudFormation template that should be used to create Load Balancer stacks
func (a *Adapter) WithCustomTemplate(template string) *Adapter { a.customTemplate = template return a }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CustomNamespaceTemplate(templateRef, template string) UaInMurModifier {\n\treturn func(targetCluster string, mur *toolchainv1alpha1.MasterUserRecord) {\n\t\tfor i, ua := range mur.Spec.UserAccounts {\n\t\t\tif ua.TargetCluster == targetCluster {\n\t\t\t\tfor j, ns := range ua.Spec.NSTemplateSet.Namespaces {\n\t\t\t\t\tif ns.TemplateRef == templateRef {\n\t\t\t\t\t\tmur.Spec.UserAccounts[i].Spec.NSTemplateSet.Namespaces[j].Template = template\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *Stack) ApplyTemplate(c *stack.Credential) (*stack.Template, error) {\n\tcred, ok := c.Credential.(*Credential)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"credential is not of type do.Credential: %T\", c.Credential)\n\t}\n\n\tbootstrap, ok := c.Bootstrap.(*Bootstrap)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"bootstrap is not of type do.Bootstrap: %T\", c.Bootstrap)\n\t}\n\n\ttemplate := s.Builder.Template\n\ttemplate.Provider[\"digitalocean\"] = map[string]interface{}{\n\t\t\"token\": cred.AccessToken,\n\t}\n\n\tkeyID, err := strconv.Atoi(bootstrap.KeyID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdroplet, err := s.modifyDroplets(keyID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttemplate.Resource[\"digitalocean_droplet\"] = droplet\n\n\tif err := template.ShadowVariables(\"FORBIDDEN\", \"digitalocean_access_token\"); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := template.Flush(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcontent, err := template.JsonOutput()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &stack.Template{\n\t\tContent: content,\n\t}, nil\n}", "func CustomClusterResourcesTemplate(template string) UaInMurModifier {\n\treturn func(targetCluster string, mur *toolchainv1alpha1.MasterUserRecord) {\n\t\tfor i, ua := range mur.Spec.UserAccounts {\n\t\t\tif ua.TargetCluster == targetCluster {\n\t\t\t\tmur.Spec.UserAccounts[i].Spec.NSTemplateSet.ClusterResources.Template = template\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func baseTemplate() *datamodel.NodeBootstrappingConfiguration {\n\tvar (\n\t\ttrueConst = true\n\t\tfalseConst = false\n\t)\n\treturn &datamodel.NodeBootstrappingConfiguration{\n\t\tContainerService: &datamodel.ContainerService{\n\t\t\tID: \"\",\n\t\t\tLocation: \"eastus\",\n\t\t\tName: \"\",\n\t\t\tPlan: nil,\n\t\t\tTags: map[string]string(nil),\n\t\t\tType: \"Microsoft.ContainerService/ManagedClusters\",\n\t\t\tProperties: &datamodel.Properties{\n\t\t\t\tClusterID: \"\",\n\t\t\t\tProvisioningState: \"\",\n\t\t\t\tOrchestratorProfile: &datamodel.OrchestratorProfile{\n\t\t\t\t\tOrchestratorType: \"Kubernetes\",\n\t\t\t\t\tOrchestratorVersion: \"1.26.0\",\n\t\t\t\t\tKubernetesConfig: &datamodel.KubernetesConfig{\n\t\t\t\t\t\tKubernetesImageBase: \"\",\n\t\t\t\t\t\tMCRKubernetesImageBase: \"\",\n\t\t\t\t\t\tClusterSubnet: \"\",\n\t\t\t\t\t\tNetworkPolicy: \"\",\n\t\t\t\t\t\tNetworkPlugin: \"kubenet\",\n\t\t\t\t\t\tNetworkMode: \"\",\n\t\t\t\t\t\tContainerRuntime: \"\",\n\t\t\t\t\t\tMaxPods: 0,\n\t\t\t\t\t\tDockerBridgeSubnet: \"\",\n\t\t\t\t\t\tDNSServiceIP: \"\",\n\t\t\t\t\t\tServiceCIDR: \"\",\n\t\t\t\t\t\tUseManagedIdentity: false,\n\t\t\t\t\t\tUserAssignedID: \"\",\n\t\t\t\t\t\tUserAssignedClientID: \"\",\n\t\t\t\t\t\tCustomHyperkubeImage: \"\",\n\t\t\t\t\t\tCustomKubeProxyImage: \"mcr.microsoft.com/oss/kubernetes/kube-proxy:v1.26.0.1\",\n\t\t\t\t\t\tCustomKubeBinaryURL: \"https://acs-mirror.azureedge.net/kubernetes/v1.26.0/binaries/kubernetes-node-linux-amd64.tar.gz\",\n\t\t\t\t\t\tMobyVersion: \"\",\n\t\t\t\t\t\tContainerdVersion: \"\",\n\t\t\t\t\t\tWindowsNodeBinariesURL: \"\",\n\t\t\t\t\t\tWindowsContainerdURL: \"\",\n\t\t\t\t\t\tWindowsSdnPluginURL: \"\",\n\t\t\t\t\t\tUseInstanceMetadata: &trueConst,\n\t\t\t\t\t\tEnableRbac: nil,\n\t\t\t\t\t\tEnableSecureKubelet: nil,\n\t\t\t\t\t\tPrivateCluster: nil,\n\t\t\t\t\t\tGCHighThreshold: 0,\n\t\t\t\t\t\tGCLowThreshold: 0,\n\t\t\t\t\t\tEnableEncryptionWithExternalKms: nil,\n\t\t\t\t\t\tAddons: nil,\n\t\t\t\t\t\tContainerRuntimeConfig: map[string]string(nil),\n\t\t\t\t\t\tControllerManagerConfig: map[string]string(nil),\n\t\t\t\t\t\tSchedulerConfig: map[string]string(nil),\n\t\t\t\t\t\tCloudProviderBackoffMode: \"v2\",\n\t\t\t\t\t\tCloudProviderBackoff: &trueConst,\n\t\t\t\t\t\tCloudProviderBackoffRetries: 6,\n\t\t\t\t\t\tCloudProviderBackoffJitter: 0.0,\n\t\t\t\t\t\tCloudProviderBackoffDuration: 5,\n\t\t\t\t\t\tCloudProviderBackoffExponent: 0.0,\n\t\t\t\t\t\tCloudProviderRateLimit: &trueConst,\n\t\t\t\t\t\tCloudProviderRateLimitQPS: 10.0,\n\t\t\t\t\t\tCloudProviderRateLimitQPSWrite: 10.0,\n\t\t\t\t\t\tCloudProviderRateLimitBucket: 100,\n\t\t\t\t\t\tCloudProviderRateLimitBucketWrite: 100,\n\t\t\t\t\t\tCloudProviderDisableOutboundSNAT: &falseConst,\n\t\t\t\t\t\tNodeStatusUpdateFrequency: \"\",\n\t\t\t\t\t\tLoadBalancerSku: \"Standard\",\n\t\t\t\t\t\tExcludeMasterFromStandardLB: nil,\n\t\t\t\t\t\tAzureCNIURLLinux: \"https://acs-mirror.azureedge.net/azure-cni/v1.1.8/binaries/azure-vnet-cni-linux-amd64-v1.1.8.tgz\",\n\t\t\t\t\t\tAzureCNIURLARM64Linux: \"\",\n\t\t\t\t\t\tAzureCNIURLWindows: \"\",\n\t\t\t\t\t\tMaximumLoadBalancerRuleCount: 250,\n\t\t\t\t\t\tPrivateAzureRegistryServer: \"\",\n\t\t\t\t\t\tNetworkPluginMode: \"\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tAgentPoolProfiles: []*datamodel.AgentPoolProfile{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"nodepool2\",\n\t\t\t\t\t\tVMSize: \"Standard_DS1_v2\",\n\t\t\t\t\t\tKubeletDiskType: \"\",\n\t\t\t\t\t\tWorkloadRuntime: \"\",\n\t\t\t\t\t\tDNSPrefix: \"\",\n\t\t\t\t\t\tOSType: \"Linux\",\n\t\t\t\t\t\tPorts: nil,\n\t\t\t\t\t\tAvailabilityProfile: \"VirtualMachineScaleSets\",\n\t\t\t\t\t\tStorageProfile: \"ManagedDisks\",\n\t\t\t\t\t\tVnetSubnetID: \"\",\n\t\t\t\t\t\tDistro: \"aks-ubuntu-containerd-18.04-gen2\",\n\t\t\t\t\t\tCustomNodeLabels: map[string]string{\n\t\t\t\t\t\t\t\"kubernetes.azure.com/mode\": \"system\",\n\t\t\t\t\t\t\t\"kubernetes.azure.com/node-image-version\": \"AKSUbuntu-1804gen2containerd-2022.01.19\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tPreprovisionExtension: nil,\n\t\t\t\t\t\tKubernetesConfig: &datamodel.KubernetesConfig{\n\t\t\t\t\t\t\tKubernetesImageBase: \"\",\n\t\t\t\t\t\t\tMCRKubernetesImageBase: \"\",\n\t\t\t\t\t\t\tClusterSubnet: \"\",\n\t\t\t\t\t\t\tNetworkPolicy: \"\",\n\t\t\t\t\t\t\tNetworkPlugin: \"\",\n\t\t\t\t\t\t\tNetworkMode: \"\",\n\t\t\t\t\t\t\tContainerRuntime: \"containerd\",\n\t\t\t\t\t\t\tMaxPods: 0,\n\t\t\t\t\t\t\tDockerBridgeSubnet: \"\",\n\t\t\t\t\t\t\tDNSServiceIP: \"\",\n\t\t\t\t\t\t\tServiceCIDR: \"\",\n\t\t\t\t\t\t\tUseManagedIdentity: false,\n\t\t\t\t\t\t\tUserAssignedID: \"\",\n\t\t\t\t\t\t\tUserAssignedClientID: \"\",\n\t\t\t\t\t\t\tCustomHyperkubeImage: \"\",\n\t\t\t\t\t\t\tCustomKubeProxyImage: \"\",\n\t\t\t\t\t\t\tCustomKubeBinaryURL: \"\",\n\t\t\t\t\t\t\tMobyVersion: \"\",\n\t\t\t\t\t\t\tContainerdVersion: \"\",\n\t\t\t\t\t\t\tWindowsNodeBinariesURL: \"\",\n\t\t\t\t\t\t\tWindowsContainerdURL: \"\",\n\t\t\t\t\t\t\tWindowsSdnPluginURL: \"\",\n\t\t\t\t\t\t\tUseInstanceMetadata: nil,\n\t\t\t\t\t\t\tEnableRbac: nil,\n\t\t\t\t\t\t\tEnableSecureKubelet: nil,\n\t\t\t\t\t\t\tPrivateCluster: nil,\n\t\t\t\t\t\t\tGCHighThreshold: 0,\n\t\t\t\t\t\t\tGCLowThreshold: 0,\n\t\t\t\t\t\t\tEnableEncryptionWithExternalKms: nil,\n\t\t\t\t\t\t\tAddons: nil,\n\t\t\t\t\t\t\tContainerRuntimeConfig: map[string]string(nil),\n\t\t\t\t\t\t\tControllerManagerConfig: map[string]string(nil),\n\t\t\t\t\t\t\tSchedulerConfig: map[string]string(nil),\n\t\t\t\t\t\t\tCloudProviderBackoffMode: \"\",\n\t\t\t\t\t\t\tCloudProviderBackoff: nil,\n\t\t\t\t\t\t\tCloudProviderBackoffRetries: 0,\n\t\t\t\t\t\t\tCloudProviderBackoffJitter: 0.0,\n\t\t\t\t\t\t\tCloudProviderBackoffDuration: 0,\n\t\t\t\t\t\t\tCloudProviderBackoffExponent: 0.0,\n\t\t\t\t\t\t\tCloudProviderRateLimit: nil,\n\t\t\t\t\t\t\tCloudProviderRateLimitQPS: 0.0,\n\t\t\t\t\t\t\tCloudProviderRateLimitQPSWrite: 0.0,\n\t\t\t\t\t\t\tCloudProviderRateLimitBucket: 0,\n\t\t\t\t\t\t\tCloudProviderRateLimitBucketWrite: 0,\n\t\t\t\t\t\t\tCloudProviderDisableOutboundSNAT: nil,\n\t\t\t\t\t\t\tNodeStatusUpdateFrequency: \"\",\n\t\t\t\t\t\t\tLoadBalancerSku: \"\",\n\t\t\t\t\t\t\tExcludeMasterFromStandardLB: nil,\n\t\t\t\t\t\t\tAzureCNIURLLinux: \"\",\n\t\t\t\t\t\t\tAzureCNIURLARM64Linux: \"\",\n\t\t\t\t\t\t\tAzureCNIURLWindows: \"\",\n\t\t\t\t\t\t\tMaximumLoadBalancerRuleCount: 0,\n\t\t\t\t\t\t\tPrivateAzureRegistryServer: \"\",\n\t\t\t\t\t\t\tNetworkPluginMode: \"\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tVnetCidrs: nil,\n\t\t\t\t\t\tWindowsNameVersion: \"\",\n\t\t\t\t\t\tCustomKubeletConfig: nil,\n\t\t\t\t\t\tCustomLinuxOSConfig: nil,\n\t\t\t\t\t\tMessageOfTheDay: \"\",\n\t\t\t\t\t\tNotRebootWindowsNode: nil,\n\t\t\t\t\t\tAgentPoolWindowsProfile: nil,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tLinuxProfile: &datamodel.LinuxProfile{\n\t\t\t\t\tAdminUsername: \"azureuser\",\n\t\t\t\t\tSSH: struct {\n\t\t\t\t\t\tPublicKeys []datamodel.PublicKey \"json:\\\"publicKeys\\\"\"\n\t\t\t\t\t}{\n\t\t\t\t\t\tPublicKeys: []datamodel.PublicKey{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tKeyData: \"dummysshkey\",\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\tSecrets: nil,\n\t\t\t\t\tDistro: \"\",\n\t\t\t\t\tCustomSearchDomain: nil,\n\t\t\t\t},\n\t\t\t\tWindowsProfile: nil,\n\t\t\t\tExtensionProfiles: nil,\n\t\t\t\tDiagnosticsProfile: nil,\n\t\t\t\tServicePrincipalProfile: &datamodel.ServicePrincipalProfile{\n\t\t\t\t\tClientID: \"msi\",\n\t\t\t\t\tSecret: \"msi\",\n\t\t\t\t\tObjectID: \"\",\n\t\t\t\t\tKeyvaultSecretRef: nil,\n\t\t\t\t},\n\t\t\t\tCertificateProfile: &datamodel.CertificateProfile{\n\t\t\t\t\tCaCertificate: \"\",\n\t\t\t\t\tAPIServerCertificate: \"\",\n\t\t\t\t\tClientCertificate: \"\",\n\t\t\t\t\tClientPrivateKey: \"\",\n\t\t\t\t\tKubeConfigCertificate: \"\",\n\t\t\t\t\tKubeConfigPrivateKey: \"\",\n\t\t\t\t},\n\t\t\t\tAADProfile: nil,\n\t\t\t\tCustomProfile: nil,\n\t\t\t\tHostedMasterProfile: &datamodel.HostedMasterProfile{\n\t\t\t\t\tFQDN: \"\",\n\t\t\t\t\tIPAddress: \"\",\n\t\t\t\t\tDNSPrefix: \"\",\n\t\t\t\t\tFQDNSubdomain: \"\",\n\t\t\t\t\tSubnet: \"\",\n\t\t\t\t\tAPIServerWhiteListRange: nil,\n\t\t\t\t\tIPMasqAgent: true,\n\t\t\t\t},\n\t\t\t\tAddonProfiles: map[string]datamodel.AddonProfile(nil),\n\t\t\t\tFeatureFlags: nil,\n\t\t\t\tCustomCloudEnv: nil,\n\t\t\t\tCustomConfiguration: nil,\n\t\t\t},\n\t\t},\n\t\tCloudSpecConfig: &datamodel.AzureEnvironmentSpecConfig{\n\t\t\tCloudName: \"AzurePublicCloud\",\n\t\t\tDockerSpecConfig: datamodel.DockerSpecConfig{\n\t\t\t\tDockerEngineRepo: \"https://aptdocker.azureedge.net/repo\",\n\t\t\t\tDockerComposeDownloadURL: \"https://github.com/docker/compose/releases/download\",\n\t\t\t},\n\t\t\tKubernetesSpecConfig: datamodel.KubernetesSpecConfig{\n\t\t\t\tAzureTelemetryPID: \"\",\n\t\t\t\tKubernetesImageBase: \"k8s.gcr.io/\",\n\t\t\t\tTillerImageBase: \"gcr.io/kubernetes-helm/\",\n\t\t\t\tACIConnectorImageBase: \"microsoft/\",\n\t\t\t\tMCRKubernetesImageBase: \"mcr.microsoft.com/\",\n\t\t\t\tNVIDIAImageBase: \"nvidia/\",\n\t\t\t\tAzureCNIImageBase: \"mcr.microsoft.com/containernetworking/\",\n\t\t\t\tCalicoImageBase: \"calico/\",\n\t\t\t\tEtcdDownloadURLBase: \"\",\n\t\t\t\tKubeBinariesSASURLBase: \"https://acs-mirror.azureedge.net/kubernetes/\",\n\t\t\t\tWindowsTelemetryGUID: \"fb801154-36b9-41bc-89c2-f4d4f05472b0\",\n\t\t\t\tCNIPluginsDownloadURL: \"https://acs-mirror.azureedge.net/cni/cni-plugins-amd64-v0.7.6.tgz\",\n\t\t\t\tVnetCNILinuxPluginsDownloadURL: \"https://acs-mirror.azureedge.net/azure-cni/v1.1.3/binaries/azure-vnet-cni-linux-amd64-v1.1.3.tgz\",\n\t\t\t\tVnetCNIWindowsPluginsDownloadURL: \"https://acs-mirror.azureedge.net/azure-cni/v1.1.3/binaries/azure-vnet-cni-singletenancy-windows-amd64-v1.1.3.zip\",\n\t\t\t\tContainerdDownloadURLBase: \"https://storage.googleapis.com/cri-containerd-release/\",\n\t\t\t\tCSIProxyDownloadURL: \"https://acs-mirror.azureedge.net/csi-proxy/v0.1.0/binaries/csi-proxy.tar.gz\",\n\t\t\t\tWindowsProvisioningScriptsPackageURL: \"https://acs-mirror.azureedge.net/aks-engine/windows/provisioning/signedscripts-v0.2.2.zip\",\n\t\t\t\tWindowsPauseImageURL: \"mcr.microsoft.com/oss/kubernetes/pause:1.4.0\",\n\t\t\t\tAlwaysPullWindowsPauseImage: false,\n\t\t\t\tCseScriptsPackageURL: \"https://acs-mirror.azureedge.net/aks/windows/cse/csescripts-v0.0.1.zip\",\n\t\t\t\tCNIARM64PluginsDownloadURL: \"https://acs-mirror.azureedge.net/cni-plugins/v0.8.7/binaries/cni-plugins-linux-arm64-v0.8.7.tgz\",\n\t\t\t\tVnetCNIARM64LinuxPluginsDownloadURL: \"https://acs-mirror.azureedge.net/azure-cni/v1.4.13/binaries/azure-vnet-cni-linux-arm64-v1.4.14.tgz\",\n\t\t\t},\n\t\t\tEndpointConfig: datamodel.AzureEndpointConfig{\n\t\t\t\tResourceManagerVMDNSSuffix: \"cloudapp.azure.com\",\n\t\t\t},\n\t\t\tOSImageConfig: map[datamodel.Distro]datamodel.AzureOSImageConfig(nil),\n\t\t},\n\t\tK8sComponents: &datamodel.K8sComponents{\n\t\t\tPodInfraContainerImageURL: \"mcr.microsoft.com/oss/kubernetes/pause:3.6\",\n\t\t\tHyperkubeImageURL: \"mcr.microsoft.com/oss/kubernetes/\",\n\t\t\tWindowsPackageURL: \"windowspackage\",\n\t\t},\n\t\tAgentPoolProfile: &datamodel.AgentPoolProfile{\n\t\t\tName: \"nodepool2\",\n\t\t\tVMSize: \"Standard_DS1_v2\",\n\t\t\tKubeletDiskType: \"\",\n\t\t\tWorkloadRuntime: \"\",\n\t\t\tDNSPrefix: \"\",\n\t\t\tOSType: \"Linux\",\n\t\t\tPorts: nil,\n\t\t\tAvailabilityProfile: \"VirtualMachineScaleSets\",\n\t\t\tStorageProfile: \"ManagedDisks\",\n\t\t\tVnetSubnetID: \"\",\n\t\t\tDistro: \"aks-ubuntu-containerd-18.04-gen2\",\n\t\t\tCustomNodeLabels: map[string]string{\n\t\t\t\t\"kubernetes.azure.com/mode\": \"system\",\n\t\t\t\t\"kubernetes.azure.com/node-image-version\": \"AKSUbuntu-1804gen2containerd-2022.01.19\",\n\t\t\t},\n\t\t\tPreprovisionExtension: nil,\n\t\t\tKubernetesConfig: &datamodel.KubernetesConfig{\n\t\t\t\tKubernetesImageBase: \"\",\n\t\t\t\tMCRKubernetesImageBase: \"\",\n\t\t\t\tClusterSubnet: \"\",\n\t\t\t\tNetworkPolicy: \"\",\n\t\t\t\tNetworkPlugin: \"\",\n\t\t\t\tNetworkMode: \"\",\n\t\t\t\tContainerRuntime: \"containerd\",\n\t\t\t\tMaxPods: 0,\n\t\t\t\tDockerBridgeSubnet: \"\",\n\t\t\t\tDNSServiceIP: \"\",\n\t\t\t\tServiceCIDR: \"\",\n\t\t\t\tUseManagedIdentity: false,\n\t\t\t\tUserAssignedID: \"\",\n\t\t\t\tUserAssignedClientID: \"\",\n\t\t\t\tCustomHyperkubeImage: \"\",\n\t\t\t\tCustomKubeProxyImage: \"\",\n\t\t\t\tCustomKubeBinaryURL: \"\",\n\t\t\t\tMobyVersion: \"\",\n\t\t\t\tContainerdVersion: \"\",\n\t\t\t\tWindowsNodeBinariesURL: \"\",\n\t\t\t\tWindowsContainerdURL: \"\",\n\t\t\t\tWindowsSdnPluginURL: \"\",\n\t\t\t\tUseInstanceMetadata: nil,\n\t\t\t\tEnableRbac: nil,\n\t\t\t\tEnableSecureKubelet: nil,\n\t\t\t\tPrivateCluster: nil,\n\t\t\t\tGCHighThreshold: 0,\n\t\t\t\tGCLowThreshold: 0,\n\t\t\t\tEnableEncryptionWithExternalKms: nil,\n\t\t\t\tAddons: nil,\n\t\t\t\tContainerRuntimeConfig: map[string]string(nil),\n\t\t\t\tControllerManagerConfig: map[string]string(nil),\n\t\t\t\tSchedulerConfig: map[string]string(nil),\n\t\t\t\tCloudProviderBackoffMode: \"\",\n\t\t\t\tCloudProviderBackoff: nil,\n\t\t\t\tCloudProviderBackoffRetries: 0,\n\t\t\t\tCloudProviderBackoffJitter: 0.0,\n\t\t\t\tCloudProviderBackoffDuration: 0,\n\t\t\t\tCloudProviderBackoffExponent: 0.0,\n\t\t\t\tCloudProviderRateLimit: nil,\n\t\t\t\tCloudProviderRateLimitQPS: 0.0,\n\t\t\t\tCloudProviderRateLimitQPSWrite: 0.0,\n\t\t\t\tCloudProviderRateLimitBucket: 0,\n\t\t\t\tCloudProviderRateLimitBucketWrite: 0,\n\t\t\t\tCloudProviderDisableOutboundSNAT: nil,\n\t\t\t\tNodeStatusUpdateFrequency: \"\",\n\t\t\t\tLoadBalancerSku: \"\",\n\t\t\t\tExcludeMasterFromStandardLB: nil,\n\t\t\t\tAzureCNIURLLinux: \"\",\n\t\t\t\tAzureCNIURLARM64Linux: \"\",\n\t\t\t\tAzureCNIURLWindows: \"\",\n\t\t\t\tMaximumLoadBalancerRuleCount: 0,\n\t\t\t\tPrivateAzureRegistryServer: \"\",\n\t\t\t\tNetworkPluginMode: \"\",\n\t\t\t},\n\t\t\tVnetCidrs: nil,\n\t\t\tWindowsNameVersion: \"\",\n\t\t\tCustomKubeletConfig: nil,\n\t\t\tCustomLinuxOSConfig: nil,\n\t\t\tMessageOfTheDay: \"\",\n\t\t\tNotRebootWindowsNode: nil,\n\t\t\tAgentPoolWindowsProfile: nil,\n\t\t},\n\t\tTenantID: \"\",\n\t\tSubscriptionID: \"\",\n\t\tResourceGroupName: \"\",\n\t\tUserAssignedIdentityClientID: \"\",\n\t\tOSSKU: \"\",\n\t\tConfigGPUDriverIfNeeded: true,\n\t\tDisable1804SystemdResolved: false,\n\t\tEnableGPUDevicePluginIfNeeded: false,\n\t\tEnableKubeletConfigFile: false,\n\t\tEnableNvidia: false,\n\t\tEnableACRTeleportPlugin: false,\n\t\tTeleportdPluginURL: \"\",\n\t\tContainerdVersion: \"\",\n\t\tRuncVersion: \"\",\n\t\tContainerdPackageURL: \"\",\n\t\tRuncPackageURL: \"\",\n\t\tKubeletClientTLSBootstrapToken: nil,\n\t\tFIPSEnabled: false,\n\t\tHTTPProxyConfig: &datamodel.HTTPProxyConfig{\n\t\t\tHTTPProxy: nil,\n\t\t\tHTTPSProxy: nil,\n\t\t\tNoProxy: &[]string{\n\t\t\t\t\"localhost\",\n\t\t\t\t\"127.0.0.1\",\n\t\t\t\t\"168.63.129.16\",\n\t\t\t\t\"169.254.169.254\",\n\t\t\t\t\"10.0.0.0/16\",\n\t\t\t\t\"agentbaker-agentbaker-e2e-t-8ecadf-c82d8251.hcp.eastus.azmk8s.io\",\n\t\t\t},\n\t\t\tTrustedCA: nil,\n\t\t},\n\t\tKubeletConfig: map[string]string{\n\t\t\t\"--address\": \"0.0.0.0\",\n\t\t\t\"--anonymous-auth\": \"false\",\n\t\t\t\"--authentication-token-webhook\": \"true\",\n\t\t\t\"--authorization-mode\": \"Webhook\",\n\t\t\t\"--azure-container-registry-config\": \"/etc/kubernetes/azure.json\",\n\t\t\t\"--cgroups-per-qos\": \"true\",\n\t\t\t\"--client-ca-file\": \"/etc/kubernetes/certs/ca.crt\",\n\t\t\t\"--cloud-config\": \"/etc/kubernetes/azure.json\",\n\t\t\t\"--cloud-provider\": \"azure\",\n\t\t\t\"--cluster-dns\": \"10.0.0.10\",\n\t\t\t\"--cluster-domain\": \"cluster.local\",\n\t\t\t\"--dynamic-config-dir\": \"/var/lib/kubelet\",\n\t\t\t\"--enforce-node-allocatable\": \"pods\",\n\t\t\t\"--event-qps\": \"0\",\n\t\t\t\"--eviction-hard\": \"memory.available<750Mi,nodefs.available<10%,nodefs.inodesFree<5%\",\n\t\t\t\"--feature-gates\": \"RotateKubeletServerCertificate=true\",\n\t\t\t\"--image-gc-high-threshold\": \"85\",\n\t\t\t\"--image-gc-low-threshold\": \"80\",\n\t\t\t\"--keep-terminated-pod-volumes\": \"false\",\n\t\t\t\"--kube-reserved\": \"cpu=100m,memory=1638Mi\",\n\t\t\t\"--kubeconfig\": \"/var/lib/kubelet/kubeconfig\",\n\t\t\t\"--max-pods\": \"110\",\n\t\t\t\"--network-plugin\": \"kubenet\",\n\t\t\t\"--node-status-update-frequency\": \"10s\",\n\t\t\t\"--pod-infra-container-image\": \"mcr.microsoft.com/oss/kubernetes/pause:3.6\",\n\t\t\t\"--pod-manifest-path\": \"/etc/kubernetes/manifests\",\n\t\t\t\"--pod-max-pids\": \"-1\",\n\t\t\t\"--protect-kernel-defaults\": \"true\",\n\t\t\t\"--read-only-port\": \"0\",\n\t\t\t\"--resolv-conf\": \"/run/systemd/resolve/resolv.conf\",\n\t\t\t\"--rotate-certificates\": \"false\",\n\t\t\t\"--streaming-connection-idle-timeout\": \"4h\",\n\t\t\t\"--tls-cert-file\": \"/etc/kubernetes/certs/kubeletserver.crt\",\n\t\t\t\"--tls-cipher-suites\": \"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,TLS_RSA_WITH_AES_256_GCM_SHA384,TLS_RSA_WITH_AES_128_GCM_SHA256\",\n\t\t\t\"--tls-private-key-file\": \"/etc/kubernetes/certs/kubeletserver.key\",\n\t\t},\n\t\tKubeproxyConfig: map[string]string(nil),\n\t\tEnableRuncShimV2: false,\n\t\tGPUInstanceProfile: \"\",\n\t\tPrimaryScaleSetName: \"\",\n\t\tSIGConfig: datamodel.SIGConfig{\n\t\t\tTenantID: \"tenantID\",\n\t\t\tSubscriptionID: \"subID\",\n\t\t\tGalleries: map[string]datamodel.SIGGalleryConfig{\n\t\t\t\t\"AKSUbuntu\": {\n\t\t\t\t\tGalleryName: \"aksubuntu\",\n\t\t\t\t\tResourceGroup: \"resourcegroup\",\n\t\t\t\t},\n\t\t\t\t\"AKSCBLMariner\": {\n\t\t\t\t\tGalleryName: \"akscblmariner\",\n\t\t\t\t\tResourceGroup: \"resourcegroup\",\n\t\t\t\t},\n\t\t\t\t\"AKSWindows\": {\n\t\t\t\t\tGalleryName: \"AKSWindows\",\n\t\t\t\t\tResourceGroup: \"AKS-Windows\",\n\t\t\t\t},\n\t\t\t\t\"AKSUbuntuEdgeZone\": {\n\t\t\t\t\tGalleryName: \"AKSUbuntuEdgeZone\",\n\t\t\t\t\tResourceGroup: \"AKS-Ubuntu-EdgeZone\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tIsARM64: false,\n\t\tCustomCATrustConfig: nil,\n\t\tDisableUnattendedUpgrades: true,\n\t\tSSHStatus: 0,\n\t\tDisableCustomData: false,\n\t}\n}", "func (s *BackendService) Template() (string, error) {\n\toutputs, err := s.addonsOutputs()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tsidecars, err := s.manifest.Sidecar.SidecarsOpts()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"convert the sidecar configuration for service %s: %w\", s.name, err)\n\t}\n\tcontent, err := s.parser.ParseBackendService(template.ServiceOpts{\n\t\tVariables: s.manifest.BackendServiceConfig.Variables,\n\t\tSecrets: s.manifest.BackendServiceConfig.Secrets,\n\t\tNestedStack: outputs,\n\t\tSidecars: sidecars,\n\t\tHealthCheck: s.manifest.BackendServiceConfig.Image.HealthCheckOpts(),\n\t\tLogConfig: s.manifest.LogConfigOpts(),\n\t})\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"parse backend service template: %w\", err)\n\t}\n\treturn content.String(), nil\n}", "func (e *Kevent) RenderCustomTemplate(tmpl *template.Template) ([]byte, error) {\n\treturn renderTemplate(e, tmpl)\n}", "func newTemplateHelper(cr *v1alpha1.Installation, extraParams map[string]string, config *config.Monitoring) *TemplateHelper {\n\tparam := Parameters{\n\t\tPlaceholder: Placeholder,\n\t\tNamespace: config.GetNamespace(),\n\t\tMonitoringKey: config.GetLabelSelector(),\n\t\tExtraParams: extraParams,\n\t}\n\n\ttemplatePath, exists := os.LookupEnv(\"TEMPLATE_PATH\")\n\tif !exists {\n\t\ttemplatePath = \"./templates/monitoring\"\n\t}\n\n\tmonitoringKey, exists := os.LookupEnv(\"MONITORING_KEY\")\n\tif exists {\n\t\tparam.MonitoringKey = monitoringKey\n\t}\n\n\treturn &TemplateHelper{\n\t\tParameters: param,\n\t\tTemplatePath: templatePath,\n\t}\n}", "func (e *ComponentStackConfig) Template() (string, error) {\n\tworkloadTemplate, err := e.box.FindString(templatePath)\n\tif err != nil {\n\t\treturn \"\", &ErrTemplateNotFound{templateLocation: templatePath, parentErr: err}\n\t}\n\n\ttemplate, err := template.New(\"template\").\n\t\tFuncs(templateFunctions).\n\t\tFuncs(sprig.FuncMap()).\n\t\tParse(workloadTemplate)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar buf bytes.Buffer\n\tif err := template.Execute(&buf, e.ComponentInput); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(buf.Bytes()), nil\n}", "func (m *TeamItemRequestBuilder) Template()(*i04a148e32be31a86cd21b897c8b55a4508d63dbae47a02eaeb122662dbd2ff9b.TemplateRequestBuilder) {\n return i04a148e32be31a86cd21b897c8b55a4508d63dbae47a02eaeb122662dbd2ff9b.NewTemplateRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (in *RecordSetGroup) GetTemplate(client dynamic.Interface) (string, error) {\n\tif client == nil {\n\t\treturn \"\", fmt.Errorf(\"k8s client not loaded for template\")\n\t}\n\ttemplate := cloudformation.NewTemplate()\n\n\ttemplate.Description = \"AWS Controller - route53.RecordSetGroup (ac-{TODO})\"\n\n\ttemplate.Outputs = map[string]interface{}{\n\t\t\"ResourceRef\": map[string]interface{}{\n\t\t\t\"Value\": cloudformation.Ref(\"RecordSetGroup\"),\n\t\t\t\"Export\": map[string]interface{}{\n\t\t\t\t\"Name\": in.Name + \"Ref\",\n\t\t\t},\n\t\t},\n\t}\n\n\troute53RecordSetGroup := &route53.RecordSetGroup{}\n\n\tif in.Spec.Comment != \"\" {\n\t\troute53RecordSetGroup.Comment = in.Spec.Comment\n\t}\n\n\t// TODO(christopherhein) move these to a defaulter\n\troute53RecordSetGroupHostedZoneRefItem := in.Spec.HostedZoneRef.DeepCopy()\n\n\tif route53RecordSetGroupHostedZoneRefItem.ObjectRef.Namespace == \"\" {\n\t\troute53RecordSetGroupHostedZoneRefItem.ObjectRef.Namespace = in.Namespace\n\t}\n\n\tin.Spec.HostedZoneRef = *route53RecordSetGroupHostedZoneRefItem\n\thostedZoneId, err := in.Spec.HostedZoneRef.String(client)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif hostedZoneId != \"\" {\n\t\troute53RecordSetGroup.HostedZoneId = hostedZoneId\n\t}\n\n\tif in.Spec.HostedZoneName != \"\" {\n\t\troute53RecordSetGroup.HostedZoneName = in.Spec.HostedZoneName\n\t}\n\n\troute53RecordSetGroupRecordSets := []route53.RecordSetGroup_RecordSet{}\n\n\tfor _, item := range in.Spec.RecordSets {\n\t\troute53RecordSetGroupRecordSet := route53.RecordSetGroup_RecordSet{}\n\n\t\tif !reflect.DeepEqual(item.AliasTarget, RecordSetGroup_AliasTarget{}) {\n\t\t\troute53RecordSetGroupRecordSetAliasTarget := route53.RecordSetGroup_AliasTarget{}\n\n\t\t\tif item.AliasTarget.DNSName != \"\" {\n\t\t\t\troute53RecordSetGroupRecordSetAliasTarget.DNSName = item.AliasTarget.DNSName\n\t\t\t}\n\n\t\t\tif item.AliasTarget.EvaluateTargetHealth || !item.AliasTarget.EvaluateTargetHealth {\n\t\t\t\troute53RecordSetGroupRecordSetAliasTarget.EvaluateTargetHealth = item.AliasTarget.EvaluateTargetHealth\n\t\t\t}\n\n\t\t\t// TODO(christopherhein) move these to a defaulter\n\t\t\troute53RecordSetGroupRecordSetAliasTargetHostedZoneRefItem := item.AliasTarget.HostedZoneRef.DeepCopy()\n\n\t\t\tif route53RecordSetGroupRecordSetAliasTargetHostedZoneRefItem.ObjectRef.Namespace == \"\" {\n\t\t\t\troute53RecordSetGroupRecordSetAliasTargetHostedZoneRefItem.ObjectRef.Namespace = in.Namespace\n\t\t\t}\n\n\t\t\titem.AliasTarget.HostedZoneRef = *route53RecordSetGroupRecordSetAliasTargetHostedZoneRefItem\n\t\t\thostedZoneId, err := item.AliasTarget.HostedZoneRef.String(client)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\tif hostedZoneId != \"\" {\n\t\t\t\troute53RecordSetGroupRecordSetAliasTarget.HostedZoneId = hostedZoneId\n\t\t\t}\n\n\t\t\troute53RecordSetGroupRecordSet.AliasTarget = &route53RecordSetGroupRecordSetAliasTarget\n\t\t}\n\n\t\tif item.Comment != \"\" {\n\t\t\troute53RecordSetGroupRecordSet.Comment = item.Comment\n\t\t}\n\n\t\tif item.Failover != \"\" {\n\t\t\troute53RecordSetGroupRecordSet.Failover = item.Failover\n\t\t}\n\n\t\tif !reflect.DeepEqual(item.GeoLocation, RecordSetGroup_GeoLocation{}) {\n\t\t\troute53RecordSetGroupRecordSetGeoLocation := route53.RecordSetGroup_GeoLocation{}\n\n\t\t\tif item.GeoLocation.ContinentCode != \"\" {\n\t\t\t\troute53RecordSetGroupRecordSetGeoLocation.ContinentCode = item.GeoLocation.ContinentCode\n\t\t\t}\n\n\t\t\tif item.GeoLocation.CountryCode != \"\" {\n\t\t\t\troute53RecordSetGroupRecordSetGeoLocation.CountryCode = item.GeoLocation.CountryCode\n\t\t\t}\n\n\t\t\tif item.GeoLocation.SubdivisionCode != \"\" {\n\t\t\t\troute53RecordSetGroupRecordSetGeoLocation.SubdivisionCode = item.GeoLocation.SubdivisionCode\n\t\t\t}\n\n\t\t\troute53RecordSetGroupRecordSet.GeoLocation = &route53RecordSetGroupRecordSetGeoLocation\n\t\t}\n\n\t\t// TODO(christopherhein) move these to a defaulter\n\t\troute53RecordSetGroupRecordSetHealthCheckRefItem := item.HealthCheckRef.DeepCopy()\n\n\t\tif route53RecordSetGroupRecordSetHealthCheckRefItem.ObjectRef.Namespace == \"\" {\n\t\t\troute53RecordSetGroupRecordSetHealthCheckRefItem.ObjectRef.Namespace = in.Namespace\n\t\t}\n\n\t\titem.HealthCheckRef = *route53RecordSetGroupRecordSetHealthCheckRefItem\n\t\thealthCheckId, err := item.HealthCheckRef.String(client)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif healthCheckId != \"\" {\n\t\t\troute53RecordSetGroupRecordSet.HealthCheckId = healthCheckId\n\t\t}\n\n\t\t// TODO(christopherhein) move these to a defaulter\n\t\troute53RecordSetGroupRecordSetHostedZoneRefItem := item.HostedZoneRef.DeepCopy()\n\n\t\tif route53RecordSetGroupRecordSetHostedZoneRefItem.ObjectRef.Namespace == \"\" {\n\t\t\troute53RecordSetGroupRecordSetHostedZoneRefItem.ObjectRef.Namespace = in.Namespace\n\t\t}\n\n\t\titem.HostedZoneRef = *route53RecordSetGroupRecordSetHostedZoneRefItem\n\t\thostedZoneId, err := item.HostedZoneRef.String(client)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif hostedZoneId != \"\" {\n\t\t\troute53RecordSetGroupRecordSet.HostedZoneId = hostedZoneId\n\t\t}\n\n\t\tif item.HostedZoneName != \"\" {\n\t\t\troute53RecordSetGroupRecordSet.HostedZoneName = item.HostedZoneName\n\t\t}\n\n\t\tif item.MultiValueAnswer || !item.MultiValueAnswer {\n\t\t\troute53RecordSetGroupRecordSet.MultiValueAnswer = item.MultiValueAnswer\n\t\t}\n\n\t\tif item.Name != \"\" {\n\t\t\troute53RecordSetGroupRecordSet.Name = item.Name\n\t\t}\n\n\t\tif item.Region != \"\" {\n\t\t\troute53RecordSetGroupRecordSet.Region = item.Region\n\t\t}\n\n\t\tif len(item.ResourceRecords) > 0 {\n\t\t\troute53RecordSetGroupRecordSet.ResourceRecords = item.ResourceRecords\n\t\t}\n\n\t\tif item.SetIdentifier != \"\" {\n\t\t\troute53RecordSetGroupRecordSet.SetIdentifier = item.SetIdentifier\n\t\t}\n\n\t\tif item.TTL != \"\" {\n\t\t\troute53RecordSetGroupRecordSet.TTL = item.TTL\n\t\t}\n\n\t\tif item.Type != \"\" {\n\t\t\troute53RecordSetGroupRecordSet.Type = item.Type\n\t\t}\n\n\t\tif item.Weight != route53RecordSetGroupRecordSet.Weight {\n\t\t\troute53RecordSetGroupRecordSet.Weight = item.Weight\n\t\t}\n\n\t}\n\n\tif len(route53RecordSetGroupRecordSets) > 0 {\n\t\troute53RecordSetGroup.RecordSets = route53RecordSetGroupRecordSets\n\t}\n\n\ttemplate.Resources = map[string]cloudformation.Resource{\n\t\t\"RecordSetGroup\": route53RecordSetGroup,\n\t}\n\n\t// json, err := template.JSONWithOptions(&intrinsics.ProcessorOptions{NoEvaluateConditions: true})\n\tjson, err := template.JSON()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(json), nil\n}", "func (s *InstanceTemplateServer) applyInstanceTemplate(ctx context.Context, c *beta.Client, request *betapb.ApplyComputeBetaInstanceTemplateRequest) (*betapb.ComputeBetaInstanceTemplate, error) {\n\tp := ProtoToInstanceTemplate(request.GetResource())\n\tres, err := c.ApplyInstanceTemplate(ctx, p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr := InstanceTemplateToProto(res)\n\treturn r, nil\n}", "func (r *Client) create(ctx context.Context, stack Stack, params ...*Parameter) error {\n\t// fetch and validate template\n\tt, err := stack.GetStackTemplate()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = r.validateTemplateParams(t, params)\n\tif err != nil {\n\t\treturn err\n\t}\n\tyaml, err := t.YAML()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstackPolicy, err := getStackPolicy(stack)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = r.Client.CreateStackWithContext(ctx, &CreateStackInput{\n\t\tCapabilities: capabilities,\n\t\tTemplateBody: aws.String(string(yaml)),\n\t\tStackName: aws.String(stack.GetStackName()),\n\t\tStackPolicyBody: stackPolicy,\n\t\tParameters: params,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func renderTemplate(context *templateContext, file string) (string, error) {\n\tfuncMap := template.FuncMap{\n\t\t\"getAWSAccountID\": getAWSAccountID,\n\t\t\"base64\": base64Encode,\n\t\t\"base64Decode\": base64Decode,\n\t\t\"manifestHash\": func(template string) (string, error) {\n\t\t\treturn manifestHash(context, file, template)\n\t\t},\n\t\t\"sha256\": func(value string) (string, error) {\n\t\t\treturn fmt.Sprintf(\"%x\", sha256.Sum256([]byte(value))), nil\n\t\t},\n\t\t\"asgSize\": asgSize,\n\t\t\"azID\": azID,\n\t\t\"azCount\": azCount,\n\t\t\"split\": split,\n\t\t\"mountUnitName\": mountUnitName,\n\t\t\"accountID\": accountID,\n\t\t\"portRanges\": portRanges,\n\t\t\"sgIngressRanges\": sgIngressRanges,\n\t\t\"splitHostPort\": splitHostPort,\n\t\t\"extractEndpointHosts\": extractEndpointHosts,\n\t\t\"publicKey\": publicKey,\n\t\t\"stupsNATSubnets\": stupsNATSubnets,\n\t\t\"amiID\": func(imageName, imageOwner string) (string, error) {\n\t\t\treturn amiID(context.awsAdapter, imageName, imageOwner)\n\t\t},\n\t\t// TODO: this function is kept for backward compatibility while\n\t\t// the the use of `nodeCIDRMaxNodesPodCIDR` is being rolled out\n\t\t// to all channels of kubernetes-on-aws. After a full rollout\n\t\t// this can be dropped.\n\t\t\"nodeCIDRMaxNodes\": func(maskSize int64, reserved int64) (int64, error) {\n\t\t\treturn nodeCIDRMaxNodes(16, maskSize, reserved)\n\t\t},\n\t\t\"nodeCIDRMaxNodesPodCIDR\": nodeCIDRMaxNodes,\n\t\t\"nodeCIDRMaxPods\": nodeCIDRMaxPods,\n\t\t\"parseInt64\": parseInt64,\n\t\t\"generateJWKSDocument\": generateJWKSDocument,\n\t\t\"generateOIDCDiscoveryDocument\": generateOIDCDiscoveryDocument,\n\t\t\"kubernetesSizeToKiloBytes\": kubernetesSizeToKiloBytes,\n\t\t\"indexedList\": indexedList,\n\t\t\"zoneDistributedNodePoolGroups\": zoneDistributedNodePoolGroups,\n\t\t\"nodeLifeCycleProviderPerNodePoolGroup\": nodeLifeCycleProviderPerNodePoolGroup,\n\t\t\"certificateExpiry\": certificateExpiry,\n\t\t\"sumQuantities\": sumQuantities,\n\t\t\"awsValidID\": awsValidID,\n\t\t\"indent\": sprig.GenericFuncMap()[\"indent\"],\n\t}\n\n\tcontent, ok := context.fileData[file]\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"template file not found: %s\", file)\n\t}\n\tt, err := template.New(file).Option(\"missingkey=error\").Funcs(funcMap).Parse(string(content))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvar out bytes.Buffer\n\n\tdata := &templateData{\n\t\tAlias: context.cluster.Alias,\n\t\tAPIServerURL: context.cluster.APIServerURL,\n\t\tChannel: context.cluster.Channel,\n\t\tConfigItems: context.cluster.ConfigItems,\n\t\tCriticalityLevel: context.cluster.CriticalityLevel,\n\t\tEnvironment: context.cluster.Environment,\n\t\tID: context.cluster.ID,\n\t\tInfrastructureAccount: context.cluster.InfrastructureAccount,\n\t\tLifecycleStatus: context.cluster.LifecycleStatus,\n\t\tLocalID: context.cluster.LocalID,\n\t\tNodePools: context.cluster.NodePools,\n\t\tRegion: context.cluster.Region,\n\t\tOwner: context.cluster.Owner,\n\t\tCluster: context.cluster,\n\t\tValues: context.values,\n\t\tNodePool: context.nodePool,\n\t}\n\n\tif ud, ok := context.values[userDataValuesKey]; ok {\n\t\tdata.UserData = ud.(string)\n\t}\n\n\tif s3path, ok := context.values[s3GeneratedFilesPathValuesKey]; ok {\n\t\tdata.S3GeneratedFilesPath = s3path.(string)\n\t}\n\n\terr = t.Execute(&out, data)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ttemplateData := out.String()\n\tcontext.templateData[file] = templateData\n\n\treturn templateData, nil\n}", "func GetNewConfigJsonTemplate(cc CodeConfig) string {\n\treturn `{\n\t\"version\": \"0.1.0\",\n \"gson_api_url\": \"https://api.your-domain-goes-here.com/v1/\",\n\t\"port\": 4000,\n\t\"new_relic_key\": \"\",\n\t\"debug\": false,\n\t\"environment\": \"test\",\n\t\"test\": { {{if .IsMSSQL}}\n\t\t\"mssql\": {\n\t\t \"aws\": {\n\t\t\t\"server\": \"\",\n\t\t\t\"port\": 1433,\n\t\t\t\"dbname\": \"\",\n\t\t\t\"username\": \"\",\n\t\t\t\"password\": \"\",\n\t\t\t\"maxidleconnections\": 10,\n\t\t\t\"maxopenconnections\": 100,\n\t\t\t\"debug\": true\n\t\t }\n\t\t}\n {{else if .IsPostgresql}}\n \"postgresql\": {\n\t\t \"aws\": {\n\t\t\t\"server\": \"\",\n\t\t\t\"port\": 5432,\n\t\t\t\"dbname\": \"\",\n\t\t\t\"username\": \"\",\n\t\t\t\"password\": \"\",\n\t\t\t\"maxidleconnections\": 10,\n\t\t\t\"maxopenconnections\": 100,\n\t\t\t\"debug\": true\n\t\t }\n\t\t}\n {{else if .IsRethinkDB}}\n\t\t\"rethinkdb\": {\n\t\t \"aws\": {\n\t\t \"addresses\":\"\",\n\t\t \"dbname\": \"\",\n\t\t \"authkey\": \"\",\n\t\t \"discoverhosts\": false,\n\t\t \"maxidleconnections\": 10,\n\t\t \"maxopenconnections\": 100,\n\t\t \"debug\": true\n\t\t}\n\t}{{end}}\n }\n}`\n}", "func TemplateBody(TemplateBody string) func(*cfn.UpdateStackInput) {\n\treturn func(params *cfn.UpdateStackInput) {\n\t\tparams.TemplateBody = aws.String(TemplateBody)\n\t}\n}", "func (m *GraphBaseServiceClient) ApplicationTemplates()(*i5310ba7d4cfddbf5de4c1be94a30f9ca8c747c30a87e76587ce88d1cbfff01b4.ApplicationTemplatesRequestBuilder) {\n return i5310ba7d4cfddbf5de4c1be94a30f9ca8c747c30a87e76587ce88d1cbfff01b4.NewApplicationTemplatesRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) ApplicationTemplates()(*i5310ba7d4cfddbf5de4c1be94a30f9ca8c747c30a87e76587ce88d1cbfff01b4.ApplicationTemplatesRequestBuilder) {\n return i5310ba7d4cfddbf5de4c1be94a30f9ca8c747c30a87e76587ce88d1cbfff01b4.NewApplicationTemplatesRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (c Controller) Template(client Client, template, nameSpace string, payload *Payload) (*Dispatched, error) {\n\tvar (\n\t\tbuf bytes.Buffer\n\t\tdispatched *Dispatched\n\t\tinstanceID string\n\t\toperation = \"provision\"\n\t)\n\n\t// wrap up the logic for instansiating a build or not\n\tinstansiateBuild := func(service *Dispatched) (*Dispatched, error) {\n\n\t\tif template != templateCloudApp {\n\t\t\tdispatched.WatchURL = client.DeployLogURL(nameSpace, service.DeploymentName)\n\t\t\treturn dispatched, nil\n\t\t}\n\n\t\tbuild, err := client.InstantiateBuild(nameSpace, service.DeploymentName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif build == nil {\n\t\t\treturn nil, errors.New(\"no build returned from call to OSCP. Unable to continue\")\n\t\t}\n\t\tdispatched.WatchURL = client.BuildConfigLogURL(nameSpace, build.Name)\n\t\tdispatched.BuildURL = client.BuildURL(nameSpace, build.Name, payload.CloudAppGUID)\n\t\treturn dispatched, nil\n\t}\n\n\tif nameSpace == \"\" {\n\t\treturn nil, errors.New(\"an empty namespace cannot be provided\")\n\t}\n\tif err := payload.Validate(template); err != nil {\n\t\treturn nil, err\n\t}\n\tinstanceID = InstanceID(nameSpace, payload.ServiceName)\n\tstatusKey := StatusKey(instanceID, operation)\n\tif err := c.statusPublisher.Clear(statusKey); err != nil {\n\t\tc.Logger.Error(\"failed to clear status key \" + statusKey + \" continuing\")\n\t}\n\tif err := c.statusPublisher.Publish(statusKey, configInProgress, \"starting deployment of service \"+payload.ServiceName); err != nil {\n\t\tc.Logger.Error(\"failed to publish status key \" + statusKey + \" continuing\")\n\t}\n\ttpl, err := c.templateLoader.Load(template)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to load template \"+template+\": \")\n\t}\n\tif err := tpl.ExecuteTemplate(&buf, template, payload); err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to execute template: \")\n\t}\n\tosTemplate, err := c.TemplateDecoder.Decode(buf.Bytes())\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to decode into an os template: \")\n\t}\n\tsearchCrit := map[string]string{\"rhmap/name\": payload.ServiceName}\n\tif payload.CloudAppGUID != \"\" {\n\t\tsearchCrit = map[string]string{\"rhmap/guid\": payload.CloudAppGUID}\n\t}\n\tdcs, err := client.FindDeploymentConfigsByLabel(nameSpace, searchCrit)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error trying to find deployment config: \")\n\t}\n\tbc, err := client.FindBuildConfigByLabel(nameSpace, searchCrit)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error trying to find build config: \")\n\t}\n\t//check if already deployed\n\tif len(dcs) > 0 || (nil != bc && len(dcs) > 0) {\n\t\tif err := c.statusPublisher.Publish(statusKey, configInProgress, \"service already exists updating\"); err != nil {\n\t\t\tc.Logger.Error(\"failed to publish status key \" + statusKey + \" continuing \" + err.Error())\n\t\t}\n\t\tdispatched, err = c.update(client, &dcs[0], bc, osTemplate, nameSpace, instanceID, payload)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"Error updating deploy: \")\n\t\t}\n\t\tdispatched.InstanceID = instanceID\n\t\tdispatched.Operation = operation\n\t\tconfigurationDetails := &Configuration{Action: operation, DeploymentName: dispatched.DeploymentName, InstanceID: dispatched.InstanceID, NameSpace: nameSpace}\n\t\tc.ConfigurationController.Configure(client, configurationDetails)\n\t\treturn instansiateBuild(dispatched)\n\t}\n\tif err := c.statusPublisher.Publish(statusKey, configInProgress, \"service does not exist creating\"); err != nil {\n\t\tc.Logger.Error(\"failed to publish status key \" + statusKey + \" continuing \" + err.Error())\n\t}\n\t_, err = deployDependencyServices(c, client, osTemplate, nameSpace, payload)\n\tif err != nil {\n\t\tc.statusPublisher.Publish(statusKey, configError, err.Error())\n\t\treturn nil, err\n\t}\n\n\tdispatched, err = c.create(client, osTemplate, nameSpace, instanceID, payload)\n\tif err != nil {\n\t\tc.statusPublisher.Publish(statusKey, configError, err.Error())\n\t\treturn nil, err\n\t}\n\tdispatched.InstanceID = instanceID\n\tdispatched.Operation = operation\n\tconfigurationDetails := &Configuration{Action: operation, DeploymentName: dispatched.DeploymentName, InstanceID: dispatched.InstanceID, NameSpace: nameSpace}\n\tc.ConfigurationController.Configure(client, configurationDetails)\n\treturn instansiateBuild(dispatched)\n\n}", "func newBootstrapTemplate(e2eCtx *E2EContext) *cfn_bootstrap.Template {\n\tBy(\"Creating a bootstrap AWSIAMConfiguration\")\n\tt := cfn_bootstrap.NewTemplate()\n\tt.Spec.BootstrapUser.Enable = true\n\tt.Spec.SecureSecretsBackends = []v1alpha3.SecretBackend{\n\t\tv1alpha3.SecretBackendSecretsManager,\n\t\tv1alpha3.SecretBackendSSMParameterStore,\n\t}\n\tregion, err := credentials.ResolveRegion(\"\")\n\tExpect(err).NotTo(HaveOccurred())\n\tt.Spec.Region = region\n\tstr, err := yaml.Marshal(t.Spec)\n\tExpect(err).NotTo(HaveOccurred())\n\tExpect(ioutil.WriteFile(path.Join(e2eCtx.Settings.ArtifactFolder, \"awsiamconfiguration.yaml\"), str, 0644)).To(Succeed())\n\tcfnData, err := t.RenderCloudFormation().YAML()\n\tExpect(err).NotTo(HaveOccurred())\n\tExpect(ioutil.WriteFile(path.Join(e2eCtx.Settings.ArtifactFolder, \"cloudformation.yaml\"), cfnData, 0644)).To(Succeed())\n\treturn &t\n}", "func (c *CloudwatchLogs) Template() *cloudformation.Template {\n\tprefix := func(suffix string) string {\n\t\treturn normalizeResourceName(\"fnb\" + c.config.Name + suffix)\n\t}\n\n\ttemplate := cloudformation.NewTemplate()\n\tfor idx, trigger := range c.config.Triggers {\n\t\t// doc: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-permission.html\n\t\ttemplate.Resources[prefix(\"Permission\"+strconv.Itoa(idx))] = &cloudformation.AWSLambdaPermission{\n\t\t\tAction: \"lambda:InvokeFunction\",\n\t\t\tFunctionName: cloudformation.GetAtt(prefix(\"\"), \"Arn\"),\n\t\t\tPrincipal: cloudformation.Join(\"\", []string{\n\t\t\t\t\"logs.\",\n\t\t\t\tcloudformation.Ref(\"AWS::Region\"), // Use the configuration region.\n\t\t\t\t\".\",\n\t\t\t\tcloudformation.Ref(\"AWS::URLSuffix\"), // awsamazon.com or .com.ch\n\t\t\t}),\n\t\t\tSourceArn: cloudformation.Join(\n\t\t\t\t\"\",\n\t\t\t\t[]string{\n\t\t\t\t\t\"arn:\",\n\t\t\t\t\tcloudformation.Ref(\"AWS::Partition\"),\n\t\t\t\t\t\":logs:\",\n\t\t\t\t\tcloudformation.Ref(\"AWS::Region\"),\n\t\t\t\t\t\":\",\n\t\t\t\t\tcloudformation.Ref(\"AWS::AccountId\"),\n\t\t\t\t\t\":log-group:\",\n\t\t\t\t\tstring(trigger.LogGroupName),\n\t\t\t\t\t\":*\",\n\t\t\t\t},\n\t\t\t),\n\t\t}\n\n\t\t// doc: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-subscriptionfilter.html\n\t\ttemplate.Resources[prefix(\"SF\")+normalizeResourceName(string(trigger.LogGroupName))] = &AWSLogsSubscriptionFilter{\n\t\t\tDestinationArn: cloudformation.GetAtt(prefix(\"\"), \"Arn\"),\n\t\t\tFilterPattern: trigger.FilterPattern,\n\t\t\tLogGroupName: string(trigger.LogGroupName),\n\t\t}\n\t}\n\treturn template\n}", "func newTemplateHelper(cr *applicationmonitoring.ApplicationMonitoring, extraParams map[string]string) *TemplateHelper {\n\tparam := Parameters{\n\t\tNamespace: cr.Namespace,\n\t\tGrafanaOperatorName: GrafanaOperatorName,\n\t\tGrafanaCrName: GrafanaCrName,\n\t\tGrafanaOperatorRoleBindingName: GrafanaOperatorRoleBindingName,\n\t\tGrafanaOperatorRoleName: GrafanaOperatorRoleName,\n\t\tGrafanaProxySecretName: GrafanaProxySecretName,\n\t\tGrafanaServiceName: GrafanaServiceName,\n\t\tGrafanaRouteName: GrafanaRouteName,\n\t\tSkipGrafanaServiceAccount: SkipGrafanaServiceAccount(),\n\t\tPrometheusOperatorName: PrometheusOperatorName,\n\t\tApplicationMonitoringName: ApplicationMonitoringName,\n\t\tPrometheusCrName: PrometheusCrName,\n\t\tPrometheusRouteName: PrometheusRouteName,\n\t\tPrometheusServiceName: PrometheusServiceName,\n\t\tPrometheusSessionSecret: PopulateSessionProxySecret(),\n\t\tPrometheusServiceAccountName: PrometheusServiceAccountName,\n\t\tAlertManagerSessionSecret: PopulateSessionProxySecret(),\n\t\tGrafanaSessionSecret: PopulateSessionProxySecret(),\n\t\tAlertManagerServiceAccountName: AlertManagerServiceAccountName,\n\t\tAlertManagerCrName: AlertManagerCrName,\n\t\tAlertManagerServiceName: AlertManagerServiceName,\n\t\tAlertManagerRouteName: AlertManagerRouteName,\n\t\tGrafanaServiceMonitorName: GrafanaServiceMonitorName,\n\t\tPrometheusServiceMonitorName: PrometheusServiceMonitorName,\n\t\tMonitoringKey: cr.Spec.LabelSelector,\n\t\tBlackboxExporterConfigmapName: BlackboxExporterConfigmapName,\n\t\tBlackboxTargets: common.Flatten(),\n\t\tScrapeConfigSecretName: ScrapeConfigSecretName,\n\t\tImageAlertManager: \"quay.io/openshift/origin-prometheus-alertmanager\",\n\t\tImageTagAlertManager: \"4.9\",\n\t\tImageOAuthProxy: \"quay.io/openshift/origin-oauth-proxy\",\n\t\tImageTagOAuthProxy: \"4.8\",\n\t\tImageGrafana: \"quay.io/openshift/origin-grafana\",\n\t\tImageTagGrafana: \"4.9\",\n\t\tImageGrafanaOperator: \"quay.io/rhoas/grafana-operator\",\n\t\tImageTagGrafanaOperator: \"v3.10.3\",\n\t\tImageConfigMapReloader: \"quay.io/openshift/origin-configmap-reloader\",\n\t\tImageTagConfigMapReloader: \"4.9\",\n\t\tImagePrometheusConfigReloader: \"quay.io/openshift/origin-prometheus-config-reloader\",\n\t\tImageTagPrometheusConfigReloader: \"4.9\",\n\t\tImagePrometheusOperator: \"quay.io/openshift-release-dev/ocp-v4.0-art-dev@sha256:19ecf8f3cb62545bc81eeddd3ef8adc105ec5bad5538ee556aade7eb8f9d6dbf\",\n\t\tImageTagPrometheusOperator: \"\",\n\t\tImagePrometheus: \"quay.io/openshift/origin-prometheus\",\n\t\tImageTagPrometheus: \"4.9\",\n\t\tImageBlackboxExporter: \"quay.io/integreatly/prometheus-blackbox-exporter\",\n\t\tImageTagBlackboxExporter: \"v0.19.0\",\n\t\tPrometheusVersion: \"v2.19.0\",\n\t\tPriorityClassName: cr.Spec.PriorityClassName,\n\t\tPrometheusRetention: cr.Spec.PrometheusRetention,\n\t\tPrometheusStorageRequest: cr.Spec.PrometheusStorageRequest,\n\t\tPrometheusInstanceNamespaces: cr.Spec.PrometheusInstanceNamespaces,\n\t\tAlertmanagerInstanceNamespaces: cr.Spec.AlertmanagerInstanceNamespaces,\n\t\tAffinity: PopulateAffinityRule(cr.Spec.Affinity),\n\t\tExtraParams: extraParams,\n\t}\n\ttemplatePath, exists := os.LookupEnv(\"TEMPLATE_PATH\")\n\tif !exists {\n\t\ttemplatePath = \"./templates\"\n\t}\n\n\tmonitoringKey, exists := os.LookupEnv(\"MONITORING_KEY\")\n\tif exists {\n\t\tparam.MonitoringKey = monitoringKey\n\t}\n\n\treturn &TemplateHelper{\n\t\tParameters: param,\n\t\tTemplatePath: templatePath,\n\t}\n}", "func NewTemplate(c *DQLConfig) (*TemplateConfig, error) {\n\t// instantiate\n\tt := &TemplateConfig{\n\t\tProjectPath: helpers.GetProjectPath(c.ProjectPath),\n\t\tTransform: \"AWS::Serverless-2016-10-31\",\n\t\tGlobals: GlobalConfig{\n\t\t\tFunction: SAMFnProp{\n\t\t\t\tEnvironment: FnEnvironment{\n\t\t\t\t\tVariables: map[string]string{\n\t\t\t\t\t\t\"LOCAL\": \"TRUE\",\n\t\t\t\t\t\t\"ENDPOINT\": \"http://dynamodb:8000\",\n\t\t\t\t\t\t\"REGION\": c.Region,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\ts, err := c.ReadServerlessConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tt.addFunctions(s)\n\tt.addResourceEnvs(s)\n\n\treturn t, nil\n}", "func (m *IntentsDeviceManagementIntentItemRequestBuilder) MigrateToTemplate()(*IntentsItemMigrateToTemplateRequestBuilder) {\n return NewIntentsItemMigrateToTemplateRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (cg *ConsumerGroup) ConsumerFromTemplate(options ...ConsumerOption) *Consumer {\n\t// TODO figure out naming strategy, is generateName enough?\n\tc := &Consumer{\n\t\tObjectMeta: cg.Spec.Template.ObjectMeta,\n\t\tSpec: cg.Spec.Template.Spec,\n\t}\n\n\townerRef := metav1.NewControllerRef(cg, ConsumerGroupGroupVersionKind)\n\tc.OwnerReferences = append(c.OwnerReferences, *ownerRef)\n\n\tfor _, opt := range options {\n\t\topt(c)\n\t}\n\treturn c\n}", "func (m *IosDeviceFeaturesConfiguration) SetAssetTagTemplate(value *string)() {\n err := m.GetBackingStore().Set(\"assetTagTemplate\", value)\n if err != nil {\n panic(err)\n }\n}", "func (tc *STemplateController) Instantiate(extra_tmpl string) (*service.Service, error) {\n\turl := urlTemplateAction(tc.ID)\n\taction := make(map[string]interface{})\n\targs := make(map[string]interface{})\n\tparams := make(map[string]interface{})\n\n\tif extra_tmpl != \"\" {\n\t\terr := json.Unmarshal([]byte(extra_tmpl), &args)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tparams[\"merge_template\"] = args\n\t}\n\n\t// Create request\n\taction[\"action\"] = map[string]interface{}{\n\t\t\"perform\": \"instantiate\",\n\t\t\"params\": params,\n\t}\n\n\t//Get response\n\tresponse, err := tc.c.ClientFlow.HTTPMethod(\"POST\", url, action)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !response.status {\n\t\treturn nil, errors.New(response.body)\n\t}\n\n\t//Build Service from response\n\tservice := &service.Service{}\n\tservice_str, err := json.Marshal(response.BodyMap()[\"DOCUMENT\"])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(service_str, service)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn service, nil\n}", "func (f *HubTransactor) SpawnTemplate(opts *bind.TransactOpts, proposedCosmosCoin string, name string, symbol string, decimals *big.Int) (*types.Transaction, error) {\n\treturn f.contract.Transact(opts, \"spawnTemplate\", proposedCosmosCoin, name, symbol, decimals)\n}", "func templateCapture(client *AzureClient) autorest.RespondDecorator {\n\treturn func(r autorest.Responder) autorest.Responder {\n\t\treturn autorest.ResponderFunc(func(resp *http.Response) error {\n\t\t\tbody, bodyString := handleBody(resp.Body, math.MaxInt64)\n\t\t\tresp.Body = body\n\n\t\t\tcaptureTemplate := getCaptureResponse(bodyString)\n\t\t\tif captureTemplate != nil {\n\t\t\t\tclient.Template = captureTemplate\n\t\t\t}\n\n\t\t\treturn r.Respond(resp)\n\t\t})\n\t}\n}", "func newTemplateHelper(cr *integreatly.Grafana) *GrafanaTemplateHelper {\n\tparam := GrafanaParamaeters{\n\t\tGrafanaImage: GrafanaImage,\n\t\tGrafanaVersion: GrafanaVersion,\n\t\tNamespace: cr.Namespace,\n\t\tGrafanaConfigMapName: GrafanaConfigMapName,\n\t\tGrafanaProvidersConfigMapName: GrafanaProvidersConfigMapName,\n\t\tGrafanaDatasourcesConfigMapName: GrafanaDatasourcesConfigMapName,\n\t\tPrometheusUrl: cr.Spec.PrometheusUrl,\n\t\tGrafanaDashboardsConfigMapName: GrafanaDashboardsConfigMapName,\n\t\tGrafanaServiceAccountName: GrafanaServiceAccountName,\n\t\tGrafanaDeploymentName: GrafanaDeploymentName,\n\t\tLogLevel: LogLevel,\n\t\tGrafanaRouteName: GrafanaRouteName,\n\t\tGrafanaServiceName: GrafanaServiceName,\n\t}\n\n\ttemplatePath := os.Getenv(\"TEMPLATE_PATH\")\n\tif templatePath == \"\" {\n\t\ttemplatePath = \"./templates\"\n\t}\n\n\treturn &GrafanaTemplateHelper{\n\t\tParameters: param,\n\t\tTemplatePath: templatePath,\n\t}\n}", "func (d *Double) TemplateBodyFromChangeSet(changeSetID, stackName string) (string, error) {\n\treturn d.TemplateBodyFromChangeSetFn(changeSetID, stackName)\n}", "func (c *Config) Template(src string) *Config {\n\tc.data = src\n\treturn c\n}", "func (cf *Cloudformation) createStack() {\n\n\tcreateStack = &cobra.Command {\n\t\tUse: \"create-efs\",\n\t\tShort: \"Create stack\",\n\t\tLong: `Create stack based on template`,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\n\t\t\tparameters := make([]*cloudformation.Parameter, 0, 5)\n\n\t\t\tonFailure, err := cmd.Flags().GetString(\"onfailure\")\n\t\t\tverifyOnFailureArg(err, onFailure)\n\n\t\t\tcapabilities, err := cmd.Flags().GetStringArray(\"capabilities\")\n\t\t\tverifyCapability(err, capabilities)\n\n\t\t\tstackName, err := cmd.Flags().GetString(\"stackname\")\n\t\t\tverify(err, \"stackname\")\n\n\t\t\tinstanceType, err := cmd.Flags().GetString(\"instance-type\")\n\t\t\tverify(err, \"instance-type\")\n\t\t\taddParameter(&parameters, \"InstanceType\", instanceType)\n\n\t\t\tkeyPair, err := cmd.Flags().GetString(\"key-pair-name\")\n\t\t\tverify(err, \"key-pair-name\")\n\t\t\taddParameter(&parameters, \"KeyName\", keyPair)\n\n\t\t\tsubnets, err := cmd.Flags().GetStringArray(\"subnets\")\n\t\t\tverify(err, \"subnets\")\n\t\t\taddParameters(&parameters, \"Subnets\", subnets)\n\n\t\t\tvpc, err := cmd.Flags().GetString(\"vpc\")\n\t\t\tverify(err, \"vpc\")\n\t\t\taddParameter(&parameters, \"VPC\" ,vpc)\n\n\t\t\timage, err := cmd.Flags().GetString(\"image\")\n\t\t\tverify(err, \"image\")\n\t\t\taddParameter(&parameters, \"ImageId\", image)\n\n\t\t\tfor _, param := range parameters {\n\t\t\t\tfmt.Printf(\"----Param : %s ---- \\n\", param)\n\t\t\t}\n\n\t\t\tcfClient := cloudformation.New(cf.sess, cf.sess.Config)\n\n\t\t\tresp, err := cf.ec2Res.createKeyPair(keyPair)\n\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Create key pair err: %s \\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\n\t\t\tcreatePemFile(resp.KeyMaterial)\n\n\t\t\tfile := readFile(\"templates/distributed_file_system.yaml\")\n\n\t\t\tif _, err := cfClient.CreateStack(&cloudformation.CreateStackInput{\n\t\t\t\tCapabilities: aws.StringSlice(capabilities),\n\t\t\t\tClientRequestToken: nil,\n\t\t\t\tDisableRollback: nil,\n\t\t\t\tEnableTerminationProtection: nil,\n\t\t\t\tNotificationARNs: nil,\n\t\t\t\tOnFailure: &onFailure,\n\t\t\t\tParameters: parameters,\n\t\t\t\tResourceTypes: nil,\n\t\t\t\tRoleARN: nil,\n\t\t\t\tRollbackConfiguration: nil,\n\t\t\t\tStackName: &stackName,\n\t\t\t\tStackPolicyBody: nil,\n\t\t\t\tStackPolicyURL: nil,\n\t\t\t\tTags: nil,\n\t\t\t\tTemplateBody: &file,\n\t\t\t\tTemplateURL: nil,\n\t\t\t\tTimeoutInMinutes: nil,\n\t\t\t}); err != nil {\n\t\t\t\tdeleteKeyPair(cf, keyPair, err)\n\t\t\t}\n\n\t\t},\n\t}\n}", "func UsePreviousTemplate(params *cfn.UpdateStackInput) {\n\tparams.UsePreviousTemplate = aws.Bool(true)\n}", "func createStackFromBody(sess client.ConfigProvider, templateBody []byte, stackName string) error {\n\n\t// Tags for the CloudFormation stack\n\ttags := []*cfn.Tag{\n\t\t{\n\t\t\tKey: aws.String(\"Product\"),\n\t\t\tValue: aws.String(\"MaxEdge\"),\n\t\t},\n\t}\n\n\t//Creates CloudFormation stack\n\tsvc := cfn.New(sess)\n\tinput := &cfn.CreateStackInput{\n\t\tTemplateBody: aws.String(string(templateBody)),\n\t\tStackName: aws.String(stackName),\n\t\tTags: tags,\n\t\tCapabilities: []*string{aws.String(\"CAPABILITY_NAMED_IAM\")}, // Required because of creating a stack that is creating IAM resources\n\t}\n\n\tfmt.Println(\"Stack creation initiated...\")\n\n\t// Creates the stack\n\t_, err := svc.CreateStack(input)\n\tif err != nil {\n\t\tfmt.Println(\"Got error creating stack:\")\n\t\tfmt.Println(err.Error())\n\t\treturn err\n\t}\n\treturn nil\n}", "func WithTemplate(t *template.Template) Config {\n\treturn func(r *router) {\n\t\tr.template = t\n\t}\n}", "func (j *ServiceTestJig) newRCTemplate(namespace string) *api.ReplicationController {\n\trc := &api.ReplicationController{\n\t\tObjectMeta: api.ObjectMeta{\n\t\t\tNamespace: namespace,\n\t\t\tName: j.Name,\n\t\t\tLabels: j.Labels,\n\t\t},\n\t\tSpec: api.ReplicationControllerSpec{\n\t\t\tReplicas: 1,\n\t\t\tSelector: j.Labels,\n\t\t\tTemplate: &api.PodTemplateSpec{\n\t\t\t\tObjectMeta: api.ObjectMeta{\n\t\t\t\t\tLabels: j.Labels,\n\t\t\t\t},\n\t\t\t\tSpec: api.PodSpec{\n\t\t\t\t\tContainers: []api.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"netexec\",\n\t\t\t\t\t\t\tImage: \"gcr.io/google_containers/netexec:1.6\",\n\t\t\t\t\t\t\tArgs: []string{\"--http-port=80\", \"--udp-port=80\"},\n\t\t\t\t\t\t\tReadinessProbe: &api.Probe{\n\t\t\t\t\t\t\t\tPeriodSeconds: 3,\n\t\t\t\t\t\t\t\tHandler: api.Handler{\n\t\t\t\t\t\t\t\t\tHTTPGet: &api.HTTPGetAction{\n\t\t\t\t\t\t\t\t\t\tPort: intstr.FromInt(80),\n\t\t\t\t\t\t\t\t\t\tPath: \"/hostName\",\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\tTerminationGracePeriodSeconds: new(int64),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\treturn rc\n}", "func BootstrapTemplate() *template.Template {\n\treturn bootstrap\n}", "func (m *IosDeviceFeaturesConfiguration) GetAssetTagTemplate()(*string) {\n val, err := m.GetBackingStore().Get(\"assetTagTemplate\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func Test_Controller_Resource_TCCPF_Template_Render(t *testing.T) {\n\ttestCases := []struct {\n\t\tname string\n\t\tctx context.Context\n\t\tcr infrastructurev1alpha3.AWSCluster\n\t\troute53Enabled bool\n\t}{\n\t\t{\n\t\t\tname: \"case 0: basic test\",\n\t\t\tctx: unittest.DefaultContext(),\n\t\t\tcr: unittest.DefaultCluster(),\n\t\t\troute53Enabled: true,\n\t\t},\n\t\t{\n\t\t\tname: \"case 1: without route 53 enabled\",\n\t\t\tctx: unittest.DefaultContext(),\n\t\t\tcr: unittest.DefaultCluster(),\n\t\t\troute53Enabled: false,\n\t\t},\n\t}\n\n\tfor i, tc := range testCases {\n\t\tt.Run(strconv.Itoa(i), func(t *testing.T) {\n\t\t\tvar err error\n\n\t\t\tk := unittest.FakeK8sClient()\n\n\t\t\tvar d *changedetection.TCCPF\n\t\t\t{\n\t\t\t\tc := changedetection.TCCPFConfig{\n\t\t\t\t\tLogger: microloggertest.New(),\n\t\t\t\t}\n\n\t\t\t\td, err = changedetection.NewTCCPF(c)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar e recorder.Interface\n\t\t\t{\n\t\t\t\tc := recorder.Config{\n\t\t\t\t\tK8sClient: k,\n\n\t\t\t\t\tComponent: \"dummy\",\n\t\t\t\t}\n\n\t\t\t\te = recorder.New(c)\n\t\t\t}\n\n\t\t\tvar h *cphostedzone.HostedZone\n\t\t\t{\n\t\t\t\tc := cphostedzone.Config{\n\t\t\t\t\tLogger: microloggertest.New(),\n\n\t\t\t\t\tRoute53Enabled: false,\n\t\t\t\t}\n\n\t\t\t\th, err = cphostedzone.New(c)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar r *Resource\n\t\t\t{\n\t\t\t\tc := Config{\n\t\t\t\t\tDetection: d,\n\t\t\t\t\tEvent: e,\n\t\t\t\t\tHostedZone: h,\n\t\t\t\t\tLogger: microloggertest.New(),\n\n\t\t\t\t\tInstallationName: \"dummy\",\n\t\t\t\t\tRoute53Enabled: tc.route53Enabled,\n\t\t\t\t}\n\n\t\t\t\tr, err = New(c)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tparams, err := r.newTemplateParams(tc.ctx, tc.cr)\n\t\t\tif err != nil {\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttemplateBody, err := template.Render(params)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\t_, err = yaml.YAMLToJSONStrict([]byte(templateBody))\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tp := filepath.Join(\"testdata\", unittest.NormalizeFileName(tc.name)+\".golden\")\n\n\t\t\tif *update {\n\t\t\t\terr := os.WriteFile(p, []byte(templateBody), 0644) // nolint: gosec\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tgoldenFile, err := os.ReadFile(p)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tif !bytes.Equal([]byte(templateBody), goldenFile) {\n\t\t\t\tt.Fatalf(\"\\n\\n%s\\n\", cmp.Diff(string(goldenFile), templateBody))\n\t\t\t}\n\t\t})\n\t}\n}", "func ImageFromTemplate(t *template.Template) ImageBuilder {\n\treturn ImageBuilderFunc(func(ctx context.Context, _ io.Writer, event events.Deployment) (image.Image, error) {\n\t\tbuf := new(bytes.Buffer)\n\t\tif err := t.Execute(buf, event); err != nil {\n\t\t\treturn image.Image{}, err\n\t\t}\n\n\t\treturn image.Decode(buf.String())\n\t})\n}", "func (r *applicationResolver) ApplicationTemplate(ctx context.Context, obj *graphql.Application) (*graphql.ApplicationTemplate, error) {\n\treturn r.app.ApplicationTemplate(ctx, obj)\n}", "func ImageFromTemplate(t *template.Template) ImageBuilder {\n\treturn ImageBuilderFunc(func(ctx context.Context, event events.Deployment) (image.Image, error) {\n\t\tbuf := new(bytes.Buffer)\n\t\tif err := t.Execute(buf, event); err != nil {\n\t\t\treturn image.Image{}, err\n\t\t}\n\n\t\treturn image.Decode(buf.String())\n\t})\n}", "func CreateTemplateMocked(t *testing.T, templateIn *types.Template) *types.Template {\n\n\tassert := assert.New(t)\n\n\t// wire up\n\tcs := &utils.MockConcertoService{}\n\tds, err := NewTemplateService(cs)\n\tassert.Nil(err, \"Couldn't load template service\")\n\tassert.NotNil(ds, \"Template service not instanced\")\n\n\t// convertMap\n\tmapIn, err := utils.ItemConvertParams(*templateIn)\n\tassert.Nil(err, \"Template test data corrupted\")\n\n\t// to json\n\tdOut, err := json.Marshal(templateIn)\n\tassert.Nil(err, \"Template test data corrupted\")\n\n\t// call service\n\tcs.On(\"Post\", \"/blueprint/templates/\", mapIn).Return(dOut, 200, nil)\n\ttemplateOut, err := ds.CreateTemplate(mapIn)\n\tassert.Nil(err, \"Error creating template list\")\n\tassert.Equal(templateIn, templateOut, \"CreateTemplate returned different templates\")\n\n\treturn templateOut\n}", "func CreateFromTemplate(yamlTemplate string, values interface{}) (jobName string, err error) {\n\tj, err := BuildFromTemplate(yamlTemplate, values)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn CreateOrReplace(j)\n}", "func (s *InspectTemplateServer) applyInspectTemplate(ctx context.Context, c *dlp.Client, request *dlppb.ApplyDlpInspectTemplateRequest) (*dlppb.DlpInspectTemplate, error) {\n\tp := ProtoToInspectTemplate(request.GetResource())\n\tres, err := c.ApplyInspectTemplate(ctx, p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr := InspectTemplateToProto(res)\n\treturn r, nil\n}", "func CreateTerraformStack(t *testing.T, terraformDir string) {\n terraformOptions := test_structure.LoadTerraformOptions(t, terraformDir)\n terraform.InitAndApply(t, terraformOptions)\n}", "func RenderStackTemplate(state *State) flaw.Flaw {\n\tfmt.Println(\" rendering stack template...\")\n\t// make new branch directory in artifacts\n\tbranchName := filepath.Join(\n\t\tos.Getenv(\"DE_ARTIFACTS_PATH\"),\n\t\tos.Getenv(\"DE_GIT_BRANCH\"),\n\t)\n\n\terr := os.MkdirAll(branchName, 0755)\n\tif err != nil {\n\t\treturn flaw.From(err)\n\t}\n\n\t// create file\n\tstate.RenderedTemplateLocal = filepath.Join(\n\t\tbranchName,\n\t\t\"completeStack\",\n\t)\n\tnewStackFile, err := os.Create(state.RenderedTemplateLocal)\n\tif err != nil {\n\t\tfmt.Println(\"trouble creating file:\", err)\n\t}\n\n\tbranchStackTemplate := template.New(\"root.gotemplate\")\n\n\tbranchStackTemplate.Delims(\"{{{\", \"}}}\")\n\n\t_, err = branchStackTemplate.ParseGlob(\"aws/stack-templates/*.gotemplate\")\n\n\tif err != nil {\n\t\thalt.Panic(flaw.From(err))\n\t}\n\n\terr = branchStackTemplate.Execute(newStackFile, nil)\n\n\tif err != nil {\n\t\thalt.Panic(flaw.From(err))\n\t}\n\n\treturn nil\n}", "func (f *HubTransactorSession) SpawnTemplate(proposedCosmosCoin string, name string, symbol string, decimals *big.Int) (*types.Transaction, error) {\n\treturn f.Contract.SpawnTemplate(&f.TransactOpts, proposedCosmosCoin, name, symbol, decimals)\n}", "func (selectManyConfig SelectManyConfig) GetTemplate(context *Context, metaType string) (assetfs.AssetInterface, error) {\n\tif metaType == \"form\" && selectManyConfig.SelectionTemplate != \"\" {\n\t\treturn context.Asset(selectManyConfig.SelectionTemplate)\n\t}\n\treturn nil, errors.New(\"not implemented\")\n}", "func (h *NotificationHub) RegisterWithTemplate(ctx context.Context, r TemplateRegistration) (raw []byte, registrationResult *RegistrationResult, err error) {\n\tvar (\n\t\tregURL = h.generateAPIURL(\"registrations\")\n\t\tmethod = postMethod\n\t\tpayload = \"\"\n\t\theaders = map[string]string{\n\t\t\t\"Content-Type\": \"application/atom+xml;type=entry;charset=utf-8\",\n\t\t}\n\t)\n\n\tswitch r.Platform {\n\tcase ApplePlatform:\n\t\tpayload = strings.Replace(appleTemplateRegXMLString, \"{{DeviceID}}\", r.DeviceID, 1)\n\tcase GcmPlatform:\n\t\tpayload = strings.Replace(gcmTemplateRegXMLString, \"{{DeviceID}}\", r.DeviceID, 1)\n\tdefault:\n\t\treturn nil, nil, errors.New(\"Notification format not implemented\")\n\t}\n\tpayload = strings.Replace(payload, \"{{Tags}}\", r.Tags, 1)\n\tpayload = strings.Replace(payload, \"{{Template}}\", r.Template, 1)\n\n\tif r.RegistrationID != \"\" {\n\t\tmethod = putMethod\n\t\tregURL.Path = path.Join(regURL.Path, r.RegistrationID)\n\t}\n\n\traw, _, err = h.exec(ctx, method, regURL, headers, bytes.NewBufferString(payload))\n\n\tif err == nil {\n\t\tif err = xml.Unmarshal(raw, &registrationResult); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif registrationResult != nil {\n\t\tregistrationResult.normalize()\n\t}\n\treturn\n}", "func NewStack(ctx *pulumi.Context,\n\tname string, args *StackArgs, opts ...pulumi.ResourceOption) (*Stack, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.TemplateUrl == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'TemplateUrl'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Stack\n\terr := ctx.RegisterResource(\"aws-native:cloudformation:Stack\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func WithTemplate(t string) Option {\n\treturn func(c *config) {\n\t\tc.Template = t\n\t}\n}", "func WithTemplate(t string) Option {\n\treturn func(c *config) {\n\t\tc.Template = t\n\t}\n}", "func (_m *ICreate) Template(language string, name string) {\n\t_m.Called(language, name)\n}", "func newTemplateHelper(cr *integreatlyv1alpha1.Gitea) *GiteaTemplateHelper {\n\tparam := GiteaParameters{\n\t\tGiteaConfigMapName: GiteaConfigMapName,\n\t\tGiteaDeploymentName: GiteaDeploymentName,\n\t\tGiteaIngressName: GiteaIngressName,\n\t\tGiteaPgDeploymentName: GiteaPgDeploymentName,\n\t\tGiteaPgPvcName: GiteaPgPvcName,\n\t\tGiteaPgServiceName: GiteaPgServiceName,\n\t\tGiteaReposPvcName: GiteaReposPvcName,\n\t\tGiteaServiceAccountName: GiteaServiceAccountName,\n\t\tGiteaServiceName: GiteaServiceName,\n\t\tProxyDeploymentName: ProxyDeploymentName,\n\t\tProxyRouteName: ProxyRouteName,\n\t\tProxyServiceName: ProxyServiceName,\n\t\tProxyServiceAccountName: ProxyServiceAccountName,\n\t\tApplicationNamespace: cr.Namespace,\n\t\tApplicationName: \"gitea\",\n\t\tHostname: cr.Spec.Hostname,\n\t\tDatabaseUser: \"gitea\",\n\t\tDatabasePassword: DatabasePassword,\n\t\tDatabaseAdminPassword: DatabaseAdminPassword,\n\t\tDatabaseName: \"gitea\",\n\t\tDatabaseMaxConnections: \"100\",\n\t\tDatabaseSharedBuffers: \"12MB\",\n\t\tInstallLock: true,\n\t\tGiteaInternalToken: generateToken(105),\n\t\tGiteaSecretKey: generateToken(10),\n\t\tGiteaImage: GiteaImage,\n\t\tGiteaVersion: GiteaVersion,\n\t\tGiteaVolumeCapacity: \"1Gi\",\n\t\tDbVolumeCapacity: \"1Gi\",\n\t}\n\n\ttemplatePath := os.Getenv(\"TEMPLATE_PATH\")\n\tif templatePath == \"\" {\n\t\ttemplatePath = \"./templates\"\n\t}\n\n\treturn &GiteaTemplateHelper{\n\t\tParameters: param,\n\t\tTemplatePath: templatePath,\n\t}\n}", "func RevertTemplate(name string) error {\n\treturn pathx.CreateTemplate(category, name, deploymentTemplate)\n}", "func (f *Sender) CreateWithCustomReplyKeyboard(templateName string, Data interface{}, kbd [][]MessageButton) error {\n\tbotMsg := f.msgFactory()\n\tbotMsg.SetData(Data)\n\n\tparams, err := renderFromTemplate(f.templateDir, templateName, f.session.Locale(), Data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttoSent := tgbotapi.NewMessage(f.session.ChatId(), params.text)\n\ttoSent.ParseMode = params.ParseMode\n\n\tif params.replyKbdMarkup != nil {\n\t\tparams.replyKbdMarkup.Keyboard = append(params.replyKbdMarkup.Keyboard, createReplyKeyboard(kbd).Keyboard...)\n\t\ttoSent.ReplyMarkup = *params.replyKbdMarkup\n\t} else {\n\t\ttoSent.ReplyMarkup = createReplyKeyboard(kbd)\n\t}\n\n\tif params.inlineKbdMarkup != nil {\n\t\ttoSent.ReplyMarkup = *params.inlineKbdMarkup\n\t}\n\tif f.bot != nil {\n\t\tif sentMsg, err := f.bot.Send(toSent); err == nil {\n\t\t\tbotMsg.SetID(int64(sentMsg.MessageID))\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tbotMsg.Save()\n\treturn nil\n}", "func (r Virtual_Guest_Block_Device_Template_Group) CreateFromExternalSource(configuration *datatypes.Container_Virtual_Guest_Block_Device_Template_Configuration) (resp datatypes.Virtual_Guest_Block_Device_Template_Group, err error) {\n\tparams := []interface{}{\n\t\tconfiguration,\n\t}\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest_Block_Device_Template_Group\", \"createFromExternalSource\", params, &r.Options, &resp)\n\treturn\n}", "func (m DeploymentOptionModel) ApplyTemplate(name string, rawtemplate string, replacement []OptionTemplate) bytes.Buffer {\n\tdynstructBuilder := dynamicstruct.NewStruct()\n\t// valarray := make(map[int]interface{})\n\n\tfor _, r := range replacement {\n\t\tdynstructBuilder.AddField(r.Key, r.Value, \"\")\n\t\t// valarray[i] = r.Value\n\t}\n\tdynstruct := dynstructBuilder.Build().New()\n\telem := reflect.ValueOf(&dynstruct).Elem()\n\tfor _, r := range replacement {\n\t\tvalue := reflect.ValueOf(r.Value)\n\t\telem.FieldByName(r.Key).Set(value)\n\t}\n\n\tt := template.Must(template.New(name).Parse(rawtemplate))\n\tvar buf bytes.Buffer\n\tw := io.Writer(&buf)\n\terr := t.Execute(w, dynstruct)\n\tif err != nil {\n\t\tlog.Fatal(\"Execute template error:\", err)\n\t}\n\treturn buf\n}", "func templateDeploy(cmd *cobra.Command, args []string) {\n\t//Check deploy template file.\n\tif len(args) <= 0 || utils.IsFileExist(args[0]) == false {\n\t\tfmt.Fprintf(os.Stderr, \"the deploy template file is required, %s\\n\", \"see https://github.com/Huawei/containerops/singular for more detail.\")\n\t\tos.Exit(1)\n\t}\n\n\ttemplate := args[0]\n\td := new(objects.Deployment)\n\n\t//Read template file and parse.\n\tif err := d.ParseFromFile(template, output); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"parse deploy template error: %s\\n\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\t//Set private key file path.\n\tif privateKey != \"\" {\n\t\td.Tools.SSH.Private, d.Tools.SSH.Public = privateKey, publicKey\n\t}\n\n\t//The integrity checking of deploy template.\n\tif err := d.Check(); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"parse deploy template error: %s\\n\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\t//Set log and error io.Writer\n\tvar logWriters io.Writer\n\n\t//Generate stdout/stderr io.Writer\n\tstdoutFile, _ := os.Create(path.Join(d.Config, \"deploy.log\"))\n\tdefer stdoutFile.Close()\n\n\t//Using MultiWriter log and error.\n\tif verbose == true {\n\t\tlogWriters = io.MultiWriter(stdoutFile, os.Stdout)\n\t} else {\n\t\tlogWriters = io.MultiWriter(stdoutFile)\n\t}\n\n\t//Deploy cloud native stack\n\tif err := module.DeployInfraStacks(d, db, logWriters, timestamp); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%s\\n\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\t//Delete droplets\n\tif del == true {\n\t\tif err := module.DeleteInfraStacks(d, logWriters, timestamp); err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"%s\\n\", err.Error())\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}", "func (c *CloudFormationTemplate) CreateStack(suffix string) {\n\tfmt.Printf(\"\\nRunning CloudFormation stack [%s]\", c.Name)\n\tsess := session.Must(session.NewSession(&aws.Config{\n\t\tRegion: aws.String(\"us-west-2\"),\n\t}))\n\tsvc := cloudformation.New(sess)\n\n\ttemplateBody := string(c.Bytes)\n\tc.StackName = c.Name + \"-\" + suffix\n\tcloudFormationValues := make(map[string]string)\n\n\tcreateStackParams := &cloudformation.CreateStackInput{\n\t\tStackName: aws.String(c.StackName),\n\t\tTemplateBody: aws.String(templateBody),\n\t}\n\n\tdescribeStacksParams := &cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(c.StackName),\n\t}\n\n\tout, err := svc.CreateStack(createStackParams)\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"AlreadyExistsException\") {\n\t\t\tfmt.Printf(\"\\nCloudFormation stack [%s] already exists. Skipping...\", c.Name)\n\t\t\tdescOut, err := svc.DescribeStacks(describeStacksParams)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tc.ParseOutput(descOut, cloudFormationValues)\n\t\t\treturn\n\t\t} else {\n\t\t\tfmt.Printf(\"%s\", err)\n\t\t\tpanic(err)\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"%s\", out)\n\t}\n\n\tstackReady := false\n\n\tfor stackReady != true {\n\n\t\tdescOut, err := svc.DescribeStacks(describeStacksParams)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%s\", err)\n\t\t\tpanic(err)\n\t\t} else {\n\t\t\tfmt.Printf(\"\\nCloudFormation stack [%s] is creating...\", c.Name)\n\t\t}\n\n\t\tif *descOut.Stacks[0].StackStatus == \"CREATE_COMPLETE\" {\n\t\t\tstackReady = true\n\t\t\tfmt.Printf(\"\\nCloudFormation stack [%s] ready...\\n\", c.Name)\n\t\t\tc.ParseOutput(descOut, cloudFormationValues)\n\t\t}\n\n\t\ttime.Sleep(time.Second * 7)\n\t}\n\n}", "func (m OpenShiftMachineV1Beta1TemplateBuilder) BuildTemplate() machinev1.ControlPlaneMachineSetTemplate {\n\ttemplate := machinev1.ControlPlaneMachineSetTemplate{\n\t\tMachineType: machinev1.OpenShiftMachineV1Beta1MachineType,\n\t\tOpenShiftMachineV1Beta1Machine: &machinev1.OpenShiftMachineV1Beta1MachineTemplate{\n\t\t\tObjectMeta: machinev1.ControlPlaneMachineSetTemplateObjectMeta{\n\t\t\t\tLabels: m.labels,\n\t\t\t},\n\t\t},\n\t}\n\n\tif m.failureDomainsBuilder != nil {\n\t\ttemplate.OpenShiftMachineV1Beta1Machine.FailureDomains = m.failureDomainsBuilder.BuildFailureDomains()\n\t}\n\n\tif m.providerSpecBuilder != nil {\n\t\ttemplate.OpenShiftMachineV1Beta1Machine.Spec.ProviderSpec.Value = m.providerSpecBuilder.BuildRawExtension()\n\t}\n\n\treturn template\n}", "func NewTemplate(a *config.AppConfig) {\n\tapp = a\n}", "func newReplicaSetFromTemplate(experiment *v1alpha1.Experiment, template v1alpha1.TemplateSpec, collisionCount *int32) appsv1.ReplicaSet {\n\tnewRSTemplate := *template.Template.DeepCopy()\n\treplicaSetAnnotations := newReplicaSetAnnotations(experiment.Name, template.Name)\n\tif newRSTemplate.Labels != nil {\n\t\tif _, ok := newRSTemplate.Labels[v1alpha1.DefaultRolloutUniqueLabelKey]; ok {\n\t\t\tdelete(newRSTemplate.Labels, v1alpha1.DefaultRolloutUniqueLabelKey)\n\t\t}\n\t}\n\tpodHash := hash.ComputePodTemplateHash(&newRSTemplate, collisionCount)\n\n\tnewRSTemplate.Labels = labelsutil.CloneAndAddLabel(newRSTemplate.Labels, v1alpha1.DefaultRolloutUniqueLabelKey, podHash)\n\t// Add podTemplateHash label to selector.\n\tnewRSSelector := labelsutil.CloneSelectorAndAddLabel(template.Selector, v1alpha1.DefaultRolloutUniqueLabelKey, podHash)\n\n\t// The annotations must be different for each template because annotations are used to match\n\t// replicasets to templates. We inject the experiment and template name in the replicaset\n\t// annotations to ensure uniqueness.\n\trs := appsv1.ReplicaSet{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: fmt.Sprintf(\"%s-%s\", experiment.Name, template.Name),\n\t\t\tNamespace: experiment.Namespace,\n\t\t\tLabels: map[string]string{\n\t\t\t\tv1alpha1.DefaultRolloutUniqueLabelKey: podHash,\n\t\t\t},\n\t\t\tOwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(experiment, controllerKind)},\n\t\t\tAnnotations: replicaSetAnnotations,\n\t\t},\n\t\tSpec: appsv1.ReplicaSetSpec{\n\t\t\tReplicas: new(int32),\n\t\t\tMinReadySeconds: template.MinReadySeconds,\n\t\t\tSelector: newRSSelector,\n\t\t\tTemplate: newRSTemplate,\n\t\t},\n\t}\n\treturn rs\n}", "func (c CloudConfig) NewMasterTemplate(ctx context.Context, data IgnitionTemplateData, encrypter encrypter.Interface) (string, error) {\n\tvar err error\n\tvar k8sAPIExtraArgs []string\n\t{\n\t\toidcExtraArgs := c.oidcExtraArgs(ctx, data)\n\t\tk8sAPIExtraArgs = append(k8sAPIExtraArgs, oidcExtraArgs...)\n\t}\n\n\tvar params k8scloudconfig.Params\n\t{\n\t\tbe := baseExtension{\n\t\t\tazure: c.azure,\n\t\t\tazureClientCredentialsConfig: c.azureClientCredentials,\n\t\t\tcalicoCIDR: data.CustomObject.Spec.Azure.VirtualNetwork.CalicoSubnetCIDR,\n\t\t\tcertFiles: data.MasterCertFiles,\n\t\t\tcustomObject: data.CustomObject,\n\t\t\tencrypter: encrypter,\n\t\t\tsubscriptionID: c.subscriptionID,\n\t\t\tvnetCIDR: data.CustomObject.Spec.Azure.VirtualNetwork.CIDR,\n\t\t}\n\n\t\tparams = k8scloudconfig.Params{}\n\t\tparams.BaseDomain = key.ClusterBaseDomain(data.CustomObject)\n\t\tparams.Cluster = data.CustomObject.Spec.Cluster\n\t\tparams.CalicoPolicyOnly = true\n\t\tparams.DockerhubToken = c.dockerhubToken\n\t\tparams.DisableIngressControllerService = true\n\t\tparams.EnableCronJobTimeZone = true\n\t\tparams.Etcd.ClientPort = defaultEtcdPort\n\t\tparams.Etcd.HighAvailability = false\n\t\tparams.Etcd.InitialClusterState = EtcdInitialClusterStateNew\n\t\tparams.ExternalCloudControllerManager = true\n\t\tparams.Kubernetes = k8scloudconfig.Kubernetes{\n\t\t\tApiserver: k8scloudconfig.KubernetesPodOptions{\n\t\t\t\tHostExtraMounts: []k8scloudconfig.KubernetesPodOptionsHostMount{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"k8s-config\",\n\t\t\t\t\t\tPath: \"/etc/kubernetes/config/\",\n\t\t\t\t\t\tReadOnly: true,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"identity-settings\",\n\t\t\t\t\t\tPath: \"/var/lib/waagent/\",\n\t\t\t\t\t\tReadOnly: true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tCommandExtraArgs: k8sAPIExtraArgs,\n\t\t\t},\n\t\t\tControllerManager: k8scloudconfig.KubernetesPodOptions{\n\t\t\t\tHostExtraMounts: []k8scloudconfig.KubernetesPodOptionsHostMount{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"identity-settings\",\n\t\t\t\t\t\tPath: \"/var/lib/waagent/\",\n\t\t\t\t\t\tReadOnly: true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tCommandExtraArgs: []string{\n\t\t\t\t\t\"--allocate-node-cidrs=true\",\n\t\t\t\t\t\"--cluster-cidr=\" + data.CustomObject.Spec.Azure.VirtualNetwork.CalicoSubnetCIDR,\n\t\t\t\t},\n\t\t\t},\n\t\t\tKubelet: k8scloudconfig.KubernetesDockerOptions{\n\t\t\t\tRunExtraArgs: []string{\n\t\t\t\t\t\"-v /var/lib/waagent:/var/lib/waagent:ro\",\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\n\t\tparams.ControllerManagerTerminatedPodGcThreshold = key.ControllerManagerTerminatedPodGcThreshold(data.Cluster)\n\n\t\tencryptedEncryptionConfig, err := encrypter.Encrypt(data.EncryptionConf)\n\t\tif err != nil {\n\t\t\treturn \"\", microerror.Mask(err)\n\t\t}\n\n\t\tparams.Extension = &masterExtension{\n\t\t\tbaseExtension: be,\n\t\t\tencryptedEncryptionConfig: encryptedEncryptionConfig,\n\t\t}\n\t\tparams.ExtraManifests = []string{}\n\t\tparams.Debug = k8scloudconfig.Debug{\n\t\t\tEnabled: c.ignition.Debug,\n\t\t\tLogsPrefix: c.ignition.LogsPrefix,\n\t\t\tLogsToken: c.ignition.LogsToken,\n\t\t}\n\t\tparams.Images = data.Images\n\t\tparams.RegistryMirrors = c.registryMirrors\n\t\tparams.Versions = data.Versions\n\t\tparams.SSOPublicKey = c.ssoPublicKey\n\t\tparams.DisableEncryptionAtREST = true // encryption key is now managed by encription-provider-operator\n\t}\n\tignitionPath := k8scloudconfig.GetIgnitionPath(c.ignition.Path)\n\tparams.Files, err = k8scloudconfig.RenderFiles(ignitionPath, params)\n\tif err != nil {\n\t\treturn \"\", microerror.Mask(err)\n\t}\n\n\treturn newCloudConfig(k8scloudconfig.MasterTemplate, params)\n}", "func (s *Cloudformation) CreateStack() (output *cloudformation.CreateStackOutput, err error) {\n\tsess := s.config.AWSSession\n\tsvc := cloudformation.New(sess)\n\n\tcftemplate := helpers.GetCloudFormationTemplate(s.config, \"s3bucket\", s.S3Bucket.Spec.CloudFormationTemplateName, s.S3Bucket.Spec.CloudFormationTemplateNamespace)\n\n\tstackInputs := cloudformation.CreateStackInput{\n\t\tStackName: aws.String(s.StackName()),\n\t\tTemplateURL: aws.String(cftemplate),\n\t\tNotificationARNs: []*string{\n\t\t\taws.String(s.topicARN),\n\t\t},\n\t}\n\n\tresourceName := helpers.CreateParam(\"ResourceName\", s.S3Bucket.Name)\n\tresourceVersion := helpers.CreateParam(\"ResourceVersion\", s.S3Bucket.ResourceVersion)\n\tnamespace := helpers.CreateParam(\"Namespace\", s.S3Bucket.Namespace)\n\tclusterName := helpers.CreateParam(\"ClusterName\", s.config.ClusterName)\n\tbucketName := helpers.CreateParam(\"BucketName\", helpers.Stringify(s.S3Bucket.Name))\n\tversioningTemp := \"{{.Obj.Spec.Versioning}}\"\n\tversioningValue, err := helpers.Templatize(versioningTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tversioning := helpers.CreateParam(\"EnableVersioning\", helpers.Stringify(versioningValue))\n\taccessControlTemp := \"{{.Obj.Spec.AccessControl}}\"\n\taccessControlValue, err := helpers.Templatize(accessControlTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\taccessControl := helpers.CreateParam(\"BucketAccessControl\", helpers.Stringify(accessControlValue))\n\tloggingenabledTemp := \"{{.Obj.Spec.Logging.Enabled}}\"\n\tloggingenabledValue, err := helpers.Templatize(loggingenabledTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tloggingenabled := helpers.CreateParam(\"EnableLogging\", helpers.Stringify(loggingenabledValue))\n\tloggingprefixTemp := \"{{.Obj.Spec.Logging.Prefix}}\"\n\tloggingprefixValue, err := helpers.Templatize(loggingprefixTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tloggingprefix := helpers.CreateParam(\"LoggingPrefix\", helpers.Stringify(loggingprefixValue))\n\twebsiteenabledTemp := \"{{.Obj.Spec.Website.Enabled}}\"\n\twebsiteenabledValue, err := helpers.Templatize(websiteenabledTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteenabled := helpers.CreateParam(\"EnableStaticSite\", helpers.Stringify(websiteenabledValue))\n\twebsiteindexPageTemp := \"{{.Obj.Spec.Website.IndexPage}}\"\n\twebsiteindexPageValue, err := helpers.Templatize(websiteindexPageTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteindexPage := helpers.CreateParam(\"StaticSiteIndex\", helpers.Stringify(websiteindexPageValue))\n\twebsiteerrorPageTemp := \"{{.Obj.Spec.Website.ErrorPage}}\"\n\twebsiteerrorPageValue, err := helpers.Templatize(websiteerrorPageTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteerrorPage := helpers.CreateParam(\"StaticSiteError\", helpers.Stringify(websiteerrorPageValue))\n\n\tparameters := []*cloudformation.Parameter{}\n\tparameters = append(parameters, resourceName)\n\tparameters = append(parameters, resourceVersion)\n\tparameters = append(parameters, namespace)\n\tparameters = append(parameters, clusterName)\n\tparameters = append(parameters, bucketName)\n\tparameters = append(parameters, versioning)\n\tparameters = append(parameters, accessControl)\n\tparameters = append(parameters, loggingenabled)\n\tparameters = append(parameters, loggingprefix)\n\tparameters = append(parameters, websiteenabled)\n\tparameters = append(parameters, websiteindexPage)\n\tparameters = append(parameters, websiteerrorPage)\n\n\tstackInputs.SetParameters(parameters)\n\n\tresourceNameTag := helpers.CreateTag(\"ResourceName\", s.S3Bucket.Name)\n\tresourceVersionTag := helpers.CreateTag(\"ResourceVersion\", s.S3Bucket.ResourceVersion)\n\tnamespaceTag := helpers.CreateTag(\"Namespace\", s.S3Bucket.Namespace)\n\tclusterNameTag := helpers.CreateTag(\"ClusterName\", s.config.ClusterName)\n\n\ttags := []*cloudformation.Tag{}\n\ttags = append(tags, resourceNameTag)\n\ttags = append(tags, resourceVersionTag)\n\ttags = append(tags, namespaceTag)\n\ttags = append(tags, clusterNameTag)\n\n\tstackInputs.SetTags(tags)\n\n\toutput, err = svc.CreateStack(&stackInputs)\n\treturn\n}", "func (r *EKSConfigTemplate) ConvertTo(dstRaw conversion.Hub) error {\n\tdst := dstRaw.(*v1beta1.EKSConfigTemplate)\n\n\treturn Convert_v1alpha3_EKSConfigTemplate_To_v1beta1_EKSConfigTemplate(r, dst, nil)\n}", "func (m *IntentsDeviceManagementIntentItemRequestBuilder) CompareWithTemplateId(templateId *string)(*IntentsItemCompareWithTemplateIdRequestBuilder) {\n return NewIntentsItemCompareWithTemplateIdRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter, templateId)\n}", "func (f *HubSession) SpawnTemplate(proposedCosmosCoin string, name string, symbol string, decimals *big.Int) (*types.Transaction, error) {\n\treturn f.Contract.SpawnTemplate(&f.TransactOpts, proposedCosmosCoin, name, symbol, decimals)\n}", "func FromConfig(l log.Logger, backedType string, cfg Config) (Backend, error) {\n\tvar (\n\t\tb Backend\n\t\terr error\n\t)\n\n\tswitch backedType {\n\tcase Azure:\n\t\tlevel.Warn(l).Log(\"msg\", \"using azure blob as backend\")\n\t\tb, err = azure.New(log.With(l, \"backend\", Azure), cfg.Azure)\n\tcase S3:\n\t\tlevel.Warn(l).Log(\"msg\", \"using aws s3 as backend\")\n\t\tb, err = s3.New(log.With(l, \"backend\", S3), cfg.S3, cfg.Debug)\n\tcase GCS:\n\t\tlevel.Warn(l).Log(\"msg\", \"using gc storage as backend\")\n\t\tb, err = gcs.New(log.With(l, \"backend\", GCS), cfg.GCS)\n\tcase FileSystem:\n\t\tlevel.Warn(l).Log(\"msg\", \"using filesystem as backend\")\n\t\tb, err = filesystem.New(log.With(l, \"backend\", FileSystem), cfg.FileSystem)\n\tcase SFTP:\n\t\tlevel.Warn(l).Log(\"msg\", \"using sftp as backend\")\n\t\tb, err = sftp.New(log.With(l, \"backend\", SFTP), cfg.SFTP)\n\tcase AliOSS:\n\t\tlevel.Warn(l).Log(\"msg\", \"using Alibaba OSS storage as backend\")\n\t\tb, err = alioss.New(log.With(l, \"backend\", AliOSS), cfg.Alioss, cfg.Debug)\n\tdefault:\n\t\treturn nil, errors.New(\"unknown backend\")\n\t}\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"initialize backend, %w\", err)\n\t}\n\n\treturn b, nil\n}", "func (m *DeploymentsClientMock) ExportTemplate(ctx context.Context, resourceGroupName string, deploymentName string) (result resources.DeploymentExportResult, err error) {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tdeploy, ok := m.FakeStore[deploymentName]\n\tif !ok {\n\t\treturn result, fmt.Errorf(\"deployment not found\")\n\t}\n\n\treturn resources.DeploymentExportResult{\n\t\tTemplate: deploy.Properties.Template,\n\t}, nil\n}", "func (c Controller) create(client Client, template *Template, nameSpace, instanceID string, deploy *Payload) (*Dispatched, error) {\n\tvar (\n\t\tdispatched = &Dispatched{}\n\t\tstatusKey = StatusKey(instanceID, \"provision\")\n\t)\n\tfor _, ob := range template.Objects {\n\t\tswitch ob.(type) {\n\t\tcase *dc.DeploymentConfig:\n\t\t\tdeployment := ob.(*dc.DeploymentConfig)\n\t\t\tdeployed, err := client.CreateDeployConfigInNamespace(nameSpace, deployment)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdispatched.DeploymentName = deployed.Name\n\t\t\tdispatched.DeploymentLabels = deployed.Labels\n\t\t\tc.statusPublisher.Publish(statusKey, configInProgress, \"deployment created \"+deployed.Name)\n\t\tcase *k8api.Service:\n\t\t\tif _, err := client.CreateServiceInNamespace(nameSpace, ob.(*k8api.Service)); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tc.statusPublisher.Publish(statusKey, configInProgress, \" created service definition \")\n\t\tcase *route.Route:\n\t\t\tr, err := client.CreateRouteInNamespace(nameSpace, ob.(*route.Route))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdispatched.Route = r\n\t\t\tc.statusPublisher.Publish(statusKey, configInProgress, \" created route definition \")\n\t\tcase *image.ImageStream:\n\t\t\tif _, err := client.CreateImageStream(nameSpace, ob.(*image.ImageStream)); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tc.statusPublisher.Publish(statusKey, configInProgress, \" created imageStream definition \")\n\t\tcase *bc.BuildConfig:\n\t\t\tbConfig := ob.(*bc.BuildConfig)\n\t\t\tif _, err := client.CreateBuildConfigInNamespace(nameSpace, bConfig); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tc.statusPublisher.Publish(statusKey, configInProgress, \" created buildConfig definition \")\n\t\tcase *k8api.Secret:\n\t\t\tif _, err := client.CreateSecretInNamespace(nameSpace, ob.(*k8api.Secret)); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tc.statusPublisher.Publish(statusKey, configInProgress, \" created secret definition \")\n\t\tcase *k8api.PersistentVolumeClaim:\n\t\t\tif _, err := client.CreatePersistentVolumeClaim(nameSpace, ob.(*k8api.PersistentVolumeClaim)); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tc.statusPublisher.Publish(statusKey, configInProgress, \" created PersistentVolumeClaim definition \")\n\t\tcase *k8api.Pod:\n\t\t\tif _, err := client.CreatePod(nameSpace, ob.(*k8api.Pod)); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tc.statusPublisher.Publish(statusKey, configInProgress, \" created Pod definition \")\n\t\tcase *k8api.ConfigMap:\n\t\t\tfmt.Println(\"creating config map\")\n\t\t\tif _, err := client.CreateConfigMap(nameSpace, ob.(*k8api.ConfigMap)); err != nil {\n\t\t\t\tfmt.Println(\"creating config map\", err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tc.statusPublisher.Publish(statusKey, configInProgress, \" created ConfigMap definition \")\n\t\t}\n\t}\n\treturn dispatched, nil\n}", "func (r *AssetRendering) Template() {\n\tv := \"template\"\n\tr.Value = &v\n}", "func (y *YogClient) CreateStack(request CreateStackRequest) (CreateStackResponse, YogError) {\n\tcsi, err := parseTemplate(request.TemplateBody)\n\tif err != nil {\n\t\tye := YogError{\n\t\t\tCode: FailedToParseYaml,\n\t\t\tMessage: \"error while parsing template\",\n\t\t\tError: err,\n\t\t\tDropletErrors: []DropletError{},\n\t\t\tStackname: request.StackName,\n\t\t}\n\t\treturn CreateStackResponse{}, ye\n\t}\n\n\tresponse := CreateStackResponse{Name: request.StackName}\n\tbuiltResources := []Resource{}\n\tfor k, v := range csi.Resources {\n\t\tvar s Service\n\t\tif _, ok := v[\"Type\"]; !ok {\n\t\t\tmessage := fmt.Sprintf(\"no 'Type' provided for resource '%s'\", k)\n\t\t\tye := YogError{\n\t\t\t\tCode: NoTypeForResource,\n\t\t\t\tMessage: message,\n\t\t\t\tError: errors.New(message),\n\t\t\t\tDropletErrors: []DropletError{},\n\t\t\t\tStackname: request.StackName,\n\t\t\t}\n\t\t\treturn CreateStackResponse{}, ye\n\t\t}\n\t\td, err := buildResource(s.Service(v[\"Type\"].(string)))\n\t\t// Droplet doesn't yet have an ID. This will be updated once they are created.\n\t\tif err != nil {\n\t\t\tye := YogError{\n\t\t\t\tCode: UnknownResourceType,\n\t\t\t\tMessage: \"\",\n\t\t\t\tError: err,\n\t\t\t\tDropletErrors: []DropletError{},\n\t\t\t\tStackname: request.StackName,\n\t\t\t}\n\t\t\treturn CreateStackResponse{}, ye\n\t\t}\n\t\terr = d.buildRequest(request.StackName, v)\n\t\tif err != nil {\n\t\t\tye := YogError{\n\t\t\t\tCode: FailedToBuildRequest,\n\t\t\t\tMessage: \"\",\n\t\t\t\tError: err,\n\t\t\t\tDropletErrors: []DropletError{},\n\t\t\t\tStackname: request.StackName,\n\t\t\t}\n\t\t\treturn CreateStackResponse{}, ye\n\t\t}\n\t\tbuiltResources = append(builtResources, d)\n\t}\n\n\tde := y.launchAllDroplets(builtResources)\n\tif len(de) != 0 {\n\t\tye := YogError{\n\t\t\tCode: ErrorLaunchingDroplets,\n\t\t\tStackname: request.StackName,\n\t\t\tError: errors.New(\"error launching droplets. please see DropletErrors for more detail\"),\n\t\t\tMessage: \"\",\n\t\t\tDropletErrors: de,\n\t\t}\n\t\treturn CreateStackResponse{}, ye\n\t}\n\terr = y.setupDropletIDsForResources(builtResources)\n\tif err != nil {\n\t\tye := YogError{\n\t\t\tCode: ErrorSettingUpDropletIDSForResources,\n\t\t\tStackname: request.StackName,\n\t\t\tError: err,\n\t\t\tMessage: \"error setting up droplet ids for resource\",\n\t\t\tDropletErrors: []DropletError{},\n\t\t}\n\t\treturn CreateStackResponse{}, ye\n\t}\n\terr = y.launchTheRestOfTheResources(builtResources)\n\tif err != nil {\n\t\tye := YogError{\n\t\t\tCode: ErrorLaunchingResource,\n\t\t\tStackname: request.StackName,\n\t\t\tError: err,\n\t\t\tMessage: \"error while trying to launch the rest of the resources\",\n\t\t\tDropletErrors: []DropletError{},\n\t\t}\n\t\treturn CreateStackResponse{}, ye\n\t}\n\n\tresponse.Resources = builtResources\n\t// Save resources here.\n\treturn response, YogError{}\n}", "func (a *Client) V2GetLBTemplate(params *V2GetLBTemplateParams) (*V2GetLBTemplateOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewV2GetLBTemplateParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"V2GetLBTemplate\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/v2/pools/{name}/lbtemplate\",\n\t\tProducesMediaTypes: []string{\"text/plain\"},\n\t\tConsumesMediaTypes: []string{\"text/plain\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &V2GetLBTemplateReader{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.(*V2GetLBTemplateOK), nil\n\n}", "func NewCfnStack_Override(c CfnStack, scope constructs.Construct, id *string, props *CfnStackProps) {\n\t_init_.Initialize()\n\n\t_jsii_.Create(\n\t\t\"aws-cdk-lib.aws_cloudformation.CfnStack\",\n\t\t[]interface{}{scope, id, props},\n\t\tc,\n\t)\n}", "func (a *Client) V2GetLBTemplate(params *V2GetLBTemplateParams) (*V2GetLBTemplateOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewV2GetLBTemplateParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"V2GetLBTemplate\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/v2/pools/{name}/lbtemplate\",\n\t\tProducesMediaTypes: []string{\"text/plain\"},\n\t\tConsumesMediaTypes: []string{\"text/plain\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &V2GetLBTemplateReader{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.(*V2GetLBTemplateOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\tunexpectedSuccess := result.(*V2GetLBTemplateDefault)\n\treturn nil, runtime.NewAPIError(\"unexpected success response: content available as default response in error\", unexpectedSuccess, unexpectedSuccess.Code())\n}", "func (c *ClusterResourceSet) Template() gfn.Template {\n\treturn *c.rs.template\n}", "func CreateFromTemplate(data interface{}, filenames ...string) *application.HTTPResponse {\n\tresponse := CreateResponse()\n\tbuf := new(bytes.Buffer)\n\ttemplate.Must(template.ParseFiles(filenames...)).Execute(buf, data)\n\tresponse.Body = buf.String()\n\treturn response\n}", "func patchTemplate(ctx context.Context, template, modifiedTemplate *unstructured.Unstructured, opts ...PatchOption) error {\n\treturn patchUnstructured(ctx, template, modifiedTemplate, \"spec.template.spec\", \"spec.template.spec\", opts...)\n}", "func LintCloudFormationTemplate(template cloudformation.Template) ([]Result, error) {\n\tvar results []Result\n\tsgs := template.GetAllAWSEC2SecurityGroupResources()\n\tfor name, sg := range sgs {\n\t\tr := LintEc2SecurityGroup(name, sg)\n\t\tfor _, result := range r {\n\t\t\tresults = append(results, result)\n\t\t}\n\t}\n\treturn results, nil\n}", "func (o InstanceGroupManagerVersionResponseOutput) InstanceTemplate() pulumi.StringOutput {\n\treturn o.ApplyT(func(v InstanceGroupManagerVersionResponse) string { return v.InstanceTemplate }).(pulumi.StringOutput)\n}", "func (a API) GetBlockTemplate(cmd *btcjson.GetBlockTemplateCmd) (e error) {\n\tRPCHandlers[\"getblocktemplate\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func (b *TriggerTemplateBuilder) ResourceTemplate(resoureceTemplate runtime.RawExtension) {\n\tb.TriggerTemplate.Spec.ResourceTemplates = append(b.TriggerTemplate.Spec.ResourceTemplates,\n\t\tv1alpha1.TriggerResourceTemplate{\n\t\t\tRawExtension: resoureceTemplate,\n\t\t})\n}", "func WithTemplate(template interface{}) OptionFn {\n\twb, err := parseExcel(template)\n\tif err != nil {\n\t\tlog.Printf(\"W! failed to open template excel %v\", err)\n\t\treturn nil\n\t}\n\n\treturn func(o *Option) { o.TemplateWorkbook = wb }\n}", "func (p *PreInplaceControl) newHookRunFromHookTemplate(metaObj metav1.Object,\n\truntimeObj runtime.Object, args []hookv1alpha1.Argument,\n\tpod *v1.Pod, preInplaceHook *hookv1alpha1.HookStep, labels map[string]string,\n\tpodNameLabelKey string) (*hookv1alpha1.HookRun, error) {\n\ttemplate, err := p.hookTemplateLister.HookTemplates(pod.Namespace).Get(preInplaceHook.TemplateName)\n\tif err != nil {\n\t\tif k8serrors.IsNotFound(err) {\n\t\t\tklog.Warningf(\"HookTemplate '%s' not found for %s/%s\",\n\t\t\t\tpreInplaceHook.TemplateName, pod.Namespace, pod.Name)\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tnameParts := []string{\"preinplace\", pod.Labels[apps.ControllerRevisionHashLabelKey],\n\t\tpod.Labels[podNameLabelKey], preInplaceHook.TemplateName}\n\tname := strings.Join(nameParts, \"-\")\n\n\trun, err := commonhookutil.NewHookRunFromTemplate(template, args, name, \"\", pod.Namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trun.Labels = labels\n\trun.OwnerReferences = []metav1.OwnerReference{*metav1.NewControllerRef(metaObj,\n\t\truntimeObj.GetObjectKind().GroupVersionKind())}\n\treturn run, nil\n}", "func (l *loader) WithTemplate(raw string) parser.Render {\n\tif l.err != nil {\n\t\treturn l\n\t}\n\tf, err := cueparser.ParseFile(\"-\", raw)\n\tif err != nil {\n\t\tl.err = errors.Errorf(\"loader parse template error\")\n\t}\n\tl.files[\"-\"] = f\n\treturn l\n}", "func (c *ControlPlaneContract) MachineTemplate() *ControlPlaneMachineTemplate {\n\treturn &ControlPlaneMachineTemplate{}\n}", "func templateForBlackBoxExporterDeployment(blackBoxImage string) appsv1.Deployment {\n\tlabels := blackbox.GenerateBlackBoxLables()\n\tlabelSelectors := metav1.LabelSelector{\n\t\tMatchLabels: labels}\n\t// hardcode the replicasize for no\n\t//replicas := m.Spec.Size\n\tvar replicas int32 = 1\n\n\tdep := appsv1.Deployment{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: blackbox.BlackBoxName,\n\t\t\tNamespace: blackbox.BlackBoxNamespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tSpec: appsv1.DeploymentSpec{\n\t\t\tReplicas: &replicas,\n\t\t\tSelector: &labelSelectors,\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: labels,\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tContainers: []corev1.Container{{\n\t\t\t\t\t\tImage: blackBoxImage,\n\t\t\t\t\t\tName: \"blackbox-exporter\",\n\t\t\t\t\t\tPorts: []corev1.ContainerPort{{\n\t\t\t\t\t\t\tContainerPort: blackbox.BlackBoxPortNumber,\n\t\t\t\t\t\t\tName: blackbox.BlackBoxPortName,\n\t\t\t\t\t\t}},\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\treturn dep\n}", "func (d *deployer) createAKSWithCustomConfig() error {\n\tklog.Infof(\"Creating the AKS cluster with custom config\")\n\tclusterID := fmt.Sprintf(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.ContainerService/managedClusters/%s\", subscriptionID, d.ResourceGroupName, d.ClusterName)\n\n\tmcConfig, encodedCustomConfig, err := d.prepareClusterConfig(clusterID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to prepare cluster config: %v\", err)\n\t}\n\toptions := arm.ClientOptions{\n\t\tClientOptions: policy.ClientOptions{\n\t\t\tAPIVersion: apiVersion,\n\t\t\tPerCallPolicies: []policy.Policy{\n\t\t\t\t&enableCustomFeaturesPolicy{},\n\t\t\t\t&changeLocationPolicy{},\n\t\t\t\t&addCustomConfigPolicy{customConfig: encodedCustomConfig},\n\t\t\t},\n\t\t},\n\t\tDisableRPRegistration: false,\n\t}\n\tclient, err := armcontainerservicev2.NewManagedClustersClient(subscriptionID, cred, &options)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to new managed cluster client with sub ID %q: %v\", subscriptionID, err)\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)\n\tdefer cancel()\n\n\tpoller, err := client.BeginCreateOrUpdate(ctx, d.ResourceGroupName, d.ClusterName, *mcConfig, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to put resource: %v\", err.Error())\n\t}\n\tif _, err = poller.PollUntilDone(ctx, nil); err != nil {\n\t\treturn fmt.Errorf(\"failed to put resource: %v\", err.Error())\n\t}\n\n\tklog.Infof(\"An AKS cluster %q in resource group %q is creating\", d.ClusterName, d.ResourceGroupName)\n\treturn nil\n}", "func TestTags(t *testing.T) {\n awsRegion := \"us-east-2\"\n tagName := \"Flugel-test\"\n tagOwner := \"InfraTeam-test\"\n\n terraformOpts := terraform.WithDefaultRetryableErrors(t, &terraform.Options{\n TerraformDir: \"../\",\n\n //Now i must map the tags.\n Vars: map[string]interface{}{\n \"tag_name\": tagName,\n \"tag_owner\": tagOwner,\n },\n\n //Then set the region to make the deploy in.\n EnvVars: map[string]string{\n \"AWS_DEFAULT_REGION\": awsRegion,\n },\n },\n )\n\n //After all the testing, the infra must be destroyed.\n defer terraform.Destroy(t, terraformOpts)\n\n //Now, let's run the deploy with all the parameters set.\n terraform.InitAndApply(t, terraformOpts)\n\n //I get the instance and bucket id's, and make first verifications.\n instanceID1 := terraform.Output(t, terraformOpts, \"instance_name_web1\")\n instanceTags1 := aws.GetTagsForEc2Instance(t, awsRegion, instanceID1)\n testTag1, containsTag := instanceTags1[\"Name\"]\n assert.True(t, containsTag, \"True\")\n assert.Equal(t, tagName, testTag1)\n testTag2, containsTag := instanceTags1[\"Owner\"]\n assert.True(t, containsTag, \"True\")\n assert.Equal(t, tagOwner, testTag2)\n\n instanceID2 := terraform.Output(t, terraformOpts, \"instance_name_web2\")\n instanceTags2 := aws.GetTagsForEc2Instance(t, awsRegion, instanceID2)\n testTag3, containsTag := instanceTags2[\"Name\"]\n assert.True(t, containsTag, \"True\")\n assert.Equal(t, tagName, testTag3)\n testTag4, containsTag := instanceTags2[\"Owner\"]\n assert.True(t, containsTag, \"True\")\n assert.Equal(t, tagOwner, testTag4)\n\n //It would be easier to simply parse plain text, but as i put myself into this let's ride with it.\n\n lburl := \"http://\" + terraform.Output(t, terraformOpts, \"load_balancer_url\") + \"/index.html\"\n maxRetries := 3\n timeBetweenRetries := 5 * time.Second\n\n http_helper.HttpGetWithRetryWithCustomValidation(t, lburl, nil, maxRetries, timeBetweenRetries, validate)\n\n // There's no module with \"get X bucket tags\", so i get the bucket id from TF, and separately i seek the bucket that contains\n // tags \"Name\" and \"Owner\" with the desired content, and make sure the id returned matches the previously deployed bucket. \n bucketID := terraform.Output(t, terraformOpts, \"bucket_id\")\n bucketwithTagN := aws.FindS3BucketWithTag (t, awsRegion, \"Name\", tagName)\n bucketwithTagO := aws.FindS3BucketWithTag (t, awsRegion, \"Owner\", tagOwner)\n assert.Equal(t, bucketwithTagN, bucketID)\n assert.Equal(t, bucketwithTagO, bucketID)\n\n}", "func (r *EKSConfigTemplateList) ConvertTo(dstRaw conversion.Hub) error {\n\tdst := dstRaw.(*v1beta1.EKSConfigTemplateList)\n\n\treturn Convert_v1alpha3_EKSConfigTemplateList_To_v1beta1_EKSConfigTemplateList(r, dst, nil)\n}", "func CreateFromTemplate(ctx context.Context, in *CreateFromTemplateInput) (*corev1.ObjectReference, error) {\n\tfrom, err := Get(ctx, in.Client, in.TemplateRef, in.Namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgenerateTemplateInput := &GenerateTemplateInput{\n\t\tTemplate: from,\n\t\tTemplateRef: in.TemplateRef,\n\t\tNamespace: in.Namespace,\n\t\tClusterName: in.ClusterName,\n\t\tOwnerRef: in.OwnerRef,\n\t\tLabels: in.Labels,\n\t\tAnnotations: in.Annotations,\n\t}\n\tto, err := GenerateTemplate(generateTemplateInput)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create the external clone.\n\tif err := in.Client.Create(ctx, to); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn GetObjectReference(to), nil\n}", "func CustomGenerateTagFunc(name, typ, tag string) string {\n\treturn fmt.Sprintf(\"json:\\\"%s\\\"\", tag)\n}", "func (c *converter) FromEntity(in *Entity) (*model.FormationTemplate, error) {\n\tif in == nil {\n\t\treturn nil, nil\n\t}\n\n\tvar unmarshalledApplicationTypes []string\n\terr := json.Unmarshal([]byte(in.ApplicationTypes), &unmarshalledApplicationTypes)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"while unmarshalling application types\")\n\t}\n\n\tvar unmarshalledRuntimeTypes []string\n\truntimeTypes := repo.JSONRawMessageFromNullableString(in.RuntimeTypes)\n\tif runtimeTypes != nil {\n\t\terr = json.Unmarshal(runtimeTypes, &unmarshalledRuntimeTypes)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"while unmarshalling runtime types\")\n\t\t}\n\t}\n\n\tvar unmarshalledLeadingProductIDs []string\n\tleadingProductIDs := repo.JSONRawMessageFromNullableString(in.LeadingProductIDs)\n\tif leadingProductIDs != nil {\n\t\terr = json.Unmarshal(leadingProductIDs, &unmarshalledLeadingProductIDs)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"while unmarshalling leading product IDs\")\n\t\t}\n\t}\n\n\tvar runtimeArtifactKind *model.RuntimeArtifactKind\n\tif kindPtr := repo.StringPtrFromNullableString(in.RuntimeArtifactKind); kindPtr != nil {\n\t\tkind := model.RuntimeArtifactKind(*kindPtr)\n\t\truntimeArtifactKind = &kind\n\t}\n\n\treturn &model.FormationTemplate{\n\t\tID: in.ID,\n\t\tName: in.Name,\n\t\tApplicationTypes: unmarshalledApplicationTypes,\n\t\tRuntimeTypes: unmarshalledRuntimeTypes,\n\t\tRuntimeTypeDisplayName: repo.StringPtrFromNullableString(in.RuntimeTypeDisplayName),\n\t\tRuntimeArtifactKind: runtimeArtifactKind,\n\t\tLeadingProductIDs: unmarshalledLeadingProductIDs,\n\t\tTenantID: repo.StringPtrFromNullableString(in.TenantID),\n\t\tSupportsReset: in.SupportsReset,\n\t}, nil\n}", "func NewTemplate(fileName string) (*Template, error) {\n\ttmplFile, err := ioutil.ReadFile(fileName)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unexpected error reading template %v\", tmplFile)\n\t}\n\ttmpl, err := text_template.New(\"gateway\").Funcs(funcMap).Parse(string(tmplFile))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Template{\n\t\ttmpl: tmpl,\n\t\tbp: NewBufferPool(defBufferSize),\n\t}, nil\n}", "func newTemplateDecoder(config *Config, decoder resources.Decoder) *templateDecoder {\n\treturn &templateDecoder{\n\t\tconfig: config,\n\t\tdecoder: decoder,\n\t}\n}", "func ExampleTemplate() {\n\ttemplate := &sp.Template{}\n\tjsonStr := `{\n\t\t\"name\": \"testy template\",\n\t\t\"content\": {\n\t\t\t\"html\": \"this is a <b>test</b> email!\",\n\t\t\t\"subject\": \"test email\",\n\t\t\t\"from\": {\n\t\t\t\t\"name\": \"tester\",\n\t\t\t\t\"email\": \"[email protected]\"\n\t\t\t},\n\t\t\t\"reply_to\": \"[email protected]\"\n\t\t}\n\t}`\n\terr := json.Unmarshal([]byte(jsonStr), template)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func MakeChannelCreationTransactionFromTemplate(\n\tchannelID string,\n\tsigner identity.SignerSerializer,\n\tconf *genesisconfig.Profile,\n\ttemplate *cb.ConfigGroup,\n) (*cb.Envelope, error) {\n\tnewChannelConfigUpdate, err := NewChannelCreateConfigUpdate(channelID, conf, template)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"config update generation failure\")\n\t}\n\n\tnewConfigUpdateEnv := &cb.ConfigUpdateEnvelope{\n\t\tConfigUpdate: protoutil.MarshalOrPanic(newChannelConfigUpdate),\n\t}\n\n\tif signer != nil {\n\t\tsigHeader, err := protoutil.NewSignatureHeader(signer)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"creating signature header failed\")\n\t\t}\n\n\t\tnewConfigUpdateEnv.Signatures = []*cb.ConfigSignature{{\n\t\t\tSignatureHeader: protoutil.MarshalOrPanic(sigHeader),\n\t\t}}\n\n\t\tnewConfigUpdateEnv.Signatures[0].Signature, err = signer.Sign(util.ConcatenateBytes(newConfigUpdateEnv.Signatures[0].SignatureHeader, newConfigUpdateEnv.ConfigUpdate))\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"signature failure over config update\")\n\t\t}\n\n\t}\n\n\treturn protoutil.CreateSignedEnvelope(cb.HeaderType_CONFIG_UPDATE, channelID, signer, newConfigUpdateEnv, msgVersion, epoch)\n}", "func ConvertSpaceTemplate(appl application.Application, request *http.Request, st spacetemplate.SpaceTemplate, additional ...SpaceTemplateConvertFunc) *app.SpaceTemplate {\n\n\t// template := base64.StdEncoding.EncodeToString([]byte(st.Template))\n\ti := &app.SpaceTemplate{\n\t\tType: APISpaceTemplates,\n\t\tID: &st.ID,\n\t\tAttributes: &app.SpaceTemplateAttributes{\n\t\t\tName: &st.Name,\n\t\t\tCreatedAt: &st.CreatedAt,\n\t\t\tUpdatedAt: &st.UpdatedAt,\n\t\t\tVersion: &st.Version,\n\t\t\tDescription: st.Description,\n\t\t\tCanConstruct: &st.CanConstruct,\n\t\t\t// Template: &template,\n\t\t},\n\t\tRelationships: &app.SpaceTemplateRelationships{\n\t\t\tWorkitemtypes: &app.RelationGeneric{\n\t\t\t\tLinks: &app.GenericLinks{\n\t\t\t\t\tRelated: ptr.String(rest.AbsoluteURL(request, app.SpaceTemplateHref(st.ID)+\"/workitemtypes\")),\n\t\t\t\t},\n\t\t\t},\n\t\t\tWorkitemlinktypes: &app.RelationGeneric{\n\t\t\t\tLinks: &app.GenericLinks{\n\t\t\t\t\tRelated: ptr.String(rest.AbsoluteURL(request, app.SpaceTemplateHref(st.ID)+\"/workitemlinktypes\")),\n\t\t\t\t},\n\t\t\t},\n\t\t\tWorkitemtypegroups: &app.RelationGeneric{\n\t\t\t\tLinks: &app.GenericLinks{\n\t\t\t\t\tRelated: ptr.String(rest.AbsoluteURL(request, app.SpaceTemplateHref(st.ID)+\"/workitemtypegroups\")),\n\t\t\t\t},\n\t\t\t},\n\t\t\tWorkitemboards: &app.RelationGeneric{\n\t\t\t\tLinks: &app.GenericLinks{\n\t\t\t\t\tRelated: ptr.String(rest.AbsoluteURL(request, app.SpaceTemplateHref(st.ID)+\"/workitemboards\")),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tLinks: &app.GenericLinks{\n\t\t\tSelf: ptr.String(rest.AbsoluteURL(request, app.SpaceTemplateHref(st.ID))),\n\t\t},\n\t}\n\n\tfor _, add := range additional {\n\t\tadd(appl, request, &st, i)\n\t}\n\treturn i\n}" ]
[ "0.5200348", "0.5190561", "0.5176106", "0.50507194", "0.49835604", "0.49048224", "0.49023888", "0.48888153", "0.48797894", "0.48579338", "0.47971332", "0.47307512", "0.4713566", "0.466707", "0.46542612", "0.4648205", "0.4648205", "0.4640566", "0.4635521", "0.4635018", "0.46079278", "0.45930442", "0.45878103", "0.4575211", "0.4568405", "0.4561825", "0.45335552", "0.45308742", "0.45257264", "0.45221788", "0.45176992", "0.45091945", "0.4507872", "0.45032948", "0.44963062", "0.44874972", "0.44841927", "0.44733763", "0.44702086", "0.44654635", "0.44648987", "0.4461491", "0.44420838", "0.44010165", "0.43936184", "0.4387576", "0.43820223", "0.437118", "0.43700683", "0.4339135", "0.43358642", "0.4333395", "0.4333395", "0.43303916", "0.4316048", "0.43139863", "0.43114206", "0.4309332", "0.4308218", "0.43066928", "0.43003064", "0.4299666", "0.42805138", "0.42747062", "0.42591092", "0.42476752", "0.4241679", "0.42404082", "0.42395157", "0.4238558", "0.42367214", "0.42365497", "0.42075527", "0.41880664", "0.41786522", "0.4178356", "0.41780725", "0.41735572", "0.41721785", "0.4171883", "0.41711256", "0.41677403", "0.41534248", "0.41440988", "0.41413072", "0.41399", "0.41352212", "0.41274968", "0.41230792", "0.41216007", "0.41200954", "0.41151217", "0.41096422", "0.40980133", "0.40977278", "0.40874568", "0.40827385", "0.40817463", "0.40790772", "0.40760618" ]
0.6128332
0
ClusterStackName returns the ClusterID tag that all resources from the same Kubernetes cluster share. It's taken from the current ec2 instance.
func (a *Adapter) ClusterID() string { return a.manifest.instance.clusterID() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func lookupStack(clustername string) (string, string, error) {\n\tcfg, err := external.LoadDefaultAWSConfig()\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tsvc := cloudformation.New(cfg)\n\tvar activeStacks = []cloudformation.StackStatus{\"CREATE_COMPLETE\"}\n\tlsreq := svc.ListStacksRequest(&cloudformation.ListStacksInput{StackStatusFilter: activeStacks})\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tlsresp, err := lsreq.Send(context.TODO())\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\t// iterate over active stacks to find the two eksctl created, by label\n\tcpstack, dpstack := \"\", \"\"\n\tfor _, stack := range lsresp.StackSummaries {\n\t\tdsreq := svc.DescribeStacksRequest(&cloudformation.DescribeStacksInput{StackName: stack.StackName})\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", err\n\t\t}\n\t\tdsresp, err := dsreq.Send(context.TODO())\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", err\n\t\t}\n\t\t// fmt.Printf(\"DEBUG:: checking stack %v if it has label with cluster name %v\\n\", *dsresp.Stacks[0].StackName, clustername)\n\t\tcnofstack := tagValueOf(dsresp.Stacks[0], \"eksctl.cluster.k8s.io/v1alpha1/cluster-name\")\n\t\tif cnofstack != \"\" && cnofstack == clustername {\n\t\t\tswitch {\n\t\t\tcase tagValueOf(dsresp.Stacks[0], \"alpha.eksctl.io/nodegroup-name\") != \"\":\n\t\t\t\tdpstack = *dsresp.Stacks[0].StackName\n\t\t\tdefault:\n\t\t\t\tcpstack = *dsresp.Stacks[0].StackName\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Printf(\"DEBUG:: found control plane stack [%v] and data plane stack [%v] for cluster %v\\n\", cpstack, dpstack, clustername)\n\treturn cpstack, dpstack, nil\n}", "func (s *Cloudformation) StackName() string {\n\treturn helpers.StackName(s.config.ClusterName, \"s3bucket\", s.S3Bucket.Name, s.S3Bucket.Namespace)\n}", "func (e *ComponentStackConfig) StackName() string {\n\tconst maxLen = 128\n\tstackName := fmt.Sprintf(\"oam-ecs-%s-%s\", e.ApplicationConfiguration.Name, e.ComponentConfiguration.InstanceName)\n\tif len(stackName) > maxLen {\n\t\treturn stackName[len(stackName)-maxLen:]\n\t}\n\treturn stackName\n}", "func getClusterNameLabel() string {\n\tkey := fmt.Sprintf(\"%s/cluster-name\", getCAPIGroup())\n\treturn key\n}", "func (m *Info) GetClusterName() string {\n\tif m.ec2Tags != nil {\n\t\treturn m.ec2Tags.getClusterName()\n\t}\n\n\treturn \"\"\n}", "func (c *Context) ClusterName() string {\n\treturn fmt.Sprintf(\"kind-%s\", c.name)\n}", "func (s stack) GetStackName() (string, fail.Error) {\n\treturn \"aws\", nil\n}", "func GetClusterName() (string, error) {\n\tif !config.IsCloudProviderEnabled(CloudProviderName) {\n\t\treturn \"\", fmt.Errorf(\"cloud provider is disabled by configuration\")\n\t}\n\ttags, err := GetTags()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to retrieve clustername from EC2: %s\", err)\n\t}\n\n\treturn extractClusterName(tags)\n}", "func (c *StackCollection) ListClusterStackNames(ctx context.Context) ([]string, error) {\n\tvar stacks []string\n\tre, err := regexp.Compile(clusterStackRegex)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"cannot list stacks\")\n\t}\n\tinput := &cloudformation.ListStacksInput{\n\t\tStackStatusFilter: defaultStackStatusFilter(),\n\t}\n\n\tpaginator := cloudformation.NewListStacksPaginator(c.cloudformationAPI, input)\n\n\tfor paginator.HasMorePages() {\n\t\tout, err := paginator.NextPage(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, s := range out.StackSummaries {\n\t\t\tif re.MatchString(*s.StackName) {\n\t\t\t\tstacks = append(stacks, *s.StackName)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn stacks, nil\n}", "func (o ElastigroupIntegrationEcsOutput) ClusterName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ElastigroupIntegrationEcs) string { return v.ClusterName }).(pulumi.StringOutput)\n}", "func (o ChangeSetOutput) StackName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ChangeSet) pulumi.StringPtrOutput { return v.StackName }).(pulumi.StringPtrOutput)\n}", "func (m *RateLimitServiceConfig) GetClusterName() string {\n\tif x, ok := m.GetServiceSpecifier().(*RateLimitServiceConfig_ClusterName); ok {\n\t\treturn x.ClusterName\n\t}\n\treturn \"\"\n}", "func ClusterTagKey(name string) string {\n\treturn fmt.Sprintf(\"%s%s\", NameGCPProviderOwned, name)\n}", "func getClusterName(utils detectorUtils) (string, error) {\n\tresp, err := utils.fetchString(\"GET\", k8sSvcURL+cwConfigmapPath)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"getClusterName() error: %w\", err)\n\t}\n\n\t// parse JSON object returned from HTTP request\n\tvar respmap map[string]json.RawMessage\n\terr = json.Unmarshal([]byte(resp), &respmap)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"getClusterName() error: cannot parse JSON: %w\", err)\n\t}\n\tvar d data\n\terr = json.Unmarshal(respmap[\"data\"], &d)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"getClusterName() error: cannot parse JSON: %w\", err)\n\t}\n\n\tclusterName := d.ClusterName\n\n\treturn clusterName, nil\n}", "func (metadata *metadataImpl) GetCurrentClusterName() string {\n\treturn metadata.currentClusterName\n}", "func (o CustomLayerOutput) StackId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *CustomLayer) pulumi.StringOutput { return v.StackId }).(pulumi.StringOutput)\n}", "func (o *HyperflexVmSnapshotInfoAllOf) GetTgtClusterName() string {\n\tif o == nil || o.TgtClusterName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.TgtClusterName\n}", "func (o AppV2Output) ClusterName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AppV2) pulumi.StringOutput { return v.ClusterName }).(pulumi.StringOutput)\n}", "func (o ElastigroupIntegrationEcsPtrOutput) ClusterName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ElastigroupIntegrationEcs) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.ClusterName\n\t}).(pulumi.StringPtrOutput)\n}", "func GetClusterId() string {\n\treturn axClusterId\n}", "func (o OceanOutput) ClusterName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Ocean) pulumi.StringOutput { return v.ClusterName }).(pulumi.StringOutput)\n}", "func bootstrapClusterName() string {\n\t// This constitutes a \"bootstrap\" invocation of \"kubectl\", we can't use the configuration because we are actually creating it\n\tcmd := exec.Command(\"kubectl\", \"config\", \"view\", \"--minify\", \"--output\", \"jsonpath={.clusters[0].name}\")\n\tif stdout, err := cmd.Output(); err == nil {\n\t\tif clusterName := strings.TrimSpace(string(stdout)); clusterName != \"\" {\n\t\t\treturn clusterName\n\t\t}\n\t}\n\treturn \"default\"\n}", "func (in *RecordSetGroup) GetStackName() string {\n\treturn in.Spec.StackName\n}", "func GetClusterName(executionSpaceName string) (string, error) {\n\tif !strings.HasPrefix(executionSpaceName, ExecutionSpacePrefix) {\n\t\treturn \"\", fmt.Errorf(\"the execution space name is in wrong format\")\n\t}\n\treturn strings.TrimPrefix(executionSpaceName, ExecutionSpacePrefix), nil\n}", "func (o ClusterManagedPrivateEndpointOutput) ClusterName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ClusterManagedPrivateEndpoint) pulumi.StringOutput { return v.ClusterName }).(pulumi.StringOutput)\n}", "func (m *GetNodePoolRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func (c *CloudFormation) Stack(name string) (*Stack, error) {\n\tparams := &cfn.DescribeStacksInput{\n\t\tNextToken: aws.String(\"NextToken\"),\n\t\tStackName: aws.String(name),\n\t}\n\tresp, err := c.srv.DescribeStacks(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(resp.Stacks) != 1 {\n\t\treturn nil, fmt.Errorf(\"Reseived %v stacks, expected one\", len(resp.Stacks))\n\t}\n\n\treturn &Stack{srv: c.srv, Stack: resp.Stacks[0]}, nil\n}", "func (o KubernetesNodePoolOutput) ClusterId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *KubernetesNodePool) pulumi.StringOutput { return v.ClusterId }).(pulumi.StringOutput)\n}", "func ContextForCluster(kindClusterName string) string {\n\treturn kubeconfig.KINDClusterKey(kindClusterName)\n}", "func getStackName(input *commands.BucketInput) string {\n\treturn strings.Replace(input.FullDomainName, \".\", \"-\", -1) + \"-cdn\"\n}", "func getClusterName(nodes []corev1.Node) string {\n\tif os.Getenv(\"CLUSTER_NAME\") != \"\" {\n\t\tclusterName = os.Getenv(\"CLUSTER_NAME\")\n\t\treturn clusterName\n\t}\n\n\tif len(nodes) == 0 {\n\t\treturn \"\"\n\t}\n\n\tnode := nodes[0]\n\tif node.Labels[clusterNameLabel] != \"\" {\n\t\treturn node.Labels[clusterNameLabel]\n\t}\n\tif node.ClusterName != \"\" {\n\t\treturn node.ClusterName\n\t}\n\n\t// Hack for clusters that don't have ClusterName as a label on the nodes (pre-1.15?)\n\tif _, hasLabel := node.Labels[gkeNodePoolLabel]; hasLabel {\n\t\t// Split/TrimPrefix:\n\t\t// gke-mycluster-1-node-pool-1-b486c6b7-chm7\n\t\t// pre^clusterName^postfix_____________^node-hash\n\t\tprefix := \"gke-\"\n\t\tpostfix := \"-\" + node.Labels[gkeNodePoolLabel]\n\t\tclusterName := strings.Split(strings.TrimPrefix(node.Name, prefix), postfix)[0]\n\t\tlog.Info(\"getClusterName: used a hack to determine the clusterName from hostname\", \"hostname\", node.Name, \"clustername\", clusterName)\n\t\treturn clusterName\n\t}\n\tlog.Error(fmt.Errorf(\"Failed to getClusterName from %#v\", node), \"getClusterName failure\")\n\tpanic(\"ClusterName could not be determined\")\n}", "func (c *ClusterK8sIO) Name() string {\n\treturn \"Cluster.cluster.k8s.io/v1alpha1\"\n}", "func (o NodeGroupDataOutput) CfnStack() cloudformation.StackOutput {\n\treturn o.ApplyT(func(v NodeGroupData) *cloudformation.Stack { return v.CfnStack }).(cloudformation.StackOutput)\n}", "func (o *HyperflexVmSnapshotInfoAllOf) GetSrcClusterName() string {\n\tif o == nil || o.SrcClusterName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.SrcClusterName\n}", "func (config *DirectClientConfig) getClusterName() (string, bool) {\n\tif config.overrides != nil && len(config.overrides.Context.Cluster) != 0 {\n\t\treturn config.overrides.Context.Cluster, true\n\t}\n\tcontext, _ := config.getContext()\n\treturn context.Cluster, false\n}", "func generateClusterName() string {\n\treturn string(uuid.NewUUID())\n}", "func (o *VirtualizationIweClusterAllOf) GetClusterName() string {\n\tif o == nil || o.ClusterName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ClusterName\n}", "func (m *RollbackNodePoolUpgradeRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func (s *ClusterScope) ClusterName() string {\n\treturn s.Cluster.Name\n}", "func (o NodeGroupDataPtrOutput) CfnStack() cloudformation.StackOutput {\n\treturn o.ApplyT(func(v *NodeGroupData) *cloudformation.Stack {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.CfnStack\n\t}).(cloudformation.StackOutput)\n}", "func GetClusterName(self *C.PyObject, args *C.PyObject) *C.PyObject {\n\tclusterName := clustername.GetClusterName()\n\n\tcStr := C.CString(clusterName)\n\tpyStr := C.PyString_FromString(cStr)\n\tC.free(unsafe.Pointer(cStr))\n\treturn pyStr\n}", "func (m *CreateNodePoolRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func (r *ReconcileServiceSync) getClusterName() string {\n\tif clusterName != \"\" {\n\t\treturn clusterName\n\t}\n\n\tif os.Getenv(\"CLUSTER_NAME\") != \"\" {\n\t\tclusterName = os.Getenv(\"CLUSTER_NAME\")\n\t\treturn clusterName\n\t}\n\n\tnodes, err := r.getNodes()\n\tlogOnError(err, \"Failed to get nodes for getClusterName\")\n\tclusterName = getClusterName(nodes)\n\treturn clusterName\n}", "func (c *StackCollection) createClusterStack(ctx context.Context, stackName string, resourceSet builder.ResourceSetReader, errCh chan error) error {\n\tclusterTags := map[string]string{\n\t\tapi.ClusterOIDCEnabledTag: strconv.FormatBool(api.IsEnabled(c.spec.IAM.WithOIDC)),\n\t}\n\tstack, err := c.createStackRequest(ctx, stackName, resourceSet, clusterTags, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\tdefer close(errCh)\n\t\ttroubleshoot := func() {\n\t\t\tstack, err := c.DescribeStack(ctx, stack)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Info(\"error describing stack to troubleshoot the cause of the failure; \"+\n\t\t\t\t\t\"check the CloudFormation console for further details\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlogger.Critical(\"unexpected status %q while waiting for CloudFormation stack %q\", stack.StackStatus, *stack.StackName)\n\t\t\tc.troubleshootStackFailureCause(ctx, stack, string(types.StackStatusCreateComplete))\n\t\t}\n\n\t\tctx, cancelFunc := context.WithTimeout(context.Background(), c.waitTimeout)\n\t\tdefer cancelFunc()\n\n\t\tstack, err := waiter.WaitForStack(ctx, c.cloudformationAPI, *stack.StackId, *stack.StackName, func(attempts int) time.Duration {\n\t\t\t// Wait 30s for the first two requests, and 1m for subsequent requests.\n\t\t\tif attempts <= 2 {\n\t\t\t\treturn 30 * time.Second\n\t\t\t}\n\t\t\treturn 1 * time.Minute\n\t\t})\n\n\t\tif err != nil {\n\t\t\ttroubleshoot()\n\t\t\terrCh <- err\n\t\t\treturn\n\t\t}\n\n\t\tif err := resourceSet.GetAllOutputs(*stack); err != nil {\n\t\t\terrCh <- errors.Wrapf(err, \"getting stack %q outputs\", *stack.StackName)\n\t\t\treturn\n\t\t}\n\n\t\terrCh <- nil\n\t}()\n\n\treturn nil\n}", "func (c *ClusterInfoResolver) PrettyClusterName() *string {\n\treturn c.prettyClusterName\n}", "func (r *Cluster) ClusterResourceId() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"clusterResourceId\"])\n}", "func (o GetClustersClusterOutput) ClusterName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetClustersCluster) string { return v.ClusterName }).(pulumi.StringOutput)\n}", "func (o ChangeSetOutput) StackId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ChangeSet) pulumi.StringOutput { return v.StackId }).(pulumi.StringOutput)\n}", "func (*StackCollection) GetNodeGroupName(s *Stack) string {\n\tif tagName := GetNodegroupTagName(s.Tags); tagName != \"\" {\n\t\treturn tagName\n\t}\n\tif strings.HasSuffix(*s.StackName, \"-nodegroup-0\") {\n\t\treturn \"legacy-nodegroup-0\"\n\t}\n\tif strings.HasSuffix(*s.StackName, \"-DefaultNodeGroup\") {\n\t\treturn \"legacy-default\"\n\t}\n\treturn \"\"\n}", "func (o ClusterCapacityProvidersOutput) ClusterName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ClusterCapacityProviders) pulumi.StringOutput { return v.ClusterName }).(pulumi.StringOutput)\n}", "func (c *Controller) getDeployCluster(hr *appv1.HelmRequest) string {\n\tif hr.Spec.ClusterName != \"\" {\n\t\treturn hr.Spec.ClusterName\n\t}\n\n\treturn hr.ClusterName\n}", "func (o *NiatelemetryNexusDashboardsAllOf) GetClusterName() string {\n\tif o == nil || o.ClusterName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ClusterName\n}", "func getStackName(input *commands.DNSInput) string {\n\treturn strings.Replace(input.HostedZone, \".\", \"-\", -1)\n}", "func (c *GCEModelContext) SafeClusterName() string {\n\treturn gce.SafeClusterName(c.Cluster.ObjectMeta.Name)\n}", "func (o *ZoneZone) GetStackId() string {\n\tif o == nil || o.StackId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.StackId\n}", "func (b *cloudBackend) getCloudStackIdentifier(stackRef backend.StackReference) (client.StackIdentifier, error) {\n\tcloudBackendStackRef, ok := stackRef.(cloudBackendReference)\n\tif !ok {\n\t\treturn client.StackIdentifier{}, errors.New(\"bad stack reference type\")\n\t}\n\n\treturn client.StackIdentifier{\n\t\tOwner: cloudBackendStackRef.owner,\n\t\tProject: cleanProjectName(string(cloudBackendStackRef.project)),\n\t\tStack: string(cloudBackendStackRef.name),\n\t}, nil\n}", "func (r *Cluster) ClusterName() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"clusterName\"])\n}", "func (o PhpAppLayerOutput) StackId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *PhpAppLayer) pulumi.StringOutput { return v.StackId }).(pulumi.StringOutput)\n}", "func (m *SetNodePoolAutoscalingRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func (o GetClustersClusterOutput) ClusterId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetClustersCluster) string { return v.ClusterId }).(pulumi.StringOutput)\n}", "func (s *SessionTrackerV1) GetClusterName() string {\n\treturn s.Spec.ClusterName\n}", "func (m *UpdateNodePoolRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func (c *AzureModelContext) NameForApplicationSecurityGroupNodes() string {\n\treturn kops.InstanceGroupRoleNode.ToLowerString() + \"s.\" + c.ClusterName()\n}", "func (m *SetNodePoolManagementRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func (o AppV2Output) ClusterId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AppV2) pulumi.StringOutput { return v.ClusterId }).(pulumi.StringOutput)\n}", "func (m *SetNodePoolSizeRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func (o ClusterOutput) ClusterId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Cluster) pulumi.StringOutput { return v.ClusterId }).(pulumi.StringOutput)\n}", "func TranslateClusterName(cluster string) string {\n\t// Use a hash to fit the resource name restriction on GCE subject to RFC1035\n\treturn fmt.Sprintf(\"robotest-%x\", Hash(cluster))\n}", "func GetClusterNames(clusterName string) (lines []string, err error) {\n\t// For now, only supports one server, so server name will be based on th cluster name\n\tcmd := exec.Command(\n\t\t\"docker\",\n\t\t\"ps\",\n\t\t\"-q\", // quiet output for parsing\n\t\t\"-a\", // show stopped nodes\n\t\t\"--no-trunc\", // don't truncate\n\t\t// filter for nodes with the cluster label\n\t\t\"--filter\", fmt.Sprintf(\"label=%s=%s\", clusterconfig.ClusterLabelKey, clusterName),\n\t\t// format to include the cluster name\n\t\t\"--format\", `{{.Names}}`,\n\t)\n\tlines, err = docker.ExecOutput(*cmd, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// currentlt only supports one server\n\t// if len(lines) != 1 {\n\t// \treturn nil, fmt.Errorf(\"k3scli don't support multiserver now...\")\n\t// }\n\treturn lines, nil\n}", "func (o HpcClusterOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *HpcCluster) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (c *ClusterInfoResolver) ClusterName() *string {\n\treturn c.clusterName\n}", "func getClusterNameForMultiVC(ctx context.Context, vs *multiVCvSphere,\n\tclientIndex int) ([]*object.ClusterComputeResource,\n\t*VsanClient, error) {\n\n\tvar vsanHealthClient *VsanClient\n\tvar err error\n\tc := newClientForMultiVC(ctx, vs)\n\n\tdatacenter := strings.Split(multiVCe2eVSphere.multivcConfig.Global.Datacenters, \",\")\n\n\tfor i, client := range c {\n\t\tif clientIndex == i {\n\t\t\tvsanHealthClient, err = newVsanHealthSvcClient(ctx, client.Client)\n\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t}\n\t}\n\n\tfinder := find.NewFinder(vsanHealthClient.vim25Client, false)\n\tdc, err := finder.Datacenter(ctx, datacenter[0])\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tfinder.SetDatacenter(dc)\n\n\tclusterComputeResource, err := finder.ClusterComputeResourceList(ctx, \"*\")\n\tframework.Logf(\"clusterComputeResource %v\", clusterComputeResource)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\n\treturn clusterComputeResource, vsanHealthClient, err\n}", "func (o StorageClusterStatusOutput) ClusterName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v StorageClusterStatus) *string { return v.ClusterName }).(pulumi.StringPtrOutput)\n}", "func (c *StackCollection) makeNodeGroupStackName(name string) string {\n\treturn fmt.Sprintf(\"eksctl-%s-nodegroup-%s\", c.spec.Metadata.Name, name)\n}", "func (o *V1VolumeClaim) GetStackId() string {\n\tif o == nil || o.StackId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.StackId\n}", "func (m *DeleteNodePoolRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func (m *GetClusterRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func (m *UpdateMasterRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func (s *Scheduler) GetClusterId() string {\n\treturn s.BcsClusterId\n}", "func (t *Tester) GetRandomClusterName() (string, error) {\n\tmanagedClusterList, err := t.ClusterClient.ClusterV1().ManagedClusters().List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, managedCluster := range managedClusterList.Items {\n\t\tclusterName := managedCluster.Name\n\t\tif !strings.HasPrefix(clusterName, \"e2e-\") {\n\t\t\treturn clusterName, nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"there is no managedCluster with the random name\")\n}", "func GetNodeClusterNameLabel() (string, error) {\n\tnodeLabels, err := GetNodeLabels()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tclusterNameLabels := []string{\n\t\t\"alpha.eksctl.io/cluster-name\", // EKS cluster-name label\n\t}\n\n\tfor _, l := range clusterNameLabels {\n\t\tif v, ok := nodeLabels[l]; ok {\n\t\t\treturn v, nil\n\t\t}\n\t}\n\treturn \"\", nil\n}", "func (m *SetMasterAuthRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func getKubeConfigContextNameFromStruct(kubeConfigStructVal *starlarkstruct.Struct) string {\n\tctxVal, err := kubeConfigStructVal.Attr(\"cluster_context\")\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\tctxName, ok := ctxVal.(starlark.String)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn ctxName.GoString()\n}", "func (c *Context) ClusterLabel() string {\n\treturn fmt.Sprintf(\"%s=%s\", ClusterLabelKey, c.name)\n}", "func clusterName(upstreamName string) string {\n\treturn upstreamName\n}", "func GetClusterNameOrDie() string {\n\tc, err := clientcmd.LoadFromFile(framework.TestContext.KubeConfig)\n\tframework.ExpectNoError(err, \"failed to load kubeconfig from file\")\n\n\tauthInfo := c.AuthInfos[c.Contexts[c.CurrentContext].AuthInfo]\n\n\tfor i, v := range authInfo.Exec.Args {\n\t\t// aws-iam-authenticator token\n\t\tif v == \"-i\" {\n\t\t\treturn authInfo.Exec.Args[i+1]\n\t\t}\n\t\t// aws eks get-token\n\t\tif v == \"--cluster-name\" {\n\t\t\treturn authInfo.Exec.Args[i+1]\n\t\t}\n\t}\n\tframework.Fail(\"failed to get EKS cluster name\")\n\treturn \"\"\n}", "func tagToCategoryName(tagName string) string {\n\treturn fmt.Sprintf(\"openshift-%s\", tagName)\n}", "func (client *XenClient) SMGetRequiredClusterStack(self string) (result []string, err error) {\n\tobj, err := client.APICall(\"SM.get_required_cluster_stack\", self)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tresult = make([]string, len(obj.([]interface{})))\n\tfor i, value := range obj.([]interface{}) {\n\t\tresult[i] = value.(string)\n\t}\n\n\treturn\n}", "func CurrentCluster() (string, error) {\n\tout, err := kubectl([]string{\"config\", \"current-context\"}...)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.Trim(string(out), \"\\r\\n\"), nil\n}", "func (o DrsVmOverrideOutput) ComputeClusterId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DrsVmOverride) pulumi.StringOutput { return v.ComputeClusterId }).(pulumi.StringOutput)\n}", "func (o ClusterTemplateOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ClusterTemplate) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (o ManagedScalingPolicyOutput) ClusterId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ManagedScalingPolicy) pulumi.StringOutput { return v.ClusterId }).(pulumi.StringOutput)\n}", "func (c *Cluster) Name() string {\n\treturn c.definition.Name\n}", "func (action *CreateEksClusterAction) GetName() string {\n\treturn \"CreateEksClusterAction\"\n}", "func (o ClusterNodeGroupOptionsPtrOutput) CloudFormationTags() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *ClusterNodeGroupOptions) map[string]string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.CloudFormationTags\n\t}).(pulumi.StringMapOutput)\n}", "func (m *ListNodePoolsRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func machineContainerName(cluster, machine string) string {\n\tif strings.HasPrefix(machine, cluster) {\n\t\treturn machine\n\t}\n\treturn fmt.Sprintf(\"%s-%s\", cluster, machine)\n}", "func (c *Cluster) DefaultContextName(project string) (string, error) {\n\tif regional, err := c.IsRegional(); err != nil {\n\t\treturn \"\", err\n\t} else if regional {\n\t\treturn fmt.Sprintf(\"gke_%s_%s_%s\", project, c.Region, c.Name), nil\n\t} else {\n\t\treturn fmt.Sprintf(\"gke_%s_%s_%s\", project, c.Zone, c.Name), nil\n\t}\n}", "func getClusterNameFromZone(ctx context.Context, availabilityZone string) string {\n\tclusterName := \"\"\n\tclusterComputeResourceList, _, err := getClusterName(ctx, &e2eVSphere)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tnimbusGeneratedVcPwd := GetAndExpectStringEnvVar(vcUIPwd)\n\tcmd := fmt.Sprintf(\"dcli +username %s +password %s +skip +show com vmware \"+\n\t\t\"vcenter consumptiondomains zones cluster associations get --zone \"+\n\t\t\"%s\", adminUser, nimbusGeneratedVcPwd, availabilityZone)\n\tvcAddress := e2eVSphere.Config.Global.VCenterHostname + \":\" + sshdPort\n\tframework.Logf(\"Invoking command %v on vCenter host %v\", cmd, vcAddress)\n\tresult, err := fssh.SSH(cmd, vcAddress, framework.TestContext.Provider)\n\tframework.Logf(\"result: %v\", result)\n\tclusterId := strings.Split(result.Stdout, \"- \")[1]\n\tclusterID := strings.TrimSpace(clusterId)\n\tframework.Logf(\"clusterId: %v\", clusterID)\n\tfmt.Print(clusterId)\n\tif err != nil || result.Code != 0 {\n\t\tfssh.LogResult(result)\n\t\tframework.Failf(\"couldn't execute command: %s on vCenter host: %v\", cmd, err)\n\t}\n\tfor _, cluster := range clusterComputeResourceList {\n\t\tclusterMoId := cluster.Reference().Value\n\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\tframework.Logf(\"cluster MOID %v\", clusterMoId)\n\t\tif clusterMoId == clusterID {\n\t\t\tframework.Logf(\"Found matching cluster domain!!\")\n\t\t\tclusterName = cluster.Name()\n\t\t\tbreak\n\t\t}\n\t}\n\tframework.Logf(\"cluster on zone is: %s\", clusterName)\n\tif clusterName == \"\" {\n\t\tframework.Failf(\"couldn't find cluster on zone %s\", availabilityZone)\n\t}\n\treturn clusterName\n\n}", "func (c *Cluster) Name() string {\n\treturn c.Name_\n}", "func (e *Ex) StackString() string {\n\treturn fmt.Sprintf(\"%v\", e.stack)\n}" ]
[ "0.6634175", "0.64011246", "0.63919973", "0.6266783", "0.604183", "0.5951883", "0.5875301", "0.58606607", "0.5757922", "0.5754143", "0.5688333", "0.56320745", "0.5579556", "0.55089194", "0.5506207", "0.5487271", "0.5485594", "0.547948", "0.54571444", "0.5456574", "0.54525596", "0.5447826", "0.5444161", "0.54189634", "0.54109323", "0.54089767", "0.5399684", "0.5390128", "0.5383766", "0.5377066", "0.5373147", "0.5370566", "0.5361664", "0.5361588", "0.5358906", "0.5351849", "0.53444", "0.53395444", "0.53370285", "0.5334809", "0.5331328", "0.5327417", "0.53273916", "0.5325758", "0.5323362", "0.531656", "0.531397", "0.5311352", "0.5291478", "0.52799916", "0.52798456", "0.5263585", "0.5249354", "0.524254", "0.5240699", "0.5237267", "0.5236941", "0.520877", "0.52068925", "0.516288", "0.5158187", "0.5149126", "0.51348007", "0.5133404", "0.51148134", "0.51138884", "0.5109115", "0.5105879", "0.5100784", "0.5087566", "0.5086943", "0.508198", "0.50791043", "0.507748", "0.50727797", "0.5057891", "0.50467455", "0.50427896", "0.50422114", "0.5039151", "0.5036748", "0.50351745", "0.50291353", "0.50208735", "0.50170827", "0.5001231", "0.4984222", "0.4982969", "0.4980128", "0.49729946", "0.49709126", "0.4970238", "0.49692777", "0.49604815", "0.49593878", "0.49560115", "0.49557674", "0.4954701", "0.49492913", "0.49384078", "0.49365515" ]
0.0
-1
VpcID returns the VPC ID the current node belongs to.
func (a *Adapter) VpcID() string { return a.manifest.instance.vpcID }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o ZoneVpcOutput) VpcId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ZoneVpc) string { return v.VpcId }).(pulumi.StringOutput)\n}", "func (vpc Vpc) ID() string {\n\treturn vpc.VpcID\n}", "func (o HostedZoneVpcOutput) VpcId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v HostedZoneVpc) string { return v.VpcId }).(pulumi.StringOutput)\n}", "func (o AccessPointVpcConfigurationOutput) VpcId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v AccessPointVpcConfiguration) string { return v.VpcId }).(pulumi.StringOutput)\n}", "func (o AwsVpcPeeringConnectionOutput) VpcId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AwsVpcPeeringConnection) pulumi.StringOutput { return v.VpcId }).(pulumi.StringOutput)\n}", "func (o InstanceOutput) VpcId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.VpcId }).(pulumi.StringOutput)\n}", "func (o Ipv4CidrBlockOutput) VpcId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Ipv4CidrBlock) pulumi.StringOutput { return v.VpcId }).(pulumi.StringOutput)\n}", "func (o TopicRuleDestinationVpcConfigurationOutput) VpcId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleDestinationVpcConfiguration) string { return v.VpcId }).(pulumi.StringOutput)\n}", "func (o AwsVpcPeeringConnectionOutput) AwsVpcId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AwsVpcPeeringConnection) pulumi.StringOutput { return v.AwsVpcId }).(pulumi.StringOutput)\n}", "func (o ClusterNodeAttributeOutput) VpcId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ClusterNodeAttribute) string { return v.VpcId }).(pulumi.StringOutput)\n}", "func (o GetVpcEndpointLinkedVpcsVpcEndpointLinkedVpcOutput) VpcId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetVpcEndpointLinkedVpcsVpcEndpointLinkedVpc) string { return v.VpcId }).(pulumi.StringOutput)\n}", "func (o GetVpcEndpointsEndpointOutput) VpcId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetVpcEndpointsEndpoint) string { return v.VpcId }).(pulumi.StringOutput)\n}", "func (o AccessPointVpcConfigurationPtrOutput) VpcId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *AccessPointVpcConfiguration) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.VpcId\n\t}).(pulumi.StringPtrOutput)\n}", "func (o M3DbOutput) ProjectVpcId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *M3Db) pulumi.StringPtrOutput { return v.ProjectVpcId }).(pulumi.StringPtrOutput)\n}", "func (o TargetGroupOutput) VpcId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v TargetGroup) *string { return v.VpcId }).(pulumi.StringPtrOutput)\n}", "func (s *DescribeDomainOutput) SetVpcId(v string) *DescribeDomainOutput {\n\ts.VpcId = &v\n\treturn s\n}", "func (o TopicRuleDestinationVpcConfigurationPtrOutput) VpcId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TopicRuleDestinationVpcConfiguration) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.VpcId\n\t}).(pulumi.StringPtrOutput)\n}", "func (o KafkaMirrorMakerOutput) ProjectVpcId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *KafkaMirrorMaker) pulumi.StringPtrOutput { return v.ProjectVpcId }).(pulumi.StringPtrOutput)\n}", "func (o ZoneAssociationOutput) VpcId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ZoneAssociation) pulumi.StringOutput { return v.VpcId }).(pulumi.StringOutput)\n}", "func (s *CreateDomainInput) SetVpcId(v string) *CreateDomainInput {\n\ts.VpcId = &v\n\treturn s\n}", "func (o TargetGroupPtrOutput) VpcId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TargetGroup) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.VpcId\n\t}).(pulumi.StringPtrOutput)\n}", "func (o StudioOutput) VpcId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Studio) pulumi.StringOutput { return v.VpcId }).(pulumi.StringOutput)\n}", "func (o EcsLaunchTemplateOutput) VpcId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *EcsLaunchTemplate) pulumi.StringOutput { return v.VpcId }).(pulumi.StringOutput)\n}", "func (s *FirewallRuleGroupAssociation) SetVpcId(v string) *FirewallRuleGroupAssociation {\n\ts.VpcId = &v\n\treturn s\n}", "func (o GetLoadBalancersBalancerOutput) VpcId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetLoadBalancersBalancer) string { return v.VpcId }).(pulumi.StringOutput)\n}", "func (o GetServerGroupsGroupOutput) VpcId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetServerGroupsGroup) string { return v.VpcId }).(pulumi.StringOutput)\n}", "func (s *ListEndpointAccessInput) SetVpcId(v string) *ListEndpointAccessInput {\n\ts.VpcId = &v\n\treturn s\n}", "func (s *NetworkSettingsSummary) SetVpcId(v string) *NetworkSettingsSummary {\n\ts.VpcId = &v\n\treturn s\n}", "func (s *ListFirewallRuleGroupAssociationsInput) SetVpcId(v string) *ListFirewallRuleGroupAssociationsInput {\n\ts.VpcId = &v\n\treturn s\n}", "func (s *CreateNetworkSettingsInput) SetVpcId(v string) *CreateNetworkSettingsInput {\n\ts.VpcId = &v\n\treturn s\n}", "func (s *AssociateFirewallRuleGroupInput) SetVpcId(v string) *AssociateFirewallRuleGroupInput {\n\ts.VpcId = &v\n\treturn s\n}", "func (s *NetworkSettings) SetVpcId(v string) *NetworkSettings {\n\ts.VpcId = &v\n\treturn s\n}", "func (o VpcIpv6CidrBlockAssociationOutput) VpcId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *VpcIpv6CidrBlockAssociation) pulumi.StringOutput { return v.VpcId }).(pulumi.StringOutput)\n}", "func (s *MountTargetDescription) SetVpcId(v string) *MountTargetDescription {\n\ts.VpcId = &v\n\treturn s\n}", "func (s *UpdateNetworkSettingsInput) SetVpcId(v string) *UpdateNetworkSettingsInput {\n\ts.VpcId = &v\n\treturn s\n}", "func (r *VpcEndpointConnectionNotification) VpcEndpointId() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"vpcEndpointId\"])\n}", "func (s *ResolverRuleAssociation) SetVPCId(v string) *ResolverRuleAssociation {\n\ts.VPCId = &v\n\treturn s\n}", "func (s *ResolverRuleAssociation) SetVPCId(v string) *ResolverRuleAssociation {\n\ts.VPCId = &v\n\treturn s\n}", "func GetLocalEc2VpcID() (string, error) {\n\tmac, err := getEc2Metadata(ec2MacURL)\n\tif err != nil {\n\t\tglog.Errorln(\"get mac error\", err)\n\t\treturn \"\", err\n\t}\n\n\tvpcURL := ec2VpcURLPrefix + mac + \"/vpc-id\"\n\tvpcID, err := getEc2Metadata(vpcURL)\n\tif err != nil {\n\t\tglog.Errorln(\"get vpc id error\", err)\n\t\treturn \"\", err\n\t}\n\treturn vpcID, nil\n}", "func (s *VpcEndpoint) SetVpcId(v string) *VpcEndpoint {\n\ts.VpcId = &v\n\treturn s\n}", "func (s *AssociateResolverRuleInput) SetVPCId(v string) *AssociateResolverRuleInput {\n\ts.VPCId = &v\n\treturn s\n}", "func (s *AssociateResolverRuleInput) SetVPCId(v string) *AssociateResolverRuleInput {\n\ts.VPCId = &v\n\treturn s\n}", "func (s *DisassociateResolverRuleInput) SetVPCId(v string) *DisassociateResolverRuleInput {\n\ts.VPCId = &v\n\treturn s\n}", "func (s *DisassociateResolverRuleInput) SetVPCId(v string) *DisassociateResolverRuleInput {\n\ts.VPCId = &v\n\treturn s\n}", "func (s *WorkforceVpcConfigResponse) SetVpcId(v string) *WorkforceVpcConfigResponse {\n\ts.VpcId = &v\n\treturn s\n}", "func (o GetVpcEndpointLinkedVpcsVpcEndpointLinkedVpcOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetVpcEndpointLinkedVpcsVpcEndpointLinkedVpc) string { return v.InstanceId }).(pulumi.StringOutput)\n}", "func VPCID(vpcID string) RequestOptionFunc {\n\treturn func(body *RequestBody) error {\n\t\tbody.VpcId = vpcID\n\t\treturn nil\n\t}\n}", "func (s *WorkforceVpcConfigRequest) SetVpcId(v string) *WorkforceVpcConfigRequest {\n\ts.VpcId = &v\n\treturn s\n}", "func (s *VpcConfigResponse) SetVpcId(v string) *VpcConfigResponse {\n\ts.VpcId = &v\n\treturn s\n}", "func (o RouteOutput) VpcEndpointId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Route) pulumi.StringPtrOutput { return v.VpcEndpointId }).(pulumi.StringPtrOutput)\n}", "func (o GetSubnetsSubnetOutput) VpdId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetSubnetsSubnet) string { return v.VpdId }).(pulumi.StringOutput)\n}", "func (s *Stack) findVPCID() (*string, fail.Error) {\n\tvar router *openstack.Router\n\tfound := false\n\trouters, err := s.Stack.ListRouters()\n\tif err != nil {\n\t\treturn nil, fail.Errorf(fmt.Sprintf(\"error listing routers: %s\", openstack.ProviderErrorToString(err)), err)\n\t}\n\tfor _, r := range routers {\n\t\tif r.Name == s.authOpts.VPCName {\n\t\t\tfound = true\n\t\t\trouter = &r\n\t\t\tbreak\n\t\t}\n\t}\n\tif found && router != nil {\n\t\treturn &router.ID, nil\n\t}\n\treturn nil, nil\n}", "func GetVPCIdFromReservations(reservations []*ec2.Reservation) string {\n\treturn *reservations[0].Instances[0].VpcId\n}", "func (m *Mux) ConnectedID() (id vpc.ID, err error) {\n\t// TODO(seanc@): Test to see make sure the descriptor has the mutate bit set.\n\n\tout := make([]byte, vpc.IDSize)\n\tif err := vpc.Ctl(m.h, vpc.Cmd(_MuxConnectedIDGetCmd), nil, out); err != nil {\n\t\treturn vpc.ID{}, errors.Wrap(err, \"unable to get VPC Mux's connected ID\")\n\t}\n\n\tbuf := bytes.NewReader(out[:])\n\tif err = binary.Read(buf, binary.LittleEndian, &id); err != nil {\n\t\treturn vpc.ID{}, errors.Wrap(err, \"failed to read VPC ID\")\n\t}\n\n\treturn id, nil\n}", "func GetVPC(connectionName string, rsType string, nameID string) (*cres.VPCInfo, error) {\n\tcblog.Info(\"call GetVPC()\")\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 nameID, err = EmptyCheckAndTrim(\"nameID\", nameID)\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.RLock(connectionName, nameID)\n\tdefer vpcSPLock.RUnlock(connectionName, nameID)\n\t// (1) get spiderIID(NameId)\n\tiidInfo, err := iidRWLock.GetIID(iidm.IIDSGROUP, connectionName, rsType, cres.IID{nameID, \"\"})\n\tif err != nil {\n\t\tcblog.Error(err)\n\t\treturn nil, err\n\t}\n\n\t// (2) get resource(driverIID)\n\tinfo, err := handler.GetVPC(getDriverIID(iidInfo.IId))\n\tif err != nil {\n\t\tcblog.Error(err)\n\t\treturn nil, err\n\t}\n\t// (3) set ResourceInfo(userIID)\n\tinfo.IId = getUserIID(iidInfo.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, info.IId.NameId, subnetInfo.IId) // VPC info.IId.NameId => 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 (o RouteOutput) VpcPeeringConnectionId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Route) pulumi.StringPtrOutput { return v.VpcPeeringConnectionId }).(pulumi.StringPtrOutput)\n}", "func (o AwsVpcPeeringConnectionOutput) AwsVpcPeeringConnectionId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AwsVpcPeeringConnection) pulumi.StringOutput { return v.AwsVpcPeeringConnectionId }).(pulumi.StringOutput)\n}", "func (r *VpcLink) ID() pulumi.IDOutput {\n\treturn r.s.ID()\n}", "func (o ZoneVpcOutput) VpcRegion() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ZoneVpc) *string { return v.VpcRegion }).(pulumi.StringPtrOutput)\n}", "func (o GetVpcEndpointLinkedVpcsVpcEndpointLinkedVpcOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetVpcEndpointLinkedVpcsVpcEndpointLinkedVpc) string { return v.Id }).(pulumi.StringOutput)\n}", "func (r *PrivateVirtualInterface) ConnectionId() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"connectionId\"])\n}", "func (o GetVpdsVpdOutput) VpdId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetVpdsVpd) string { return v.VpdId }).(pulumi.StringOutput)\n}", "func (r *VpnConnectionRoute) VpnConnectionId() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"vpnConnectionId\"])\n}", "func (r *VpcEndpointConnectionNotification) VpcEndpointServiceId() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"vpcEndpointServiceId\"])\n}", "func (o HostedZoneVpcOutput) VpcRegion() pulumi.StringOutput {\n\treturn o.ApplyT(func(v HostedZoneVpc) string { return v.VpcRegion }).(pulumi.StringOutput)\n}", "func (s *VPCService) GetVPCID(name string, opts ...OptionFunc) (string, int, error) {\n\tp := &ListVPCsParams{}\n\tp.p = make(map[string]interface{})\n\n\tp.p[\"name\"] = name\n\n\tfor _, fn := range append(s.cs.options, opts...) {\n\t\tif err := fn(s.cs, p); err != nil {\n\t\t\treturn \"\", -1, err\n\t\t}\n\t}\n\n\tl, err := s.ListVPCs(p)\n\tif err != nil {\n\t\treturn \"\", -1, err\n\t}\n\n\tif l.Count == 0 {\n\t\treturn \"\", l.Count, fmt.Errorf(\"No match found for %s: %+v\", name, l)\n\t}\n\n\tif l.Count == 1 {\n\t\treturn l.VPCs[0].Id, l.Count, nil\n\t}\n\n\tif l.Count > 1 {\n\t\tfor _, v := range l.VPCs {\n\t\t\tif v.Name == name {\n\t\t\t\treturn v.Id, l.Count, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", l.Count, fmt.Errorf(\"Could not find an exact match for %s: %+v\", name, l)\n}", "func (o GetVpcEndpointLinkedVpcsVpcEndpointLinkedVpcOutput) VswitchId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetVpcEndpointLinkedVpcsVpcEndpointLinkedVpc) string { return v.VswitchId }).(pulumi.StringOutput)\n}", "func (r *DefaultVpcDhcpOptions) OwnerId() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"ownerId\"])\n}", "func (c *clientConn) PeerID() (spiffeid.ID, error) {\n\treturn PeerIDFromConnectionState(c.Conn.ConnectionState())\n}", "func (pc peerConn) ID() ID {\r\n\treturn PubKeyToID(pc.conn.(*tmconn.SecretConnection).RemotePubKey())\r\n}", "func (r *DefaultVpcDhcpOptions) ID() pulumi.IDOutput {\n\treturn r.s.ID()\n}", "func (client *Client) GetPlayerID() int {\n\treturn client.id\n}", "func GetNetworkID() (string, error) {\n\tif !config.IsCloudProviderEnabled(CloudProviderName) {\n\t\treturn \"\", fmt.Errorf(\"cloud provider is disabled by configuration\")\n\t}\n\tresp, err := getMetadataItem(\"/network/interfaces/macs\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tmacs := strings.Split(strings.TrimSpace(resp), \"\\n\")\n\tvpcIDs := common.NewStringSet()\n\n\tfor _, mac := range macs {\n\t\tif mac == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tmac = strings.TrimSuffix(mac, \"/\")\n\t\tid, err := getMetadataItem(fmt.Sprintf(\"/network/interfaces/macs/%s/vpc-id\", mac))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tvpcIDs.Add(id)\n\t}\n\n\tswitch len(vpcIDs) {\n\tcase 0:\n\t\treturn \"\", fmt.Errorf(\"EC2: GetNetworkID no mac addresses returned\")\n\tcase 1:\n\t\treturn vpcIDs.GetAll()[0], nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"EC2: GetNetworkID too many mac addresses returned\")\n\t}\n}", "func (vm *vmQemu) vsockID() int {\n\treturn vm.id + 3\n}", "func (id eipID) IsVPC() bool {\n\treturn strings.HasPrefix(string(id), \"eipalloc-\")\n}", "func (o *PcloudPvminstancesNetworksGetParams) SetPvmInstanceID(pvmInstanceID string) {\n\to.PvmInstanceID = pvmInstanceID\n}", "func (o ConnectionCloudSqlPtrOutput) InstanceId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ConnectionCloudSql) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.InstanceId\n\t}).(pulumi.StringPtrOutput)\n}", "func (o RepoDomainListPtrOutput) Vpc() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *RepoDomainList) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Vpc\n\t}).(pulumi.StringPtrOutput)\n}", "func (o GetReposRepoDomainListOutput) Vpc() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetReposRepoDomainList) string { return v.Vpc }).(pulumi.StringOutput)\n}", "func (s *ResolverEndpoint) SetHostVPCId(v string) *ResolverEndpoint {\n\ts.HostVPCId = &v\n\treturn s\n}", "func (s *ResolverEndpoint) SetHostVPCId(v string) *ResolverEndpoint {\n\ts.HostVPCId = &v\n\treturn s\n}", "func (o RepoDomainListOutput) Vpc() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v RepoDomainList) *string { return v.Vpc }).(pulumi.StringPtrOutput)\n}", "func (o *NiatelemetryVpcDetails) GetClassId() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.ClassId\n}", "func (r DescribeCacheInstancesRequest) GetRegionId() string {\n return r.RegionId\n}", "func (s *WorkforceVpcConfigResponse) SetVpcEndpointId(v string) *WorkforceVpcConfigResponse {\n\ts.VpcEndpointId = &v\n\treturn s\n}", "func (r *LaunchConfiguration) VpcClassicLinkId() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"vpcClassicLinkId\"])\n}", "func (server *Server) GetPlayerID() int {\n\treturn server.id\n}", "func GetVDVSPID(ip string) (string, error) {\n\tout, err := ssh.InvokeCommand(ip, dockercli.GetVDVSPID)\n\tif err != nil {\n\t\tlog.Printf(\"Unable to get docker-volume-vsphere pid\")\n\t\treturn \"\", err\n\t}\n\treturn out, nil\n}", "func (o AwsVpcPeeringConnectionOutput) AwsVpcRegion() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AwsVpcPeeringConnection) pulumi.StringOutput { return v.AwsVpcRegion }).(pulumi.StringOutput)\n}", "func (*BgpAmazonVpcs) GetPath() string { return \"/api/objects/bgp/amazon_vpc/\" }", "func (o ConnectionCloudSqlOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ConnectionCloudSql) string { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (s *scope) InstanceID() string {\n\treturn s.instance.InstanceID\n}", "func (c *ClientMgr) Vpc() *ecs.Client {\n\tc.Lock()\n\tdefer c.Unlock()\n\ttokenUpdated, err := c.refreshToken()\n\tlogrus.Debugf(\"Token update: %v, %v\", tokenUpdated, err)\n\tif err != nil {\n\t\tlogrus.Errorf(\"Error refresh OpenAPI token: %v\", err)\n\t}\n\treturn c.vpc\n}", "func (aws *awsCloudProvider) GetInstanceID(node *apiv1.Node) string {\n\treturn node.Spec.ProviderID\n}", "func (p *ProjectCard) GetNodeID() string {\n\tif p == nil || p.NodeID == nil {\n\t\treturn \"\"\n\t}\n\treturn *p.NodeID\n}", "func (i *instances) InstanceID(ctx context.Context, nodeName types.NodeName) (string, error) {\n\tvm, err := i.discoverNodeByName(ctx, nodeName)\n\tif err != nil {\n\t\tklog.Errorf(\"Error trying to find VM: %v\", err)\n\t\treturn \"\", err\n\t}\n\tif vm == nil {\n\t\tklog.V(4).Info(\"instances.InstanceID() InstanceNotFound \", nodeName)\n\t\treturn \"\", cloudprovider.InstanceNotFound\n\t}\n\n\tif vm.Status.BiosUUID == \"\" {\n\t\treturn \"\", errBiosUUIDEmpty\n\t}\n\n\tklog.V(4).Infof(\"instances.InstanceID() called to get vm: %v uuid: %v\", nodeName, vm.Status.BiosUUID)\n\treturn vm.Status.BiosUUID, nil\n}", "func (o VpcIpamScopeOutput) IpamId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *VpcIpamScope) pulumi.StringOutput { return v.IpamId }).(pulumi.StringOutput)\n}", "func (s AwsEc2VpcDetails) String() string {\n\treturn awsutil.Prettify(s)\n}", "func PPid() int {\n\tif !IsChild() {\n\t\treturn Pid()\n\t}\n\tppidValue := os.Getenv(envKeyPPid)\n\tif ppidValue != \"\" && ppidValue != \"0\" {\n\t\treturn gconv.Int(ppidValue)\n\t}\n\treturn PPidOS()\n}", "func (endpoint *BridgedMacvlanEndpoint) PciAddr() string {\n\treturn endpoint.PCIAddr\n}" ]
[ "0.70958114", "0.7021178", "0.70081663", "0.69484353", "0.69469905", "0.6893211", "0.6839423", "0.68181646", "0.6776505", "0.6775017", "0.6704507", "0.6665544", "0.666223", "0.6541551", "0.6534889", "0.6534633", "0.6505329", "0.64901376", "0.645327", "0.6452794", "0.64369947", "0.642917", "0.6379572", "0.63289446", "0.62116337", "0.61744434", "0.61645657", "0.613299", "0.6125654", "0.6105978", "0.61059403", "0.6105422", "0.6066077", "0.60514826", "0.6010373", "0.59947336", "0.5981285", "0.5981285", "0.59275866", "0.58663195", "0.5828722", "0.5828722", "0.5783518", "0.5783518", "0.57567316", "0.5677705", "0.56630445", "0.5654917", "0.5614456", "0.5584738", "0.55816084", "0.5492138", "0.54894876", "0.5454811", "0.53971714", "0.5386011", "0.5313631", "0.5233904", "0.5200232", "0.51727104", "0.5150081", "0.5146393", "0.5138344", "0.51097965", "0.50708854", "0.50561607", "0.50021577", "0.49978632", "0.49884275", "0.49628654", "0.4947803", "0.49322805", "0.49312615", "0.49088395", "0.49083006", "0.4891598", "0.4871549", "0.48557353", "0.48511043", "0.4849188", "0.4849188", "0.4830652", "0.47846693", "0.47826135", "0.47806996", "0.4738139", "0.47362757", "0.47347003", "0.47212532", "0.4707351", "0.4687619", "0.46867135", "0.46866083", "0.46825364", "0.46732354", "0.46724382", "0.46672884", "0.4661456", "0.4654528", "0.46536517" ]
0.71462744
0
InstanceID returns the instance ID the current node is running on.
func (a *Adapter) InstanceID() string { return a.manifest.instance.id }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func InstanceID() string {\n\treturn instanceID\n}", "func (c *Client) InstanceID() (int, error) {\n\tresp, err := c.get(\"/instance-id\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn strconv.Atoi(resp)\n}", "func (i *instances) InstanceID(ctx context.Context, nodeName types.NodeName) (string, error) {\n\tvm, err := i.discoverNodeByName(ctx, nodeName)\n\tif err != nil {\n\t\tklog.Errorf(\"Error trying to find VM: %v\", err)\n\t\treturn \"\", err\n\t}\n\tif vm == nil {\n\t\tklog.V(4).Info(\"instances.InstanceID() InstanceNotFound \", nodeName)\n\t\treturn \"\", cloudprovider.InstanceNotFound\n\t}\n\n\tif vm.Status.BiosUUID == \"\" {\n\t\treturn \"\", errBiosUUIDEmpty\n\t}\n\n\tklog.V(4).Infof(\"instances.InstanceID() called to get vm: %v uuid: %v\", nodeName, vm.Status.BiosUUID)\n\treturn vm.Status.BiosUUID, nil\n}", "func (i *instances) InstanceID(ctx context.Context, nodeName types.NodeName) (string, error) {\n\tdroplet, err := dropletByName(ctx, i.resources.gclient, nodeName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strconv.Itoa(droplet.ID), nil\n}", "func (s *Server) InstanceID() string {\n\treturn s.serverInstanceID\n}", "func (s *Server) InstanceID() string {\n\treturn s.serverInstanceID\n}", "func (s *scope) InstanceID() string {\n\treturn s.instance.InstanceID\n}", "func (d *driver) InstanceID(\n\tctx types.Context,\n\topts types.Store) (*types.InstanceID, error) {\n\treturn utils.InstanceID(ctx)\n}", "func (m *metadata) GetInstanceID() string {\n\treturn m.instanceID\n}", "func (s *singleton) GetInstanceId() int64 {\n\treturn s.id\n}", "func (i *Instances) InstanceID(name string) (string, error) {\n\t// Create context\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\t// Create vSphere client\n\tc, err := vsphereLogin(i.cfg, ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer c.Logout(ctx)\n\n\tvm, err := getVirtualMachineByName(i.cfg, ctx, c, name)\n\n\tvar mvm mo.VirtualMachine\n\terr = getVirtualMachineManagedObjectReference(ctx, c, vm, \"summary\", &mvm)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif mvm.Summary.Runtime.PowerState == ActivePowerState {\n\t\treturn \"/\" + vm.InventoryPath, nil\n\t}\n\n\tif mvm.Summary.Config.Template == false {\n\t\tglog.Warning(\"VM %s, is not in %s state\", name, ActivePowerState)\n\t} else {\n\t\tglog.Warning(\"VM %s, is a template\", name)\n\t}\n\n\treturn \"\", cloudprovider.InstanceNotFound\n}", "func (m *Machine) InstanceId() (instance.Id, error) {\n\tvar results params.StringResults\n\targs := params.Entities{\n\t\tEntities: []params.Entity{{Tag: m.tag.String()}},\n\t}\n\terr := m.st.call(\"InstanceId\", args, &results)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(results.Results) != 1 {\n\t\treturn \"\", fmt.Errorf(\"expected 1 result, got %d\", len(results.Results))\n\t}\n\tresult := results.Results[0]\n\tif result.Error != nil {\n\t\treturn \"\", result.Error\n\t}\n\treturn instance.Id(result.Result), nil\n}", "func (o InstanceOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (o InstanceOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (o InstanceOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (o SnapshotOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Snapshot) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func GetInstanceID() (string, error) {\n\tvalue := os.Getenv(\"AWS_INSTANCE_ID\")\n\tif len(value) > 0 {\n\t\treturn value, nil\n\t}\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(\"GET\", \"http://169.254.169.254/latest/meta-data/instance-id\", nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(data), nil\n}", "func (m *Info) GetInstanceID() string {\n\treturn m.ec2Metadata.getInstanceID()\n}", "func (inst Instance) ID() int {\n\treturn inst.id\n}", "func instanceID() string {\n\ttimeout := time.Duration(5 * time.Second)\n\tclient := http.Client{\n\t\tTimeout: timeout,\n\t}\n\tr, err := client.Get(metadataURL)\n\tif err != nil {\n\t\tlog.Warnf(fmt.Sprint(\"error requesting metadata. \", err.Error()))\n\t\treturn \"\"\n\t}\n\tdefer r.Body.Close()\n\n\tvar metadata = new(metaDataID)\n\terr = json.NewDecoder(r.Body).Decode(metadata)\n\tif err != nil {\n\t\tlog.Warnf(fmt.Sprint(\"error parsing metadata. \", err.Error()))\n\t\treturn \"\"\n\t}\n\n\treturn metadata.UUID\n}", "func (o GetChartNamespacesNamespaceOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetChartNamespacesNamespace) string { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (m *WorkflowCreateRequest) GetInstanceID() string {\n\tif m != nil {\n\t\treturn m.InstanceID\n\t}\n\treturn \"\"\n}", "func (o ConnectionCloudSqlOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ConnectionCloudSql) string { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (i *Instance) ID() string {\n\treturn i.InstanceID\n}", "func (o BgpIpOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *BgpIp) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (o RouteOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Route) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (o EnterpriseProxyAccessOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *EnterpriseProxyAccess) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (o GetChainsChainOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetChainsChain) string { return v.InstanceId }).(pulumi.StringOutput)\n}", "func GetInstanceId() string {\n\tcmd := \"curl\"\n\tcmdArgs := []string{\"-s\", \"http://169.254.169.254/latest/meta-data/instance-id\"}\n\tout, err := exec.Command(cmd, cmdArgs...).Output()\n\tif err != nil {\n\t\tlog.Printf(\"Instance Id err is %s\\n\", err)\n\t\treturn \"\"\n\t}\n\tlog.Printf(\"The instance id is %s\\n\", out)\n\treturn string(out)\n}", "func GetInstanceId() string {\n\tcmd := \"curl\"\n\tcmdArgs := []string{\"-s\", \"http://169.254.169.254/latest/meta-data/instance-id\"}\n\tout, err := exec.Command(cmd, cmdArgs...).Output()\n\tif err != nil {\n\t\tlog.Printf(\"Instance Id err is %s\\n\", err)\n\t\treturn \"\"\n\t}\n\tlog.Printf(\"The instance id is %s\\n\", out)\n\treturn string(out)\n}", "func (o ConnectionCloudSqlPtrOutput) InstanceId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ConnectionCloudSql) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.InstanceId\n\t}).(pulumi.StringPtrOutput)\n}", "func (o DomainAttachmentOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DomainAttachment) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (o UserOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *User) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (aws *awsCloudProvider) GetInstanceID(node *apiv1.Node) string {\n\treturn node.Spec.ProviderID\n}", "func (o BandwidthPackageAttachmentOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *BandwidthPackageAttachment) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func NewInstanceID() string {\n\tg := uuid.Must(uuid.NewV4())\n\tp := strings.Split(g.String(), \"-\")\n\treturn p[len(p)-1]\n}", "func (o AlidnsDomainAttachmentOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AlidnsDomainAttachment) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (i *Instance) ID() string {\n\treturn i.MachineID\n}", "func (o AssociationOutput) InstanceId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Association) pulumi.StringPtrOutput { return v.InstanceId }).(pulumi.StringPtrOutput)\n}", "func (did *SPDeviceInformationData) InstanceID() (string, error) {\n\trequiredSize := uint32(0)\n\terr := setupDiGetDeviceInstanceId(w32.HANDLE(did.devInfo), &did.spDeviceInformationData, nil, 0, &requiredSize)\n\n\tbuff := make([]uint16, requiredSize)\n\terr = setupDiGetDeviceInstanceId(w32.HANDLE(did.devInfo), &did.spDeviceInformationData, unsafe.Pointer(&buff[0]), uint32(len(buff)), &requiredSize)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn windows.UTF16ToString(buff[:]), err\n}", "func GetInstanceID() (string, error) {\n\tif !config.IsCloudProviderEnabled(CloudProviderName) {\n\t\treturn \"\", fmt.Errorf(\"cloud provider is disabled by configuration\")\n\t}\n\n\tinstanceID, err := getMetadataItemWithMaxLength(\"/instance-id\", config.Datadog.GetInt(\"metadata_endpoints_max_hostname_size\"))\n\tif err != nil {\n\t\tif instanceID, found := cache.Cache.Get(instanceIDCacheKey); found {\n\t\t\tlog.Debugf(\"Unable to get ec2 instanceID from aws metadata, returning cached instanceID '%s': %s\", instanceID, err)\n\t\t\treturn instanceID.(string), nil\n\t\t}\n\t\treturn \"\", err\n\t}\n\n\tcache.Cache.Set(instanceIDCacheKey, instanceID, cache.NoExpiration)\n\n\treturn instanceID, nil\n}", "func (o InstanceFromTemplateOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *InstanceFromTemplate) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (c *Client) GetInstanceID() (string, error) {\n\tresp, err := c.httpClient.Get(instanceMetadataBaseURL + \"/hetzner/v1/metadata/instance-id\")\n\tif err != nil {\n\t\tvar neterr net.Error\n\t\tif errors.As(err, &neterr) && (neterr.Timeout() || neterr.Temporary()) {\n\t\t\treturn \"\", &errorx.RetryableError{Message: \"timeout or temporary error in HTTP request\", Err: neterr}\n\t\t}\n\t\treturn \"\", fmt.Errorf(\"error in http request: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"unexpected status code %d != 200\", resp.StatusCode)\n\t\tif resp.StatusCode >= 500 && resp.StatusCode < 600 {\n\t\t\treturn \"\", &errorx.RetryableError{Message: \"retryable HTTP error\", Err: err}\n\t\t}\n\t\treturn \"\", err\n\t}\n\tinstanceIDB, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error reading response body: %w\", err)\n\t}\n\treturn string(instanceIDB), nil\n}", "func (o InstanceAttachmentOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *InstanceAttachment) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (o EndpointAclPolicyOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *EndpointAclPolicy) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (o GetRegistryEnterpriseNamespacesResultOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetRegistryEnterpriseNamespacesResult) string { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (o GetVpcEndpointLinkedVpcsVpcEndpointLinkedVpcOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetVpcEndpointLinkedVpcsVpcEndpointLinkedVpc) string { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (client *AWSClient) GetInstanceID() (string, error) {\n\tif client.svcEC2Metadata.Available() {\n\t\ti, err := client.svcEC2Metadata.GetInstanceIdentityDocument()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn i.InstanceID, nil\n\t}\n\treturn \"\", errors.New(\"program is not running with EC2 Instance or metadata service is not available\")\n}", "func (inst *Instance) ID() string {\n\tif inst == nil || inst.inst == nil {\n\t\treturn \"\"\n\t}\n\treturn inst.inst.ID()\n}", "func (o GetChartRepositoriesRepositoryOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetChartRepositoriesRepository) string { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (o GetEndpointAclPoliciesPolicyOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetEndpointAclPoliciesPolicy) string { return v.InstanceId }).(pulumi.StringOutput)\n}", "func GetInstanceID(svc *ec2metadata.EC2Metadata) (string, error) {\n\tdoc, err := svc.GetInstanceIdentityDocument()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn doc.InstanceID, nil\n}", "func (i *instance) appID() string {\n\treturn i.opts.appID()\n}", "func getVmssInstanceID(machineName string) (string, error) {\n\tnameLength := len(machineName)\n\tif nameLength < 6 {\n\t\treturn \"\", ErrorNotVmssInstance\n\t}\n\n\tinstanceID, err := strconv.ParseUint(machineName[nameLength-6:], 36, 64)\n\tif err != nil {\n\t\treturn \"\", ErrorNotVmssInstance\n\t}\n\n\treturn fmt.Sprintf(\"%d\", instanceID), nil\n}", "func (o *CloudVolumeInstanceAttachment) GetInstanceId() string {\n\tif o == nil || o.InstanceId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.InstanceId\n}", "func readInstanceID() string {\n\tconst instanceIDFile = \"/var/lib/cloud/data/instance-id\"\n\tidBytes, err := ioutil.ReadFile(instanceIDFile)\n\tif err != nil {\n\t\tglog.Infof(\"Failed to get instance id from file: %v\", err)\n\t\treturn \"\"\n\t} else {\n\t\tinstanceID := string(idBytes)\n\t\tinstanceID = strings.TrimSpace(instanceID)\n\t\tglog.Infof(\"Get instance id from file: %s\", instanceID)\n\t\treturn instanceID\n\t}\n}", "func (s *Store) NodeID() uint64 { return s.id }", "func (o InstanceNodeOutput) Id() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InstanceNode) *string { return v.Id }).(pulumi.StringPtrOutput)\n}", "func GetAppInstanceId(r *http.Request) string {\n\tquery, _ := GetHTTPTags(r)\n\treturn query.Get(AppInstanceIdStr)\n}", "func (c *Client) NodeID() uint64 { return c.nodeID }", "func (s *Service) InstanceKey() string {\n\treturn s.InstanceName.String()\n}", "func (s *ServiceInstance) getID() serviceInstanceID {\n\treturn serviceInstanceID{\n\t\taddress: s.Address.String(),\n\t\tname: serviceInstanceName(s.InstanceName),\n\t}\n}", "func (n *Node) ID() string {\n\treturn n.IP\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 (dc *Client) GetRuntimeID(accountID, instanceID string) (string, error) {\n\tquery := dc.queryProvider.RuntimeForInstanceId(instanceID)\n\treq := machineGraph.NewRequest(query)\n\treq.Header.Add(accountIDKey, accountID)\n\n\tdc.log.Info(\"Send request to director\")\n\tresponse, err := dc.getRuntimeIdFromDirector(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdc.log.Info(\"Extract the RuntimeID from the response\")\n\treturn dc.getIDFromRuntime(&response.Result)\n}", "func (s *Server) ID() string {\n\treturn s.Config().GetUuid()\n}", "func (o InstanceOutput) InstanceNum() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.InstanceNum }).(pulumi.StringOutput)\n}", "func PID() int {\n\treturn os.Getpid()\n}", "func (h *httpCloud) ExternalID(instance string) (string, error) {\n\treturn instance, nil\n}", "func (i *instances) ExternalID(ctx context.Context, nodeName types.NodeName) (string, error) {\n\treturn i.InstanceID(ctx, nodeName)\n}", "func pid(instance int) (pid string, err error) {\n file, err := os.Open(pidFileName(instance))\n if err != nil {\n return\n }\n\n defer file.Close()\n\n scanner := bufio.NewScanner(file)\n scanner.Scan()\n pid = scanner.Text()\n return\n}", "func (os *OpenStack) GetInstanceByID(instanceID string) (*servers.Server, error) {\n\tserver, err := servers.Get(os.compute, instanceID).Extract()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn server, nil\n}", "func instanceID(resourceSpec *runtime.RawExtension) (string, error) {\n\tif resourceSpec == nil {\n\t\treturn \"\", nil\n\t}\n\n\tspec := partialSpec{}\n\terr := json.Unmarshal(resourceSpec.Raw, &spec)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unmarshalling StateResource spec failed\")\n\t}\n\n\treturn spec.InstanceID, nil\n}", "func Getpid() int", "func (o RouteOutput) InstanceOwnerId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Route) pulumi.StringOutput { return v.InstanceOwnerId }).(pulumi.StringOutput)\n}", "func (_options *ListTopicsOptions) SetInstanceID(instanceID string) *ListTopicsOptions {\n\t_options.InstanceID = core.StringPtr(instanceID)\n\treturn _options\n}", "func (c *Config) InstanceKey(_ string) (string, error) {\n\tdsn, err := c.getDataSourceNames()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(dsn) != 1 {\n\t\treturn \"\", fmt.Errorf(\"can't automatically determine a value for `instance` with %d DSN. either use 1 DSN or manually assign a value for `instance` in the integration config\", len(dsn))\n\t}\n\n\ts, err := parsePostgresURL(dsn[0])\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"cannot parse DSN: %w\", err)\n\t}\n\n\t// Assign default values to s.\n\t//\n\t// PostgreSQL hostspecs can contain multiple host pairs. We'll assign a host\n\t// and port by default, but otherwise just use the hostname.\n\tif _, ok := s[\"host\"]; !ok {\n\t\ts[\"host\"] = \"localhost\"\n\t\ts[\"port\"] = \"5432\"\n\t}\n\n\thostport := s[\"host\"]\n\tif p, ok := s[\"port\"]; ok {\n\t\thostport += fmt.Sprintf(\":%s\", p)\n\t}\n\treturn fmt.Sprintf(\"postgresql://%s/%s\", hostport, s[\"dbname\"]), nil\n}", "func (_options *CreateTopicOptions) SetInstanceID(instanceID string) *CreateTopicOptions {\n\t_options.InstanceID = core.StringPtr(instanceID)\n\treturn _options\n}", "func (_options *DeleteTopicOptions) SetInstanceID(instanceID string) *DeleteTopicOptions {\n\t_options.InstanceID = core.StringPtr(instanceID)\n\treturn _options\n}", "func (c *Config) InstanceKey(agentKey string) (string, error) {\n\turl, err := url.Parse(string(c.ConnectionString))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to parse connection string URL: %w\", err)\n\t}\n\n\treturn url.Host, nil\n}", "func (t *TableNode) PID() string {\n\treturn t.PUID\n}", "func (s *Session) GetCurrentInstance() *Instance {\n\treturn s.CurrentInstance\n}", "func (e *Etcd) TaskID(ctx context.Context, node string) (id string, err error) {\n\treturn e.Get(ctx, fmt.Sprintf(\"%s/%s/taskid\", InstanceDirPrefix, node))\n}", "func (b *InstanceBuild) InstanceIDWithoutPrefix() string {\n\treturn strings.TrimPrefix(b.InstanceID, \"i-\")\n}", "func (_options *GetTopicOptions) SetInstanceID(instanceID string) *GetTopicOptions {\n\t_options.InstanceID = core.StringPtr(instanceID)\n\treturn _options\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 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 (i *Instances) ExternalID(name string) (string, error) {\n\t// Create context\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\t// Create vSphere client\n\tc, err := vsphereLogin(i.cfg, ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer c.Logout(ctx)\n\n\tvm, err := getVirtualMachineByName(i.cfg, ctx, c, name)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar mvm mo.VirtualMachine\n\terr = getVirtualMachineManagedObjectReference(ctx, c, vm, \"summary\", &mvm)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif mvm.Summary.Runtime.PowerState == ActivePowerState {\n\t\treturn vm.InventoryPath, nil\n\t}\n\n\tif mvm.Summary.Config.Template == false {\n\t\tglog.Warningf(\"VM %s, is not in %s state\", name, ActivePowerState)\n\t} else {\n\t\tglog.Warningf(\"VM %s, is a template\", name)\n\t}\n\n\treturn \"\", cloudprovider.InstanceNotFound\n}", "func (a *App) GetNodeID() string {\n\tif a == nil || a.NodeID == nil {\n\t\treturn \"\"\n\t}\n\treturn *a.NodeID\n}", "func (n *node) ID() NodeID {\n\treturn n.id\n}", "func GetLocalEc2InstanceID() (string, error) {\n\treturn getEc2Metadata(ec2InstanceIDURL)\n}", "func (n Node) ID() int64 {\n\treturn n.id\n}", "func (o *ExportData) GetIntegrationInstanceID() *string {\n\treturn &o.IntegrationInstanceID\n}", "func (_options *ReplaceTopicOptions) SetInstanceID(instanceID string) *ReplaceTopicOptions {\n\t_options.InstanceID = core.StringPtr(instanceID)\n\treturn _options\n}", "func (inst *IndependentInstance) StepID() int {\n\treturn inst.stepID\n}", "func (n *Node) ID() string {\n\treturn n.id\n}", "func (n *Node) ID() string {\n\treturn n.id\n}", "func (s *DefaultVocabulary) SetInstanceId(v string) *DefaultVocabulary {\n\ts.InstanceId = &v\n\treturn s\n}", "func (o InstanceMemcacheNodeOutput) NodeId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InstanceMemcacheNode) *string { return v.NodeId }).(pulumi.StringPtrOutput)\n}", "func (n *node) ID() string {\n\treturn n.id\n}" ]
[ "0.7966648", "0.7694622", "0.7651121", "0.7553367", "0.75086725", "0.75086725", "0.74904203", "0.74120426", "0.73663956", "0.7230504", "0.7180342", "0.7156372", "0.69985044", "0.69985044", "0.69985044", "0.6971348", "0.6943605", "0.69339204", "0.6921669", "0.6906843", "0.6884655", "0.6879828", "0.6874776", "0.6847915", "0.683964", "0.6784416", "0.67351216", "0.6727911", "0.672039", "0.672039", "0.6713481", "0.6699246", "0.669831", "0.6682083", "0.66286474", "0.6623737", "0.6607785", "0.6599987", "0.6584667", "0.65789205", "0.6522302", "0.650294", "0.6471958", "0.6467642", "0.646152", "0.6457116", "0.64368", "0.6425939", "0.6402131", "0.6389825", "0.62746084", "0.6253225", "0.6110297", "0.60054153", "0.59767884", "0.5935936", "0.5934947", "0.5893587", "0.58914113", "0.58911276", "0.58706456", "0.5811351", "0.57782525", "0.577507", "0.577006", "0.5766223", "0.57330894", "0.5713194", "0.57040864", "0.5690373", "0.56846875", "0.56523514", "0.56446934", "0.5635263", "0.56228733", "0.5620926", "0.5614265", "0.5595362", "0.5583787", "0.5583436", "0.55728424", "0.55662626", "0.55601335", "0.55377203", "0.55316323", "0.55314404", "0.55280906", "0.55268854", "0.5522473", "0.55202216", "0.55071527", "0.5505882", "0.5500082", "0.55000466", "0.549643", "0.54921377", "0.54921377", "0.5483636", "0.54790497", "0.5454166" ]
0.75311035
4
AutoScalingGroupName returns the name of the Auto Scaling Group the current node belongs to
func (a *Adapter) AutoScalingGroupName() string { return a.manifest.autoScalingGroup.name }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o NodeGroupDataOutput) AutoScalingGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v NodeGroupData) string { return v.AutoScalingGroupName }).(pulumi.StringOutput)\n}", "func (n namer) AutoScalingGroupName(sku string) string {\n\t// return n.ctx.Name + \"-node-group-\" + sku\n\treturn stringutil.DomainForm(n.cluster.Name + \"-\" + strings.Replace(sku, \".\", \"-\", -1)) // + \"-V\" + strconv.FormatInt(n.ctx.ContextVersion, 10))\n}", "func (n namer) AutoScalingGroupName(sku string) string {\n\t// return n.ctx.Name + \"-node-group-\" + sku\n\treturn stringutil.DomainForm(n.cluster.Name + \"-\" + strings.Replace(sku, \".\", \"-\", -1)) // + \"-V\" + strconv.FormatInt(n.ctx.ContextVersion, 10))\n}", "func (o NodeGroupDataPtrOutput) AutoScalingGroupName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *NodeGroupData) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.AutoScalingGroupName\n\t}).(pulumi.StringPtrOutput)\n}", "func (m *Info) GetAutoScalingGroupName() string {\n\tif m.ec2Tags != nil {\n\t\treturn m.ec2Tags.getAutoScalingGroupName()\n\t}\n\n\treturn \"\"\n}", "func (o DscNodeConfigurationOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DscNodeConfiguration) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (o ClusterApplicationConfigOutput) NodeGroupName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ClusterApplicationConfig) *string { return v.NodeGroupName }).(pulumi.StringPtrOutput)\n}", "func (o ManagedInstanceActiveDirectoryAdministratorOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ManagedInstanceActiveDirectoryAdministrator) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (c *StackCollection) GetNodeGroupAutoScalingGroupName(s *Stack) (string, error) {\n\tinput := &cfn.DescribeStackResourceInput{\n\t\tStackName: s.StackName,\n\t\tLogicalResourceId: aws.String(\"NodeGroup\"),\n\t}\n\n\tres, err := c.cloudformationAPI.DescribeStackResource(input)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn *res.StackResourceDetail.PhysicalResourceId, nil\n}", "func GetAutoscalingGroupName(svc autoscalingiface.AutoScalingAPI, instanceID string) (string, error) {\n\tautoInstance, err := svc.DescribeAutoScalingInstances(\n\t\t&autoscaling.DescribeAutoScalingInstancesInput{\n\t\t\tInstanceIds: []*string{\n\t\t\t\taws.String(instanceID),\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn *autoInstance.AutoScalingInstances[0].AutoScalingGroupName, nil\n}", "func (o SharedAccessPolicyOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *SharedAccessPolicy) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (o LinuxWebAppOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *LinuxWebApp) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (s *NatGatewaySpec) ResourceGroupName() string {\n\treturn s.ResourceGroup\n}", "func (o ClusterNodeGroupOutput) NodeGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ClusterNodeGroup) string { return v.NodeGroupName }).(pulumi.StringOutput)\n}", "func (o ClusterManagedPrivateEndpointOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ClusterManagedPrivateEndpoint) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (o ClusterBootstrapScriptNodeSelectorOutput) NodeGroupName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ClusterBootstrapScriptNodeSelector) *string { return v.NodeGroupName }).(pulumi.StringPtrOutput)\n}", "func (o LookupSnapshotPolicyResultOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupSnapshotPolicyResult) string { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (o RulesEngineOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *RulesEngine) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (o FrontdoorProfileOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *FrontdoorProfile) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (o AnalyzerOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Analyzer) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (o HybridConnectionOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *HybridConnection) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (o HybridConnectionOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *HybridConnection) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (s *InboundNatSpec) ResourceGroupName() string {\n\treturn s.ResourceGroup\n}", "func (o ResourceGroupOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ResourceGroup) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (o StreamInputIotHubOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *StreamInputIotHub) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (o IotHubDeviceUpdateAccountOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *IotHubDeviceUpdateAccount) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (o RouteOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Route) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (c *StackCollection) GetManagedNodeGroupAutoScalingGroupName(s *Stack) (string, error) {\n\tinput := &eks.DescribeNodegroupInput{\n\t\tClusterName: aws.String(getClusterNameTag(s)),\n\t\tNodegroupName: aws.String(c.GetNodeGroupName(s)),\n\t}\n\n\tres, err := c.eksAPI.DescribeNodegroup(input)\n\tif err != nil {\n\t\tlogger.Warning(\"couldn't get managed nodegroup details for stack %q\", *s.StackName)\n\t\treturn \"\", nil\n\t}\n\n\tasgs := []string{}\n\n\tif res.Nodegroup.Resources != nil {\n\t\tfor _, v := range res.Nodegroup.Resources.AutoScalingGroups {\n\t\t\tasgs = append(asgs, aws.StringValue(v.Name))\n\t\t}\n\t}\n\treturn strings.Join(asgs, \",\"), nil\n\n}", "func makeInstanceGroupName(clusterID string) string {\n\tprefix := \"k8s-ig\"\n\t// clusterID might be empty for legacy clusters\n\tif clusterID == \"\" {\n\t\treturn prefix\n\t}\n\treturn fmt.Sprintf(\"%s--%s\", prefix, clusterID)\n}", "func (m *LogicAppTriggerEndpointConfiguration) GetResourceGroupName()(*string) {\n val, err := m.GetBackingStore().Get(\"resourceGroupName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func CloudGroupName() string {\n\tif groupName := os.Getenv(\"BAAS_MONGODB_CLOUD_GROUP_NAME\"); groupName != \"\" {\n\t\treturn groupName\n\t}\n\treturn defaultGroupName\n}", "func (o ConnectionCertificateOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ConnectionCertificate) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (o NetworkPacketCaptureOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *NetworkPacketCapture) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (o LogzMonitorOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *LogzMonitor) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (o CertificateOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Certificate) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (o ScheduledQueryRulesAlertV2Output) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ScheduledQueryRulesAlertV2) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (o EciScalingConfigurationOutput) ContainerGroupName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *EciScalingConfiguration) pulumi.StringPtrOutput { return v.ContainerGroupName }).(pulumi.StringPtrOutput)\n}", "func (*StackCollection) GetNodeGroupName(s *Stack) string {\n\tif tagName := GetNodegroupTagName(s.Tags); tagName != \"\" {\n\t\treturn tagName\n\t}\n\tif strings.HasSuffix(*s.StackName, \"-nodegroup-0\") {\n\t\treturn \"legacy-nodegroup-0\"\n\t}\n\tif strings.HasSuffix(*s.StackName, \"-DefaultNodeGroup\") {\n\t\treturn \"legacy-default\"\n\t}\n\treturn \"\"\n}", "func (o DataCollectionRuleOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DataCollectionRule) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (c *AzureModelContext) NameForApplicationSecurityGroupNodes() string {\n\treturn kops.InstanceGroupRoleNode.ToLowerString() + \"s.\" + c.ClusterName()\n}", "func (s *LBSpec) ResourceGroupName() string {\n\treturn s.ResourceGroup\n}", "func (o ExpressRoutePortAuthorizationOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ExpressRoutePortAuthorization) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (o FederatedIdentityCredentialOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *FederatedIdentityCredential) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (o PolicyFileShareOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *PolicyFileShare) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (o RouteFilterOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *RouteFilter) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (s *NICSpec) ResourceGroupName() string {\n\treturn s.ResourceGroup\n}", "func (si *ServiceInformation) GetGroupName() string {\n\treturn fmt.Sprintf(\"%s-group\", si.ServiceName)\n}", "func (o TopicRuleCloudwatchLogOutput) LogGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleCloudwatchLog) string { return v.LogGroupName }).(pulumi.StringOutput)\n}", "func (o RunBookOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *RunBook) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (o EciScalingConfigurationOutput) ScalingGroupId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *EciScalingConfiguration) pulumi.StringOutput { return v.ScalingGroupId }).(pulumi.StringOutput)\n}", "func (o FirewallNetworkRuleCollectionOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *FirewallNetworkRuleCollection) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (o EciScalingConfigurationOutput) ScalingConfigurationName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *EciScalingConfiguration) pulumi.StringOutput { return v.ScalingConfigurationName }).(pulumi.StringOutput)\n}", "func (o TopicRuleErrorActionCloudwatchLogsOutput) LogGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleErrorActionCloudwatchLogs) string { return v.LogGroupName }).(pulumi.StringOutput)\n}", "func (o *ApplianceGroupOpStatus) GetGroupName() string {\n\tif o == nil || o.GroupName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.GroupName\n}", "func (o ThingGroupOutput) ParentGroupName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ThingGroup) pulumi.StringPtrOutput { return v.ParentGroupName }).(pulumi.StringPtrOutput)\n}", "func BaseGroupName() string {\n\treturn baseGroupName\n}", "func BaseGroupName() string {\n\treturn baseGroupName\n}", "func (o ClusterOutput) ParameterGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Cluster) pulumi.StringOutput { return v.ParameterGroupName }).(pulumi.StringOutput)\n}", "func (o SecurityGroupIngressOutput) SecurityGroupName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v SecurityGroupIngress) *string { return v.SecurityGroupName }).(pulumi.StringPtrOutput)\n}", "func (impl *ServerServerGroup) ResourceName() string {\n\treturn \"server-servergroup\"\n}", "func (o ClusterNodeGroupOptionsOutput) AutoScalingGroupTags() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v ClusterNodeGroupOptions) map[string]string { return v.AutoScalingGroupTags }).(pulumi.StringMapOutput)\n}", "func (o *ReservationModel) GetGroupName() string {\n\tif o == nil || o.GroupName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.GroupName\n}", "func (o InstanceGroupOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *InstanceGroup) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (o GroupPolicyOutput) GroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *GroupPolicy) pulumi.StringOutput { return v.GroupName }).(pulumi.StringOutput)\n}", "func GroupName() string {\n\treturn groupName\n}", "func (o ThingGroupMetadataOutput) ParentGroupName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ThingGroupMetadata) *string { return v.ParentGroupName }).(pulumi.StringPtrOutput)\n}", "func (m *LogicAppTriggerEndpointConfiguration) SetResourceGroupName(value *string)() {\n err := m.GetBackingStore().Set(\"resourceGroupName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (p StorageProvider) GroupName() string {\n\treturn servicecatalog.GroupName\n}", "func (client *Client) GetStatsGroupName() (s string) {\n\ts10 := strconv.FormatInt(int64(client.myUniqueID), 10)\n\treturn clientSideGroupPrefix + s10\n}", "func SetGroupName(name string) {\n\tgroupName = name\n}", "func (s *SubnetSpec) ResourceGroupName() string {\n\treturn s.VNetResourceGroup\n}", "func (c *AzureModelContext) NameForApplicationSecurityGroupControlPlane() string {\n\treturn kops.InstanceGroupRoleControlPlane.ToLowerString() + \".\" + c.ClusterName()\n}", "func (p *AWS) updateAutoScalingGroup(asgName string, ltName string) error {\n\tasgCli := autoscaling.New(p.session)\n\n\tparams := &autoscaling.UpdateAutoScalingGroupInput{\n\t\tAutoScalingGroupName: aws.String(asgName),\n\t\tLaunchTemplate: &autoscaling.LaunchTemplateSpecification{\n\t\t\tLaunchTemplateName: aws.String(ltName),\n\t\t\tVersion: aws.String(\"$Default\"),\n\t\t},\n\t}\n\n\tif _, err := asgCli.UpdateAutoScalingGroup(params); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (o ElastigroupScalingUpPolicyOutput) MetricName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingUpPolicy) string { return v.MetricName }).(pulumi.StringOutput)\n}", "func (o ResourceGroupOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ResourceGroup) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (asg *autoScalingGroup) resourcePath() string {\n\treturn autoscalingGroupResourcePath\n}", "func (o ElastigroupScalingTargetPolicyOutput) MetricName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingTargetPolicy) string { return v.MetricName }).(pulumi.StringOutput)\n}", "func (o ClusterNodeGroupOptionsPtrOutput) AutoScalingGroupTags() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *ClusterNodeGroupOptions) map[string]string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.AutoScalingGroupTags\n\t}).(pulumi.StringMapOutput)\n}", "func (as *AutoScaling) CreateAutoScalingGroup(ag AutoScalingGroup) (\n\tresp *AutoScalingGroupsResp, err error) {\n\tresp = &AutoScalingGroupsResp{}\n\tparams := makeParams(\"CreateAutoScalingGroup\")\n\tparams[\"AutoScalingGroupName\"] = ag.AutoScalingGroupName\n\tparams[\"MaxSize\"] = strconv.FormatInt(ag.MaxSize, 10)\n\tparams[\"MinSize\"] = strconv.FormatInt(ag.MinSize, 10)\n\tparams[\"LaunchConfigurationName\"] = ag.LaunchConfigurationName\n\taddParamsList(params, \"AvailabilityZones.member\", ag.AvailabilityZones)\n\tif len(ag.LoadBalancerNames) > 0 {\n\t\taddParamsList(params, \"LoadBalancerNames.member\", ag.LoadBalancerNames)\n\t}\n\tif ag.DefaultCooldown > 0 {\n\t\tparams[\"DefaultCooldown\"] = strconv.FormatInt(ag.DefaultCooldown, 10)\n\t}\n\tif ag.DesiredCapacity > 0 {\n\t\tparams[\"DesiredCapacity\"] = strconv.FormatInt(ag.DesiredCapacity, 10)\n\t}\n\tif ag.HealthCheckGracePeriod > 0 {\n\t\tparams[\"HealthCheckGracePeriod\"] = strconv.FormatInt(ag.HealthCheckGracePeriod, 10)\n\t}\n\tif ag.HealthCheckType == \"ELB\" {\n\t\tparams[\"HealthCheckType\"] = ag.HealthCheckType\n\t}\n\tif len(ag.VPCZoneIdentifier) > 0 {\n\t\tparams[\"VPCZoneIdentifier\"] = ag.VPCZoneIdentifier\n\t}\n\tif len(ag.TerminationPolicies) > 0 {\n\t\taddParamsList(params, \"TerminationPolicies.member\", ag.TerminationPolicies)\n\t}\n\t// TODO(JP) : Implement Tags\n\t//if len(ag.Tags) > 0 {\n\t//\taddParamsList(params, \"Tags\", ag.Tags)\n\t//}\n\n\terr = as.query(params, resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}", "func (o ElastigroupScalingDownPolicyOutput) MetricName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingDownPolicy) string { return v.MetricName }).(pulumi.StringOutput)\n}", "func (as *AutoScaling) UpdateAutoScalingGroup(ag AutoScalingGroup) (resp *SimpleResp, err error) {\n\tresp = &SimpleResp{}\n\tparams := makeParams(\"UpdateAutoScalingGroup\")\n\tparams[\"AutoScalingGroupName\"] = ag.AutoScalingGroupName\n\taddParamsList(params, \"AvailabilityZones.member\", ag.AvailabilityZones)\n\tif ag.DefaultCooldown > 0 {\n\t\tparams[\"DefaultCooldown\"] = strconv.FormatInt(ag.DefaultCooldown, 10)\n\t}\n\tparams[\"DesiredCapacity\"] = strconv.FormatInt(ag.DesiredCapacity, 10)\n\tif ag.HealthCheckGracePeriod > 0 {\n\t\tparams[\"HealthCheckGracePeriod\"] = strconv.FormatInt(ag.HealthCheckGracePeriod, 10)\n\t}\n\tif ag.HealthCheckType == \"ELB\" {\n\t\tparams[\"HealthCheckType\"] = ag.HealthCheckType\n\t}\n\tparams[\"LaunchConfigurationName\"] = ag.LaunchConfigurationName\n\tif ag.MaxSize > 0 {\n\t\tparams[\"MaxSize\"] = strconv.FormatInt(ag.MaxSize, 10)\n\t}\n\tif ag.MinSize > 0 {\n\t\tparams[\"MinSize\"] = strconv.FormatInt(ag.MinSize, 10)\n\t}\n\tif len(ag.TerminationPolicies) > 0 {\n\t\taddParamsList(params, \"TerminationPolicies.member\", ag.TerminationPolicies)\n\t}\n\tif len(ag.VPCZoneIdentifier) > 0 {\n\t\tparams[\"VPCZoneIdentifier\"] = ag.VPCZoneIdentifier\n\t}\n\terr = as.query(params, resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}", "func ServiceName(instanceGroupName string) string {\n\treturn names.Sanitize(instanceGroupName)\n}", "func Convert(cfg Config, name string) AutoScaleGroup {\n\treturn AutoScaleGroup{\n\t\tName: name,\n\t\tMetricsCalculatePeriod: cfg.MetricsCalculatePeriod,\n\t\tScaleUpThreshold: cfg.ScaleUpThreshold,\n\t\tScaleDownThreshold: cfg.ScaleDownThreshold,\n\t\tLabelSelector: cfg.LabelSelector,\n\t\tMetricSource: MetricSource{\n\t\t\tType: cfg.MetricSource,\n\t\t\tCacheExpireTime: cfg.MetricCacheExpireTime,\n\t\t},\n\t\tProvisioner: Provisioner{\n\t\t\tType: cfg.BackendProvsioner,\n\t\t\tMaxNodeNum: cfg.MaxNodeNum,\n\t\t\tMinNodeNum: cfg.MinNodeNum,\n\t\t\tRancherAnnotationNamespace: cfg.RancherAnnotationNamespace,\n\t\t\tRancherNodePoolNamePrefix: cfg.RancherNodePoolNamePrefix,\n\t\t},\n\t\tAlarmWindow: cfg.AlarmWindow,\n\t\tAlarmCoolDown: cfg.AlarmCoolDown,\n\t\tAlarmCancelWindow: cfg.AlarmCancelWindow,\n\t\tMaxBackendFailure: cfg.MaxBackendFailure,\n\t\tScaleUpTimeout: cfg.ScaleUpTimeout,\n\t}\n}", "func (group *ResourceGroup) AzureName() string {\n\treturn group.Spec.AzureName\n}", "func (group *ResourceGroup) AzureName() string {\n\treturn group.Spec.AzureName\n}", "func GetGroupName(inputGroup string) (string, error) {\n\tu, err := user.Current()\n\tif err == nil {\n\t\t//Only root could specify a filter username\n\t\tif u.Username == \"root\" {\n\t\t\tif inputGroup == \"\" {\n\t\t\t\treturn \"\", nil\n\t\t\t} else {\n\t\t\t\treturn inputGroup, nil\n\t\t\t}\n\t\t} else {\n\t\t\tif inputGroup != \"\" {\n\t\t\t\tvar err = errors.New(\"Only root could specify -g groupname!\")\n\t\t\t\treturn \"\", err\n\t\t\t} else {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", err\n}", "func (o PowerBIOutputDataSourceOutput) GroupName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v PowerBIOutputDataSource) *string { return v.GroupName }).(pulumi.StringPtrOutput)\n}", "func GenerateGroupName(affixes ...string) string {\n\t// go1.10+\n\t// import strings\n\t// var b strings.Builder\n\t// b.WriteString(BaseGroupName())\n\tb := bytes.NewBufferString(BaseGroupName())\n\tb.WriteRune('-')\n\tfor _, affix := range affixes {\n\t\tb.WriteString(affix)\n\t\tb.WriteRune('-')\n\t}\n\treturn randname.GenerateWithPrefix(b.String(), 5)\n}", "func (o *IgroupCreateRequest) InitiatorGroupName() string {\n\tvar r string\n\tif o.InitiatorGroupNamePtr == nil {\n\t\treturn r\n\t}\n\tr = *o.InitiatorGroupNamePtr\n\treturn r\n}", "func (c *AzureModelContext) NameForResourceGroup() string {\n\treturn c.Cluster.AzureResourceGroupName()\n}", "func (c *NodeGroup) generateName() string {\n\treturn fmt.Sprintf(\"%s-%s\", strings.ReplaceAll(c.Name, \" \", \"-\"), uuid.NewString()[:8])\n}", "func (o ClusterNodeGroupOptionsOutput) KeyName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ClusterNodeGroupOptions) *string { return v.KeyName }).(pulumi.StringPtrOutput)\n}", "func k8sObjectName(doc *yaml.Node) (string, error) {\n\t// iterate over content\n\tit := yit.FromNode(doc.Content[0]).\n\t\t// Access nested 'metadata' attribute\n\t\tValuesForMap(\n\t\t\tyit.WithStringValue(\"metadata\"),\n\t\t\tyit.WithKind(yaml.MappingNode),\n\t\t).\n\t\t// Access nested 'name' attribute\n\t\tValuesForMap(\n\t\t\tyit.WithStringValue(\"name\"),\n\t\t\tyit.StringValue,\n\t\t)\n\n\t// no need to iterate in a loop here, the StringValue predicate\n\t// guarantees we get a single node\n\tnode, ok := it()\n\tif !ok || node.Value == \"\" {\n\t\treturn \"\", errors.New(\"missing metadata.name attribute\")\n\t}\n\n\treturn node.Value, nil\n}", "func (o GetServerGroupsGroupOutput) ServerGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetServerGroupsGroup) string { return v.ServerGroupName }).(pulumi.StringOutput)\n}", "func getClusterNameLabel() string {\n\tkey := fmt.Sprintf(\"%s/cluster-name\", getCAPIGroup())\n\treturn key\n}", "func (c *MetricsController) enqueueAutoscalingGroup(obj interface{}) {\n\tvar key string\n\tvar err error\n\tif key, err = cache.MetaNamespaceKeyFunc(obj); err != nil {\n\t\tlog.Errorf(\"Error enqueueing AutoscalingGroup: %s\", err)\n\t\treturn\n\t}\n\tlog.Debugf(\"%s: added %q to workqueue\", metricsControllerName, key)\n\tc.workqueue.AddRateLimited(key)\n}", "func (c *Config) GetServiceGroupName() []string {\n\tvar sgNames []string\n\tfor _, conf := range c.Server.PortList {\n\t\tsgNames = append(sgNames, conf.SGName)\n\t}\n\treturn sgNames\n}", "func (o IopingSpecPodConfigPodSchedulingOutput) NodeName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v IopingSpecPodConfigPodScheduling) *string { return v.NodeName }).(pulumi.StringPtrOutput)\n}", "func getNodeGroupMinSizeAnnotationKey() string {\n\tkey := fmt.Sprintf(\"%s/cluster-api-autoscaler-node-group-min-size\", getCAPIGroup())\n\treturn key\n}", "func (o ClusterNodeGroupOptionsPtrOutput) KeyName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ClusterNodeGroupOptions) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.KeyName\n\t}).(pulumi.StringPtrOutput)\n}" ]
[ "0.8316761", "0.81702137", "0.81702137", "0.7956318", "0.7528973", "0.6624974", "0.6509952", "0.6492119", "0.64409494", "0.6380685", "0.63749176", "0.6328928", "0.6293692", "0.62818784", "0.6260782", "0.6259074", "0.6155628", "0.61387604", "0.6136681", "0.6133578", "0.6118592", "0.6118592", "0.6113121", "0.61064464", "0.6096331", "0.6094867", "0.6078801", "0.60758823", "0.6066118", "0.60476804", "0.6036825", "0.60232246", "0.6012241", "0.5953067", "0.59328675", "0.59196645", "0.5873696", "0.58605534", "0.58545434", "0.58535403", "0.580262", "0.5784259", "0.5778458", "0.57749647", "0.5739479", "0.5726185", "0.56889844", "0.5673523", "0.5632783", "0.5632402", "0.5601914", "0.55997974", "0.55653673", "0.5558279", "0.5557798", "0.5529827", "0.5529827", "0.5513578", "0.5513063", "0.55071247", "0.55001265", "0.54794556", "0.54700315", "0.54553956", "0.5442162", "0.54335445", "0.54189956", "0.54052514", "0.5381845", "0.534948", "0.53439456", "0.53430957", "0.53379303", "0.5318069", "0.5286595", "0.52686334", "0.52602637", "0.5248336", "0.5238893", "0.5234697", "0.5218304", "0.5212431", "0.52103263", "0.5191399", "0.5191399", "0.51862025", "0.5182744", "0.5182515", "0.51771164", "0.51553565", "0.5149567", "0.51393664", "0.51373565", "0.5134691", "0.51320344", "0.5126059", "0.5081447", "0.50748545", "0.5073571", "0.5070929" ]
0.8134883
3
SecurityGroupID returns the security group ID that should be used to create Load Balancers.
func (a *Adapter) SecurityGroupID() string { return a.manifest.securityGroup.id }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Canary) GetCanaryLoadBalancerSecurityGroup(region schemas.RegionConfig) (*string, error) {\n\tclient, err := selectClientFromList(c.AWSClients, region.Region)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnewLBName := c.GenerateCanaryLBSecurityGroupName(region.Region)\n\n\tgroupID, err := client.EC2Service.GetSecurityGroup(newLBName)\n\tif err != nil {\n\t\tc.Logger.Warn(err.Error())\n\t\treturn nil, nil\n\t}\n\n\tc.Logger.Debugf(\"Found existing lb security group id: %s\", *groupID)\n\n\treturn groupID, nil\n}", "func NewSecurityGroup() *SecurityGroup {\n\tthis := SecurityGroup{}\n\treturn &this\n}", "func (m *Group) GetSecurityIdentifier()(*string) {\n return m.securityIdentifier\n}", "func createSecurityGroup(client ec2iface.EC2API, vpcID, clusterName string) (string, error) {\n\tvar securityGroupID string\n\n\tnewSecurityGroupName := resourceNamePrefix + clusterName\n\tcsgOut, err := client.CreateSecurityGroup(&ec2.CreateSecurityGroupInput{\n\t\tVpcId: &vpcID,\n\t\tGroupName: aws.String(newSecurityGroupName),\n\t\tDescription: aws.String(fmt.Sprintf(\"Security group for the Kubernetes cluster %s\", clusterName)),\n\t})\n\tif err != nil {\n\t\tif awsErr, ok := err.(awserr.Error); !ok || awsErr.Code() != \"InvalidGroup.Duplicate\" {\n\t\t\treturn \"\", fmt.Errorf(\"failed to create security group %s: %v\", newSecurityGroupName, err)\n\t\t}\n\t\tdescribeOut, err := client.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{\n\t\t\tFilters: []*ec2.Filter{{\n\t\t\t\tName: aws.String(\"group-name\"),\n\t\t\t\tValues: []*string{aws.String(newSecurityGroupName)}}},\n\t\t})\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to get security group after creation failed because the group already existed: %v\", err)\n\t\t}\n\t\tif n := len(describeOut.SecurityGroups); n != 1 {\n\t\t\treturn \"\", fmt.Errorf(\"expected to get exactly one security group after create failed because the group already existed, got %d\", n)\n\t\t}\n\n\t\tsecurityGroupID = aws.StringValue(describeOut.SecurityGroups[0].GroupId)\n\t}\n\tif csgOut != nil && csgOut.GroupId != nil {\n\t\tsecurityGroupID = *csgOut.GroupId\n\t}\n\tklog.V(2).Infof(\"Security group %s for cluster %s created with id %s.\", newSecurityGroupName, clusterName, securityGroupID)\n\n\t// Add permissions.\n\t_, err = client.AuthorizeSecurityGroupIngress(&ec2.AuthorizeSecurityGroupIngressInput{\n\t\tGroupId: aws.String(securityGroupID),\n\t\tIpPermissions: []*ec2.IpPermission{\n\t\t\t(&ec2.IpPermission{}).\n\t\t\t\t// all protocols from within the sg\n\t\t\t\tSetIpProtocol(\"-1\").\n\t\t\t\tSetUserIdGroupPairs([]*ec2.UserIdGroupPair{\n\t\t\t\t\t(&ec2.UserIdGroupPair{}).\n\t\t\t\t\t\tSetGroupId(securityGroupID),\n\t\t\t\t}),\n\t\t\t(&ec2.IpPermission{}).\n\t\t\t\t// tcp:22 from everywhere\n\t\t\t\tSetIpProtocol(\"tcp\").\n\t\t\t\tSetFromPort(provider.DefaultSSHPort).\n\t\t\t\tSetToPort(provider.DefaultSSHPort).\n\t\t\t\tSetIpRanges([]*ec2.IpRange{\n\t\t\t\t\t{CidrIp: aws.String(\"0.0.0.0/0\")},\n\t\t\t\t}),\n\t\t\t(&ec2.IpPermission{}).\n\t\t\t\t// ICMP from/to everywhere\n\t\t\t\tSetIpProtocol(\"icmp\").\n\t\t\t\tSetFromPort(-1). // any port\n\t\t\t\tSetToPort(-1). // any port\n\t\t\t\tSetIpRanges([]*ec2.IpRange{\n\t\t\t\t\t{CidrIp: aws.String(\"0.0.0.0/0\")},\n\t\t\t\t}),\n\t\t\t(&ec2.IpPermission{}).\n\t\t\t\t// ICMPv6 from/to everywhere\n\t\t\t\tSetIpProtocol(\"icmpv6\").\n\t\t\t\tSetFromPort(-1). // any port\n\t\t\t\tSetToPort(-1). // any port\n\t\t\t\tSetIpv6Ranges([]*ec2.Ipv6Range{\n\t\t\t\t\t{CidrIpv6: aws.String(\"::/0\")},\n\t\t\t\t}),\n\t\t},\n\t})\n\tif err != nil {\n\t\tif awsErr, ok := err.(awserr.Error); !ok || awsErr.Code() != \"InvalidPermission.Duplicate\" {\n\t\t\treturn \"\", fmt.Errorf(\"failed to authorize security group %s with id %s: %v\", newSecurityGroupName, securityGroupID, err)\n\t\t}\n\t}\n\n\treturn securityGroupID, nil\n}", "func (o SecurityGroupRuleOutput) SecurityGroupRuleId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *SecurityGroupRule) pulumi.StringOutput { return v.SecurityGroupRuleId }).(pulumi.StringOutput)\n}", "func (c *Canary) CreateCanaryLBSecurityGroup(tg *elbv2.TargetGroup, region schemas.RegionConfig) (*string, error) {\n\tclient, err := selectClientFromList(c.AWSClients, region.Region)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlbSGName := c.GenerateCanaryLBSecurityGroupName(region.Region)\n\n\tduplicated := false\n\tgroupID, err := client.EC2Service.CreateSecurityGroup(lbSGName, tg.VpcId)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok && aerr.Code() == \"InvalidGroup.Duplicate\" {\n\t\t\tc.Logger.Debugf(\"Security group is already created: %s\", lbSGName)\n\t\t\tduplicated = true\n\t\t}\n\t\tif !duplicated {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif duplicated {\n\t\tgroupID, err = client.EC2Service.GetSecurityGroup(lbSGName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tc.Logger.Debugf(\"Found existing security group id: %s\", *groupID)\n\t}\n\n\t// inbound\n\tif err := client.EC2Service.UpdateInboundRules(*groupID, \"tcp\", \"0.0.0.0/0\", \"inbound from internet\", 80, 80); err != nil {\n\t\tc.Logger.Warn(err.Error())\n\t}\n\n\t// outbound\n\tif err := client.EC2Service.UpdateOutboundRules(*groupID, \"-1\", \"0.0.0.0/0\", \"outbound to internet\", -1, -1); err != nil {\n\t\tc.Logger.Warn(err.Error())\n\t}\n\n\treturn groupID, nil\n}", "func (o *SecurityGroup) GetSecurityGroupId() string {\n\tif o == nil || o.SecurityGroupId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.SecurityGroupId\n}", "func (o EcsLaunchTemplateOutput) SecurityGroupId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *EcsLaunchTemplate) pulumi.StringPtrOutput { return v.SecurityGroupId }).(pulumi.StringPtrOutput)\n}", "func (o SecurityGroupIngressOutput) SecurityGroupId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v SecurityGroupIngress) *string { return v.SecurityGroupId }).(pulumi.StringPtrOutput)\n}", "func ExampleRDS_CreateDBSecurityGroup_shared00() {\n\tsvc := rds.New(session.New())\n\tinput := &rds.CreateDBSecurityGroupInput{\n\t\tDBSecurityGroupDescription: aws.String(\"My DB security group\"),\n\t\tDBSecurityGroupName: aws.String(\"mydbsecuritygroup\"),\n\t}\n\n\tresult, err := svc.CreateDBSecurityGroup(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.ErrCodeDBSecurityGroupAlreadyExistsFault:\n\t\t\t\tfmt.Println(rds.ErrCodeDBSecurityGroupAlreadyExistsFault, aerr.Error())\n\t\t\tcase rds.ErrCodeDBSecurityGroupQuotaExceededFault:\n\t\t\t\tfmt.Println(rds.ErrCodeDBSecurityGroupQuotaExceededFault, aerr.Error())\n\t\t\tcase rds.ErrCodeDBSecurityGroupNotSupportedFault:\n\t\t\t\tfmt.Println(rds.ErrCodeDBSecurityGroupNotSupportedFault, aerr.Error())\n\t\t\tdefault:\n\t\t\t\tfmt.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\tfmt.Println(err.Error())\n\t\t}\n\t\treturn\n\t}\n\n\tfmt.Println(result)\n}", "func (instance *Host) DisableSecurityGroup(ctx context.Context, sgInstance resources.SecurityGroup) (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.InvalidParameterError(\"ctx\", \"cannot be nil\")\n\t}\n\tif sgInstance == nil {\n\t\treturn fail.InvalidParameterError(\"sgInstance\", \"cannot be nil\")\n\t}\n\n\tsgName := sgInstance.GetName()\n\tsgID, err := sgInstance.GetID()\n\tif err != nil {\n\t\treturn fail.ConvertError(err)\n\t}\n\n\thid, err := instance.GetID()\n\tif err != nil {\n\t\treturn fail.ConvertError(err)\n\t}\n\n\tsvc := instance.Service()\n\txerr := instance.Alter(ctx, func(_ data.Clonable, props *serialize.JSONProperties) fail.Error {\n\t\treturn props.Alter(hostproperty.SecurityGroupsV1, func(clonable data.Clonable) fail.Error {\n\t\t\thsgV1, ok := clonable.(*propertiesv1.HostSecurityGroups)\n\t\t\tif !ok {\n\t\t\t\treturn fail.InconsistentError(\"'*propertiesv1.HostSecurityGroups' expected, '%s' provided\", reflect.TypeOf(clonable).String())\n\t\t\t}\n\n\t\t\tvar asg *abstract.SecurityGroup\n\t\t\txerr := sgInstance.Inspect(ctx, func(clonable data.Clonable, _ *serialize.JSONProperties) fail.Error {\n\t\t\t\tvar ok bool\n\t\t\t\tif asg, ok = clonable.(*abstract.SecurityGroup); !ok {\n\t\t\t\t\treturn fail.InconsistentError(\"'*abstract.SecurityGroup' expected, '%s' provided\", reflect.TypeOf(clonable).String())\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\txerr = debug.InjectPlannedFail(xerr)\n\t\t\tif xerr != nil {\n\t\t\t\treturn xerr\n\t\t\t}\n\n\t\t\t// First check if the security group is not already registered for the Host with the exact same state\n\t\t\tvar found bool\n\t\t\tfor k := range hsgV1.ByID {\n\t\t\t\tif k == asg.ID {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\treturn fail.NotFoundError(\"security group '%s' is not bound to Host '%s'\", sgName, sgID)\n\t\t\t}\n\n\t\t\t{\n\t\t\t\t// Bind the security group on provider side; if security group not binded, considered as a success\n\t\t\t\txerr = svc.UnbindSecurityGroupFromHost(ctx, asg, hid)\n\t\t\t\txerr = debug.InjectPlannedFail(xerr)\n\t\t\t\tif xerr != nil {\n\t\t\t\t\tswitch xerr.(type) {\n\t\t\t\t\tcase *fail.ErrNotFound:\n\t\t\t\t\t\tdebug.IgnoreError2(ctx, xerr)\n\t\t\t\t\t\t// continue\n\t\t\t\t\tdefault:\n\t\t\t\t\t\treturn xerr\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// found, update properties\n\t\t\thsgV1.ByID[asg.ID].Disabled = true\n\t\t\treturn nil\n\t\t})\n\t})\n\tif xerr != nil {\n\t\treturn xerr\n\t}\n\n\treturn nil\n}", "func GetSecurityGroup(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *SecurityGroupState, opts ...pulumi.ResourceOption) (*SecurityGroup, error) {\n\tvar resource SecurityGroup\n\terr := ctx.ReadResource(\"aws:elasticache/securityGroup:SecurityGroup\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (o *FiltersVmGroup) GetSecurityGroupIds() []string {\n\tif o == nil || o.SecurityGroupIds == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.SecurityGroupIds\n}", "func (s *SubnetListener) BindSecurityGroup(inctx context.Context, in *protocol.SecurityGroupSubnetBindRequest) (empty *googleprotobuf.Empty, err error) {\n\tdefer fail.OnExitConvertToGRPCStatus(inctx, &err)\n\tdefer fail.OnExitLogError(inctx, &err)\n\tdefer fail.OnExitWrapError(inctx, &err, \"cannot bind Security Group to Subnet\")\n\n\tempty = &googleprotobuf.Empty{}\n\tif s == nil {\n\t\treturn empty, fail.InvalidInstanceError()\n\t}\n\tif in == nil {\n\t\treturn empty, fail.InvalidParameterError(\"in\", \"cannot be nil\")\n\t}\n\tif inctx == nil {\n\t\treturn empty, fail.InvalidParameterError(\"inctx\", \"cannot be nil\")\n\t}\n\n\tnetworkRef, _ := srvutils.GetReference(in.GetNetwork())\n\tsubnetRef, _ := srvutils.GetReference(in.GetSubnet())\n\tif subnetRef == \"\" {\n\t\treturn empty, fail.InvalidRequestError(\"neither name nor id given as reference for Subnet\")\n\t}\n\n\tsgRef, _ := srvutils.GetReference(in.GetGroup())\n\tif sgRef == \"\" {\n\t\treturn empty, fail.InvalidRequestError(\"neither name nor id given as reference for Security Group\")\n\t}\n\n\tjob, xerr := PrepareJob(inctx, in.GetNetwork().GetTenantId(), fmt.Sprintf(\"/network/%s/subnet/%s/securitygroup/%s/bind\", networkRef, subnetRef, sgRef))\n\tif xerr != nil {\n\t\treturn empty, xerr\n\t}\n\tdefer job.Close()\n\n\tvar enable resources.SecurityGroupActivation\n\tswitch in.GetState() {\n\tcase protocol.SecurityGroupState_SGS_DISABLED:\n\t\tenable = resources.SecurityGroupDisable\n\tdefault:\n\t\tenable = resources.SecurityGroupEnable\n\t}\n\n\thandler := handlers.NewSubnetHandler(job)\n\treturn empty, handler.BindSecurityGroup(networkRef, subnetRef, sgRef, enable)\n}", "func (o GetLoadBalancersBalancerOutput) SecurityGroupIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetLoadBalancersBalancer) []string { return v.SecurityGroupIds }).(pulumi.StringArrayOutput)\n}", "func (provider *ResourceProvider) SecurityGroup(id string) (*reachAWS.SecurityGroup, error) {\n\tinput := &ec2.DescribeSecurityGroupsInput{\n\t\tGroupIds: []*string{\n\t\t\taws.String(id),\n\t\t},\n\t}\n\tresult, err := provider.ec2.DescribeSecurityGroups(input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = ensureSingleResult(len(result.SecurityGroups), \"security group\", id); err != nil {\n\t\treturn nil, err\n\t}\n\n\tsecurityGroup := newSecurityGroupFromAPI(result.SecurityGroups[0])\n\treturn &securityGroup, nil\n}", "func (o EciScalingConfigurationOutput) SecurityGroupId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *EciScalingConfiguration) pulumi.StringPtrOutput { return v.SecurityGroupId }).(pulumi.StringPtrOutput)\n}", "func (o SecurityGroupRuleOutput) SecurityGroupId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *SecurityGroupRule) pulumi.StringOutput { return v.SecurityGroupId }).(pulumi.StringOutput)\n}", "func (c *Client) GetSecurityGroup(ctx context.Context, zone, id string) (*SecurityGroup, error) {\n\tresp, err := c.GetSecurityGroupWithResponse(ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsecurityGroup := securityGroupFromAPI(resp.JSON200)\n\tsecurityGroup.c = c\n\tsecurityGroup.zone = zone\n\n\treturn securityGroup, nil\n}", "func (o *FiltersSecurityGroup) GetSecurityGroupIds() []string {\n\tif o == nil || o.SecurityGroupIds == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.SecurityGroupIds\n}", "func (s *Service) CreateOrUpdateNetworkSecurityGroup(resourceGroupName string, networkSecurityGroupName string, location string) (*armada.SecurityGroupsCreateOrUpdateFuture, error) {\n\t//JEB if networkSecurityGroupName == \"\" {\n\t//JEB networkSecurityGroupName = SecurityGroupDefaultName\n\t//JEB }\n\t//JEB sshInbound := armada.SecurityRule{\n\t//JEB Name: to.StringPtr(\"ClusterAPISSH\"),\n\t//JEB SecurityRulePropertiesFormat: &armada.SecurityRulePropertiesFormat{\n\t//JEB Protocol: armada.SecurityRuleProtocolTCP,\n\t//JEB SourcePortRange: to.StringPtr(\"*\"),\n\t//JEB DestinationPortRange: to.StringPtr(\"22\"),\n\t//JEB SourceAddressPrefix: to.StringPtr(\"*\"),\n\t//JEB DestinationAddressPrefix: to.StringPtr(\"*\"),\n\t//JEB Priority: to.Int32Ptr(1000),\n\t//JEB Direction: armada.SecurityRuleDirectionInbound,\n\t//JEB Access: armada.SecurityRuleAccessAllow,\n\t//JEB },\n\t//JEB }\n\t//JEB\n\t//JEB kubernetesInbound := armada.SecurityRule{\n\t//JEB Name: to.StringPtr(\"KubernetesAPI\"),\n\t//JEB SecurityRulePropertiesFormat: &armada.SecurityRulePropertiesFormat{\n\t//JEB Protocol: armada.SecurityRuleProtocolTCP,\n\t//JEB SourcePortRange: to.StringPtr(\"*\"),\n\t//JEB DestinationPortRange: to.StringPtr(\"6443\"),\n\t//JEB SourceAddressPrefix: to.StringPtr(\"*\"),\n\t//JEB DestinationAddressPrefix: to.StringPtr(\"*\"),\n\t//JEB Priority: to.Int32Ptr(1001),\n\t//JEB Direction: armada.SecurityRuleDirectionInbound,\n\t//JEB Access: armada.SecurityRuleAccessAllow,\n\t//JEB },\n\t//JEB }\n\t//JEB\n\t//JEB securityGroupProperties := armada.SecurityGroupPropertiesFormat{\n\t//JEB SecurityRules: &[]armada.SecurityRule{sshInbound, kubernetesInbound},\n\t//JEB }\n\t//JEB securityGroup := armada.SecurityGroup{\n\t//JEB Location: to.StringPtr(location),\n\t//JEB SecurityGroupPropertiesFormat: &securityGroupProperties,\n\t//JEB }\n\t//JEB sgFuture, err := s.scope.AirshipClients.SecurityGroups.CreateOrUpdate(s.scope.Context, resourceGroupName, networkSecurityGroupName, securityGroup)\n\t//JEB if err != nil {\n\t//JEB return nil, err\n\t//JEB }\n\t//JEB return &sgFuture, nil\n\treturn &armada.SecurityGroupsCreateOrUpdateFuture{}, nil\n}", "func NewSecurityGroup(ctx *pulumi.Context,\n\tname string, args *SecurityGroupArgs, opts ...pulumi.ResourceOption) (*SecurityGroup, error) {\n\tif args == nil || args.SecurityGroupNames == nil {\n\t\treturn nil, errors.New(\"missing required argument 'SecurityGroupNames'\")\n\t}\n\tif args == nil {\n\t\targs = &SecurityGroupArgs{}\n\t}\n\tif args.Description == nil {\n\t\targs.Description = pulumi.StringPtr(\"Managed by Pulumi\")\n\t}\n\tvar resource SecurityGroup\n\terr := ctx.RegisterResource(\"aws:elasticache/securityGroup:SecurityGroup\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (net *NetworkComponentInput) CreateSecurityGroup(con aws.EstablishConnectionInput) (NetworkComponentResponse, error) {\n\n\tec2, seserr := con.EstablishConnection()\n\tif seserr != nil {\n\t\treturn NetworkComponentResponse{}, seserr\n\t}\n\tsecurity, secerr := ec2.CreateSecurityGroup(\n\t\t&aws.CreateNetworkInput{\n\t\t\tVpcId: net.VpcIds[0],\n\t\t\tName: net.Name + \"_sec\",\n\t\t},\n\t)\n\tif secerr != nil {\n\t\treturn NetworkComponentResponse{}, secerr\n\t}\n\n\tsctags := new(Tag)\n\tsctags.Resource = *security.GroupId\n\tsctags.Name = \"Name\"\n\tsctags.Value = net.Name + \"_sec\"\n\t_, sctagerr := sctags.CreateTags(con)\n\tif sctagerr != nil {\n\t\treturn NetworkComponentResponse{}, sctagerr\n\t}\n\n\t//creating egree and ingres rules for the security group which I created just now\n\tfor _, port := range net.Ports {\n\t\tintport, _ := strconv.ParseInt(port, 10, 64)\n\t\tingreserr := ec2.CreateIngressRule(\n\t\t\t&aws.IngressEgressInput{\n\t\t\t\tPort: intport,\n\t\t\t\tSecId: *security.GroupId,\n\t\t\t},\n\t\t)\n\t\tif ingreserr != nil {\n\t\t\treturn NetworkComponentResponse{}, ingreserr\n\t\t}\n\t}\n\tegreserr := ec2.CreateEgressRule(\n\t\t&aws.IngressEgressInput{\n\t\t\tSecId: *security.GroupId,\n\t\t},\n\t)\n\tif egreserr != nil {\n\t\treturn NetworkComponentResponse{}, egreserr\n\t}\n\n\tif net.GetRaw == true {\n\t\treturn NetworkComponentResponse{CreateSecurityRaw: security}, nil\n\t}\n\treturn NetworkComponentResponse{SecGroupIds: []string{*security.GroupId}}, nil\n}", "func CreateSecurityGroup(s resources.SecurityGroup) {\n\tdir, err := ioutil.TempDir(\"\", \"simple-security-group\")\n\tExpect(err).ToNot(HaveOccurred())\n\tdefer os.RemoveAll(dir)\n\n\ttempfile := filepath.Join(dir, \"security-group.json\")\n\n\tsecurityGroup, err := json.Marshal(s.Rules)\n\tExpect(err).ToNot(HaveOccurred())\n\n\terr = ioutil.WriteFile(tempfile, securityGroup, 0666)\n\tExpect(err).ToNot(HaveOccurred())\n\tEventually(CF(\"create-security-group\", s.Name, tempfile)).Should(Exit(0))\n}", "func (s *ServerLaunchConfiguration) SetSecurityGroup(v string) *ServerLaunchConfiguration {\n\ts.SecurityGroup = &v\n\treturn s\n}", "func (s *HostListener) DisableSecurityGroup(ctx context.Context, in *protocol.SecurityGroupHostBindRequest) (empty *googleprotobuf.Empty, err error) {\n\tdefer fail.OnExitConvertToGRPCStatus(&err)\n\tdefer fail.OnExitWrapError(&err, \"cannot disable security group on host\")\n\tdefer fail.OnPanic(&err)\n\n\tempty = &googleprotobuf.Empty{}\n\tif s == nil {\n\t\treturn empty, fail.InvalidInstanceError()\n\t}\n\tif in == nil {\n\t\treturn empty, fail.InvalidParameterError(\"in\", \"cannot be nil\")\n\t}\n\tif ctx == nil {\n\t\treturn empty, 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\thostRef, hostRefLabel := srvutils.GetReference(in.GetHost())\n\tif hostRef == \"\" {\n\t\treturn empty, fail.InvalidRequestError(\"neither name nor id given as reference of host\")\n\t}\n\n\tsgRef, sgRefLabel := srvutils.GetReference(in.GetGroup())\n\tif sgRef == \"\" {\n\t\treturn empty, fail.InvalidRequestError(\"neither name nor id given as reference of Security Group\")\n\t}\n\n\tjob, xerr := PrepareJob(ctx, in.GetHost().GetTenantId(), fmt.Sprintf(\"/host/%s/securitygroup/%s/disable\", hostRef, sgRef))\n\tif xerr != nil {\n\t\treturn empty, xerr\n\t}\n\tdefer job.Close()\n\n\ttracer := debug.NewTracer(job.Task(), tracing.ShouldTrace(\"listeners.host\"), \"(%s, %s)\", hostRefLabel, sgRefLabel).WithStopwatch().Entering()\n\tdefer tracer.Exiting()\n\tdefer fail.OnExitLogError(&err, tracer.TraceMessage())\n\n\thostInstance, xerr := hostfactory.Load(job.Service(), hostRef)\n\tif xerr != nil {\n\t\tswitch xerr.(type) {\n\t\tcase *fail.ErrNotFound:\n\t\t\t// considered as a success\n\t\t\tdebug.IgnoreError(xerr)\n\t\t\treturn empty, nil\n\t\tdefault:\n\t\t\treturn empty, xerr\n\t\t}\n\t}\n\n\tdefer hostInstance.Released()\n\n\tsgInstance, xerr := securitygroupfactory.Load(job.Service(), sgRef)\n\tif xerr != nil {\n\t\tswitch xerr.(type) {\n\t\tcase *fail.ErrNotFound:\n\t\t\t// considered as a success\n\t\t\tdebug.IgnoreError(xerr)\n\t\t\treturn empty, nil\n\t\tdefault:\n\t\t\treturn empty, xerr\n\t\t}\n\t}\n\n\tdefer sgInstance.Released()\n\n\tif xerr = hostInstance.DisableSecurityGroup(job.Context(), sgInstance); xerr != nil {\n\t\tswitch xerr.(type) {\n\t\tcase *fail.ErrNotFound:\n\t\t\t// considered as a success\n\t\t\tdebug.IgnoreError(xerr)\n\t\t\treturn empty, nil\n\t\tdefault:\n\t\t\treturn empty, xerr\n\t\t}\n\t}\n\n\treturn empty, nil\n}", "func (c *Canary) GetEC2CanarySecurityGroup(tg *elbv2.TargetGroup, region schemas.RegionConfig, lbSg *string, completeCanary bool) error {\n\tclient, err := selectClientFromList(c.AWSClients, region.Region)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnewSGName := c.GenerateCanarySecurityGroupName(region.Region)\n\n\tif completeCanary {\n\t\tgroupID, err := client.EC2Service.GetSecurityGroup(newSGName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.Deployer.SecurityGroup[region.Region] = groupID\n\t\tc.Logger.Debugf(\"Found existing security group id: %s\", *groupID)\n\n\t\treturn nil\n\t}\n\n\tduplicated := false\n\tgroupID, err := client.EC2Service.CreateSecurityGroup(newSGName, tg.VpcId)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok && aerr.Code() == \"InvalidGroup.Duplicate\" {\n\t\t\tc.Logger.Debugf(\"Security group is already created: %s\", newSGName)\n\t\t\tduplicated = true\n\t\t}\n\n\t\tif !duplicated {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif duplicated {\n\t\tgroupID, err = client.EC2Service.GetSecurityGroup(newSGName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.Logger.Debugf(\"Found existing security group id: %s\", *groupID)\n\t} else if err := client.EC2Service.UpdateOutboundRules(*groupID, \"-1\", \"0.0.0.0/0\", \"outbound to internet\", -1, -1); err != nil {\n\t\tc.Logger.Warn(err.Error())\n\t}\n\n\t// inbound\n\tif err := client.EC2Service.UpdateInboundRulesWithGroup(*groupID, \"tcp\", \"Allow access from canary load balancer\", lbSg, *tg.Port, *tg.Port); err != nil {\n\t\tc.Logger.Warn(err.Error())\n\t}\n\n\tc.Deployer.SecurityGroup[region.Region] = groupID\n\tc.Logger.Debugf(\"Security group for this canary deployment: %s\", *groupID)\n\n\treturn nil\n}", "func (s *HostListener) BindSecurityGroup(ctx context.Context, in *protocol.SecurityGroupHostBindRequest) (empty *googleprotobuf.Empty, err error) {\n\tdefer fail.OnExitConvertToGRPCStatus(&err)\n\tdefer fail.OnExitWrapError(&err, \"cannot bind Security Group to Host\")\n\tdefer fail.OnPanic(&err)\n\n\tempty = &googleprotobuf.Empty{}\n\tif s == nil {\n\t\treturn empty, fail.InvalidInstanceError()\n\t}\n\tif in == nil {\n\t\treturn empty, fail.InvalidParameterError(\"in\", \"cannot be nil\")\n\t}\n\tif ctx == nil {\n\t\treturn empty, 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\thostRef, hostRefLabel := srvutils.GetReference(in.GetHost())\n\tif hostRef == \"\" {\n\t\treturn empty, fail.InvalidRequestError(\"neither name nor id given as reference for Host\")\n\t}\n\n\tsgRef, sgRefLabel := srvutils.GetReference(in.GetGroup())\n\tif hostRef == \"\" {\n\t\treturn empty, fail.InvalidRequestError(\"neither name nor id given as reference for Security Group\")\n\t}\n\n\tjob, xerr := PrepareJob(ctx, in.GetGroup().GetTenantId(), fmt.Sprintf(\"/host/%s/securitygroup/%s/bind\", hostRef, sgRef))\n\tif xerr != nil {\n\t\treturn empty, xerr\n\t}\n\tdefer job.Close()\n\n\ttracer := debug.NewTracer(job.Task(), tracing.ShouldTrace(\"listeners.host\"), \"(%s, %s)\", hostRefLabel, sgRefLabel).WithStopwatch().Entering()\n\tdefer tracer.Exiting()\n\tdefer fail.OnExitLogError(&err, tracer.TraceMessage())\n\n\thostInstance, xerr := hostfactory.Load(job.Service(), hostRef)\n\tif xerr != nil {\n\t\treturn empty, xerr\n\t}\n\n\tdefer hostInstance.Released()\n\n\tsgInstance, xerr := securitygroupfactory.Load(job.Service(), sgRef)\n\tif xerr != nil {\n\t\treturn empty, xerr\n\t}\n\n\tdefer sgInstance.Released()\n\n\tvar enable resources.SecurityGroupActivation\n\tswitch in.GetState() {\n\tcase protocol.SecurityGroupState_SGS_DISABLED:\n\t\tenable = resources.SecurityGroupDisable\n\tdefault:\n\t\tenable = resources.SecurityGroupEnable\n\t}\n\n\tif xerr = hostInstance.BindSecurityGroup(job.Context(), sgInstance, enable); xerr != nil {\n\t\treturn empty, xerr\n\t}\n\treturn empty, nil\n}", "func NewSecurityGroup(name string, protocol string, destination string, ports *string, description *string) resources.SecurityGroup {\n\treturn resources.SecurityGroup{\n\t\tName: name,\n\t\tRules: []resources.Rule{{\n\t\t\tProtocol: protocol,\n\t\t\tDestination: destination,\n\t\t\tPorts: ports,\n\t\t\tDescription: description,\n\t\t}},\n\t}\n}", "func CreateNetworkSecurityGroup(ctx context.Context, nsgName string) (nsg network.SecurityGroup, err error) {\n\tnsgClient := getNsgClient()\n\tfuture, err := nsgClient.CreateOrUpdate(\n\t\tctx,\n\t\tconfig.GroupName(),\n\t\tnsgName,\n\t\tnetwork.SecurityGroup{\n\t\t\tLocation: to.StringPtr(config.Location()),\n\t\t\tSecurityGroupPropertiesFormat: &network.SecurityGroupPropertiesFormat{\n\t\t\t\tSecurityRules: &[]network.SecurityRule{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: to.StringPtr(\"allow_ssh\"),\n\t\t\t\t\t\tSecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{\n\t\t\t\t\t\t\tProtocol: network.SecurityRuleProtocolTCP,\n\t\t\t\t\t\t\tSourceAddressPrefix: to.StringPtr(\"0.0.0.0/0\"),\n\t\t\t\t\t\t\tSourcePortRange: to.StringPtr(\"1-65535\"),\n\t\t\t\t\t\t\tDestinationAddressPrefix: to.StringPtr(\"0.0.0.0/0\"),\n\t\t\t\t\t\t\tDestinationPortRange: to.StringPtr(\"22\"),\n\t\t\t\t\t\t\tAccess: network.SecurityRuleAccessAllow,\n\t\t\t\t\t\t\tDirection: network.SecurityRuleDirectionInbound,\n\t\t\t\t\t\t\tPriority: to.Int32Ptr(100),\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\tName: to.StringPtr(\"allow_https\"),\n\t\t\t\t\t\tSecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{\n\t\t\t\t\t\t\tProtocol: network.SecurityRuleProtocolTCP,\n\t\t\t\t\t\t\tSourceAddressPrefix: to.StringPtr(\"0.0.0.0/0\"),\n\t\t\t\t\t\t\tSourcePortRange: to.StringPtr(\"1-65535\"),\n\t\t\t\t\t\t\tDestinationAddressPrefix: to.StringPtr(\"0.0.0.0/0\"),\n\t\t\t\t\t\t\tDestinationPortRange: to.StringPtr(\"443\"),\n\t\t\t\t\t\t\tAccess: network.SecurityRuleAccessAllow,\n\t\t\t\t\t\t\tDirection: network.SecurityRuleDirectionInbound,\n\t\t\t\t\t\t\tPriority: to.Int32Ptr(200),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t)\n\n\tif err != nil {\n\t\treturn nsg, fmt.Errorf(\"cannot create nsg: %v\", err)\n\t}\n\n\terr = future.WaitForCompletion(ctx, nsgClient.Client)\n\tif err != nil {\n\t\treturn nsg, fmt.Errorf(\"cannot get nsg create or update future response: %v\", err)\n\t}\n\n\treturn future.Result(nsgClient)\n}", "func (o SecurityGroupRuleOutput) SourceSecurityGroupId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *SecurityGroupRule) pulumi.StringOutput { return v.SourceSecurityGroupId }).(pulumi.StringOutput)\n}", "func (m SecurityListRequest) GetSecurityID() (v string, err quickfix.MessageRejectError) {\n\tvar f field.SecurityIDField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func (s *SubnetListener) DisableSecurityGroup(inctx context.Context, in *protocol.SecurityGroupSubnetBindRequest) (empty *googleprotobuf.Empty, err error) {\n\tdefer fail.OnExitConvertToGRPCStatus(inctx, &err)\n\tdefer fail.OnExitLogError(inctx, &err)\n\tdefer fail.OnExitWrapError(inctx, &err, \"cannot disable Security Group of Subnet\")\n\n\tempty = &googleprotobuf.Empty{}\n\tif s == nil {\n\t\treturn empty, fail.InvalidInstanceError()\n\t}\n\tif in == nil {\n\t\treturn empty, fail.InvalidParameterError(\"in\", \"cannot be nil\")\n\t}\n\tif inctx == nil {\n\t\treturn empty, fail.InvalidParameterError(\"inctx\", \"cannot be nil\")\n\t}\n\n\tnetworkRef, _ := srvutils.GetReference(in.GetNetwork())\n\tsubnetRef, _ := srvutils.GetReference(in.GetSubnet())\n\tif subnetRef == \"\" {\n\t\treturn empty, fail.InvalidRequestError(\"neither name nor id given as reference for Subnet\")\n\t}\n\n\tsgRef, _ := srvutils.GetReference(in.GetGroup())\n\tif sgRef == \"\" {\n\t\treturn empty, fail.InvalidRequestError(\"neither name nor id given as reference of Security Group\")\n\t}\n\n\tjob, xerr := PrepareJob(inctx, in.GetNetwork().GetTenantId(), fmt.Sprintf(\"/network/%s/subnet/%s/securitygroup/%s/disable\", networkRef, subnetRef, sgRef))\n\tif xerr != nil {\n\t\treturn empty, xerr\n\t}\n\tdefer job.Close()\n\n\thandler := handlers.NewSubnetHandler(job)\n\treturn empty, handler.DisableSecurityGroup(networkRef, subnetRef, sgRef)\n}", "func (c *ALIModelContext) LinkToSecurityGroup(role kops.InstanceGroupRole) *alitasks.SecurityGroup {\n\treturn &alitasks.SecurityGroup{Name: s(c.GetNameForSecurityGroup(role))}\n}", "func (c *Canary) DeleteLBSecurityGroup(region schemas.RegionConfig) error {\n\tif c.LBSecurityGroup[region.Region] == nil {\n\t\tc.Logger.Debugf(\"No lb security group to delete\")\n\t\treturn nil\n\t}\n\n\tclient, err := selectClientFromList(c.AWSClients, region.Region)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.Logger.Debug(\"Wait 30 seconds until load balancer is successfully terminated\")\n\ttime.Sleep(30 * time.Second)\n\n\tretry := int64(4)\n\tfor {\n\t\terr = client.EC2Service.DeleteSecurityGroup(*c.LBSecurityGroup[region.Region])\n\t\tif err != nil {\n\t\t\tif retry > 0 {\n\t\t\t\tretry--\n\t\t\t\tc.Logger.Debugf(\"error occurred on lb deletion and remained retry count is %d\", retry)\n\t\t\t\ttime.Sleep(time.Duration(1+5*(3-retry)) * time.Second)\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tc.Logger.Debugf(\"Delete load balancer security group: %s\", *c.LBSecurityGroup[region.Region])\n\n\treturn nil\n}", "func (o *SecurityGroup) GetNetId() string {\n\tif o == nil || o.NetId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.NetId\n}", "func (v *SubnetValidator) SubnetID() ids.ID {\n\treturn v.Subnet\n}", "func NewSecurityGroupCollector(logger log.Logger, client *scw.Client, failures *prometheus.CounterVec, duration *prometheus.HistogramVec, cfg config.Target) *SecurityGroupCollector {\n\tif failures != nil {\n\t\tfailures.WithLabelValues(\"security_group\").Add(0)\n\t}\n\n\tlabels := []string{\"id\", \"name\", \"zone\", \"org\", \"project\"}\n\tcollector := &SecurityGroupCollector{\n\t\tclient: client,\n\t\tinstance: instance.NewAPI(client),\n\t\tlogger: log.With(logger, \"collector\", \"security_group\"),\n\t\tfailures: failures,\n\t\tduration: duration,\n\t\tconfig: cfg,\n\n\t\tDefined: prometheus.NewDesc(\n\t\t\t\"scw_security_group_defined\",\n\t\t\t\"Constant value of 1 that this security group is defined\",\n\t\t\tlabels,\n\t\t\tnil,\n\t\t),\n\t\tEnableDefault: prometheus.NewDesc(\n\t\t\t\"scw_security_group_enable_default\",\n\t\t\t\"1 if the security group is enabled by default, 0 otherwise\",\n\t\t\tlabels,\n\t\t\tnil,\n\t\t),\n\t\tProjectDefault: prometheus.NewDesc(\n\t\t\t\"scw_security_group_project_default\",\n\t\t\t\"1 if the security group is an project default, 0 otherwise\",\n\t\t\tlabels,\n\t\t\tnil,\n\t\t),\n\t\tStateful: prometheus.NewDesc(\n\t\t\t\"scw_security_group_stateful\",\n\t\t\t\"1 if the security group is stateful by default, 0 otherwise\",\n\t\t\tlabels,\n\t\t\tnil,\n\t\t),\n\t\tInboundDefault: prometheus.NewDesc(\n\t\t\t\"scw_security_group_inbound_default_policy\",\n\t\t\t\"1 if the security group inbound default policy is accept, 0 otherwise\",\n\t\t\tlabels,\n\t\t\tnil,\n\t\t),\n\t\tOutboundDefault: prometheus.NewDesc(\n\t\t\t\"scw_security_group_outbound_default_policy\",\n\t\t\t\"1 if the security group outbound default policy is accept, 0 otherwise\",\n\t\t\tlabels,\n\t\t\tnil,\n\t\t),\n\t\tServers: prometheus.NewDesc(\n\t\t\t\"scw_security_group_servers_count\",\n\t\t\t\"Number of servers attached to the security group\",\n\t\t\tlabels,\n\t\t\tnil,\n\t\t),\n\t\tCreated: prometheus.NewDesc(\n\t\t\t\"scw_security_group_created_timestamp\",\n\t\t\t\"Timestamp when the security group have been created\",\n\t\t\tlabels,\n\t\t\tnil,\n\t\t),\n\t\tModified: prometheus.NewDesc(\n\t\t\t\"scw_security_group_modified_timestamp\",\n\t\t\t\"Timestamp when the security group have been modified\",\n\t\t\tlabels,\n\t\t\tnil,\n\t\t),\n\t}\n\n\tif cfg.Org != \"\" {\n\t\tcollector.org = scw.StringPtr(cfg.Org)\n\t}\n\n\tif cfg.Project != \"\" {\n\t\tcollector.project = scw.StringPtr(cfg.Project)\n\t}\n\n\treturn collector\n}", "func (in *SecurityGroup) DeepCopy() *SecurityGroup {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SecurityGroup)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func GetSecurityGroupInfo(sess *session.Session) (*ec2.DescribeSecurityGroupsOutput, error) {\n // snippet-start:[ec2.go.describe_security_groups.call]\n svc := ec2.New(sess)\n\n result, err := svc.DescribeSecurityGroups(nil)\n // snippet-end:[ec2.go.describe_security_groups.call]\n if err != nil {\n return nil, err\n }\n\n return result, nil\n}", "func (o ClusterNodeAttributeOutput) SecurityGroupId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ClusterNodeAttribute) string { return v.SecurityGroupId }).(pulumi.StringOutput)\n}", "func SecurityGroupByID(conn *ec2.EC2, id string) (*ec2.SecurityGroup, error) {\n\treq := &ec2.DescribeSecurityGroupsInput{\n\t\tGroupIds: aws.StringSlice([]string{id}),\n\t}\n\tresult, err := conn.DescribeSecurityGroups(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif result == nil || len(result.SecurityGroups) == 0 || result.SecurityGroups[0] == nil {\n\t\treturn nil, nil\n\t}\n\n\treturn result.SecurityGroups[0], nil\n}", "func (m SecurityListRequest) SetSecurityID(v string) {\n\tm.Set(field.NewSecurityID(v))\n}", "func (m CrossOrderCancelReplaceRequest) GetSecurityID() (v string, err quickfix.MessageRejectError) {\n\tvar f field.SecurityIDField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func (m *Group) SetSecurityIdentifier(value *string)() {\n m.securityIdentifier = value\n}", "func (o *VirtualMachineToAlternativeRestoreOptions) GetNetworkSecurityGroupId() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.NetworkSecurityGroupId\n}", "func CreateNetworkSecurityGroupRule() {}", "func (sv *ContrailTypeLogicService) DeleteSecurityGroup(\n\tctx context.Context, request *services.DeleteSecurityGroupRequest) (\n\tresponse *services.DeleteSecurityGroupResponse, err error) {\n\n\tuuid := request.ID\n\n\terr = sv.InTransactionDoer.DoInTransaction(ctx, func(ctx context.Context) error {\n\t\tvar getResponse *services.GetSecurityGroupResponse\n\t\tif getResponse, err = sv.ReadService.GetSecurityGroup(ctx, &services.GetSecurityGroupRequest{\n\t\t\tID: uuid,\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsg := getResponse.GetSecurityGroup()\n\n\t\t// TODO: handle configured security group ID\n\t\tif err = sv.deallocateSecurityGroupID(ctx, sg.SecurityGroupID); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tresponse, err = sv.BaseService.DeleteSecurityGroup(ctx, request)\n\t\treturn err\n\t})\n\n\treturn response, err\n}", "func (o EnvironmentNetworkConfigurationOutput) SecurityGroupIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v EnvironmentNetworkConfiguration) []string { return v.SecurityGroupIds }).(pulumi.StringArrayOutput)\n}", "func NewGetSecurityGroupRequest(server string, id string) (*http.Request, error) {\n\tvar err error\n\n\tvar pathParam0 string\n\n\tpathParam0, err = runtime.StyleParam(\"simple\", false, \"id\", id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tqueryUrl, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbasePath := fmt.Sprintf(\"/security-group/%s\", pathParam0)\n\tif basePath[0] == '/' {\n\t\tbasePath = basePath[1:]\n\t}\n\n\tqueryUrl, err = queryUrl.Parse(basePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"GET\", queryUrl.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn req, nil\n}", "func GetSecurityGroupConfig(s *ec2.SecurityGroup) []AWSResourceConfig {\n\tcf := SecurityGroupConfig{\n\t\tConfig: Config{\n\t\t\tName: s.GroupName,\n\t\t\tTags: s.Tags,\n\t\t},\n\t\tGroupName: s.GroupName,\n\t\tGroupDescription: s.GroupDescription,\n\t}\n\n\tingresses := make([]IngressEgress, 0)\n\tfor _, i := range s.SecurityGroupIngress {\n\t\tingress := IngressEgress{\n\t\t\tIPProtocol: i.IpProtocol,\n\t\t\tDescription: i.Description,\n\t\t\tCidrIP: []string{i.CidrIp},\n\t\t\tCidrIpv6: []string{i.CidrIpv6},\n\t\t\tFromPort: i.FromPort,\n\t\t\tToPort: i.ToPort,\n\t\t}\n\t\tingresses = append(ingresses, ingress)\n\t}\n\tcf.SecurityGroupIngress = ingresses\n\n\tegresses := make([]IngressEgress, 0)\n\tfor _, e := range s.SecurityGroupEgress {\n\t\tegress := IngressEgress{\n\t\t\tIPProtocol: e.IpProtocol,\n\t\t\tDescription: e.Description,\n\t\t\tCidrIP: []string{e.CidrIp},\n\t\t\tCidrIpv6: []string{e.CidrIpv6},\n\t\t\tFromPort: e.FromPort,\n\t\t\tToPort: e.ToPort,\n\t\t}\n\t\tegresses = append(egresses, egress)\n\t}\n\tcf.SecurityGroupEgress = egresses\n\n\treturn []AWSResourceConfig{{\n\t\tResource: cf,\n\t\tMetadata: s.AWSCloudFormationMetadata,\n\t}}\n}", "func (o StudioOutput) WorkspaceSecurityGroupId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Studio) pulumi.StringOutput { return v.WorkspaceSecurityGroupId }).(pulumi.StringOutput)\n}", "func (o *SecurityGroup) SetSecurityGroupId(v string) {\n\to.SecurityGroupId = &v\n}", "func (o *SecurityGroup) GetSecurityGroupName() string {\n\tif o == nil || o.SecurityGroupName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.SecurityGroupName\n}", "func dataSourceSecurityGroupAttributes(d *schema.ResourceData, data map[string]interface{}) error {\n security_group_id := data[\"id\"].(string)\n log.Printf(\"[DEBUG] Retrieved twcc_security_group: %s\", security_group_id)\n\n d.SetId(security_group_id)\n d.Set(\"name\", data[\"name\"])\n security_group_rules := flattenSecurityGroupRulesInfo(data[\"security_group_rules\"].([]interface{}))\n d.Set(\"security_group_rules\", security_group_rules)\n\n return nil\n}", "func (sv *ContrailTypeLogicService) CreateSecurityGroup(\n\tctx context.Context, request *services.CreateSecurityGroupRequest) (\n\tresponse *services.CreateSecurityGroupResponse, err error) {\n\n\tsg := request.SecurityGroup\n\n\tif err = sv.disallowManualSecurityGroupID(nil, sg, nil); err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = sv.InTransactionDoer.DoInTransaction(ctx, func(ctx context.Context) error {\n\t\terr = sg.GetSecurityGroupEntries().CheckSecurityGroupRules()\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to check Policy Rules\")\n\t\t}\n\t\tsg.SecurityGroupEntries.FillRuleUUIDs()\n\t\t// TODO: handle configured security group ID\n\t\tif sg.SecurityGroupID, err = sv.allocateSecurityGroupID(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif response, err = sv.BaseService.CreateSecurityGroup(ctx, request); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n\n\treturn response, err\n}", "func (m CrossOrderCancelReplaceRequest) SetSecurityID(v string) {\n\tm.Set(field.NewSecurityID(v))\n}", "func DeleteSecurityGroup(s resources.SecurityGroup) {\n\tif s.Name == \"\" {\n\t\tfmt.Println(\"Empty security group name. Skipping deletion.\")\n\t\treturn\n\t}\n\tEventually(CF(\"delete-security-group\", s.Name, \"-f\")).Should(Exit(0))\n}", "func dataSourceIBMIsSecurityGroupsID(d *schema.ResourceData) string {\n\treturn time.Now().UTC().String()\n}", "func (instance *Host) EnableSecurityGroup(ctx context.Context, sg resources.SecurityGroup) (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.InvalidParameterError(\"ctx\", \"cannot be nil\")\n\t}\n\tif sg == nil {\n\t\treturn fail.InvalidParameterError(\"sg\", \"cannot be null value of 'SecurityGroup'\")\n\t}\n\n\thid, err := instance.GetID()\n\tif err != nil {\n\t\treturn fail.ConvertError(err)\n\t}\n\n\tsgName := sg.GetName()\n\n\t// instance.Lock()\n\t// defer instance.Unlock()\n\n\tsvc := instance.Service()\n\txerr := instance.Alter(ctx, func(_ data.Clonable, props *serialize.JSONProperties) fail.Error {\n\t\treturn props.Inspect(hostproperty.SecurityGroupsV1, func(clonable data.Clonable) fail.Error {\n\t\t\thsgV1, ok := clonable.(*propertiesv1.HostSecurityGroups)\n\t\t\tif !ok {\n\t\t\t\treturn fail.InconsistentError(\"'*propertiesv1.HostSecurityGroups' expected, '%s' provided\", reflect.TypeOf(clonable).String())\n\t\t\t}\n\n\t\t\tvar asg *abstract.SecurityGroup\n\t\t\txerr := sg.Inspect(ctx, func(clonable data.Clonable, _ *serialize.JSONProperties) fail.Error {\n\t\t\t\tvar ok bool\n\t\t\t\tif asg, ok = clonable.(*abstract.SecurityGroup); !ok {\n\t\t\t\t\treturn fail.InconsistentError(\"'*abstract.SecurityGroup' expected, '%s' provided\", reflect.TypeOf(clonable).String())\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\txerr = debug.InjectPlannedFail(xerr)\n\t\t\tif xerr != nil {\n\t\t\t\treturn xerr\n\t\t\t}\n\n\t\t\t// First check if the security group is not already registered for the Host with the exact same state\n\t\t\tvar found bool\n\t\t\tfor k := range hsgV1.ByID {\n\t\t\t\tif k == asg.ID {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\treturn fail.NotFoundError(\"security group '%s' is not bound to Host '%s'\", sgName, hid)\n\t\t\t}\n\n\t\t\t{\n\t\t\t\t// Bind the security group on provider side; if already bound (*fail.ErrDuplicate), considered as a success\n\t\t\t\txerr = svc.BindSecurityGroupToHost(ctx, asg, hid)\n\t\t\t\txerr = debug.InjectPlannedFail(xerr)\n\t\t\t\tif xerr != nil {\n\t\t\t\t\tswitch xerr.(type) {\n\t\t\t\t\tcase *fail.ErrDuplicate:\n\t\t\t\t\t\tdebug.IgnoreError2(ctx, xerr)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\treturn xerr\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// found and updated, update metadata\n\t\t\thsgV1.ByID[asg.ID].Disabled = false\n\t\t\treturn nil\n\t\t})\n\t})\n\tif xerr != nil {\n\t\treturn xerr\n\t}\n\n\treturn nil\n}", "func (o EcsLaunchTemplateOutput) SecurityGroupIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *EcsLaunchTemplate) pulumi.StringArrayOutput { return v.SecurityGroupIds }).(pulumi.StringArrayOutput)\n}", "func NewSecurityGroupRule(ctx *pulumi.Context,\n\tname string, args *SecurityGroupRuleArgs, opts ...pulumi.ResourceOption) (*SecurityGroupRule, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.FromPort == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'FromPort'\")\n\t}\n\tif args.Protocol == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Protocol'\")\n\t}\n\tif args.SecurityGroupId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'SecurityGroupId'\")\n\t}\n\tif args.ToPort == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'ToPort'\")\n\t}\n\tif args.Type == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Type'\")\n\t}\n\tvar resource SecurityGroupRule\n\terr := ctx.RegisterResource(\"aws:ec2/securityGroupRule:SecurityGroupRule\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (o GetListenersListenerOutput) SecurityPolicyId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetListenersListener) string { return v.SecurityPolicyId }).(pulumi.StringOutput)\n}", "func (o ClusterManagedPrivateEndpointOutput) GroupId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ClusterManagedPrivateEndpoint) pulumi.StringOutput { return v.GroupId }).(pulumi.StringOutput)\n}", "func dataSourceIBMIsSecurityGroupRulesID(d *schema.ResourceData) string {\n\treturn time.Now().UTC().String()\n}", "func ExampleDeviceSecurityGroupsClient_Get() {\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\tclientFactory, err := armsecurity.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewDeviceSecurityGroupsClient().Get(ctx, \"subscriptions/20ff7fc3-e762-44dd-bd96-b71116dcdc23/resourceGroups/SampleRG/providers/Microsoft.Devices/iotHubs/sampleiothub\", \"samplesecuritygroup\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.DeviceSecurityGroup = armsecurity.DeviceSecurityGroup{\n\t// \tName: to.Ptr(\"samplesecuritygroup\"),\n\t// \tType: to.Ptr(\"Microsoft.Security/deviceSecurityGroups\"),\n\t// \tID: to.Ptr(\"/subscriptions/20ff7fc3-e762-44dd-bd96-b71116dcdc23/resourceGroups/SampleRG/providers/Microsoft.Devices/iotHubs/sampleiothub/providers/Microsoft.Security/deviceSecurityGroups/samplesecuritygroup\"),\n\t// \tProperties: &armsecurity.DeviceSecurityGroupProperties{\n\t// \t\tAllowlistRules: []armsecurity.AllowlistCustomAlertRuleClassification{\n\t// \t\t\t&armsecurity.ConnectionToIPNotAllowed{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when an outbound connection is created between your device and an ip that isn't allowed\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Outbound connection to an ip that isn't allowed\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"ConnectionToIpNotAllowed\"),\n\t// \t\t\t\tValueType: to.Ptr(armsecurity.ValueTypeIPCidr),\n\t// \t\t\t\tAllowlistValues: []*string{\n\t// \t\t\t\t},\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.LocalUserNotAllowed{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when a local user that isn't allowed logins to the device\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Login by a local user that isn't allowed\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"LocalUserNotAllowed\"),\n\t// \t\t\t\tValueType: to.Ptr(armsecurity.ValueTypeString),\n\t// \t\t\t\tAllowlistValues: []*string{\n\t// \t\t\t\t},\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.ProcessNotAllowed{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when a process that isn't allowed is executed\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Execution of a process that isn't allowed\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"ProcessNotAllowed\"),\n\t// \t\t\t\tValueType: to.Ptr(armsecurity.ValueTypeString),\n\t// \t\t\t\tAllowlistValues: []*string{\n\t// \t\t\t\t},\n\t// \t\t}},\n\t// \t\tDenylistRules: []*armsecurity.DenylistCustomAlertRule{\n\t// \t\t},\n\t// \t\tThresholdRules: []armsecurity.ThresholdCustomAlertRuleClassification{\n\t// \t\t},\n\t// \t\tTimeWindowRules: []armsecurity.TimeWindowCustomAlertRuleClassification{\n\t// \t\t\t&armsecurity.ActiveConnectionsNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of active connections of a device in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of active connections is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"ActiveConnectionsNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.AmqpC2DMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (AMQP protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of cloud to device messages (AMQP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"AmqpC2DMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.MqttC2DMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (MQTT protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of cloud to device messages (MQTT protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"MqttC2DMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.HTTPC2DMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (HTTP protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of cloud to device messages (HTTP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"HttpC2DMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.AmqpC2DRejectedMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (AMQP protocol) that were rejected by the device in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of rejected cloud to device messages (AMQP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"AmqpC2DRejectedMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.MqttC2DRejectedMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (MQTT protocol) that were rejected by the device in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of rejected cloud to device messages (MQTT protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"MqttC2DRejectedMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.HTTPC2DRejectedMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (HTTP protocol) that were rejected by the device in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of rejected cloud to device messages (HTTP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"HttpC2DRejectedMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.AmqpD2CMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of device to cloud messages (AMQP protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of device to cloud messages (AMQP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"AmqpD2CMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.MqttD2CMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of device to cloud messages (MQTT protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of device to cloud messages (MQTT protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"MqttD2CMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.HTTPD2CMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of device to cloud messages (HTTP protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of device to cloud messages (HTTP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"HttpD2CMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.DirectMethodInvokesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of direct method invokes in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of direct method invokes is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"DirectMethodInvokesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.FailedLocalLoginsNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of failed local logins on the device in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of failed local logins is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"FailedLocalLoginsNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.FileUploadsNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of file uploads from the device to the cloud in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of file uploads is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"FileUploadsNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.QueuePurgesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of device queue purges in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of device queue purges is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"QueuePurgesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.TwinUpdatesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of twin updates (by the device or the service) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of twin updates is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"TwinUpdatesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.UnauthorizedOperationsNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number unauthorized operations in the time window is not in the allowed range. Unauthorized operations are operations that affect the device (or done by it) that fail because of an unauthorized error\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of unauthorized operations is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"UnauthorizedOperationsNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t}},\n\t// \t},\n\t// }\n}", "func (s AwsRdsDbInstanceVpcSecurityGroup) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (c *Client) CreateSecurityGroup(ctx context.Context, zone string,\n\tsecurityGroup *SecurityGroup) (*SecurityGroup, error) {\n\tresp, err := c.CreateSecurityGroupWithResponse(ctx, papi.CreateSecurityGroupJSONRequestBody{\n\t\tDescription: &securityGroup.Description,\n\t\tName: securityGroup.Name,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := papi.NewPoller().\n\t\tWithTimeout(c.timeout).\n\t\tPoll(ctx, c.OperationPoller(zone, *resp.JSON200.Id))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.GetSecurityGroup(ctx, zone, *res.(*papi.Reference).Id)\n}", "func (o *CreateLoadBalancerRequest) GetSecurityGroups() []string {\n\tif o == nil || o.SecurityGroups == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.SecurityGroups\n}", "func ExampleRDS_DescribeDBSecurityGroups_shared00() {\n\tsvc := rds.New(session.New())\n\tinput := &rds.DescribeDBSecurityGroupsInput{\n\t\tDBSecurityGroupName: aws.String(\"mydbsecuritygroup\"),\n\t}\n\n\tresult, err := svc.DescribeDBSecurityGroups(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.ErrCodeDBSecurityGroupNotFoundFault:\n\t\t\t\tfmt.Println(rds.ErrCodeDBSecurityGroupNotFoundFault, aerr.Error())\n\t\t\tdefault:\n\t\t\t\tfmt.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\tfmt.Println(err.Error())\n\t\t}\n\t\treturn\n\t}\n\n\tfmt.Println(result)\n}", "func (o SecurityGroupIngressOutput) SecurityGroupName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v SecurityGroupIngress) *string { return v.SecurityGroupName }).(pulumi.StringPtrOutput)\n}", "func (o KubernetesClusterIngressApplicationGatewayOutput) SubnetId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v KubernetesClusterIngressApplicationGateway) *string { return v.SubnetId }).(pulumi.StringPtrOutput)\n}", "func (o GetKubernetesClusterIngressApplicationGatewayOutput) SubnetId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetKubernetesClusterIngressApplicationGateway) string { return v.SubnetId }).(pulumi.StringOutput)\n}", "func (o LoadBalancerFrontendIpConfigurationOutput) SubnetId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LoadBalancerFrontendIpConfiguration) *string { return v.SubnetId }).(pulumi.StringPtrOutput)\n}", "func (c *Client) DeleteSecurityGroup(ctx context.Context, zone, id string) error {\n\tresp, err := c.DeleteSecurityGroupWithResponse(apiv2.WithZone(ctx, zone), id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = papi.NewPoller().\n\t\tWithTimeout(c.timeout).\n\t\tPoll(ctx, c.OperationPoller(zone, *resp.JSON200.Id))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (o GetServerGroupsGroupOutput) ResourceGroupId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetServerGroupsGroup) string { return v.ResourceGroupId }).(pulumi.StringOutput)\n}", "func ExampleDeviceSecurityGroupsClient_CreateOrUpdate() {\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\tclientFactory, err := armsecurity.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewDeviceSecurityGroupsClient().CreateOrUpdate(ctx, \"subscriptions/20ff7fc3-e762-44dd-bd96-b71116dcdc23/resourceGroups/SampleRG/providers/Microsoft.Devices/iotHubs/sampleiothub\", \"samplesecuritygroup\", armsecurity.DeviceSecurityGroup{\n\t\tProperties: &armsecurity.DeviceSecurityGroupProperties{\n\t\t\tTimeWindowRules: []armsecurity.TimeWindowCustomAlertRuleClassification{\n\t\t\t\t&armsecurity.ActiveConnectionsNotInAllowedRange{\n\t\t\t\t\tIsEnabled: to.Ptr(true),\n\t\t\t\t\tRuleType: to.Ptr(\"ActiveConnectionsNotInAllowedRange\"),\n\t\t\t\t\tMaxThreshold: to.Ptr[int32](30),\n\t\t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t\t\t\t\tTimeWindowSize: to.Ptr(\"PT05M\"),\n\t\t\t\t}},\n\t\t},\n\t}, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.DeviceSecurityGroup = armsecurity.DeviceSecurityGroup{\n\t// \tName: to.Ptr(\"samplesecuritygroup\"),\n\t// \tType: to.Ptr(\"Microsoft.Security/deviceSecurityGroups\"),\n\t// \tID: to.Ptr(\"/subscriptions/20ff7fc3-e762-44dd-bd96-b71116dcdc23/resourceGroups/SampleRG/providers/Microsoft.Devices/iotHubs/sampleiothub/providers/Microsoft.Security/deviceSecurityGroups/samplesecuritygroup\"),\n\t// \tProperties: &armsecurity.DeviceSecurityGroupProperties{\n\t// \t\tAllowlistRules: []armsecurity.AllowlistCustomAlertRuleClassification{\n\t// \t\t\t&armsecurity.ConnectionToIPNotAllowed{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when an outbound connection is created between your device and an ip that isn't allowed\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Outbound connection to an ip that isn't allowed\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"ConnectionToIpNotAllowed\"),\n\t// \t\t\t\tAllowlistValues: []*string{\n\t// \t\t\t\t},\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.LocalUserNotAllowed{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when a local user that isn't allowed logins to the device\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Login by a local user that isn't allowed\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"LocalUserNotAllowed\"),\n\t// \t\t\t\tAllowlistValues: []*string{\n\t// \t\t\t\t},\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.ProcessNotAllowed{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when a process that isn't allowed is executed\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Execution of a process that isn't allowed\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"ProcessNotAllowed\"),\n\t// \t\t\t\tAllowlistValues: []*string{\n\t// \t\t\t\t},\n\t// \t\t}},\n\t// \t\tDenylistRules: []*armsecurity.DenylistCustomAlertRule{\n\t// \t\t},\n\t// \t\tThresholdRules: []armsecurity.ThresholdCustomAlertRuleClassification{\n\t// \t\t},\n\t// \t\tTimeWindowRules: []armsecurity.TimeWindowCustomAlertRuleClassification{\n\t// \t\t\t&armsecurity.ActiveConnectionsNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of active connections of a device in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of active connections is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(true),\n\t// \t\t\t\tRuleType: to.Ptr(\"ActiveConnectionsNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](30),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT05M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.AmqpC2DMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (AMQP protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of cloud to device messages (AMQP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"AmqpC2DMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.MqttC2DMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (MQTT protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of cloud to device messages (MQTT protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"MqttC2DMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.HTTPC2DMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (HTTP protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of cloud to device messages (HTTP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"HttpC2DMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.AmqpC2DRejectedMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (AMQP protocol) that were rejected by the device in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of rejected cloud to device messages (AMQP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"AmqpC2DRejectedMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.MqttC2DRejectedMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (MQTT protocol) that were rejected by the device in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of rejected cloud to device messages (MQTT protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"MqttC2DRejectedMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.HTTPC2DRejectedMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (HTTP protocol) that were rejected by the device in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of rejected cloud to device messages (HTTP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"HttpC2DRejectedMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.AmqpD2CMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of device to cloud messages (AMQP protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of device to cloud messages (AMQP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"AmqpD2CMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.MqttD2CMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of device to cloud messages (MQTT protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of device to cloud messages (MQTT protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"MqttD2CMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.HTTPD2CMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of device to cloud messages (HTTP protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of device to cloud messages (HTTP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"HttpD2CMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.DirectMethodInvokesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of direct method invokes in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of direct method invokes is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"DirectMethodInvokesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.FailedLocalLoginsNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of failed local logins on the device in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of failed local logins is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"FailedLocalLoginsNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.FileUploadsNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of file uploads from the device to the cloud in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of file uploads is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"FileUploadsNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.QueuePurgesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of device queue purges in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of device queue purges is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"QueuePurgesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.TwinUpdatesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of twin updates (by the device or the service) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of twin updates is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"TwinUpdatesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.UnauthorizedOperationsNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number unauthorized operations in the time window is not in the allowed range. Unauthorized operations are operations that affect the device (or done by it) that fail because of an unauthorized error\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of unauthorized operations is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"UnauthorizedOperationsNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t}},\n\t// \t},\n\t// }\n}", "func (o RegistryNetworkRuleSetVirtualNetworkOutput) SubnetId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RegistryNetworkRuleSetVirtualNetwork) string { return v.SubnetId }).(pulumi.StringOutput)\n}", "func (o LinkServiceNatIpConfigurationOutput) SubnetId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LinkServiceNatIpConfiguration) string { return v.SubnetId }).(pulumi.StringOutput)\n}", "func (c *MockAzureCloud) NetworkSecurityGroup() azure.NetworkSecurityGroupsClient {\n\treturn c.NetworkSecurityGroupsClient\n}", "func (a *Azure) DeleteNetworkSecurityGroup(ctx *lepton.Context, securityGroupID string) error {\n\tlogger := ctx.Logger()\n\n\tnsgClient, err := a.getNsgClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsecurityGroupName := getAzureResourceNameFromID(securityGroupID)\n\tsecurityGroup, err := nsgClient.Get(context.TODO(), a.groupName, securityGroupName, \"\")\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn errors.New(\"error getting network security group\")\n\t}\n\n\tif !hasAzureOpsTags(securityGroup.Tags) {\n\t\treturn errors.New(\"security group not created by ops\")\n\t} else if securityGroup.Subnets != nil && len(*securityGroup.Subnets) != 0 {\n\t\treturn errors.New(\"existing subnetworks are using this security group\")\n\t} else {\n\t\tlogger.Infof(\"Deleting %s...\", *securityGroup.ID)\n\t\tnsgTask, err := nsgClient.Delete(context.TODO(), a.groupName, *securityGroup.Name)\n\t\tif err != nil {\n\t\t\tlogger.Error(err)\n\t\t\treturn errors.New(\"failed deleting security group\")\n\t\t}\n\n\t\terr = nsgTask.WaitForCompletionRef(context.TODO(), nsgClient.Client)\n\t\tif err != nil {\n\t\t\tlogger.Error(err)\n\t\t\treturn errors.New(\"failed waiting for security group deletion\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func (o OceanOutput) SecurityGroupIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *Ocean) pulumi.StringArrayOutput { return v.SecurityGroupIds }).(pulumi.StringArrayOutput)\n}", "func (stg *securityTestGroup) testSecurityGroupCreateDelete() {\n\t// sg params\n\tsg := security.SecurityGroup{\n\t\tTypeMeta: api.TypeMeta{Kind: \"SecurityGroup\"},\n\t\tObjectMeta: api.ObjectMeta{\n\t\t\tTenant: \"default\",\n\t\t\tNamespace: \"default\",\n\t\t\tName: \"group1\",\n\t\t},\n\t\tSpec: security.SecurityGroupSpec{\n\t\t\tWorkloadSelector: labels.SelectorFromSet(labels.Set{\"env\": \"production\", \"app\": \"procurement\"}),\n\t\t},\n\t}\n\tvar securityGroupRestIf security.SecurityV1SecurityGroupInterface\n\tapiGwAddr := ts.tu.ClusterVIP + \":\" + globals.APIGwRESTPort\n\trestSvc, err := apiclient.NewRestAPIClient(apiGwAddr)\n\tif err == nil {\n\t\tBy(\"Creating SecurityGroup Client ------\")\n\t\tsecurityGroupRestIf = restSvc.SecurityV1().SecurityGroup()\n\t}\n\tExpect(err).ShouldNot(HaveOccurred())\n\tExpect(stg.securityRestIf).ShouldNot(Equal(nil))\n\n\tctx := ts.tu.MustGetLoggedInContext(context.Background())\n\t// create sg policy\n\tresp, err := securityGroupRestIf.Create(ctx, &sg)\n\tExpect(err).ShouldNot(HaveOccurred())\n\n\t// verify we can read the policy back\n\trsg, err := securityGroupRestIf.Get(ctx, &sg.ObjectMeta)\n\tExpect(err).ShouldNot(HaveOccurred())\n\tExpect(rsg).Should(Equal(resp))\n\n\t// verify agents have the policy\n\tEventually(func() bool {\n\t\tfor _, naplesIP := range ts.tu.NaplesNodeIPs {\n\t\t\tsglist, err := stg.getSecurityGroups(naplesIP)\n\t\t\tif err != nil {\n\t\t\t\tBy(fmt.Sprintf(\"ts:%s security group list failed, err: %+v sgs: %+v\", time.Now().String(), err, sglist))\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif (len(sglist) != 1) || (sglist[0].Name != sg.Name) {\n\t\t\t\tBy(fmt.Sprintf(\"ts:%s security group list has invalid items, security groups: %+v\", time.Now().String(), sglist))\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tBy(fmt.Sprintf(\"ts:%s security group list success, err: %+v sgs: %+v\", time.Now().String(), err, sglist))\n\t\t}\n\t\treturn true\n\t}, 30, 1).Should(BeTrue(), \"Failed to get security groups on netagent\")\n\n\t// delete the sg policy\n\tEventually(func() error {\n\t\t_, err = securityGroupRestIf.Delete(ctx, &sg.ObjectMeta)\n\t\treturn err\n\t}, 30, 1).ShouldNot(HaveOccurred())\n\n\t// verify policy is gone from the agents\n\tEventually(func() bool {\n\t\tfor _, naplesIP := range ts.tu.NaplesNodeIPs {\n\t\t\tsglist, err := stg.getSecurityGroups(naplesIP)\n\t\t\tif err != nil {\n\t\t\t\tBy(fmt.Sprintf(\"ts:%s security group list failed, err: %+v sgs: %+v\", time.Now().String(), err, sglist))\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif len(sglist) != 0 {\n\t\t\t\tBy(fmt.Sprintf(\"ts:%s security group list has invalid items, sg groups: %+v\", time.Now().String(), sglist))\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tBy(fmt.Sprintf(\"ts:%s security group list success, err: %+v sgs: %+v\", time.Now().String(), err, sglist))\n\t\t}\n\t\treturn true\n\t}, 30, 1).Should(BeTrue(), \"Failed to get security groups on netagent\")\n}", "func (c *Canary) DetachSecurityGroup(nis []*ec2.InstanceNetworkInterface, region schemas.RegionConfig, excludeSg string) error {\n\tclient, err := selectClientFromList(c.AWSClients, region.Region)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, ni := range nis {\n\t\tvar sgs []*string\n\t\tfor _, group := range ni.Groups {\n\t\t\tif *group.GroupId != excludeSg {\n\t\t\t\tsgs = append(sgs, group.GroupId)\n\t\t\t}\n\t\t}\n\t\tif len(sgs) > 0 {\n\t\t\terr = client.EC2Service.ModifyNetworkInterfaces(ni.NetworkInterfaceId, sgs)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tc.Logger.Debugf(\"Remove security group from eni: %s\", *ni.NetworkInterfaceId)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (*CreateSecurityGroupRequest) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_vpc_v1_security_group_service_proto_rawDescGZIP(), []int{3}\n}", "func (o GetLoadBalancersBalancerOutput) ResourceGroupId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetLoadBalancersBalancer) string { return v.ResourceGroupId }).(pulumi.StringOutput)\n}", "func (o KubernetesClusterApiServerAccessProfileOutput) SubnetId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v KubernetesClusterApiServerAccessProfile) *string { return v.SubnetId }).(pulumi.StringPtrOutput)\n}", "func (s *stack) BindSecurityGroupToSubnet(sgParam stacks.SecurityGroupParameter, subnetID string) fail.Error {\n\tif s == nil {\n\t\treturn fail.InvalidInstanceError()\n\t}\n\tif subnetID == \"\" {\n\t\treturn fail.InvalidParameterError(\"subnetID\", \"cannot be empty string\")\n\t}\n\n\treturn nil\n}", "func (s *SubnetListener) ListSecurityGroups(inctx context.Context, in *protocol.SecurityGroupSubnetBindRequest) (_ *protocol.SecurityGroupBondsResponse, err error) {\n\tdefer fail.OnExitConvertToGRPCStatus(inctx, &err)\n\tdefer fail.OnExitLogError(inctx, &err)\n\tdefer fail.OnExitWrapError(inctx, &err, \"cannot list Security Groups bound to Subnet\")\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 inctx == nil {\n\t\treturn nil, fail.InvalidParameterError(\"inctx\", \"cannot be nil\")\n\t}\n\n\tnetworkRef, _ := srvutils.GetReference(in.GetNetwork())\n\tsubnetRef, _ := srvutils.GetReference(in.GetSubnet())\n\tif subnetRef == \"\" {\n\t\treturn nil, fail.InvalidRequestError(\"neither name nor id given as reference for Subnet\")\n\t}\n\n\tjob, xerr := PrepareJob(inctx, in.GetNetwork().GetTenantId(), fmt.Sprintf(\"network/%s/subnet/%s/securitygroups/list\", networkRef, subnetRef))\n\tif xerr != nil {\n\t\treturn nil, xerr\n\t}\n\tdefer job.Close()\n\n\tstate := securitygroupstate.Enum(in.GetState())\n\n\thandler := handlers.NewSubnetHandler(job)\n\tbonds, xerr := handler.ListSecurityGroups(networkRef, subnetRef, state)\n\tif xerr != nil {\n\t\treturn nil, xerr\n\t}\n\n\tresp := converters.SecurityGroupBondsFromPropertyToProtocol(bonds, \"subnets\")\n\treturn resp, nil\n}", "func GetCspanID(ctx context.Context) (string, error) {\n\treturn getString(ctx, cspanIDKey)\n}", "func ExampleRDS_DeleteDBSecurityGroup_shared00() {\n\tsvc := rds.New(session.New())\n\tinput := &rds.DeleteDBSecurityGroupInput{\n\t\tDBSecurityGroupName: aws.String(\"mysecgroup\"),\n\t}\n\n\tresult, err := svc.DeleteDBSecurityGroup(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.ErrCodeInvalidDBSecurityGroupStateFault:\n\t\t\t\tfmt.Println(rds.ErrCodeInvalidDBSecurityGroupStateFault, aerr.Error())\n\t\t\tcase rds.ErrCodeDBSecurityGroupNotFoundFault:\n\t\t\t\tfmt.Println(rds.ErrCodeDBSecurityGroupNotFoundFault, aerr.Error())\n\t\t\tdefault:\n\t\t\t\tfmt.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\tfmt.Println(err.Error())\n\t\t}\n\t\treturn\n\t}\n\n\tfmt.Println(result)\n}", "func (a *Azure) CreateNetworkSecurityGroup(ctx context.Context, location string, nsgName string, c *types.Config) (nsg *network.SecurityGroup, err error) {\n\tnsgClient, err := a.getNsgClient()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar securityRules []network.SecurityRule\n\n\tfor _, ports := range c.RunConfig.Ports {\n\t\tvar rule = a.buildFirewallRule(network.SecurityRuleProtocolTCP, ports)\n\t\tsecurityRules = append(securityRules, rule)\n\t}\n\n\tfor _, ports := range c.RunConfig.UDPPorts {\n\t\tvar rule = a.buildFirewallRule(network.SecurityRuleProtocolUDP, ports)\n\t\tsecurityRules = append(securityRules, rule)\n\t}\n\n\tfuture, err := nsgClient.CreateOrUpdate(\n\t\tctx,\n\t\ta.groupName,\n\t\tnsgName,\n\t\tnetwork.SecurityGroup{\n\t\t\tLocation: to.StringPtr(location),\n\t\t\tSecurityGroupPropertiesFormat: &network.SecurityGroupPropertiesFormat{\n\t\t\t\tSecurityRules: &securityRules,\n\t\t\t},\n\t\t\tTags: getAzureDefaultTags(),\n\t\t},\n\t)\n\n\tif err != nil {\n\t\treturn nsg, fmt.Errorf(\"cannot create nsg: %v\", err)\n\t}\n\n\terr = future.WaitForCompletionRef(ctx, nsgClient.Client)\n\tif err != nil {\n\t\treturn nsg, fmt.Errorf(\"cannot get nsg create or update future response: %v\", err)\n\t}\n\n\tnsgValue, err := future.Result(*nsgClient)\n\tnsg = &nsgValue\n\treturn\n}", "func NewDeleteSecurityGroupRequest(server string, id string) (*http.Request, error) {\n\tvar err error\n\n\tvar pathParam0 string\n\n\tpathParam0, err = runtime.StyleParam(\"simple\", false, \"id\", id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tqueryUrl, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbasePath := fmt.Sprintf(\"/security-group/%s\", pathParam0)\n\tif basePath[0] == '/' {\n\t\tbasePath = basePath[1:]\n\t}\n\n\tqueryUrl, err = queryUrl.Parse(basePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"DELETE\", queryUrl.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn req, nil\n}", "func (o GetResolverInboundEndpointIpConfigurationOutput) SubnetId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetResolverInboundEndpointIpConfiguration) string { return v.SubnetId }).(pulumi.StringOutput)\n}", "func (m OrderStatusRequest) GetSecurityID() (v string, err quickfix.MessageRejectError) {\n\tvar f field.SecurityIDField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func (client *Client) LoadBalancerLeaveSecurityGroup(request *LoadBalancerLeaveSecurityGroupRequest) (_result *LoadBalancerLeaveSecurityGroupResponse, _err error) {\n\truntime := &util.RuntimeOptions{}\n\t_result = &LoadBalancerLeaveSecurityGroupResponse{}\n\t_body, _err := client.LoadBalancerLeaveSecurityGroupWithOptions(request, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_result = _body\n\treturn _result, _err\n}", "func (o KubernetesClusterIngressApplicationGatewayPtrOutput) SubnetId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *KubernetesClusterIngressApplicationGateway) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.SubnetId\n\t}).(pulumi.StringPtrOutput)\n}", "func (o GetVpcEndpointsEndpointOutput) SecurityGroupIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetVpcEndpointsEndpoint) []string { return v.SecurityGroupIds }).(pulumi.StringArrayOutput)\n}", "func (o ResolverInboundEndpointIpConfigurationOutput) SubnetId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResolverInboundEndpointIpConfiguration) string { return v.SubnetId }).(pulumi.StringOutput)\n}", "func (o ServiceVirtualNetworkConfigurationOutput) SubnetId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ServiceVirtualNetworkConfiguration) string { return v.SubnetId }).(pulumi.StringOutput)\n}" ]
[ "0.62743926", "0.6094887", "0.60606396", "0.5976136", "0.59231603", "0.59077597", "0.58887666", "0.58294344", "0.57898843", "0.5747376", "0.5697769", "0.5626909", "0.5623109", "0.56145775", "0.5611285", "0.5597488", "0.5582124", "0.5576479", "0.55550325", "0.55489683", "0.55240697", "0.5498799", "0.5453204", "0.5425003", "0.5406716", "0.5396224", "0.5367114", "0.5352978", "0.53523695", "0.5351429", "0.53460824", "0.5338009", "0.52736366", "0.525574", "0.5253788", "0.5244712", "0.52380335", "0.5230443", "0.52278596", "0.52273804", "0.52179164", "0.5209909", "0.5207444", "0.5182369", "0.51797205", "0.5158569", "0.5155162", "0.51484245", "0.51441306", "0.5133627", "0.5125995", "0.5124314", "0.511917", "0.5110312", "0.5106144", "0.5094966", "0.5091668", "0.50842243", "0.5076741", "0.5071776", "0.5066187", "0.5059914", "0.50473374", "0.50439924", "0.50380903", "0.503575", "0.5026026", "0.5017182", "0.50156856", "0.50098217", "0.4998473", "0.49968573", "0.4981645", "0.4971566", "0.4963602", "0.49420977", "0.49376553", "0.49367458", "0.49348503", "0.49333802", "0.49227887", "0.49211937", "0.4919854", "0.4914966", "0.4911399", "0.48996183", "0.48986667", "0.48979917", "0.4896063", "0.48958793", "0.48929727", "0.48913467", "0.48832768", "0.48806798", "0.4865727", "0.48641583", "0.48581737", "0.4856589", "0.48553333", "0.48552626" ]
0.61620134
1
PrivateSubnetIDs returns a slice with the private subnet IDs discovered by the adapter.
func (a *Adapter) PrivateSubnetIDs() []string { return getSubnetIDs(a.manifest.privateSubnets) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func PrivateNets() []*net.IPNet {\n\treturn privateNets\n}", "func (d *Discovery) GetPrivatePorts() []uint16 {\n\treturn d.privatePorts\n}", "func PrivateNetworkInterfaces(logger log.Logger) []string {\n\tints, err := net.Interfaces()\n\tif err != nil {\n\t\tlevel.Warn(logger).Log(\"msg\", \"error getting network interfaces\", \"err\", err)\n\t}\n\treturn privateNetworkInterfaces(ints, []string{}, logger)\n}", "func (c *Client) PrivateNetworks() (string, error) {\n\treturn c.get(\"/private-networks\")\n}", "func isPrivateSubnet(ips string) bool {\n\tip := net.ParseIP(ips)\n\tfor _, r := range privateCIDRs {\n\t\tif r.Contains(ip) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (a *Adapter) PublicSubnetIDs() []string {\n\treturn getSubnetIDs(a.manifest.publicSubnets)\n}", "func IsPrivateSubnet(ipaddr net.IP) bool {\n\tif ip := ipaddr.To4(); ip != nil {\n\t\tfor _, r := range privateRanges {\n\t\t\tif inRange(r, ip) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}", "func AllowPrivateSubnetForMyip() *net.IPNet {\n\tvar ip = net.ParseIP(myip)\n\tfor i, ipr := range privateCIDRs {\n\t\tif ipr.Contains(ip) {\n\t\t\t//remove ipr\n\t\t\tprivateCIDRs = append(privateCIDRs[:i], privateCIDRs[i+1:]...)\n\t\t\treturn ipr\n\t\t}\n\t}\n\treturn nil\n}", "func (pl *Peerlist) GetPrivateAddresses() []string {\n\tpl.lock.RLock()\n\tdefer pl.lock.RUnlock()\n\n\treturn pl.getAddresses(true)\n}", "func (o NetworkInterfaceOutput) PrivateIpAddresses() NetworkInterfacePrivateIpAddressSpecificationArrayOutput {\n\treturn o.ApplyT(func(v *NetworkInterface) NetworkInterfacePrivateIpAddressSpecificationArrayOutput {\n\t\treturn v.PrivateIpAddresses\n\t}).(NetworkInterfacePrivateIpAddressSpecificationArrayOutput)\n}", "func (o GetServiceAdditionalLocationOutput) PrivateIpAddresses() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetServiceAdditionalLocation) []string { return v.PrivateIpAddresses }).(pulumi.StringArrayOutput)\n}", "func (o ServiceAdditionalLocationOutput) PrivateIpAddresses() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ServiceAdditionalLocation) []string { return v.PrivateIpAddresses }).(pulumi.StringArrayOutput)\n}", "func (o *LinkPrivateIpsRequest) GetPrivateIps() []string {\n\tif o == nil || o.PrivateIps == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.PrivateIps\n}", "func (o *FiltersVmGroup) GetSubnetIds() []string {\n\tif o == nil || o.SubnetIds == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.SubnetIds\n}", "func (o *FiltersNatService) GetSubnetIds() []string {\n\tif o == nil || o.SubnetIds == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.SubnetIds\n}", "func (keyDB *KeyDB) GetPrivateIdentities() ([]string, error) {\n\tvar identities []string\n\trows, err := keyDB.getPrivateIdentitiesQuery.Query()\n\tif err != nil {\n\t\treturn nil, log.Error(\"keydb: no private identities found\")\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar identity string\n\t\tif err := rows.Scan(&identity); err != nil {\n\t\t\treturn nil, log.Error(err)\n\t\t}\n\t\tidentities = append(identities, identity)\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, log.Error(err)\n\t}\n\treturn identities, nil\n}", "func (o ElastigroupNetworkInterfaceOutput) PrivateIpAddress() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupNetworkInterface) *string { return v.PrivateIpAddress }).(pulumi.StringPtrOutput)\n}", "func (o NetworkInterfaceOutput) SecondaryPrivateIpAddresses() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *NetworkInterface) pulumi.StringArrayOutput { return v.SecondaryPrivateIpAddresses }).(pulumi.StringArrayOutput)\n}", "func (o AiEndpointDeployedModelOutput) PrivateEndpoints() AiEndpointDeployedModelPrivateEndpointArrayOutput {\n\treturn o.ApplyT(func(v AiEndpointDeployedModel) []AiEndpointDeployedModelPrivateEndpoint { return v.PrivateEndpoints }).(AiEndpointDeployedModelPrivateEndpointArrayOutput)\n}", "func privateNetworkInterfaces(all []net.Interface, fallback []string, logger log.Logger) []string {\n\tvar privInts []string\n\tfor _, i := range all {\n\t\taddrs, err := getInterfaceAddrs(&i)\n\t\tif err != nil {\n\t\t\tlevel.Warn(logger).Log(\"msg\", \"error getting addresses from network interface\", \"interface\", i.Name, \"err\", err)\n\t\t}\n\t\tfor _, a := range addrs {\n\t\t\ts := a.String()\n\t\t\tip, _, err := net.ParseCIDR(s)\n\t\t\tif err != nil {\n\t\t\t\tlevel.Warn(logger).Log(\"msg\", \"error parsing network interface IP address\", \"interface\", i.Name, \"addr\", s, \"err\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif ip.IsPrivate() {\n\t\t\t\tprivInts = append(privInts, i.Name)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif len(privInts) == 0 {\n\t\treturn fallback\n\t}\n\treturn privInts\n}", "func (r *reader) GetDNSOverTLSPrivateAddresses() (privateAddresses []string, err error) {\n\ts, err := r.envParams.GetEnv(\"DOT_PRIVATE_ADDRESS\")\n\tif err != nil {\n\t\treturn nil, err\n\t} else if len(s) == 0 {\n\t\treturn nil, nil\n\t}\n\tprivateAddresses = strings.Split(s, \",\")\n\tfor _, address := range privateAddresses {\n\t\tip := net.ParseIP(address)\n\t\t_, _, err := net.ParseCIDR(address)\n\t\tif ip == nil && err != nil {\n\t\t\treturn nil, fmt.Errorf(\"private address %q is not a valid IP or CIDR range\", address)\n\t\t}\n\t}\n\treturn privateAddresses, nil\n}", "func IsPrivateSubnet(ipAddress net.IP) bool {\n\t// my use case is only concerned with ipv4 atm\n\tif ipCheck := ipAddress.To4(); ipCheck != nil {\n\t\t// iterate over all our ranges\n\t\tfor _, r := range privateRanges {\n\t\t\t// check if this ip is in a private range\n\t\t\tif inRange(r, ipAddress) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func (s *ClusterScope) PrivateEndpointSpecs() []azure.ResourceSpecGetter {\n\tnumberOfSubnets := len(s.AzureCluster.Spec.NetworkSpec.Subnets)\n\tif s.IsAzureBastionEnabled() {\n\t\tnumberOfSubnets++\n\t}\n\n\tprivateEndpointSpecs := make([]azure.ResourceSpecGetter, 0, numberOfSubnets)\n\n\tsubnets := s.AzureCluster.Spec.NetworkSpec.Subnets\n\tif s.IsAzureBastionEnabled() {\n\t\tsubnets = append(subnets, s.AzureCluster.Spec.BastionSpec.AzureBastion.Subnet)\n\t}\n\n\tfor _, subnet := range subnets {\n\t\tprivateEndpointSpecs = append(privateEndpointSpecs, s.getPrivateEndpoints(subnet)...)\n\t}\n\n\treturn privateEndpointSpecs\n}", "func (o OceanOutput) SubnetIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *Ocean) pulumi.StringArrayOutput { return v.SubnetIds }).(pulumi.StringArrayOutput)\n}", "func (o NetworkInterfaceOutput) PrivateIpAddress() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *NetworkInterface) pulumi.StringPtrOutput { return v.PrivateIpAddress }).(pulumi.StringPtrOutput)\n}", "func (f *FakeInstance) ListPrivateNetworks(_ context.Context, _ string, _ *govultr.ListOptions) ([]govultr.PrivateNetwork, *govultr.Meta, *http.Response, error) {\n\tpanic(\"implement me\")\n}", "func (o TopicRuleDestinationVpcConfigurationPtrOutput) SubnetIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *TopicRuleDestinationVpcConfiguration) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.SubnetIds\n\t}).(pulumi.StringArrayOutput)\n}", "func (o LookupGroupResultOutput) SubnetIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v LookupGroupResult) []string { return v.SubnetIds }).(pulumi.StringArrayOutput)\n}", "func (o RouterInterfaceResponseOutput) PrivateIpAddress() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RouterInterfaceResponse) string { return v.PrivateIpAddress }).(pulumi.StringOutput)\n}", "func (o TopicRuleDestinationVpcConfigurationOutput) SubnetIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v TopicRuleDestinationVpcConfiguration) []string { return v.SubnetIds }).(pulumi.StringArrayOutput)\n}", "func (i *InstanceServiceHandler) ListPrivateNetworks(ctx context.Context, instanceID string, options *ListOptions) ([]PrivateNetwork, *Meta, error) {\n\turi := fmt.Sprintf(\"%s/%s/private-networks\", instancePath, instanceID)\n\treq, err := i.client.NewRequest(ctx, http.MethodGet, uri, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tnewValues, err := query.Values(options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq.URL.RawQuery = newValues.Encode()\n\n\tnetworks := new(privateNetworksBase)\n\tif err = i.client.DoWithContext(ctx, req, networks); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn networks.PrivateNetworks, networks.Meta, nil\n}", "func (o EnvironmentNetworkConfigurationPtrOutput) SubnetIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *EnvironmentNetworkConfiguration) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.SubnetIds\n\t}).(pulumi.StringArrayOutput)\n}", "func onlyPrivate(addrs []ma.Multiaddr) []ma.Multiaddr {\n\troutable := []ma.Multiaddr{}\n\tfor _, addr := range addrs {\n\t\tif manet.IsPrivateAddr(addr) {\n\t\t\troutable = append(routable, addr)\n\t\t\tlog.Debugf(\"\\tprivate - %s\\n\", addr.String())\n\t\t} else {\n\t\t\tlog.Debugf(\"\\tpublic - %s\\n\", addr.String())\n\t\t}\n\t}\n\treturn routable\n}", "func (o RouterInterfaceOutput) PrivateIpAddress() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v RouterInterface) *string { return v.PrivateIpAddress }).(pulumi.StringPtrOutput)\n}", "func (o EnvironmentNetworkConfigurationOutput) SubnetIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v EnvironmentNetworkConfiguration) []string { return v.SubnetIds }).(pulumi.StringArrayOutput)\n}", "func (o *LinkPrivateIpsRequest) SetPrivateIps(v []string) {\n\to.PrivateIps = &v\n}", "func (p *Plan) GetPrivateRepos() int {\n\tif p == nil || p.PrivateRepos == nil {\n\t\treturn 0\n\t}\n\treturn *p.PrivateRepos\n}", "func (o StudioOutput) SubnetIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *Studio) pulumi.StringArrayOutput { return v.SubnetIds }).(pulumi.StringArrayOutput)\n}", "func (o GetResolverInboundEndpointIpConfigurationOutput) PrivateIpAddress() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetResolverInboundEndpointIpConfiguration) string { return v.PrivateIpAddress }).(pulumi.StringOutput)\n}", "func (o *FiltersSubnet) GetSubnetIds() []string {\n\tif o == nil || o.SubnetIds == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.SubnetIds\n}", "func (o DatabaseReplicaOutput) PrivateNetworkUuid() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DatabaseReplica) pulumi.StringOutput { return v.PrivateNetworkUuid }).(pulumi.StringOutput)\n}", "func (o ElastigroupNetworkInterfaceOutput) SecondaryPrivateIpAddressCount() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupNetworkInterface) *string { return v.SecondaryPrivateIpAddressCount }).(pulumi.StringPtrOutput)\n}", "func PrivateIP(ip string) bool {\n\taddr := net.ParseIP(RemovePort(strings.TrimSpace(ip)))\n\tif addr == nil { // Not an IP address?\n\t\treturn true\n\t}\n\n\tfor _, c := range privateCIDR {\n\t\tif c.Contains(addr) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (client *AWSClient) GetPrivateIPsOfInstancesOfAutoscalingGroup(name string) ([]string, error) {\n\tgroup, exists, err := client.getAutoscalingGroup(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, fmt.Errorf(\"autoscaling group %v doesn't exists\", name)\n\t}\n\n\tinstances, err := client.getInstancesOfAutoscalingGroup(group)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result []string\n\tfor _, ins := range instances {\n\t\tif len(ins.NetworkInterfaces) > 0 && ins.NetworkInterfaces[0].PrivateIpAddress != nil {\n\t\t\tresult = append(result, *ins.NetworkInterfaces[0].PrivateIpAddress)\n\t\t}\n\t}\n\n\treturn result, nil\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 TestPrivateSharedSubnet(t *testing.T) {\n\tnewIntegrationTest(\"private-shared-subnet.example.com\", \"private-shared-subnet\").\n\t\twithAddons(\n\t\t\tawsEBSCSIAddon,\n\t\t\tdnsControllerAddon,\n\t\t\tawsCCMAddon,\n\t\t).\n\t\twithPrivate().\n\t\trunTestTerraformAWS(t)\n}", "func (o ResolverInboundEndpointIpConfigurationOutput) PrivateIpAddress() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResolverInboundEndpointIpConfiguration) *string { return v.PrivateIpAddress }).(pulumi.StringPtrOutput)\n}", "func (config *Config) getPrivateDockerRegistries() error {\n\tcredentials, ok := os.LookupEnv(\"securedRegistries.json\")\n\tif !ok {\n\t\treturn fmt.Errorf(\"cannot find Private Docker Registries: environment variable securedRegistries not found\")\n\t}\n\n\tprivateDockerRegistries := map[string]*common.RegistryAuth{}\n\terr := json.Unmarshal([]byte(credentials), &privateDockerRegistries)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to unmarshall Private Docker registries due to %+v\", err)\n\t}\n\n\tdockerRegistries := []*common.RegistryAuth{}\n\tfor _, privatedockerRegistry := range privateDockerRegistries {\n\t\tdockerRegistries = append(dockerRegistries, privatedockerRegistry)\n\t}\n\n\tconfig.ImageFacade.PrivateDockerRegistries = dockerRegistries\n\n\treturn nil\n}", "func (o GetLBFrontendIpConfigurationOutput) PrivateIpAddress() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetLBFrontendIpConfiguration) string { return v.PrivateIpAddress }).(pulumi.StringOutput)\n}", "func NewPrivateDiscoverer() Discoverer {\n\treturn NewDiscoverer(\n\t\tPublicIPv4DiscovererOption(privatePublicIPv4),\n\t\tPublicIPv6DiscovererOption(privatePublicIPv6),\n\t)\n}", "func flattenPrivateCloudNetworkConfigSlice(c *Client, i interface{}, res *PrivateCloud) []PrivateCloudNetworkConfig {\n\ta, ok := i.([]interface{})\n\tif !ok {\n\t\treturn []PrivateCloudNetworkConfig{}\n\t}\n\n\tif len(a) == 0 {\n\t\treturn []PrivateCloudNetworkConfig{}\n\t}\n\n\titems := make([]PrivateCloudNetworkConfig, 0, len(a))\n\tfor _, item := range a {\n\t\titems = append(items, *flattenPrivateCloudNetworkConfig(c, item.(map[string]interface{}), res))\n\t}\n\n\treturn items\n}", "func (o ResourceManagementPrivateLinkEndpointConnectionsResponseOutput) PrivateEndpointConnections() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ResourceManagementPrivateLinkEndpointConnectionsResponse) []string {\n\t\treturn v.PrivateEndpointConnections\n\t}).(pulumi.StringArrayOutput)\n}", "func GetAllPrivateKeys(s *aklib.DBConfig) ([]string, error) {\n\tvar pk []string\n\terr := s.DB.View(func(txn *badger.Txn) error {\n\t\tit := txn.NewIterator(badger.DefaultIteratorOptions)\n\t\tdefer it.Close()\n\t\tfor it.Seek([]byte{byte(db.HeaderWallet)}); it.ValidForPrefix([]byte{byte(db.HeaderWallet)}); it.Next() {\n\t\t\tpk = append(pk, string(it.Item().KeyCopy(nil)))\n\t\t}\n\t\treturn nil\n\t})\n\treturn pk, err\n}", "func (o LoadBalancerFrontendIpConfigurationOutput) PrivateIpAddress() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LoadBalancerFrontendIpConfiguration) *string { return v.PrivateIpAddress }).(pulumi.StringPtrOutput)\n}", "func (c *Client) Private(id *key.Identity) ([]byte, error) {\n\tephScalar := key.KeyGroup.Scalar()\n\tephPoint := key.KeyGroup.Point().Mul(ephScalar, nil)\n\tephBuff, err := ephPoint.MarshalBinary()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tobj, err := ecies.Encrypt(key.KeyGroup, id.Key, ephBuff, EciesHash)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := c.client.PrivateRand(context.TODO(), id, &drand.PrivateRandRequest{Request: obj})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ecies.Decrypt(key.KeyGroup, ephScalar, resp.GetResponse(), EciesHash)\n}", "func (o *PublicIp) SetPrivateIp(v string) {\n\to.PrivateIp = &v\n}", "func (o *PublicIp) SetPrivateIp(v string) {\n\to.PrivateIp = &v\n}", "func (o LinkServiceNatIpConfigurationOutput) PrivateIpAddress() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LinkServiceNatIpConfiguration) *string { return v.PrivateIpAddress }).(pulumi.StringPtrOutput)\n}", "func (o ResourceManagementPrivateLinkEndpointConnectionsResponsePtrOutput) PrivateEndpointConnections() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *ResourceManagementPrivateLinkEndpointConnectionsResponse) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PrivateEndpointConnections\n\t}).(pulumi.StringArrayOutput)\n}", "func (daemon *Daemon) Subnets() ([]net.IPNet, []net.IPNet) {\n\tvar v4Subnets []net.IPNet\n\tvar v6Subnets []net.IPNet\n\n\tfor _, managedNetwork := range daemon.netController.Networks() {\n\t\tv4infos, v6infos := managedNetwork.IpamInfo()\n\t\tfor _, info := range v4infos {\n\t\t\tif info.IPAMData.Pool != nil {\n\t\t\t\tv4Subnets = append(v4Subnets, *info.IPAMData.Pool)\n\t\t\t}\n\t\t}\n\t\tfor _, info := range v6infos {\n\t\t\tif info.IPAMData.Pool != nil {\n\t\t\t\tv6Subnets = append(v6Subnets, *info.IPAMData.Pool)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn v4Subnets, v6Subnets\n}", "func Subnets(supernet *net.IPNet, prefix int) []*net.IPNet {\n\tones, bits := supernet.Mask.Size()\n\tif ones > prefix || bits < prefix {\n\t\treturn nil\n\t}\n\n\tip := supernet.IP\n\tmask := net.CIDRMask(prefix, bits)\n\tsize, _ := uint128.Pow2(uint(bits - prefix))\n\n\tsubnets := make([]*net.IPNet, 1<<uint(prefix-ones))\n\tfor i := 0; i < len(subnets); i++ {\n\t\tif i > 0 {\n\t\t\tlast, _ := uint128.NewFromBytes(subnets[i-1].IP)\n\t\t\tbuf := last.Add(size).Bytes()\n\n\t\t\t// Uint128 always returns a 16-byte slice. We only need the last\n\t\t\t// 4 bytes for IPv4 addresses.\n\t\t\tip = buf[16-len(ip):]\n\t\t}\n\n\t\tsubnets[i] = &net.IPNet{\n\t\t\tIP: ip,\n\t\t\tMask: mask,\n\t\t}\n\t}\n\n\treturn subnets\n}", "func (um *UserManager) GetPrivateIPFSNetworksForUser(username string) ([]string, error) {\n\tu, err := um.FindByUserName(username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn u.IPFSNetworkNames, nil\n}", "func GetPrivateIP(client Clients, ctx context.Context,\n\tresourceGroup string, networkInterface string, expand string) (PrivateIPAddress string,\n\tIPConfiguration string, err error) {\n\tvmInterface := client.VMInterface\n\tinterfaces, err := vmInterface.Get(ctx, resourceGroup, networkInterface, expand)\n\tif err != nil {\n\t\t\treturn\n\t}\n\tinterfaceinfo := *interfaces.InterfacePropertiesFormat.IPConfigurations\n\tinterfID := *interfaceinfo[0].InterfaceIPConfigurationPropertiesFormat\n\tIPConfiguration = *interfaceinfo[0].Name\n\tif interfID.PrivateIPAddress != nil {\n\t\t\tPrivateIPAddress = *interfID.PrivateIPAddress\n\t}\n\treturn\n}", "func (c *MockVirtualNetworkClient) GetPrivateIP(ctx context.Context, id string) (*core.PrivateIp, error) {\n\tprivateIpAddress := \"10.0.20.1\"\n\treturn &core.PrivateIp{\n\t\tIpAddress: &privateIpAddress,\n\t}, nil\n}", "func (c *ClientWithResponses) ListPrivateNetworksWithResponse(ctx context.Context) (*ListPrivateNetworksResponse, error) {\n\trsp, err := c.ListPrivateNetworks(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseListPrivateNetworksResponse(rsp)\n}", "func (o *LinkPublicIpRequest) SetPrivateIp(v string) {\n\to.PrivateIp = &v\n}", "func (o *PublicIp) GetPrivateIp() string {\n\tif o == nil || o.PrivateIp == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.PrivateIp\n}", "func (o *PublicIp) GetPrivateIp() string {\n\tif o == nil || o.PrivateIp == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.PrivateIp\n}", "func (pl PredicateList) Privates() PredicateList {\n\treturn pl.filter(Predicate.IsPrivate)\n}", "func GetPrivateRecordSet(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *PrivateRecordSetState, opts ...pulumi.ResourceOption) (*PrivateRecordSet, error) {\n\tvar resource PrivateRecordSet\n\terr := ctx.ReadResource(\"azure-native:network/v20200101:PrivateRecordSet\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func IsPrivateIP(ips string) bool {\n\tip := net.ParseIP(ips)\n\tfor _, cidr := range privateCIDRs {\n\t\t_, nt, err := net.ParseCIDR(cidr)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif nt.Contains(ip) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func GetSubnetIPs(subnet string) (result []net.IP) {\n\tip, ipnet, err := net.ParseCIDR(subnet)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); inc(ip) {\n\t\tresult = append(result, net.ParseIP(ip.String()))\n\t}\n\treturn\n}", "func (decryptor *PgDecryptor) GetPrivateKeys() ([]*keys.PrivateKey, error) {\n\tif decryptor.IsWithZone() {\n\t\treturn decryptor.keyStore.GetZonePrivateKeys(decryptor.GetMatchedZoneID())\n\t}\n\treturn decryptor.keyStore.GetServerDecryptionPrivateKeys(decryptor.clientID)\n}", "func (o InstanceOutput) IngressPrivateIp() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.IngressPrivateIp }).(pulumi.StringOutput)\n}", "func (o *FiltersNatService) GetSubnetIdsOk() ([]string, bool) {\n\tif o == nil || o.SubnetIds == nil {\n\t\tvar ret []string\n\t\treturn ret, false\n\t}\n\treturn *o.SubnetIds, true\n}", "func IsIPPrivate(ip net.IP) bool {\n\tfor _, ipnet := range privateIPNets {\n\t\tif ipnet.Contains(ip) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func private(bits int) (k *rsa.PrivateKey, err error) {\n\t// Private Key generation\n\tif k, err = rsa.GenerateKey(rand.Reader, bits); err != nil {\n\t\treturn k, err\n\t}\n\n\t// Validate Private Key\n\treturn k, k.Validate()\n}", "func (c *Client) PrivateChannels() ([]discord.Channel, error) {\n\tvar dms []discord.Channel\n\treturn dms, c.RequestJSON(&dms, \"GET\", EndpointMe+\"/channels\")\n}", "func (c *MockVirtualNetworkClient) GetPrivateIP(ctx context.Context, id string) (*core.PrivateIp, error) {\n\treturn &core.PrivateIp{IpAddress: &privateIP}, nil\n}", "func (i *Identity) GetPrivateSigners(req *idp.GetPrivateSignersRequest) ([]idp.TemporalSigner, error) {\n\treturn nil, errors.New(\"NotImplemented\")\n}", "func (o *InlineResponse200115) SetPrivate(v string) {\n\to.Private = &v\n}", "func (o EcsLaunchTemplateOutput) PrivateIpAddress() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *EcsLaunchTemplate) pulumi.StringPtrOutput { return v.PrivateIpAddress }).(pulumi.StringPtrOutput)\n}", "func (a *Application) PrivateChannels() []*channel.Channel {\n\ta.RLock()\n\tdefer a.RUnlock()\n\n\tvar channels []*channel.Channel\n\n\tfor _, c := range a.channels {\n\t\tif c.IsPrivate() {\n\t\t\tchannels = append(channels, c)\n\t\t}\n\t}\n\n\treturn channels\n}", "func (r Virtual_Guest) GetFirewallProtectableSubnets() (resp []datatypes.Network_Subnet, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getFirewallProtectableSubnets\", nil, &r.Options, &resp)\n\treturn\n}", "func (o *FiltersSubnet) GetNetIds() []string {\n\tif o == nil || o.NetIds == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.NetIds\n}", "func (f *FilterConfig) privateIP(ip net.IP) bool {\n\tfor _, cidr := range f.privateCIDRs {\n\t\tif cidr.Contains(ip) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (s *ClusterScope) APIServerPrivateIP() string {\n\treturn s.APIServerLB().FrontendIPs[0].PrivateIPAddress\n}", "func (o NetworkInterfaceOutput) SecondaryPrivateIpAddressCount() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *NetworkInterface) pulumi.IntPtrOutput { return v.SecondaryPrivateIpAddressCount }).(pulumi.IntPtrOutput)\n}", "func (o *LinkPublicIpRequest) GetPrivateIp() string {\n\tif o == nil || o.PrivateIp == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.PrivateIp\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 (o ContainerServiceOutput) PrivateRegistryAccess() ContainerServicePrivateRegistryAccessOutput {\n\treturn o.ApplyT(func(v *ContainerService) ContainerServicePrivateRegistryAccessOutput { return v.PrivateRegistryAccess }).(ContainerServicePrivateRegistryAccessOutput)\n}", "func (o *FiltersVmGroup) GetSubnetIdsOk() (*[]string, bool) {\n\tif o == nil || o.SubnetIds == nil {\n\t\treturn nil, false\n\t}\n\treturn o.SubnetIds, true\n}", "func (c *cfService) PrivateDomains() PrivateDomains {\n\treturn newPrivateDomainAPI(c.Client)\n}", "func (keyDB *KeyDB) GetPrivateIdentitiesForDomain(domain string) ([]string, error) {\n\tvar identities []string\n\tall, err := keyDB.GetPrivateIdentities()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdmn := identity.MapDomain(domain)\n\tfor _, id := range all {\n\t\t_, idDomain, err := identity.Split(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif idDomain == dmn {\n\t\t\tidentities = append(identities, id)\n\t\t}\n\t}\n\treturn identities, nil\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 (s *NetworkInterface) SetPrivateIpAddress(v string) *NetworkInterface {\n\ts.PrivateIpAddress = &v\n\treturn s\n}", "func (o GetWorkspacePrivateEndpointConnectionResultOutput) PrivateEndpointId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetWorkspacePrivateEndpointConnectionResult) string { return v.PrivateEndpointId }).(pulumi.StringOutput)\n}", "func flattenPrivateCloudStateEnumSlice(c *Client, i interface{}, res *PrivateCloud) []PrivateCloudStateEnum {\n\ta, ok := i.([]interface{})\n\tif !ok {\n\t\treturn []PrivateCloudStateEnum{}\n\t}\n\n\tif len(a) == 0 {\n\t\treturn []PrivateCloudStateEnum{}\n\t}\n\n\titems := make([]PrivateCloudStateEnum, 0, len(a))\n\tfor _, item := range a {\n\t\titems = append(items, *flattenPrivateCloudStateEnum(item.(interface{})))\n\t}\n\n\treturn items\n}", "func (o *InlineResponse20049Post) SetPrivate(v string) {\n\to.Private = &v\n}", "func (csi ChannelStoreImpl) GetPrivate(db *gorm.DB) []models.Channel {\n\tchannels := []models.Channel{}\n\tdb.Where(\"private = ?\", true).Find(&channels)\n\treturn channels\n}" ]
[ "0.68231964", "0.64657307", "0.6398693", "0.63024354", "0.6225061", "0.618172", "0.6147592", "0.6138173", "0.6109878", "0.606566", "0.6050834", "0.60140425", "0.59562993", "0.59441864", "0.58901244", "0.5881163", "0.5871929", "0.58298874", "0.5818916", "0.58129025", "0.5787037", "0.56218153", "0.5601991", "0.55928755", "0.5565471", "0.55614287", "0.55409807", "0.5504848", "0.5500015", "0.5496039", "0.5484773", "0.5466521", "0.5462814", "0.5425605", "0.5406681", "0.5363997", "0.53514814", "0.5343582", "0.5342549", "0.53410715", "0.5317237", "0.53161097", "0.52970046", "0.5295727", "0.5290816", "0.5288027", "0.5257159", "0.5256897", "0.5247099", "0.5244032", "0.5241095", "0.5229897", "0.52241004", "0.5216299", "0.5208776", "0.52023286", "0.52023286", "0.519131", "0.518472", "0.51785845", "0.5176133", "0.51680744", "0.5099159", "0.50715536", "0.50631815", "0.5059096", "0.50546163", "0.50546163", "0.5053153", "0.50391346", "0.502895", "0.50282556", "0.5018988", "0.50072813", "0.49827462", "0.49626446", "0.49562845", "0.49519888", "0.49492073", "0.4946281", "0.49377608", "0.49266285", "0.49228138", "0.49204955", "0.4918249", "0.49131662", "0.49118268", "0.4894523", "0.4883814", "0.48833215", "0.48728788", "0.48665497", "0.4866178", "0.4863148", "0.4863014", "0.4859179", "0.4854134", "0.48514062", "0.48446977", "0.48018548" ]
0.83112925
0
PublicSubnetIDs returns a slice with the public subnet IDs discovered by the adapter.
func (a *Adapter) PublicSubnetIDs() []string { return getSubnetIDs(a.manifest.publicSubnets) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a *Adapter) PrivateSubnetIDs() []string {\n\treturn getSubnetIDs(a.manifest.privateSubnets)\n}", "func (o *FiltersNatService) GetSubnetIds() []string {\n\tif o == nil || o.SubnetIds == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.SubnetIds\n}", "func (h *Hub) PublicSubnetMask() (result string, err error) {\n\treturn h.client.sendXPathRequest(mySagemcomBoxDeviceInfoPublicSubnetMask)\n}", "func (o *FiltersVmGroup) GetSubnetIds() []string {\n\tif o == nil || o.SubnetIds == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.SubnetIds\n}", "func GetPublicIps(ctx context.Context, c clientset.Interface) ([]string, error) {\n\tnodes, err := GetReadySchedulableNodes(ctx, c)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"get schedulable and ready nodes error: %w\", err)\n\t}\n\tips := CollectAddresses(nodes, v1.NodeExternalIP)\n\tif len(ips) == 0 {\n\t\t// If ExternalIP isn't set, assume the test programs can reach the InternalIP\n\t\tips = CollectAddresses(nodes, v1.NodeInternalIP)\n\t}\n\treturn ips, nil\n}", "func (pl *Peerlist) GetPublicAddresses() []string {\n\tpl.lock.RLock()\n\tdefer pl.lock.RUnlock()\n\n\treturn pl.getAddresses(false)\n}", "func (o *FiltersSubnet) GetSubnetIds() []string {\n\tif o == nil || o.SubnetIds == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.SubnetIds\n}", "func Subnets(supernet *net.IPNet, prefix int) []*net.IPNet {\n\tones, bits := supernet.Mask.Size()\n\tif ones > prefix || bits < prefix {\n\t\treturn nil\n\t}\n\n\tip := supernet.IP\n\tmask := net.CIDRMask(prefix, bits)\n\tsize, _ := uint128.Pow2(uint(bits - prefix))\n\n\tsubnets := make([]*net.IPNet, 1<<uint(prefix-ones))\n\tfor i := 0; i < len(subnets); i++ {\n\t\tif i > 0 {\n\t\t\tlast, _ := uint128.NewFromBytes(subnets[i-1].IP)\n\t\t\tbuf := last.Add(size).Bytes()\n\n\t\t\t// Uint128 always returns a 16-byte slice. We only need the last\n\t\t\t// 4 bytes for IPv4 addresses.\n\t\t\tip = buf[16-len(ip):]\n\t\t}\n\n\t\tsubnets[i] = &net.IPNet{\n\t\t\tIP: ip,\n\t\t\tMask: mask,\n\t\t}\n\t}\n\n\treturn subnets\n}", "func GetSubnetIPs(subnet string) (result []net.IP) {\n\tip, ipnet, err := net.ParseCIDR(subnet)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); inc(ip) {\n\t\tresult = append(result, net.ParseIP(ip.String()))\n\t}\n\treturn\n}", "func (o OceanOutput) SubnetIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *Ocean) pulumi.StringArrayOutput { return v.SubnetIds }).(pulumi.StringArrayOutput)\n}", "func (client Client) PublicIPAddresses() network.PublicIPAddressesClient {\n\tif client.publidAddresses == nil {\n\t\tclnt := network.NewPublicIPAddressesClientWithBaseURI(client.baseURI, client.subscriptionID)\n\t\tclnt.Authorizer = client.Authorizer\n\t\tclnt.RequestInspector = client.RequestInspector\n\t\tclnt.ResponseInspector = client.ResponseInspector\n\t\tclient.publidAddresses = &clnt\t\t\n\t}\t\n\treturn *client.publidAddresses\n}", "func (o StudioOutput) SubnetIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *Studio) pulumi.StringArrayOutput { return v.SubnetIds }).(pulumi.StringArrayOutput)\n}", "func GetAllPublicClients() []PublicClient {\n clients := make([]PublicClient, 0);\n\n for _, client := range currentClients {\n thisClient := PublicClient { IdentityToken: client.ClientToken, IdentityName: client.ClientName, VoteHistory: client.VoteHistory, QueueHistory: client.QueueHistory }\n\n clients = append(clients, thisClient)\n }\n\n return clients;\n}", "func (c *MockPublicIPAddressesClient) List(ctx context.Context, resourceGroupName string) ([]network.PublicIPAddress, error) {\n\tvar l []network.PublicIPAddress\n\tfor _, lb := range c.PubIPs {\n\t\tl = append(l, lb)\n\t}\n\treturn l, nil\n}", "func PublicIpv4In(vs ...string) predicate.Agent {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Agent(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(FieldPublicIpv4), v...))\n\t})\n}", "func (o LookupGroupResultOutput) SubnetIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v LookupGroupResult) []string { return v.SubnetIds }).(pulumi.StringArrayOutput)\n}", "func (o EnvironmentNetworkConfigurationPtrOutput) SubnetIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *EnvironmentNetworkConfiguration) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.SubnetIds\n\t}).(pulumi.StringArrayOutput)\n}", "func (pl *Peerlist) RandomPublic(count int) []Peer {\n\tpl.lock.RLock()\n\tdefer pl.lock.RUnlock()\n\n\treturn pl.random(count, false)\n}", "func (o TopicRuleDestinationVpcConfigurationOutput) SubnetIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v TopicRuleDestinationVpcConfiguration) []string { return v.SubnetIds }).(pulumi.StringArrayOutput)\n}", "func (o EnvironmentNetworkConfigurationOutput) SubnetIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v EnvironmentNetworkConfiguration) []string { return v.SubnetIds }).(pulumi.StringArrayOutput)\n}", "func getLocalIPs() (ips []string) {\n\tips = make([]string, 0, 6)\n\n\taddrs, err := net.InterfaceAddrs()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, addr := range addrs {\n\t\tip, _, err := net.ParseCIDR(addr.String())\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tips = append(ips, ip.String())\n\t}\n\treturn\n}", "func (o TopicRuleDestinationVpcConfigurationPtrOutput) SubnetIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *TopicRuleDestinationVpcConfiguration) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.SubnetIds\n\t}).(pulumi.StringArrayOutput)\n}", "func onlyPublic(addrs []ma.Multiaddr) []ma.Multiaddr {\n\troutable := []ma.Multiaddr{}\n\tfor _, addr := range addrs {\n\t\tif manet.IsPublicAddr(addr) {\n\t\t\troutable = append(routable, addr)\n\t\t}\n\t}\n\treturn routable\n}", "func (daemon *Daemon) Subnets() ([]net.IPNet, []net.IPNet) {\n\tvar v4Subnets []net.IPNet\n\tvar v6Subnets []net.IPNet\n\n\tfor _, managedNetwork := range daemon.netController.Networks() {\n\t\tv4infos, v6infos := managedNetwork.IpamInfo()\n\t\tfor _, info := range v4infos {\n\t\t\tif info.IPAMData.Pool != nil {\n\t\t\t\tv4Subnets = append(v4Subnets, *info.IPAMData.Pool)\n\t\t\t}\n\t\t}\n\t\tfor _, info := range v6infos {\n\t\t\tif info.IPAMData.Pool != nil {\n\t\t\t\tv6Subnets = append(v6Subnets, *info.IPAMData.Pool)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn v4Subnets, v6Subnets\n}", "func (o *FiltersNatService) GetSubnetIdsOk() ([]string, bool) {\n\tif o == nil || o.SubnetIds == nil {\n\t\tvar ret []string\n\t\treturn ret, false\n\t}\n\treturn *o.SubnetIds, true\n}", "func (o *FiltersSubnet) GetNetIds() []string {\n\tif o == nil || o.NetIds == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.NetIds\n}", "func (m *ValidatorSet) GetValidatorPublicKeys() (x []*ValidatorPublicKeys) {\n\tif m == nil {\n\t\treturn x\n\t}\n\treturn m.ValidatorPublicKeys\n}", "func (client Client) Subnets() network.SubnetsClient {\n\tif client.subnets == nil {\n\t\tclnt := network.NewSubnetsClientWithBaseURI(client.baseURI, client.subscriptionID)\n\t\tclnt.Authorizer = client.Authorizer\n\t\tclnt.RequestInspector = client.RequestInspector\n\t\tclnt.ResponseInspector = client.ResponseInspector\n\t\tclient.subnets = &clnt\t\t\n\t}\t\n\treturn *client.subnets\n}", "func getLocalIPs() (ips []string) {\n\tips = make([]string, 0, 6)\n\n\taddrs, err := net.InterfaceAddrs()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, addr := range addrs {\n\t\tif ipnet, ok := addr.(*net.IPNet); ok {\n\t\t\tif ipnet.IP.To4() != nil {\n\t\t\t\tips = append(ips, ipnet.IP.String())\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (cm *connectionsManager) getConnectionPublicKeys() []credentials.StaticSizedPublicKey {\n\tcm.mu.Lock()\n\tdefer cm.mu.Unlock()\n\n\tkeys := []credentials.StaticSizedPublicKey{}\n\tfor k := range cm.conns {\n\t\tkeys = append(keys, k)\n\t}\n\n\treturn keys\n}", "func (o NetworkPeeringResponseOutput) ExportSubnetRoutesWithPublicIp() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v NetworkPeeringResponse) bool { return v.ExportSubnetRoutesWithPublicIp }).(pulumi.BoolOutput)\n}", "func (o ServiceAdditionalLocationOutput) PublicIpAddresses() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ServiceAdditionalLocation) []string { return v.PublicIpAddresses }).(pulumi.StringArrayOutput)\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 IpAddressGen(subnet string) []string {\n\tipAddress, ipNet, err := net.ParseCIDR(subnet)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tvar ipAddresses []string\n\n\tfor ipAddress := ipAddress.Mask(ipNet.Mask); ipNet.Contains(ipAddress); inc(ipAddress) {\n\t\tipAddresses = append(ipAddresses, ipAddress.String())\n\t}\n\n\treturn ipAddresses\n\n}", "func (o NetworkPeeringResponseOutput) ImportSubnetRoutesWithPublicIp() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v NetworkPeeringResponse) bool { return v.ImportSubnetRoutesWithPublicIp }).(pulumi.BoolOutput)\n}", "func GetPublicIPAddressID(client Clients,\n\tctx context.Context, resourceGroup string, networkInterface string,\n\texpand string) (PublicIPAddressID string, err error) {\n\tvmInterface := client.VMInterface\n\tinterfaces, err := vmInterface.Get(ctx, resourceGroup, networkInterface, expand)\n\tif err != nil {\n\t\t\treturn\n\t}\n\tinterfaceinfo := *interfaces.InterfacePropertiesFormat.IPConfigurations\n\tinterfID := *interfaceinfo[0].InterfaceIPConfigurationPropertiesFormat\n\n\tif interfID.PublicIPAddress != nil && interfID.PublicIPAddress.ID != nil {\n\t\t\tID := strings.Split(*interfID.PublicIPAddress.ID, \"/\")\n\t\t\tPublicIPAddressID = ID[8]\n\t} else {\n\t\t\terr = errors.New(\"Vm has no publicIPname\")\n\t}\n\treturn\n}", "func (h *Hub) PublicIPAddress() (result string, err error) {\n\treturn h.client.sendXPathRequest(mySagemcomBoxDeviceInfoPublicIpv4)\n}", "func GetVlans(givenIp string) ([]*Vlan, error) {\n\tconst BUCKET = \"netops-dev\"\n\tclient, err := gocb.Connect(\"http://localhost:8091/\")\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tbucket, err := client.OpenBucket(BUCKET, BUCKET)\n\tif err != nil {\n\t\tlog.Fatal(\"when connecting to couchbase: \", err)\n\t}\n\tif bucket == nil {\n\t\tlog.Fatal(\"couchbase connection went wrong\")\n\t}\n\tbucket.Manager(\"\", \"\").CreatePrimaryIndex(\"\", true, false)\n\n\t// Remove all data from the bucket\n\t{\n\t\t_, err := bucket.ExecuteN1qlQuery(gocb.NewN1qlQuery(\"delete from `netops-dev`\"), []interface{}{})\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\tipnetsStr := []string{\n\t\t\"192.168.1.1/28\",\n\t\t\"192.168.1.28/28\",\n\t\t\"192.168.1.80/28\",\n\t\t\"192.168.1.250/28\",\n\t}\n\n\t// Turn ip net strings into a slice of IPNet\n\tipnets := make(map[string]*net.IPNet)\n\tfor _, ipStr := range ipnetsStr {\n\t\t_, ipnet, err := net.ParseCIDR(ipStr)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"skipping '%v' as it doesn't seem to be a valid CIDR (RFC 4632, RFC 4291)\", ipStr)\n\t\t\tcontinue\n\t\t}\n\t\tipnets[ipStr] = ipnet\n\t}\n\n\tfor str, ipnet := range ipnets {\n\t\tbucket.Upsert(str,\n\t\t\t&Vlan{str, ip2int(ipnet.IP), ip2int(net.IP(ipnet.Mask)), *ipnet}, 0,\n\t\t)\n\t}\n\n\t{\n\t\trows, err := bucket.ExecuteN1qlQuery(gocb.NewN1qlQuery(\n\t\t\t\"select maskIpv4, subnetIpv4, vlanId \"+\n\t\t\t\t\"from `netops-dev`\"), []interface{}{})\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tvar vlan Vlan\n\t\tfor rows.Next(&vlan) {\n\t\t\tvlan.IPNet = net.IPNet{\n\t\t\t\tIP: int2ip(vlan.SubnetIpv4),\n\t\t\t\tMask: net.IPMask(int2ip(vlan.MaskIpv4)),\n\t\t\t}\n\t\t\tfmt.Printf(\"%v\\n\", vlan.IPNet)\n\t\t}\n\t}\n\n\tipStr := givenIp\n\tip := ip2int(net.ParseIP(ipStr))\n\trows, err := bucket.ExecuteN1qlQuery(gocb.NewN1qlQuery(\n\t\t\"select maskIpv4, subnetIpv4, vlanId \"+\n\t\t\t\"from `netops-dev` \"+\n\t\t\t\"where bitand($1, maskIpv4) = subnetIpv4\"), []interface{}{ip})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar vlan Vlan\n\tvar vlans []Vlan\n\tfor rows.Next(&vlan) {\n\t\tvlan.IPNet = net.IPNet{\n\t\t\tIP: int2ip(vlan.SubnetIpv4),\n\t\t\tMask: net.IPMask(int2ip(vlan.MaskIpv4)),\n\t\t}\n\t\tvlans = append(vlans, vlan)\n\t}\n\tfmt.Printf(\"lookup for '%v': \", ipStr)\n\tfor _, vlan := range vlans {\n\t\tfmt.Printf(\"%v \", vlan.IPNet.String())\n\t}\n\tfmt.Print(\"\\n\")\n\treturn nil, nil\n}", "func (o GetServiceAdditionalLocationOutput) PublicIpAddresses() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetServiceAdditionalLocation) []string { return v.PublicIpAddresses }).(pulumi.StringArrayOutput)\n}", "func PrivateNets() []*net.IPNet {\n\treturn privateNets\n}", "func (s *ClusterScope) Subnets() infrav1.Subnets {\n\treturn s.AzureCluster.Spec.NetworkSpec.Subnets\n}", "func PublicIpv6In(vs ...string) predicate.Agent {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Agent(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(FieldPublicIpv6), v...))\n\t})\n}", "func (c *MockAzureCloud) PublicIPAddress() azure.PublicIPAddressesClient {\n\treturn c.PublicIPAddressesClient\n}", "func (o *FiltersVmGroup) GetSubnetIdsOk() (*[]string, bool) {\n\tif o == nil || o.SubnetIds == nil {\n\t\treturn nil, false\n\t}\n\treturn o.SubnetIds, true\n}", "func CIDRArrayToIPNetSlice(val *[]net.IPNet) sql.Scanner {\n\treturn cidrArrayToIPNetSlice{val: val}\n}", "func (o *FiltersSubnet) GetSubnetIdsOk() ([]string, bool) {\n\tif o == nil || o.SubnetIds == nil {\n\t\tvar ret []string\n\t\treturn ret, false\n\t}\n\treturn *o.SubnetIds, true\n}", "func (o LookupVirtualNetworkResultOutput) Subnets() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v LookupVirtualNetworkResult) []string { return v.Subnets }).(pulumi.StringArrayOutput)\n}", "func privateNetworkInterfaces(all []net.Interface, fallback []string, logger log.Logger) []string {\n\tvar privInts []string\n\tfor _, i := range all {\n\t\taddrs, err := getInterfaceAddrs(&i)\n\t\tif err != nil {\n\t\t\tlevel.Warn(logger).Log(\"msg\", \"error getting addresses from network interface\", \"interface\", i.Name, \"err\", err)\n\t\t}\n\t\tfor _, a := range addrs {\n\t\t\ts := a.String()\n\t\t\tip, _, err := net.ParseCIDR(s)\n\t\t\tif err != nil {\n\t\t\t\tlevel.Warn(logger).Log(\"msg\", \"error parsing network interface IP address\", \"interface\", i.Name, \"addr\", s, \"err\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif ip.IsPrivate() {\n\t\t\t\tprivInts = append(privInts, i.Name)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif len(privInts) == 0 {\n\t\treturn fallback\n\t}\n\treturn privInts\n}", "func (o *FiltersNatService) GetNetIds() []string {\n\tif o == nil || o.NetIds == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.NetIds\n}", "func (o *FiltersSubnet) GetIpRanges() []string {\n\tif o == nil || o.IpRanges == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.IpRanges\n}", "func NetList(ip net.IP, subnet net.IP) (IPlist []net.IP) {\n\t//ip, ipnet, err := net.ParseCIDR(cidrNet)\n\tmask := net.IPv4Mask(subnet[0], subnet[1], subnet[2], subnet[3])\n\tipnet := net.IPNet{ip, mask}\n\tfor ip := ip.Mask(mask); ipnet.Contains(ip); incIP(ip) {\n\t\tIPlist = append(IPlist, net.IP{ip[0], ip[1], ip[2], ip[3]})\n\t}\n\treturn\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 (ipam *Ipam) GetSubnets(id string) ([]models.Subnet, error) {\n\tsession := ipam.session.Copy()\n\tdefer session.Close()\n\n\tvar subnets []models.Subnet\n\n\tsession.DB(IpamDatabase).C(IpamCollectionSubnets).Find(bson.M{\"pool\": bson.ObjectIdHex(id)}).All(&subnets)\n\n\treturn subnets, nil\n}", "func (r Virtual_Disk_Image) GetPublicIsoImages() (resp []datatypes.Virtual_Disk_Image, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Disk_Image\", \"getPublicIsoImages\", nil, &r.Options, &resp)\n\treturn\n}", "func (u *User) GetPublicRepos() int {\n\tif u == nil || u.PublicRepos == nil {\n\t\treturn 0\n\t}\n\treturn *u.PublicRepos\n}", "func AsPublic(id int64) string {\n\treturn strconv.FormatInt(id, 10)\n}", "func (d *PublicRoomsServerDatabase) GetPublicRooms(offset int64, limit int16, filter string) ([]types.PublicRoom, error) {\n\treturn d.statements.selectPublicRooms(offset, limit, filter)\n}", "func (o GetReposRepoDomainListOutput) Public() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetReposRepoDomainList) string { return v.Public }).(pulumi.StringOutput)\n}", "func ExtractPublicIPs(page pagination.Page) ([]PublicIP, error) {\n\tvar res []PublicIP\n\tcasted := page.(PublicIPPage).Body\n\terr := mapstructure.Decode(casted, &res)\n\n\tvar rawNodesDetails []interface{}\n\tswitch casted.(type) {\n\tcase interface{}:\n\t\trawNodesDetails = casted.([]interface{})\n\tdefault:\n\t\treturn res, fmt.Errorf(\"Unknown type: %v\", reflect.TypeOf(casted))\n\t}\n\n\tfor i := range rawNodesDetails {\n\t\tthisNodeDetails := (rawNodesDetails[i]).(map[string]interface{})\n\n\t\tif t, ok := thisNodeDetails[\"created\"].(string); ok && t != \"\" {\n\t\t\tcreationTime, err := time.Parse(time.RFC3339, t)\n\t\t\tif err != nil {\n\t\t\t\treturn res, err\n\t\t\t}\n\t\t\tres[i].CreatedAt = creationTime\n\t\t}\n\n\t\tif t, ok := thisNodeDetails[\"updated\"].(string); ok && t != \"\" {\n\t\t\tupdatedTime, err := time.Parse(time.RFC3339, t)\n\t\t\tif err != nil {\n\t\t\t\treturn res, err\n\t\t\t}\n\t\t\tres[i].UpdatedAt = updatedTime\n\t\t}\n\n\t\tif cs, ok := thisNodeDetails[\"cloud_server\"].(map[string]interface{}); ok {\n\t\t\tif t, ok := cs[\"created\"].(string); ok && t != \"\" {\n\t\t\t\tcreationTime, err := time.Parse(time.RFC3339, t)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn res, err\n\t\t\t\t}\n\t\t\t\tres[i].CloudServer.CreatedAt = creationTime\n\t\t\t}\n\t\t\tif t, ok := cs[\"updated\"].(string); ok && t != \"\" {\n\t\t\t\tupdatedTime, err := time.Parse(time.RFC3339, t)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn res, err\n\t\t\t\t}\n\t\t\t\tres[i].CloudServer.UpdatedAt = updatedTime\n\t\t\t}\n\t\t\tif cn, ok := cs[\"cloud_network\"].(map[string]interface{}); ok {\n\t\t\t\tif t, ok := cn[\"created\"].(string); ok && t != \"\" {\n\t\t\t\t\tcreationTime, err := time.Parse(time.RFC3339, t)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn res, err\n\t\t\t\t\t}\n\t\t\t\t\tres[i].CloudServer.CloudNetwork.CreatedAt = creationTime\n\t\t\t\t}\n\t\t\t\tif t, ok := cn[\"updated\"].(string); ok && t != \"\" {\n\t\t\t\t\tupdatedTime, err := time.Parse(time.RFC3339, t)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn res, err\n\t\t\t\t\t}\n\t\t\t\t\tres[i].CloudServer.CloudNetwork.UpdatedAt = updatedTime\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res, err\n}", "func isPrivateSubnet(ips string) bool {\n\tip := net.ParseIP(ips)\n\tfor _, r := range privateCIDRs {\n\t\tif r.Contains(ip) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func stupsNATSubnets(vpcCidr string) ([]string, error) {\n\t_, vpcNet, err := net.ParseCIDR(vpcCidr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// subdivide the network into /size+2 subnets first, take the second one\n\tsubnetSize, _ := vpcNet.Mask.Size()\n\tif subnetSize == 0 || subnetSize > 24 {\n\t\treturn nil, fmt.Errorf(\"invalid subnet, expecting at least /24: %s\", vpcNet)\n\t}\n\n\taddrs, err := subdivide(vpcNet, subnetSize+2)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnatNetworks, err := subdivide(addrs[1], 28)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result []string\n\tfor i := 0; i < 3; i++ {\n\t\tresult = append(result, natNetworks[i].String())\n\t}\n\treturn result, nil\n}", "func hosts(cidr string) ([]string, error) {\n\tip, ipnet, err := net.ParseCIDR(cidr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar ips []string\n\n\tfor ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); inc(ip) {\n\t\tips = append(ips, ip.String())\n\t}\n\t// remove network address and broadcast address\n\treturn ips[1 : len(ips)-1], nil\n}", "func GetSubnetIDsFromReservations(reservations []*ec2.Reservation) []string {\n\tuniqueMap := map[string]bool{}\n\tsubnetIds := []string{}\n\tfor _, reservation := range reservations {\n\t\tfor _, instance := range reservation.Instances {\n\t\t\tif *instance.SubnetId != \"\" {\n\t\t\t\tif _, ok := uniqueMap[*instance.SubnetId]; !ok {\n\t\t\t\t\tuniqueMap[*instance.SubnetId] = true\n\t\t\t\t\tsubnetIds = append(subnetIds, *instance.SubnetId)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn subnetIds\n}", "func boundIPs(c *caddy.Controller) (ips []net.IP) {\n\tconf := dnsserver.GetConfig(c)\n\thosts := conf.ListenHosts\n\tif hosts == nil || hosts[0] == \"\" {\n\t\thosts = nil\n\t\taddrs, err := net.InterfaceAddrs()\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t\tfor _, addr := range addrs {\n\t\t\thosts = append(hosts, addr.String())\n\t\t}\n\t}\n\tfor _, host := range hosts {\n\t\tip, _, _ := net.ParseCIDR(host)\n\t\tip4 := ip.To4()\n\t\tif ip4 != nil && !ip4.IsLoopback() {\n\t\t\tips = append(ips, ip4)\n\t\t\tcontinue\n\t\t}\n\t\tip6 := ip.To16()\n\t\tif ip6 != nil && !ip6.IsLoopback() {\n\t\t\tips = append(ips, ip6)\n\t\t}\n\t}\n\treturn ips\n}", "func PrivateNetworkInterfaces(logger log.Logger) []string {\n\tints, err := net.Interfaces()\n\tif err != nil {\n\t\tlevel.Warn(logger).Log(\"msg\", \"error getting network interfaces\", \"err\", err)\n\t}\n\treturn privateNetworkInterfaces(ints, []string{}, logger)\n}", "func (sqlStore *SQLStore) GetSubnets(filter *model.SubnetFilter) ([]*model.Subnet, error) {\n\treturn sqlStore.getSubnets(sqlStore.db, filter)\n}", "func (o *SyntheticsTriggerCITestRunResult) SetPublicId(v string) {\n\to.PublicId = &v\n}", "func (j *JoinHelper) getAllIPs () ([]string, error){\n\n\tvpnName := j.getVPNNicName()\n\tips := make ([]string, 0)\n\n\tinterfaces, err := net.Interfaces()\n\tif err != nil {\n\t\treturn ips, err\n\t}\n\tfor _, iface := range interfaces {\n\t\tif iface.Name != vpnName {\n\t\t\taddresses, err := iface.Addrs()\n\t\t\tif err != nil {\n\t\t\t\treturn ips, err\n\t\t\t}\n\t\t\tfor _, addr := range addresses {\n\t\t\t\tnetIP, ok := addr.(*net.IPNet)\n\t\t\t\tif ok && !netIP.IP.IsLoopback() && netIP.IP.To4() != nil {\n\t\t\t\t\tip := netIP.IP.String()\n\t\t\t\t\tips = append(ips, ip)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ips, nil\n}", "func AllowPrivateSubnetForMyip() *net.IPNet {\n\tvar ip = net.ParseIP(myip)\n\tfor i, ipr := range privateCIDRs {\n\t\tif ipr.Contains(ip) {\n\t\t\t//remove ipr\n\t\t\tprivateCIDRs = append(privateCIDRs[:i], privateCIDRs[i+1:]...)\n\t\t\treturn ipr\n\t\t}\n\t}\n\treturn nil\n}", "func PublicIpv4Contains(v string) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.Contains(s.C(FieldPublicIpv4), v))\n\t})\n}", "func GetPublicKeys(chain engine.ChainReader, header *block.Header, reCalculate bool) ([]*bls.PublicKey, error) {\n\tshardState := new(shard.State)\n\tvar err error\n\tif reCalculate {\n\t\tshardState, _ = committee.WithStakingEnabled.Compute(header.Epoch(), chain)\n\t} else {\n\t\tshardState, err = chain.ReadShardState(header.Epoch())\n\t\tif err != nil {\n\t\t\treturn nil, ctxerror.New(\"failed to read shard state of epoch\",\n\t\t\t\t\"epoch\", header.Epoch().Uint64()).WithCause(err)\n\t\t}\n\t}\n\n\tcommittee := shardState.FindCommitteeByID(header.ShardID())\n\tif committee == nil {\n\t\treturn nil, ctxerror.New(\"cannot find shard in the shard state\",\n\t\t\t\"blockNumber\", header.Number(),\n\t\t\t\"shardID\", header.ShardID(),\n\t\t)\n\t}\n\tvar committerKeys []*bls.PublicKey\n\n\tutils.Logger().Print(committee.Slots)\n\tfor _, member := range committee.Slots {\n\t\tcommitterKey := new(bls.PublicKey)\n\t\terr := member.BlsPublicKey.ToLibBLSPublicKey(committerKey)\n\t\tif err != nil {\n\t\t\treturn nil, ctxerror.New(\"cannot convert BLS public key\",\n\t\t\t\t\"blsPublicKey\", member.BlsPublicKey).WithCause(err)\n\t\t}\n\t\tcommitterKeys = append(committerKeys, committerKey)\n\t}\n\treturn committerKeys, nil\n}", "func (users Users) PublicUsers() []interface{} {\n\tresult := make([]interface{}, len(users))\n\tfor index, user := range users {\n\t\tresult[index] = user.PublicUser()\n\t}\n\treturn result\n}", "func (users Users) PublicUsers() []interface{} {\n\tresult := make([]interface{}, len(users))\n\tfor index, user := range users {\n\t\tresult[index] = user.PublicUser()\n\t}\n\treturn result\n}", "func (_Ethdkg *EthdkgCaller) PublicKeys(opts *bind.CallOpts, arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Ethdkg.contract.Call(opts, out, \"public_keys\", arg0, arg1)\n\treturn *ret0, err\n}", "func PublicIpv4(v string) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldPublicIpv4), v))\n\t})\n}", "func (priv *PrivateKey) Public() (*PublicKey, error) {\n\tslice, err := curve25519.X25519(priv[:], curve25519.Basepoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tp, _ := PublicKeyFromSlice(slice)\n\treturn p, nil\n}", "func (e *Endpoints) CIDRPrefixes() ([]*net.IPNet, error) {\n\tprefixes := make([]string, len(e.Backends))\n\tindex := 0\n\tfor ip := range e.Backends {\n\t\tprefixes[index] = ip\n\t\tindex++\n\t}\n\n\tvalid, invalid := ip.ParseCIDRs(prefixes)\n\tif len(invalid) > 0 {\n\t\treturn nil, fmt.Errorf(\"invalid IPs specified as backends: %+v\", invalid)\n\t}\n\n\treturn valid, nil\n}", "func (o *FiltersNatService) HasSubnetIds() bool {\n\tif o != nil && o.SubnetIds != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func NewPublicIPAddressesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) *PublicIPAddressesClient {\n\tcp := arm.ClientOptions{}\n\tif options != nil {\n\t\tcp = *options\n\t}\n\tif len(cp.Endpoint) == 0 {\n\t\tcp.Endpoint = arm.AzurePublicCloud\n\t}\n\tclient := &PublicIPAddressesClient{\n\t\tsubscriptionID: subscriptionID,\n\t\thost: string(cp.Endpoint),\n\t\tpl: armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, &cp),\n\t}\n\treturn client\n}", "func (yad *yandexDisk) ListPublicResources(fields []string, limit int, offset int, previewCrop bool, previewSize string, resourceType string) (l *PublicResourcesList, e error) {\n\tvalues := url.Values{}\n\tvalues.Add(\"fields\", strings.Join(fields, \",\"))\n\tvalues.Add(\"limit\", strconv.Itoa(limit))\n\tvalues.Add(\"offset\", strconv.Itoa(offset))\n\tvalues.Add(\"preview_crop\", strconv.FormatBool(previewCrop))\n\tvalues.Add(\"preview_size\", previewSize)\n\tvalues.Add(\"type\", resourceType)\n\n\treq, e := yad.client.request(http.MethodGet, \"/disk/resources/public?\"+values.Encode(), nil)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\n\tl = new(PublicResourcesList)\n\t_, e = yad.client.getResponse(req, &l)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\treturn\n}", "func (c *MockSubnetsClient) List(ctx context.Context, resourceGroupName, virtualNetworkName string) ([]network.Subnet, error) {\n\tvar l []network.Subnet\n\tfor _, subnet := range c.Subnets {\n\t\tl = append(l, subnet)\n\t}\n\treturn l, nil\n}", "func (o RepoDomainListOutput) Public() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v RepoDomainList) *string { return v.Public }).(pulumi.StringPtrOutput)\n}", "func (o *FiltersVmGroup) SetSubnetIds(v []string) {\n\to.SubnetIds = &v\n}", "func (o KubernetesClusterNetworkProfileLoadBalancerProfileOutput) OutboundIpAddressIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v KubernetesClusterNetworkProfileLoadBalancerProfile) []string { return v.OutboundIpAddressIds }).(pulumi.StringArrayOutput)\n}", "func (v *Vault) ListPublicKeys(ctx context.Context) vault.StoredKeysIterator {\n\treturn &azureIterator{\n\t\tctx: ctx,\n\t\tv: v,\n\t}\n}", "func (c *Client) IPs() (IPAddrs, error) {\n\tresp, err := c.Get(\"/public-ip-list\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar m map[string][]string\n\tif err := decodeBodyMap(resp.Body, &m); err != nil {\n\t\treturn nil, err\n\t}\n\treturn IPAddrs(m[\"addresses\"]), nil\n}", "func (o RepoDomainListPtrOutput) Public() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *RepoDomainList) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Public\n\t}).(pulumi.StringPtrOutput)\n}", "func CreateListPublicIpAddressPoolCidrBlocksResponse() (response *ListPublicIpAddressPoolCidrBlocksResponse) {\n\tresponse = &ListPublicIpAddressPoolCidrBlocksResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func knownPublicRegions(architecture types.Architecture) map[string]string {\n\trequired := rhcos.AMIRegions(architecture)\n\n\tregions := make(map[string]string)\n\tfor _, region := range endpoints.AwsPartition().Regions() {\n\t\tif required.Has(region.ID()) {\n\t\t\tregions[region.ID()] = region.Description()\n\t\t}\n\t}\n\treturn regions\n}", "func sanitizeAddrsplodedSet(public, private []ma.Multiaddr) []ma.Multiaddr {\n\ttype portAndAddr struct {\n\t\taddr ma.Multiaddr\n\t\tport int\n\t}\n\n\tprivports := make(map[int]struct{})\n\tpubaddrs := make(map[string][]portAndAddr)\n\n\tfor _, a := range private {\n\t\t_, port := addrKeyAndPort(a)\n\t\tprivports[port] = struct{}{}\n\t}\n\n\tfor _, a := range public {\n\t\tkey, port := addrKeyAndPort(a)\n\t\tpubaddrs[key] = append(pubaddrs[key], portAndAddr{addr: a, port: port})\n\t}\n\n\tvar result []ma.Multiaddr\n\tfor _, pas := range pubaddrs {\n\t\tif len(pas) == 1 {\n\t\t\t// it's not addrsploded\n\t\t\tresult = append(result, pas[0].addr)\n\t\t\tcontinue\n\t\t}\n\n\t\thaveAddr := false\n\t\tfor _, pa := range pas {\n\t\t\tif _, ok := privports[pa.port]; ok {\n\t\t\t\t// it matches a privately bound port, use it\n\t\t\t\tresult = append(result, pa.addr)\n\t\t\t\thaveAddr = true\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif pa.port == 4001 || pa.port == 4002 {\n\t\t\t\t// it's a default port, use it\n\t\t\t\tresult = append(result, pa.addr)\n\t\t\t\thaveAddr = true\n\t\t\t}\n\t\t}\n\n\t\tif !haveAddr {\n\t\t\t// we weren't able to select a port; bite the bullet and use them all\n\t\t\tfor _, pa := range pas {\n\t\t\t\tresult = append(result, pa.addr)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result\n}", "func (o *FiltersSubnet) HasSubnetIds() bool {\n\tif o != nil && o.SubnetIds != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *FiltersNet) GetIpRanges() []string {\n\tif o == nil || o.IpRanges == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.IpRanges\n}", "func (o *FiltersVmGroup) HasSubnetIds() bool {\n\tif o != nil && o.SubnetIds != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func localIPv4s() ([]string, error) {\n\tvar ips []string\n\taddrs, err := net.InterfaceAddrs()\n\tif err != nil {\n\t\treturn ips, err\n\t}\n\n\tfor _, a := range addrs {\n\t\tif ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil {\n\t\t\tips = append(ips, ipnet.IP.String())\n\t\t}\n\t}\n\n\treturn ips, nil\n}", "func (o KubernetesClusterNetworkProfileLoadBalancerProfileOutput) OutboundIpPrefixIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v KubernetesClusterNetworkProfileLoadBalancerProfile) []string { return v.OutboundIpPrefixIds }).(pulumi.StringArrayOutput)\n}", "func validateAllPrivateOrPublicSubnets(userSubnets []string) error {\n\tutilitySubnets := 0\n\tfor _, userSubnet := range userSubnets {\n\t\tif strings.HasPrefix(userSubnet, \"utility-\") {\n\t\t\tutilitySubnets++\n\t\t}\n\t}\n\n\tif utilitySubnets != 0 && len(userSubnets) != utilitySubnets {\n\t\treturn fmt.Errorf(\"error instance group cannot span public and private subnets\")\n\t}\n\treturn nil\n}", "func (c *V3Client) getPublicRepositories(ctx context.Context, sinceRepoID int64) ([]*Repository, error) {\n\tpath := \"repositories\"\n\tif sinceRepoID > 0 {\n\t\tpath += \"?per_page=100&since=\" + strconv.FormatInt(sinceRepoID, 10)\n\t}\n\treturn c.listRepositories(ctx, path)\n}", "func (s *serfNet) MembersID() (list [][]byte) {\n\tmembers := s._serf.Members()\n\tfor i := 0; i < len(members); i++ {\n\t\tvar port string\n\t\tif len(members[i].Name) < 20 {\n\t\t\tcontinue\n\t\t}\n\t\tif len(members[i].Name) == 20 {\n\t\t\tport = \"9501\"\n\t\t\tcontinue\n\t\t} else {\n\t\t\tport = members[i].Name[20:]\n\t\t}\n\t\tfmt.Println(members[i].Addr.String() + \":\" + port)\n\t\tfmt.Println(\"len \", len(members[i].Name))\n\t\tif members[i].Status == serf.StatusAlive {\n\t\t\tlist = append(list, []byte(members[i].Name))\n\t\t}\n\n\t}\n\treturn\n}", "func (o ClusterNodeGroupOptionsOutput) NodeSubnetIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ClusterNodeGroupOptions) []string { return v.NodeSubnetIds }).(pulumi.StringArrayOutput)\n}", "func Public() []Service {\n\tc.mutex.RLock()\n\tdefer c.mutex.RUnlock()\n\n\tvar services []Service\n\tfor _, service := range c.services {\n\t\tif !service.Public {\n\t\t\tcontinue\n\t\t}\n\n\t\tservices = append(services, service)\n\t}\n\n\treturn services\n}" ]
[ "0.61891586", "0.5924014", "0.57987916", "0.57511437", "0.57172686", "0.57081604", "0.54603547", "0.5409055", "0.54011387", "0.53628165", "0.53247654", "0.521296", "0.5211982", "0.520052", "0.515711", "0.51483375", "0.51237404", "0.51102495", "0.5107029", "0.51025856", "0.5092361", "0.50542647", "0.50254357", "0.499971", "0.49607152", "0.49182263", "0.48877135", "0.48806658", "0.48758605", "0.48633057", "0.47962844", "0.4774533", "0.4770777", "0.4758759", "0.4754732", "0.47324237", "0.47242916", "0.47241697", "0.4721569", "0.47202456", "0.46802387", "0.46791336", "0.46773514", "0.46759322", "0.46602586", "0.46600875", "0.46547636", "0.46392187", "0.46157905", "0.45708552", "0.45613182", "0.4559375", "0.45578143", "0.4547548", "0.45469624", "0.45398012", "0.452963", "0.4521943", "0.45207378", "0.45178285", "0.4513749", "0.45106852", "0.44954744", "0.4488818", "0.44841802", "0.44808334", "0.4477774", "0.44772163", "0.44686452", "0.44650504", "0.44625616", "0.4462307", "0.4462307", "0.44590878", "0.44589645", "0.44573137", "0.44438097", "0.44425517", "0.44386452", "0.4430748", "0.44251803", "0.44188648", "0.4415479", "0.44142097", "0.44053915", "0.44049695", "0.43973792", "0.43939713", "0.43933266", "0.43781728", "0.43775734", "0.43700677", "0.4362146", "0.43529448", "0.4350683", "0.43500224", "0.4345456", "0.43448648", "0.43447226", "0.4341531" ]
0.8309432
0
FindManagedStacks returns all CloudFormation stacks containing the controller management tags that match the current cluster and are ready to be used. The stack status is used to filter.
func (a *Adapter) FindManagedStacks() ([]*Stack, error) { stacks, err := findManagedStacks(a.cloudformation, a.ClusterID()) if err != nil { return nil, err } targetGroupARNs := make([]string, len(stacks)) for i, stack := range stacks { targetGroupARNs[i] = stack.targetGroupARN } // This call is idempotent and safe to execute every time if err := attachTargetGroupsToAutoScalingGroup(a.autoscaling, targetGroupARNs, a.AutoScalingGroupName()); err != nil { log.Printf("FindManagedStacks() failed to attach target groups to ASG: %v", err) } return stacks, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func DescribeStacks(r string) {\n\tsvc := cloudformation.New(getSession(r))\n\n\tstatii := []*string{\n\t\taws.String(\"CREATE_COMPLETE\"),\n\t\taws.String(\"CREATE_IN_PROGRESS\"),\n\t\taws.String(\"UPDATE_COMPLETE\"),\n\t\taws.String(\"UPDATE_IN_PROGRESS\"),\n\t}\n\n\tstackSummaries, err := svc.ListStacks(&cloudformation.ListStacksInput{\n\t\tStackStatusFilter: statii,\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor _, stack := range stackSummaries.StackSummaries {\n\t\tlog.Print(\"%-52v %-40v %-20v\", *stack.StackName,\n\t\t\tstack.CreationTime.Format(\"Mon Jan 2 15:04:05 MST 2006\"),\n\t\t\t*stack.StackStatus,\n\t\t)\n\t\t// List change sets:\n\t\tchangeSets := DescribeChangeSets(r, *stack.StackName)\n\t\tfor _, change := range changeSets.Summaries {\n\t\t\tlog.Print(\"\\tchange set -> %-30v %-40v %-20v\", *change.ChangeSetName,\n\t\t\t\tchange.CreationTime.Format(\"Mon Jan 2 15:04:05 MST 2006\"),\n\t\t\t\t*change.ExecutionStatus,\n\t\t\t)\n\t\t}\n\t}\n}", "func (m *MockCloudformationAPI) DescribeStacks(input *cloudformation.DescribeStacksInput) (*cloudformation.DescribeStacksOutput, error) {\n\tif m.FailDescribe {\n\t\treturn nil, m.Err\n\t}\n\n\treturn &cloudformation.DescribeStacksOutput{\n\t\tStacks: []*cloudformation.Stack{\n\t\t\t&cloudformation.Stack{\n\t\t\t\tStackName: aws.String(\"foo\"),\n\t\t\t\tStackStatus: aws.String(m.Status),\n\t\t\t\tOutputs: []*cloudformation.Output{\n\t\t\t\t\t&cloudformation.Output{\n\t\t\t\t\t\tOutputKey: aws.String(\"CustomerGateway0\"),\n\t\t\t\t\t\tOutputValue: aws.String(\"test-CustomerGatewayID\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, nil\n}", "func lookupStack(clustername string) (string, string, error) {\n\tcfg, err := external.LoadDefaultAWSConfig()\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tsvc := cloudformation.New(cfg)\n\tvar activeStacks = []cloudformation.StackStatus{\"CREATE_COMPLETE\"}\n\tlsreq := svc.ListStacksRequest(&cloudformation.ListStacksInput{StackStatusFilter: activeStacks})\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tlsresp, err := lsreq.Send(context.TODO())\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\t// iterate over active stacks to find the two eksctl created, by label\n\tcpstack, dpstack := \"\", \"\"\n\tfor _, stack := range lsresp.StackSummaries {\n\t\tdsreq := svc.DescribeStacksRequest(&cloudformation.DescribeStacksInput{StackName: stack.StackName})\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", err\n\t\t}\n\t\tdsresp, err := dsreq.Send(context.TODO())\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", err\n\t\t}\n\t\t// fmt.Printf(\"DEBUG:: checking stack %v if it has label with cluster name %v\\n\", *dsresp.Stacks[0].StackName, clustername)\n\t\tcnofstack := tagValueOf(dsresp.Stacks[0], \"eksctl.cluster.k8s.io/v1alpha1/cluster-name\")\n\t\tif cnofstack != \"\" && cnofstack == clustername {\n\t\t\tswitch {\n\t\t\tcase tagValueOf(dsresp.Stacks[0], \"alpha.eksctl.io/nodegroup-name\") != \"\":\n\t\t\t\tdpstack = *dsresp.Stacks[0].StackName\n\t\t\tdefault:\n\t\t\t\tcpstack = *dsresp.Stacks[0].StackName\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Printf(\"DEBUG:: found control plane stack [%v] and data plane stack [%v] for cluster %v\\n\", cpstack, dpstack, clustername)\n\treturn cpstack, dpstack, nil\n}", "func (client *XenClient) SMGetRequiredClusterStack(self string) (result []string, err error) {\n\tobj, err := client.APICall(\"SM.get_required_cluster_stack\", self)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tresult = make([]string, len(obj.([]interface{})))\n\tfor i, value := range obj.([]interface{}) {\n\t\tresult[i] = value.(string)\n\t}\n\n\treturn\n}", "func (client *CraneDockerClient) filterStackServices(namespace string) ([]swarm.Service, error) {\n\treturn client.ListServiceSpec(types.ServiceListOptions{Filter: client.getStackFilter(namespace)})\n}", "func (a *StacksApiService) GetStacks(ctx _context.Context) apiGetStacksRequest {\n\treturn apiGetStacksRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t}\n}", "func ProcessStacks(\n\tcliConfig schema.CliConfiguration,\n\tconfigAndStacksInfo schema.ConfigAndStacksInfo,\n\tcheckStack bool,\n) (schema.ConfigAndStacksInfo, error) {\n\n\t// Check if stack was provided\n\tif checkStack && len(configAndStacksInfo.Stack) < 1 {\n\t\tmessage := fmt.Sprintf(\"'stack' is required. Usage: atmos %s <command> <component> -s <stack>\", configAndStacksInfo.ComponentType)\n\t\treturn configAndStacksInfo, errors.New(message)\n\t}\n\n\t// Check if component was provided\n\tif len(configAndStacksInfo.ComponentFromArg) < 1 {\n\t\tmessage := fmt.Sprintf(\"'component' is required. Usage: atmos %s <command> <component> <arguments_and_flags>\", configAndStacksInfo.ComponentType)\n\t\treturn configAndStacksInfo, errors.New(message)\n\t}\n\n\tconfigAndStacksInfo.StackFromArg = configAndStacksInfo.Stack\n\n\tstacksMap, rawStackConfigs, err := FindStacksMap(cliConfig, false)\n\tif err != nil {\n\t\treturn configAndStacksInfo, err\n\t}\n\n\t// Print the stack config files\n\tif cliConfig.Logs.Level == u.LogLevelTrace {\n\t\tvar msg string\n\t\tif cliConfig.StackType == \"Directory\" {\n\t\t\tmsg = \"\\nFound the config file for the provided stack:\"\n\t\t} else {\n\t\t\tmsg = \"\\nFound stack config files:\"\n\t\t}\n\t\tu.LogTrace(cliConfig, msg)\n\t\terr = u.PrintAsYAML(cliConfig.StackConfigFilesRelativePaths)\n\t\tif err != nil {\n\t\t\treturn configAndStacksInfo, err\n\t\t}\n\t}\n\n\t// Check and process stacks\n\tif cliConfig.StackType == \"Directory\" {\n\t\terr = FindComponentConfig(\n\t\t\t&configAndStacksInfo,\n\t\t\tconfigAndStacksInfo.Stack,\n\t\t\tstacksMap,\n\t\t\tconfigAndStacksInfo.ComponentType,\n\t\t\tconfigAndStacksInfo.ComponentFromArg,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn configAndStacksInfo, err\n\t\t}\n\n\t\tconfigAndStacksInfo.ComponentEnvList = u.ConvertEnvVars(configAndStacksInfo.ComponentEnvSection)\n\t\tconfigAndStacksInfo.StackFile = configAndStacksInfo.Stack\n\n\t\t// Process context\n\t\tconfigAndStacksInfo.Context = cfg.GetContextFromVars(configAndStacksInfo.ComponentVarsSection)\n\t\tconfigAndStacksInfo.Context.Component = configAndStacksInfo.ComponentFromArg\n\t\tconfigAndStacksInfo.Context.BaseComponent = configAndStacksInfo.BaseComponentPath\n\n\t\tconfigAndStacksInfo.ContextPrefix, err = cfg.GetContextPrefix(configAndStacksInfo.Stack,\n\t\t\tconfigAndStacksInfo.Context,\n\t\t\tcliConfig.Stacks.NamePattern,\n\t\t\tconfigAndStacksInfo.Stack,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn configAndStacksInfo, err\n\t\t}\n\t} else {\n\t\tfoundStackCount := 0\n\t\tvar foundStacks []string\n\t\tvar foundConfigAndStacksInfo schema.ConfigAndStacksInfo\n\n\t\tfor stackName := range stacksMap {\n\t\t\t// Check if we've found the component config\n\t\t\terr = FindComponentConfig(\n\t\t\t\t&configAndStacksInfo,\n\t\t\t\tstackName,\n\t\t\t\tstacksMap,\n\t\t\t\tconfigAndStacksInfo.ComponentType,\n\t\t\t\tconfigAndStacksInfo.ComponentFromArg,\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconfigAndStacksInfo.ComponentEnvList = u.ConvertEnvVars(configAndStacksInfo.ComponentEnvSection)\n\n\t\t\t// Process context\n\t\t\tconfigAndStacksInfo.Context = cfg.GetContextFromVars(configAndStacksInfo.ComponentVarsSection)\n\t\t\tconfigAndStacksInfo.Context.Component = configAndStacksInfo.ComponentFromArg\n\t\t\tconfigAndStacksInfo.Context.BaseComponent = configAndStacksInfo.BaseComponentPath\n\n\t\t\tconfigAndStacksInfo.ContextPrefix, err = cfg.GetContextPrefix(configAndStacksInfo.Stack,\n\t\t\t\tconfigAndStacksInfo.Context,\n\t\t\t\tcliConfig.Stacks.NamePattern,\n\t\t\t\tstackName,\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Check if we've found the stack\n\t\t\tif configAndStacksInfo.Stack == configAndStacksInfo.ContextPrefix {\n\t\t\t\tconfigAndStacksInfo.StackFile = stackName\n\t\t\t\tfoundConfigAndStacksInfo = configAndStacksInfo\n\t\t\t\tfoundStackCount++\n\t\t\t\tfoundStacks = append(foundStacks, stackName)\n\n\t\t\t\tu.LogDebug(\n\t\t\t\t\tcliConfig,\n\t\t\t\t\tfmt.Sprintf(\"Found config for the component '%s' for the stack '%s' in the stack config file '%s'\",\n\t\t\t\t\t\tconfigAndStacksInfo.ComponentFromArg,\n\t\t\t\t\t\tconfigAndStacksInfo.Stack,\n\t\t\t\t\t\tstackName,\n\t\t\t\t\t))\n\t\t\t}\n\t\t}\n\n\t\tif foundStackCount == 0 {\n\t\t\ty, _ := u.ConvertToYAML(cliConfig)\n\n\t\t\treturn configAndStacksInfo,\n\t\t\t\tfmt.Errorf(\"\\nSearched all stack YAML files, but could not find config for the component '%s' in the stack '%s'.\\n\"+\n\t\t\t\t\t\"Check that all variables in the stack name pattern '%s' are correctly defined in the stack config files.\\n\"+\n\t\t\t\t\t\"Are the component and stack names correct? Did you forget an import?\\n\\n\\nCLI config:\\n\\n%v\",\n\t\t\t\t\tconfigAndStacksInfo.ComponentFromArg,\n\t\t\t\t\tconfigAndStacksInfo.Stack,\n\t\t\t\t\tcliConfig.Stacks.NamePattern,\n\t\t\t\t\ty)\n\t\t} else if foundStackCount > 1 {\n\t\t\terr = fmt.Errorf(\"\\nFound duplicate config for the component '%s' for the stack '%s' in the files: %v.\\n\"+\n\t\t\t\t\"Check that all context variables in the stack name pattern '%s' are correctly defined in the files and not duplicated.\\n\"+\n\t\t\t\t\"Check that all imports are valid.\",\n\t\t\t\tconfigAndStacksInfo.ComponentFromArg,\n\t\t\t\tconfigAndStacksInfo.Stack,\n\t\t\t\tstrings.Join(foundStacks, \", \"),\n\t\t\t\tcliConfig.Stacks.NamePattern)\n\t\t\tu.LogErrorAndExit(err)\n\t\t} else {\n\t\t\tconfigAndStacksInfo = foundConfigAndStacksInfo\n\t\t}\n\t}\n\n\tif len(configAndStacksInfo.Command) == 0 {\n\t\tconfigAndStacksInfo.Command = configAndStacksInfo.ComponentType\n\t}\n\n\t// Process component path and name\n\tconfigAndStacksInfo.ComponentFolderPrefix = \"\"\n\tcomponentPathParts := strings.Split(configAndStacksInfo.ComponentFromArg, \"/\")\n\tcomponentPathPartsLength := len(componentPathParts)\n\tif componentPathPartsLength > 1 {\n\t\tcomponentFromArgPartsWithoutLast := componentPathParts[:componentPathPartsLength-1]\n\t\tconfigAndStacksInfo.ComponentFolderPrefix = strings.Join(componentFromArgPartsWithoutLast, \"/\")\n\t\tconfigAndStacksInfo.Component = componentPathParts[componentPathPartsLength-1]\n\t} else {\n\t\tconfigAndStacksInfo.Component = configAndStacksInfo.ComponentFromArg\n\t}\n\tconfigAndStacksInfo.ComponentFolderPrefixReplaced = strings.Replace(configAndStacksInfo.ComponentFolderPrefix, \"/\", \"-\", -1)\n\n\t// Process base component path and name\n\tif len(configAndStacksInfo.BaseComponentPath) > 0 {\n\t\tbaseComponentPathParts := strings.Split(configAndStacksInfo.BaseComponentPath, \"/\")\n\t\tbaseComponentPathPartsLength := len(baseComponentPathParts)\n\t\tif baseComponentPathPartsLength > 1 {\n\t\t\tbaseComponentPartsWithoutLast := baseComponentPathParts[:baseComponentPathPartsLength-1]\n\t\t\tconfigAndStacksInfo.ComponentFolderPrefix = strings.Join(baseComponentPartsWithoutLast, \"/\")\n\t\t\tconfigAndStacksInfo.BaseComponent = baseComponentPathParts[baseComponentPathPartsLength-1]\n\t\t} else {\n\t\t\tconfigAndStacksInfo.ComponentFolderPrefix = \"\"\n\t\t\tconfigAndStacksInfo.BaseComponent = configAndStacksInfo.BaseComponentPath\n\t\t}\n\t\tconfigAndStacksInfo.ComponentFolderPrefixReplaced = strings.Replace(configAndStacksInfo.ComponentFolderPrefix, \"/\", \"-\", -1)\n\t}\n\n\t// Get the final component\n\tif len(configAndStacksInfo.BaseComponent) > 0 {\n\t\tconfigAndStacksInfo.FinalComponent = configAndStacksInfo.BaseComponent\n\t} else {\n\t\tconfigAndStacksInfo.FinalComponent = configAndStacksInfo.Component\n\t}\n\n\t// workspace\n\tworkspace, err := BuildTerraformWorkspace(\n\t\tconfigAndStacksInfo.Stack,\n\t\tcliConfig.Stacks.NamePattern,\n\t\tconfigAndStacksInfo.ComponentMetadataSection,\n\t\tconfigAndStacksInfo.Context,\n\t)\n\tif err != nil {\n\t\treturn configAndStacksInfo, err\n\t}\n\n\tconfigAndStacksInfo.TerraformWorkspace = workspace\n\tconfigAndStacksInfo.ComponentSection[\"workspace\"] = workspace\n\n\t// Add imports\n\tconfigAndStacksInfo.ComponentSection[\"imports\"] = configAndStacksInfo.ComponentImportsSection\n\n\t// Add Atmos component and stack\n\tconfigAndStacksInfo.ComponentSection[\"atmos_component\"] = configAndStacksInfo.ComponentFromArg\n\tconfigAndStacksInfo.ComponentSection[\"atmos_stack\"] = configAndStacksInfo.StackFromArg\n\tconfigAndStacksInfo.ComponentSection[\"atmos_stack_file\"] = configAndStacksInfo.StackFile\n\n\t// Add Atmos CLI config\n\tatmosCliConfig := map[string]any{}\n\tatmosCliConfig[\"base_path\"] = cliConfig.BasePath\n\tatmosCliConfig[\"components\"] = cliConfig.Components\n\tatmosCliConfig[\"stacks\"] = cliConfig.Stacks\n\tatmosCliConfig[\"workflows\"] = cliConfig.Workflows\n\tconfigAndStacksInfo.ComponentSection[\"atmos_cli_config\"] = atmosCliConfig\n\n\t// If the command-line component does not inherit anything, then the Terraform/Helmfile component is the same as the provided one\n\tif comp, ok := configAndStacksInfo.ComponentSection[\"component\"].(string); !ok || comp == \"\" {\n\t\tconfigAndStacksInfo.ComponentSection[\"component\"] = configAndStacksInfo.ComponentFromArg\n\t}\n\n\t// Spacelift stack\n\tspaceliftStackName, err := BuildSpaceliftStackNameFromComponentConfig(\n\t\tcliConfig,\n\t\tconfigAndStacksInfo.ComponentFromArg,\n\t\tconfigAndStacksInfo.Stack,\n\t\tconfigAndStacksInfo.ComponentSettingsSection,\n\t\tconfigAndStacksInfo.ComponentVarsSection,\n\t)\n\n\tif err != nil {\n\t\treturn configAndStacksInfo, err\n\t}\n\n\tif spaceliftStackName != \"\" {\n\t\tconfigAndStacksInfo.ComponentSection[\"spacelift_stack\"] = spaceliftStackName\n\t}\n\n\t// Atlantis project\n\tatlantisProjectName, err := BuildAtlantisProjectNameFromComponentConfig(\n\t\tcliConfig,\n\t\tconfigAndStacksInfo.ComponentFromArg,\n\t\tconfigAndStacksInfo.ComponentSettingsSection,\n\t\tconfigAndStacksInfo.ComponentVarsSection,\n\t)\n\n\tif err != nil {\n\t\treturn configAndStacksInfo, err\n\t}\n\n\tif atlantisProjectName != \"\" {\n\t\tconfigAndStacksInfo.ComponentSection[\"atlantis_project\"] = atlantisProjectName\n\t}\n\n\t// Add component info, including Terraform config\n\tcomponentInfo := map[string]any{}\n\tcomponentInfo[\"component_type\"] = configAndStacksInfo.ComponentType\n\n\tif configAndStacksInfo.ComponentType == \"terraform\" {\n\t\tcomponentPath := constructTerraformComponentWorkingDir(cliConfig, configAndStacksInfo)\n\t\tcomponentInfo[\"component_path\"] = componentPath\n\t\tterraformConfiguration, _ := tfconfig.LoadModule(componentPath)\n\t\tcomponentInfo[\"terraform_config\"] = terraformConfiguration\n\t} else if configAndStacksInfo.ComponentType == \"helmfile\" {\n\t\tcomponentInfo[\"component_path\"] = constructHelmfileComponentWorkingDir(cliConfig, configAndStacksInfo)\n\t}\n\n\tconfigAndStacksInfo.ComponentSection[\"component_info\"] = componentInfo\n\n\t// `sources` (stack config files where the variables and other settings are defined)\n\tsources, err := ProcessConfigSources(configAndStacksInfo, rawStackConfigs)\n\tif err != nil {\n\t\treturn configAndStacksInfo, err\n\t}\n\n\tconfigAndStacksInfo.ComponentSection[\"sources\"] = sources\n\n\t// Component dependencies\n\tcomponentDeps, componentDepsAll, err := FindComponentDependencies(configAndStacksInfo.StackFile, sources)\n\tif err != nil {\n\t\treturn configAndStacksInfo, err\n\t}\n\tconfigAndStacksInfo.ComponentSection[\"deps\"] = componentDeps\n\tconfigAndStacksInfo.ComponentSection[\"deps_all\"] = componentDepsAll\n\n\treturn configAndStacksInfo, nil\n}", "func FindStacksMap(cliConfig schema.CliConfiguration, ignoreMissingFiles bool) (\n\tmap[string]any,\n\tmap[string]map[string]any,\n\terror,\n) {\n\t// Process stack config file(s)\n\t_, stacksMap, rawStackConfigs, err := s.ProcessYAMLConfigFiles(\n\t\tcliConfig.StacksBaseAbsolutePath,\n\t\tcliConfig.TerraformDirAbsolutePath,\n\t\tcliConfig.HelmfileDirAbsolutePath,\n\t\tcliConfig.StackConfigFilesAbsolutePaths,\n\t\tfalse,\n\t\ttrue,\n\t\tignoreMissingFiles,\n\t)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn stacksMap, rawStackConfigs, nil\n}", "func Status(ctx context.Context,\n\tserviceName string,\n\tserviceDescription string,\n\tredact bool,\n\tlogger *zerolog.Logger) error {\n\n\tawsConfig, awsConfigErr := spartaAWS.NewConfig(ctx, logger)\n\tif awsConfigErr != nil {\n\t\treturn awsConfigErr\n\t}\n\tcfSvc := awsv2CF.NewFromConfig(awsConfig)\n\n\tparams := &awsv2CF.DescribeStacksInput{\n\t\tStackName: aws.String(serviceName),\n\t}\n\tdescribeStacksResponse, describeStacksResponseErr := cfSvc.DescribeStacks(ctx, params)\n\n\tif describeStacksResponseErr != nil {\n\t\tif strings.Contains(describeStacksResponseErr.Error(), \"does not exist\") {\n\t\t\tlogger.Info().Str(\"Region\", awsConfig.Region).Msg(\"Stack does not exist\")\n\t\t\treturn nil\n\t\t}\n\t\treturn describeStacksResponseErr\n\t}\n\tif len(describeStacksResponse.Stacks) > 1 {\n\t\treturn errors.Errorf(\"More than 1 stack returned for %s. Count: %d\",\n\t\t\tserviceName,\n\t\t\tlen(describeStacksResponse.Stacks))\n\t}\n\n\t// What's the current accountID?\n\tredactor := func(stringValue string) string {\n\t\treturn stringValue\n\t}\n\tif redact {\n\t\tinput := &awsv2STS.GetCallerIdentityInput{}\n\n\t\tstsSvc := awsv2STS.NewFromConfig(awsConfig)\n\t\tidentityResponse, identityResponseErr := stsSvc.GetCallerIdentity(ctx, input)\n\t\tif identityResponseErr != nil {\n\t\t\treturn identityResponseErr\n\t\t}\n\t\tredactedValue := strings.Repeat(\"*\", len(*identityResponse.Account))\n\t\tredactor = func(stringValue string) string {\n\t\t\treturn strings.Replace(stringValue,\n\t\t\t\t*identityResponse.Account,\n\t\t\t\tredactedValue,\n\t\t\t\t-1)\n\t\t}\n\t}\n\n\t// Report on what's up with the stack...\n\tlogSectionHeader(\"Stack Summary\", dividerLength, logger)\n\tstackInfo := describeStacksResponse.Stacks[0]\n\tlogger.Info().Str(\"Id\", redactor(*stackInfo.StackId)).Msg(\"StackId\")\n\tlogger.Info().Str(\"Description\", redactor(*stackInfo.Description)).Msg(\"Description\")\n\tlogger.Info().Str(\"State\", string(stackInfo.StackStatus)).Msg(\"Status\")\n\tif stackInfo.StackStatusReason != nil {\n\t\tlogger.Info().Str(\"Reason\", *stackInfo.StackStatusReason).Msg(\"Reason\")\n\t}\n\tlogger.Info().Str(\"Time\", stackInfo.CreationTime.UTC().String()).Msg(\"Created\")\n\tif stackInfo.LastUpdatedTime != nil {\n\t\tlogger.Info().Str(\"Time\", stackInfo.LastUpdatedTime.UTC().String()).Msg(\"Last Update\")\n\t}\n\tif stackInfo.DeletionTime != nil {\n\t\tlogger.Info().Str(\"Time\", stackInfo.DeletionTime.UTC().String()).Msg(\"Deleted\")\n\t}\n\n\tlogger.Info()\n\tif len(stackInfo.Parameters) != 0 {\n\t\tlogSectionHeader(\"Parameters\", dividerLength, logger)\n\t\tfor _, eachParam := range stackInfo.Parameters {\n\t\t\tlogger.Info().Str(\"Value\",\n\t\t\t\tredactor(*eachParam.ParameterValue)).Msg(*eachParam.ParameterKey)\n\t\t}\n\t\tlogger.Info().Msg(\"\")\n\t}\n\tif len(stackInfo.Tags) != 0 {\n\t\tlogSectionHeader(\"Tags\", dividerLength, logger)\n\t\tfor _, eachTag := range stackInfo.Tags {\n\t\t\tlogger.Info().Str(\"Value\",\n\t\t\t\tredactor(*eachTag.Value)).Msg(*eachTag.Key)\n\t\t}\n\t\tlogger.Info().Msg(\"\")\n\t}\n\tif len(stackInfo.Outputs) != 0 {\n\t\tlogSectionHeader(\"Outputs\", dividerLength, logger)\n\t\tfor _, eachOutput := range stackInfo.Outputs {\n\t\t\tstatement := logger.Info().Str(\"Value\",\n\t\t\t\tredactor(*eachOutput.OutputValue))\n\t\t\tif eachOutput.ExportName != nil {\n\t\t\t\tstatement.Str(\"ExportName\", *eachOutput.ExportName)\n\t\t\t}\n\t\t\tstatement.Msg(*eachOutput.OutputKey)\n\t\t}\n\t\tlogger.Info()\n\t}\n\treturn nil\n}", "func (m *MockCfnClient) ListStacks(regexNameFilter *regexp.Regexp, statusFilter []types.StackStatus) ([]cfn.Stack, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListStacks\", regexNameFilter, statusFilter)\n\tret0, _ := ret[0].([]cfn.Stack)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (s *Cloudformation) WaitUntilStackDeleted() (err error) {\n\tsess := s.config.AWSSession\n\tsvc := cloudformation.New(sess)\n\n\tstackInputs := cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(s.StackName()),\n\t}\n\n\terr = svc.WaitUntilStackDeleteComplete(&stackInputs)\n\treturn\n}", "func (tester *ServiceTester) VerifyStacks(t *testing.T) {\n\tvar stack api.Stack\n\n\tstack = aws.NullStack() // nolint\n\tstack = gcp.NullStack() // nolint\n\tstack = huaweicloud.NullStack() // nolint\n\tstack = openstack.NullStack() // nolint\n\tstack = outscale.NullStack() // nolint\n\n\t_ = stack\n}", "func (c *client) Stacks() ([]string, error) {\n\tcfg, err := c.fetchConfig()\n\tif err != nil || cfg == nil {\n\t\treturn nil, err\n\t}\n\n\tvar stack struct {\n\t\tStack struct {\n\t\t\tRunImage struct {\n\t\t\t\tImage string `json:\"image\"`\n\t\t\t} `json:\"runImage\"`\n\t\t} `json:\"stack\"`\n\t}\n\n\tif err := json.NewDecoder(strings.NewReader(cfg.Config.Labels[metadataLabel])).Decode(&stack); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn []string{stack.Stack.RunImage.Image}, nil\n}", "func (c *StackCollection) createClusterStack(ctx context.Context, stackName string, resourceSet builder.ResourceSetReader, errCh chan error) error {\n\tclusterTags := map[string]string{\n\t\tapi.ClusterOIDCEnabledTag: strconv.FormatBool(api.IsEnabled(c.spec.IAM.WithOIDC)),\n\t}\n\tstack, err := c.createStackRequest(ctx, stackName, resourceSet, clusterTags, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\tdefer close(errCh)\n\t\ttroubleshoot := func() {\n\t\t\tstack, err := c.DescribeStack(ctx, stack)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Info(\"error describing stack to troubleshoot the cause of the failure; \"+\n\t\t\t\t\t\"check the CloudFormation console for further details\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlogger.Critical(\"unexpected status %q while waiting for CloudFormation stack %q\", stack.StackStatus, *stack.StackName)\n\t\t\tc.troubleshootStackFailureCause(ctx, stack, string(types.StackStatusCreateComplete))\n\t\t}\n\n\t\tctx, cancelFunc := context.WithTimeout(context.Background(), c.waitTimeout)\n\t\tdefer cancelFunc()\n\n\t\tstack, err := waiter.WaitForStack(ctx, c.cloudformationAPI, *stack.StackId, *stack.StackName, func(attempts int) time.Duration {\n\t\t\t// Wait 30s for the first two requests, and 1m for subsequent requests.\n\t\t\tif attempts <= 2 {\n\t\t\t\treturn 30 * time.Second\n\t\t\t}\n\t\t\treturn 1 * time.Minute\n\t\t})\n\n\t\tif err != nil {\n\t\t\ttroubleshoot()\n\t\t\terrCh <- err\n\t\t\treturn\n\t\t}\n\n\t\tif err := resourceSet.GetAllOutputs(*stack); err != nil {\n\t\t\terrCh <- errors.Wrapf(err, \"getting stack %q outputs\", *stack.StackName)\n\t\t\treturn\n\t\t}\n\n\t\terrCh <- nil\n\t}()\n\n\treturn nil\n}", "func StacksGet(w http.ResponseWriter, r *http.Request) {\n\tresp, err := goreq.Request{\n\t\tMethod: \"GET\",\n\t\tUri: remoteURL + \"/stacks\",\n\t}.Do()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer resp.Body.Close()\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(resp.StatusCode)\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tw.Write(body)\n}", "func (c *Client) Stacks() (StackItems, error) {\n\tstacks := StackItems{}\n\terr := c.request(\"GET\", \"/api/instances\", nil, nil, &stacks)\n\tif err != nil {\n\t\treturn stacks, err\n\t}\n\n\treturn stacks, err\n}", "func Count() (int){\n\tcfg, err := config.LoadDefaultConfig(context.TODO())\n if err != nil {\n panic(\"unable to load SDK config, \" + err.Error())\n\t}\n\t\n\tclient := cloudformation.NewFromConfig(cfg);\n\tinput := &cloudformation.DescribeStacksInput{}\n\n\tresp, _ := client.DescribeStacks(context.TODO(), input)\n\tcount := len(resp.Stacks)\n\treturn count\n}", "func (a *Client) GetNetworkSwitchStacks(params *GetNetworkSwitchStacksParams, authInfo runtime.ClientAuthInfoWriter) (*GetNetworkSwitchStacksOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetNetworkSwitchStacksParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getNetworkSwitchStacks\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/networks/{networkId}/switchStacks\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetNetworkSwitchStacksReader{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.(*GetNetworkSwitchStacksOK)\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 getNetworkSwitchStacks: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (s *Cloudformation) CreateStack() (output *cloudformation.CreateStackOutput, err error) {\n\tsess := s.config.AWSSession\n\tsvc := cloudformation.New(sess)\n\n\tcftemplate := helpers.GetCloudFormationTemplate(s.config, \"s3bucket\", s.S3Bucket.Spec.CloudFormationTemplateName, s.S3Bucket.Spec.CloudFormationTemplateNamespace)\n\n\tstackInputs := cloudformation.CreateStackInput{\n\t\tStackName: aws.String(s.StackName()),\n\t\tTemplateURL: aws.String(cftemplate),\n\t\tNotificationARNs: []*string{\n\t\t\taws.String(s.topicARN),\n\t\t},\n\t}\n\n\tresourceName := helpers.CreateParam(\"ResourceName\", s.S3Bucket.Name)\n\tresourceVersion := helpers.CreateParam(\"ResourceVersion\", s.S3Bucket.ResourceVersion)\n\tnamespace := helpers.CreateParam(\"Namespace\", s.S3Bucket.Namespace)\n\tclusterName := helpers.CreateParam(\"ClusterName\", s.config.ClusterName)\n\tbucketName := helpers.CreateParam(\"BucketName\", helpers.Stringify(s.S3Bucket.Name))\n\tversioningTemp := \"{{.Obj.Spec.Versioning}}\"\n\tversioningValue, err := helpers.Templatize(versioningTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tversioning := helpers.CreateParam(\"EnableVersioning\", helpers.Stringify(versioningValue))\n\taccessControlTemp := \"{{.Obj.Spec.AccessControl}}\"\n\taccessControlValue, err := helpers.Templatize(accessControlTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\taccessControl := helpers.CreateParam(\"BucketAccessControl\", helpers.Stringify(accessControlValue))\n\tloggingenabledTemp := \"{{.Obj.Spec.Logging.Enabled}}\"\n\tloggingenabledValue, err := helpers.Templatize(loggingenabledTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tloggingenabled := helpers.CreateParam(\"EnableLogging\", helpers.Stringify(loggingenabledValue))\n\tloggingprefixTemp := \"{{.Obj.Spec.Logging.Prefix}}\"\n\tloggingprefixValue, err := helpers.Templatize(loggingprefixTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tloggingprefix := helpers.CreateParam(\"LoggingPrefix\", helpers.Stringify(loggingprefixValue))\n\twebsiteenabledTemp := \"{{.Obj.Spec.Website.Enabled}}\"\n\twebsiteenabledValue, err := helpers.Templatize(websiteenabledTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteenabled := helpers.CreateParam(\"EnableStaticSite\", helpers.Stringify(websiteenabledValue))\n\twebsiteindexPageTemp := \"{{.Obj.Spec.Website.IndexPage}}\"\n\twebsiteindexPageValue, err := helpers.Templatize(websiteindexPageTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteindexPage := helpers.CreateParam(\"StaticSiteIndex\", helpers.Stringify(websiteindexPageValue))\n\twebsiteerrorPageTemp := \"{{.Obj.Spec.Website.ErrorPage}}\"\n\twebsiteerrorPageValue, err := helpers.Templatize(websiteerrorPageTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteerrorPage := helpers.CreateParam(\"StaticSiteError\", helpers.Stringify(websiteerrorPageValue))\n\n\tparameters := []*cloudformation.Parameter{}\n\tparameters = append(parameters, resourceName)\n\tparameters = append(parameters, resourceVersion)\n\tparameters = append(parameters, namespace)\n\tparameters = append(parameters, clusterName)\n\tparameters = append(parameters, bucketName)\n\tparameters = append(parameters, versioning)\n\tparameters = append(parameters, accessControl)\n\tparameters = append(parameters, loggingenabled)\n\tparameters = append(parameters, loggingprefix)\n\tparameters = append(parameters, websiteenabled)\n\tparameters = append(parameters, websiteindexPage)\n\tparameters = append(parameters, websiteerrorPage)\n\n\tstackInputs.SetParameters(parameters)\n\n\tresourceNameTag := helpers.CreateTag(\"ResourceName\", s.S3Bucket.Name)\n\tresourceVersionTag := helpers.CreateTag(\"ResourceVersion\", s.S3Bucket.ResourceVersion)\n\tnamespaceTag := helpers.CreateTag(\"Namespace\", s.S3Bucket.Namespace)\n\tclusterNameTag := helpers.CreateTag(\"ClusterName\", s.config.ClusterName)\n\n\ttags := []*cloudformation.Tag{}\n\ttags = append(tags, resourceNameTag)\n\ttags = append(tags, resourceVersionTag)\n\ttags = append(tags, namespaceTag)\n\ttags = append(tags, clusterNameTag)\n\n\tstackInputs.SetTags(tags)\n\n\toutput, err = svc.CreateStack(&stackInputs)\n\treturn\n}", "func InfoStack(ctx context.Context, svc *cf.CloudFormation, opts *RequestOptions) ([]StackOutput, error) {\n\tinput := &cf.DescribeStacksInput{\n\t\tStackName: aws.String(opts.StackName),\n\t\tNextToken: aws.String(strconv.Itoa(opts.Page)),\n\t}\n\toutput, err := svc.DescribeStacksWithContext(ctx, input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar stack *cf.Stack\n\tfor _, stack = range output.Stacks {\n\t\t//if stack.StackName == input.StackName {\n\t\tif aws.StringValue(stack.StackName) == opts.StackName {\n\t\t\tbreak\n\t\t}\n\t\tstack = nil\n\t}\n\n\tif stack == nil {\n\t\treturn nil, errors.New(\"stack not found: \" + opts.StackName)\n\t}\n\n\tstackOutputs := []StackOutput{}\n\tfor _, o := range stack.Outputs {\n\t\tstackOutputs = append(stackOutputs, StackOutput{\n\t\t\tDescription: aws.StringValue(o.Description),\n\t\t\tOutputKey: aws.StringValue(o.OutputKey),\n\t\t\tOutputValue: aws.StringValue(o.OutputValue),\n\t\t})\n\t}\n\n\treturn stackOutputs, nil\n}", "func (client *BuildServiceClient) listSupportedStacksCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, options *BuildServiceClientListSupportedStacksOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/supportedStacks\"\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\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 serviceName == \"\" {\n\t\treturn nil, errors.New(\"parameter serviceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{serviceName}\", url.PathEscape(serviceName))\n\tif buildServiceName == \"\" {\n\t\treturn nil, errors.New(\"parameter buildServiceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{buildServiceName}\", url.PathEscape(buildServiceName))\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-01-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (c *StackCollection) ListStacks(ctx context.Context) ([]*Stack, error) {\n\tstacks, err := c.ListStacksWithStatuses(ctx)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"describing CloudFormation stacks for %q\", c.spec.Metadata.Name)\n\t}\n\tif len(stacks) == 0 {\n\t\tlogger.Debug(\"No stacks found for %s\", c.spec.Metadata.Name)\n\t}\n\treturn stacks, nil\n}", "func (c *CloudFormation) Stack(name string) (*Stack, error) {\n\tparams := &cfn.DescribeStacksInput{\n\t\tNextToken: aws.String(\"NextToken\"),\n\t\tStackName: aws.String(name),\n\t}\n\tresp, err := c.srv.DescribeStacks(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(resp.Stacks) != 1 {\n\t\treturn nil, fmt.Errorf(\"Reseived %v stacks, expected one\", len(resp.Stacks))\n\t}\n\n\treturn &Stack{srv: c.srv, Stack: resp.Stacks[0]}, nil\n}", "func (c *StackCollection) ListStacksMatching(ctx context.Context, nameRegex string, statusFilters ...types.StackStatus) ([]*Stack, error) {\n\tvar (\n\t\tsubErr error\n\t\tstack *Stack\n\t)\n\n\tre, err := regexp.Compile(nameRegex)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"cannot list stacks\")\n\t}\n\tinput := &cloudformation.ListStacksInput{\n\t\tStackStatusFilter: defaultStackStatusFilter(),\n\t}\n\tif len(statusFilters) > 0 {\n\t\tinput.StackStatusFilter = statusFilters\n\t}\n\tstacks := []*Stack{}\n\n\tpaginator := cloudformation.NewListStacksPaginator(c.cloudformationAPI, input)\n\n\tfor paginator.HasMorePages() {\n\t\tout, err := paginator.NextPage(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, s := range out.StackSummaries {\n\t\t\tif re.MatchString(*s.StackName) {\n\t\t\t\tstack, subErr = c.DescribeStack(ctx, &Stack{StackName: s.StackName, StackId: s.StackId})\n\t\t\t\tif subErr != nil {\n\t\t\t\t\t// this shouldn't return the error, but just stop the pagination and return whatever it gathered so far.\n\t\t\t\t\treturn stacks, nil\n\t\t\t\t}\n\t\t\t\tstacks = append(stacks, stack)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn stacks, nil\n}", "func (b *localBackend) GetStackTags(ctx context.Context,\n\tstack backend.Stack) (map[apitype.StackTagName]string, error) {\n\n\t// The local backend does not currently persist tags.\n\treturn nil, errors.New(\"stack tags not supported in --local mode\")\n}", "func GetExistingTaggedStackNames(cfSvc *cloudformation.CloudFormation, tags map[string]string) ([]string, error) {\n\tnames := make([]string, 0)\n\n\terr := cfSvc.DescribeStacksPages(&cloudformation.DescribeStacksInput{}, func(page *cloudformation.DescribeStacksOutput, lastPage bool) bool {\n\t\tfor _, stack := range page.Stacks {\n\t\t\tstackTags := getFlattenedTags(stack.Tags)\n\t\t\tok := true\n\t\t\tfor k, v := range tags {\n\t\t\t\tif stackTags[k] != v {\n\t\t\t\t\tok = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ok && stack.StackName != nil {\n\t\t\t\tnames = append(names, *stack.StackName)\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n\n\treturn names, err\n}", "func (o *InstanceStatusKubernetes) GetSmartstackOk() (*SmartstackStatus, bool) {\n\tif o == nil || o.Smartstack == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Smartstack, true\n}", "func (client *BuildServiceClient) listSupportedStacksHandleResponse(resp *http.Response) (BuildServiceClientListSupportedStacksResponse, error) {\n\tresult := BuildServiceClientListSupportedStacksResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.SupportedStacksCollection); err != nil {\n\t\treturn BuildServiceClientListSupportedStacksResponse{}, err\n\t}\n\treturn result, nil\n}", "func Poll(\n\tctx context.Context,\n\tstopc chan struct{},\n\tlg *zap.Logger,\n\teksAPI eksiface.EKSAPI,\n\tclusterName string,\n\tmngName string,\n\tdesiredNodeGroupStatus string,\n\tinitialWait time.Duration,\n\twait time.Duration,\n) <-chan ManagedNodeGroupStatus {\n\tlg.Info(\"polling mng\",\n\t\tzap.String(\"cluster-name\", clusterName),\n\t\tzap.String(\"mng-name\", mngName),\n\t\tzap.String(\"desired-status\", desiredNodeGroupStatus),\n\t)\n\n\tnow := time.Now()\n\n\tch := make(chan ManagedNodeGroupStatus, 10)\n\tgo func() {\n\t\t// very first poll should be no-wait\n\t\t// in case stack has already reached desired status\n\t\t// wait from second interation\n\t\twaitDur := time.Duration(0)\n\n\t\tfirst := true\n\t\tfor ctx.Err() == nil {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tlg.Warn(\"wait aborted\", zap.Error(ctx.Err()))\n\t\t\t\tch <- ManagedNodeGroupStatus{NodeGroupName: mngName, NodeGroup: nil, Error: ctx.Err()}\n\t\t\t\tclose(ch)\n\t\t\t\treturn\n\n\t\t\tcase <-stopc:\n\t\t\t\tlg.Warn(\"wait stopped\", zap.Error(ctx.Err()))\n\t\t\t\tch <- ManagedNodeGroupStatus{NodeGroupName: mngName, NodeGroup: nil, Error: errors.New(\"wait stopped\")}\n\t\t\t\tclose(ch)\n\t\t\t\treturn\n\n\t\t\tcase <-time.After(waitDur):\n\t\t\t\t// very first poll should be no-wait\n\t\t\t\t// in case stack has already reached desired status\n\t\t\t\t// wait from second interation\n\t\t\t\tif waitDur == time.Duration(0) {\n\t\t\t\t\twaitDur = wait\n\t\t\t\t}\n\t\t\t}\n\n\t\t\toutput, err := eksAPI.DescribeNodegroup(&aws_eks.DescribeNodegroupInput{\n\t\t\t\tClusterName: aws.String(clusterName),\n\t\t\t\tNodegroupName: aws.String(mngName),\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tif IsDeleted(err) {\n\t\t\t\t\tif desiredNodeGroupStatus == ManagedNodeGroupStatusDELETEDORNOTEXIST {\n\t\t\t\t\t\tlg.Info(\"managed node group is already deleted as desired; exiting\", zap.Error(err))\n\t\t\t\t\t\tch <- ManagedNodeGroupStatus{NodeGroupName: mngName, NodeGroup: nil, Error: nil}\n\t\t\t\t\t\tclose(ch)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tlg.Warn(\"managed node group does not exist\", zap.Error(err))\n\t\t\t\t\tch <- ManagedNodeGroupStatus{NodeGroupName: mngName, NodeGroup: nil, Error: err}\n\t\t\t\t\tclose(ch)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tlg.Warn(\"describe managed node group failed; retrying\", zap.Error(err))\n\t\t\t\tch <- ManagedNodeGroupStatus{NodeGroupName: mngName, NodeGroup: nil, Error: err}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif output.Nodegroup == nil {\n\t\t\t\tlg.Warn(\"expected non-nil managed node group; retrying\")\n\t\t\t\tch <- ManagedNodeGroupStatus{NodeGroupName: mngName, NodeGroup: nil, Error: fmt.Errorf(\"unexpected empty response %+v\", output.GoString())}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tnodeGroup := output.Nodegroup\n\t\t\tcurrentStatus := aws.StringValue(nodeGroup.Status)\n\t\t\tlg.Info(\"poll\",\n\t\t\t\tzap.String(\"cluster-name\", clusterName),\n\t\t\t\tzap.String(\"mng-name\", mngName),\n\t\t\t\tzap.String(\"status\", currentStatus),\n\t\t\t\tzap.String(\"started\", humanize.RelTime(now, time.Now(), \"ago\", \"from now\")),\n\t\t\t)\n\t\t\tswitch currentStatus {\n\t\t\tcase desiredNodeGroupStatus:\n\t\t\t\tch <- ManagedNodeGroupStatus{NodeGroupName: mngName, NodeGroup: nodeGroup, Error: nil}\n\t\t\t\tlg.Info(\"desired managed node group status; done\", zap.String(\"status\", currentStatus))\n\t\t\t\tclose(ch)\n\t\t\t\treturn\n\t\t\tcase aws_eks.NodegroupStatusCreateFailed,\n\t\t\t\taws_eks.NodegroupStatusDeleteFailed,\n\t\t\t\taws_eks.NodegroupStatusDegraded:\n\t\t\t\tch <- ManagedNodeGroupStatus{NodeGroupName: mngName, NodeGroup: nodeGroup, Error: fmt.Errorf(\"unexpected mng status %q\", currentStatus)}\n\t\t\t\tclose(ch)\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tch <- ManagedNodeGroupStatus{NodeGroupName: mngName, NodeGroup: nodeGroup, Error: nil}\n\t\t\t}\n\n\t\t\tif first {\n\t\t\t\tlg.Info(\"sleeping\", zap.Duration(\"initial-wait\", initialWait))\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\tlg.Warn(\"wait aborted\", zap.Error(ctx.Err()))\n\t\t\t\t\tch <- ManagedNodeGroupStatus{NodeGroupName: mngName, NodeGroup: nil, Error: ctx.Err()}\n\t\t\t\t\tclose(ch)\n\t\t\t\t\treturn\n\t\t\t\tcase <-stopc:\n\t\t\t\t\tlg.Warn(\"wait stopped\", zap.Error(ctx.Err()))\n\t\t\t\t\tch <- ManagedNodeGroupStatus{NodeGroupName: mngName, NodeGroup: nil, Error: errors.New(\"wait stopped\")}\n\t\t\t\t\tclose(ch)\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(initialWait):\n\t\t\t\t}\n\t\t\t\tfirst = false\n\t\t\t}\n\t\t}\n\n\t\tlg.Warn(\"wait aborted\", zap.Error(ctx.Err()))\n\t\tch <- ManagedNodeGroupStatus{NodeGroupName: mngName, NodeGroup: nil, Error: ctx.Err()}\n\t\tclose(ch)\n\t\treturn\n\t}()\n\treturn ch\n}", "func (c *StackCollection) DescribeNodeGroupStacks() ([]*Stack, error) {\n\tstacks, err := c.DescribeStacks()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(stacks) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tnodeGroupStacks := []*Stack{}\n\tfor _, s := range stacks {\n\t\tif *s.StackStatus == cfn.StackStatusDeleteComplete {\n\t\t\tcontinue\n\t\t}\n\t\tif c.GetNodeGroupName(s) != \"\" {\n\t\t\tnodeGroupStacks = append(nodeGroupStacks, s)\n\t\t}\n\t}\n\tlogger.Debug(\"nodegroups = %v\", nodeGroupStacks)\n\treturn nodeGroupStacks, nil\n}", "func findContainers(managedResource *hclConfigs.Resource, jsonBody jsonObj, hclBody *hclsyntax.Body) (containers []output.ContainerDetails, initContainers []output.ContainerDetails) {\n\tif isKuberneteResource(managedResource) {\n\t\tcontainers, initContainers = extractContainerImagesFromk8sResources(managedResource, hclBody)\n\t} else if isAzureConatinerResource(managedResource) {\n\t\tcontainers = fetchContainersFromAzureResource(jsonBody)\n\t} else if isAwsConatinerResource(managedResource) {\n\t\tcontainers = fetchContainersFromAwsResource(jsonBody, hclBody, managedResource.DeclRange.Filename)\n\t}\n\treturn\n}", "func (m *Machine) WaitForExtendedStatefulSets(namespace string, labels string) error {\n\treturn wait.PollImmediate(m.PollInterval, m.PollTimeout, func() (bool, error) {\n\t\treturn m.ExtendedStatefulSetExists(namespace, labels)\n\t})\n}", "func (r DescribeStacksRequest) Send(ctx context.Context) (*DescribeStacksResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &DescribeStacksResponse{\n\t\tDescribeStacksOutput: r.Request.Data.(*DescribeStacksOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func TestCFCreateStack(t *testing.T) {\n\tt.Parallel()\n\n\texpectedName := fmt.Sprintf(\"terratest-cf-example-%s\", random.UniqueId())\n\n\tCFOptions := &cloudformation.Options{\n\t\tCFFile: \"../examples/cloudformation-aws-example/cf_create_test.yml\",\n\t\tStackName: expectedName,\n\t\tAWSRegion: \"us-west-2\",\n\t}\n\tdefer cloudformation.DeleteStack(t, CFOptions)\n\n\tcloudformation.CreateStack(t, CFOptions)\n\tlist := cloudformation.ListResources(t, CFOptions)\n\tfilteredList := cloudformation.FilterResources(list, \"DummyResource\")\n\tassert.Contains(t, filteredList, \"cloudformation-waitcondition-\")\n}", "func stackEvents(stackID string, cfService *cloudformation.CloudFormation) ([]*cloudformation.StackEvent, error) {\n\tvar events []*cloudformation.StackEvent\n\n\tnextToken := \"\"\n\tfor {\n\t\tparams := &cloudformation.DescribeStackEventsInput{\n\t\t\tStackName: aws.String(stackID),\n\t\t}\n\t\tif len(nextToken) > 0 {\n\t\t\tparams.NextToken = aws.String(nextToken)\n\t\t}\n\n\t\tresp, err := cfService.DescribeStackEvents(params)\n\t\tif nil != err {\n\t\t\treturn nil, err\n\t\t}\n\t\tevents = append(events, resp.StackEvents...)\n\t\tif nil == resp.NextToken {\n\t\t\tbreak\n\t\t} else {\n\t\t\tnextToken = *resp.NextToken\n\t\t}\n\t}\n\treturn events, nil\n}", "func (m *Mockapi) DescribeStacks(arg0 *cloudformation.DescribeStacksInput) (*cloudformation.DescribeStacksOutput, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DescribeStacks\", arg0)\n\tret0, _ := ret[0].(*cloudformation.DescribeStacksOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func WaitForInfraServices(ctx context.Context, kc *kubernetes.Clientset) error {\n\tfor _, app := range daemonsetWhitelist {\n\t\tlog.Infof(\"checking daemonset %s/%s\", app.Namespace, app.Name)\n\n\t\terr := wait.PollImmediateUntil(time.Second, func() (bool, error) {\n\t\t\tds, err := kc.AppsV1().DaemonSets(app.Namespace).Get(app.Name, metav1.GetOptions{})\n\t\t\tswitch {\n\t\t\tcase kerrors.IsNotFound(err):\n\t\t\t\treturn false, nil\n\t\t\tcase err == nil:\n\t\t\t\treturn ds.Status.DesiredNumberScheduled == ds.Status.CurrentNumberScheduled &&\n\t\t\t\t\tds.Status.DesiredNumberScheduled == ds.Status.NumberReady &&\n\t\t\t\t\tds.Status.DesiredNumberScheduled == ds.Status.UpdatedNumberScheduled &&\n\t\t\t\t\tds.Generation == ds.Status.ObservedGeneration, nil\n\t\t\tdefault:\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}, ctx.Done())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor _, app := range deploymentWhitelist {\n\t\tlog.Infof(\"checking deployment %s/%s\", app.Namespace, app.Name)\n\n\t\terr := wait.PollImmediateUntil(time.Second, func() (bool, error) {\n\t\t\td, err := kc.AppsV1().Deployments(app.Namespace).Get(app.Name, metav1.GetOptions{})\n\t\t\tswitch {\n\t\t\tcase kerrors.IsNotFound(err):\n\t\t\t\treturn false, nil\n\t\t\tcase err == nil:\n\t\t\t\tspecReplicas := int32(1)\n\t\t\t\tif d.Spec.Replicas != nil {\n\t\t\t\t\tspecReplicas = *d.Spec.Replicas\n\t\t\t\t}\n\n\t\t\t\treturn specReplicas == d.Status.Replicas &&\n\t\t\t\t\tspecReplicas == d.Status.ReadyReplicas &&\n\t\t\t\t\tspecReplicas == d.Status.AvailableReplicas &&\n\t\t\t\t\tspecReplicas == d.Status.UpdatedReplicas &&\n\t\t\t\t\td.Generation == d.Status.ObservedGeneration, nil\n\t\t\tdefault:\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}, ctx.Done())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *CloudFormationTemplate) CreateStack(suffix string) {\n\tfmt.Printf(\"\\nRunning CloudFormation stack [%s]\", c.Name)\n\tsess := session.Must(session.NewSession(&aws.Config{\n\t\tRegion: aws.String(\"us-west-2\"),\n\t}))\n\tsvc := cloudformation.New(sess)\n\n\ttemplateBody := string(c.Bytes)\n\tc.StackName = c.Name + \"-\" + suffix\n\tcloudFormationValues := make(map[string]string)\n\n\tcreateStackParams := &cloudformation.CreateStackInput{\n\t\tStackName: aws.String(c.StackName),\n\t\tTemplateBody: aws.String(templateBody),\n\t}\n\n\tdescribeStacksParams := &cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(c.StackName),\n\t}\n\n\tout, err := svc.CreateStack(createStackParams)\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"AlreadyExistsException\") {\n\t\t\tfmt.Printf(\"\\nCloudFormation stack [%s] already exists. Skipping...\", c.Name)\n\t\t\tdescOut, err := svc.DescribeStacks(describeStacksParams)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tc.ParseOutput(descOut, cloudFormationValues)\n\t\t\treturn\n\t\t} else {\n\t\t\tfmt.Printf(\"%s\", err)\n\t\t\tpanic(err)\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"%s\", out)\n\t}\n\n\tstackReady := false\n\n\tfor stackReady != true {\n\n\t\tdescOut, err := svc.DescribeStacks(describeStacksParams)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%s\", err)\n\t\t\tpanic(err)\n\t\t} else {\n\t\t\tfmt.Printf(\"\\nCloudFormation stack [%s] is creating...\", c.Name)\n\t\t}\n\n\t\tif *descOut.Stacks[0].StackStatus == \"CREATE_COMPLETE\" {\n\t\t\tstackReady = true\n\t\t\tfmt.Printf(\"\\nCloudFormation stack [%s] ready...\\n\", c.Name)\n\t\t\tc.ParseOutput(descOut, cloudFormationValues)\n\t\t}\n\n\t\ttime.Sleep(time.Second * 7)\n\t}\n\n}", "func (s *Cloudformation) UpdateStack(updated *awsV1alpha1.S3Bucket) (output *cloudformation.UpdateStackOutput, err error) {\n\tsess := s.config.AWSSession\n\tsvc := cloudformation.New(sess)\n\n\tcftemplate := helpers.GetCloudFormationTemplate(s.config, \"s3bucket\", updated.Spec.CloudFormationTemplateName, updated.Spec.CloudFormationTemplateNamespace)\n\n\tstackInputs := cloudformation.UpdateStackInput{\n\t\tStackName: aws.String(s.StackName()),\n\t\tTemplateURL: aws.String(cftemplate),\n\t\tNotificationARNs: []*string{\n\t\t\taws.String(s.topicARN),\n\t\t},\n\t}\n\n\tresourceName := helpers.CreateParam(\"ResourceName\", s.S3Bucket.Name)\n\tresourceVersion := helpers.CreateParam(\"ResourceVersion\", s.S3Bucket.ResourceVersion)\n\tnamespace := helpers.CreateParam(\"Namespace\", s.S3Bucket.Namespace)\n\tclusterName := helpers.CreateParam(\"ClusterName\", s.config.ClusterName)\n\tbucketName := helpers.CreateParam(\"BucketName\", helpers.Stringify(s.S3Bucket.Name))\n\tversioningTemp := \"{{.Obj.Spec.Versioning}}\"\n\tversioningValue, err := helpers.Templatize(versioningTemp, helpers.Data{Obj: updated, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tversioning := helpers.CreateParam(\"EnableVersioning\", helpers.Stringify(versioningValue))\n\taccessControlTemp := \"{{.Obj.Spec.AccessControl}}\"\n\taccessControlValue, err := helpers.Templatize(accessControlTemp, helpers.Data{Obj: updated, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\taccessControl := helpers.CreateParam(\"BucketAccessControl\", helpers.Stringify(accessControlValue))\n\tloggingenabledTemp := \"{{.Obj.Spec.Logging.Enabled}}\"\n\tloggingenabledValue, err := helpers.Templatize(loggingenabledTemp, helpers.Data{Obj: updated, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tloggingenabled := helpers.CreateParam(\"EnableLogging\", helpers.Stringify(loggingenabledValue))\n\tloggingprefixTemp := \"{{.Obj.Spec.Logging.Prefix}}\"\n\tloggingprefixValue, err := helpers.Templatize(loggingprefixTemp, helpers.Data{Obj: updated, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tloggingprefix := helpers.CreateParam(\"LoggingPrefix\", helpers.Stringify(loggingprefixValue))\n\twebsiteenabledTemp := \"{{.Obj.Spec.Website.Enabled}}\"\n\twebsiteenabledValue, err := helpers.Templatize(websiteenabledTemp, helpers.Data{Obj: updated, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteenabled := helpers.CreateParam(\"EnableStaticSite\", helpers.Stringify(websiteenabledValue))\n\twebsiteindexPageTemp := \"{{.Obj.Spec.Website.IndexPage}}\"\n\twebsiteindexPageValue, err := helpers.Templatize(websiteindexPageTemp, helpers.Data{Obj: updated, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteindexPage := helpers.CreateParam(\"StaticSiteIndex\", helpers.Stringify(websiteindexPageValue))\n\twebsiteerrorPageTemp := \"{{.Obj.Spec.Website.ErrorPage}}\"\n\twebsiteerrorPageValue, err := helpers.Templatize(websiteerrorPageTemp, helpers.Data{Obj: updated, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteerrorPage := helpers.CreateParam(\"StaticSiteError\", helpers.Stringify(websiteerrorPageValue))\n\n\tparameters := []*cloudformation.Parameter{}\n\tparameters = append(parameters, resourceName)\n\tparameters = append(parameters, resourceVersion)\n\tparameters = append(parameters, namespace)\n\tparameters = append(parameters, clusterName)\n\tparameters = append(parameters, bucketName)\n\tparameters = append(parameters, versioning)\n\tparameters = append(parameters, accessControl)\n\tparameters = append(parameters, loggingenabled)\n\tparameters = append(parameters, loggingprefix)\n\tparameters = append(parameters, websiteenabled)\n\tparameters = append(parameters, websiteindexPage)\n\tparameters = append(parameters, websiteerrorPage)\n\n\tstackInputs.SetParameters(parameters)\n\n\tresourceNameTag := helpers.CreateTag(\"ResourceName\", s.S3Bucket.Name)\n\tresourceVersionTag := helpers.CreateTag(\"ResourceVersion\", s.S3Bucket.ResourceVersion)\n\tnamespaceTag := helpers.CreateTag(\"Namespace\", s.S3Bucket.Namespace)\n\tclusterNameTag := helpers.CreateTag(\"ClusterName\", s.config.ClusterName)\n\n\ttags := []*cloudformation.Tag{}\n\ttags = append(tags, resourceNameTag)\n\ttags = append(tags, resourceVersionTag)\n\ttags = append(tags, namespaceTag)\n\ttags = append(tags, clusterNameTag)\n\n\tstackInputs.SetTags(tags)\n\n\toutput, err = svc.UpdateStack(&stackInputs)\n\treturn\n}", "func (c *StackCollection) ListClusterStackNames(ctx context.Context) ([]string, error) {\n\tvar stacks []string\n\tre, err := regexp.Compile(clusterStackRegex)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"cannot list stacks\")\n\t}\n\tinput := &cloudformation.ListStacksInput{\n\t\tStackStatusFilter: defaultStackStatusFilter(),\n\t}\n\n\tpaginator := cloudformation.NewListStacksPaginator(c.cloudformationAPI, input)\n\n\tfor paginator.HasMorePages() {\n\t\tout, err := paginator.NextPage(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, s := range out.StackSummaries {\n\t\t\tif re.MatchString(*s.StackName) {\n\t\t\t\tstacks = append(stacks, *s.StackName)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn stacks, nil\n}", "func (a *API) Stacks() string {\n\ta.logger.Debug(\"debug_stacks\")\n\tbuf := new(bytes.Buffer)\n\terr := pprof.Lookup(\"goroutine\").WriteTo(buf, 2)\n\tif err != nil {\n\t\ta.logger.Error(\"Failed to create stacks\", \"error\", err.Error())\n\t}\n\treturn buf.String()\n}", "func (r apiGetStacksRequest) Execute() (StackGetStacksResponse, *_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 StackGetStacksResponse\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"StacksApiService.GetStacks\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/stack/v1/stacks\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\t\t\t\t\t\n\tif r.pageRequestFirst != nil {\n\t\tlocalVarQueryParams.Add(\"page_request.first\", parameterToString(*r.pageRequestFirst, \"\"))\n\t}\n\tif r.pageRequestAfter != nil {\n\t\tlocalVarQueryParams.Add(\"page_request.after\", parameterToString(*r.pageRequestAfter, \"\"))\n\t}\n\tif r.pageRequestFilter != nil {\n\t\tlocalVarQueryParams.Add(\"page_request.filter\", parameterToString(*r.pageRequestFilter, \"\"))\n\t}\n\tif r.pageRequestSortBy != nil {\n\t\tlocalVarQueryParams.Add(\"page_request.sort_by\", parameterToString(*r.pageRequestSortBy, \"\"))\n\t}\n\tif r.accountId != nil {\n\t\tlocalVarQueryParams.Add(\"account_id\", parameterToString(*r.accountId, \"\"))\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{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.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 := r.apiService.client.callAPI(req)\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 == 401 {\n\t\t\tvar v StackpathapiStatus\n\t\t\terr = r.apiService.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 StackpathapiStatus\n\t\t\terr = r.apiService.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\t\tvar v StackpathapiStatus\n\t\t\terr = r.apiService.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\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.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 EnableStacks() {\n\tstacks = true\n}", "func (r *ReconcileExtendedStatefulSet) createVolumeManagementStatefulSets(ctx context.Context, exStatefulSet *essv1a1.ExtendedStatefulSet, statefulSet *v1beta2.StatefulSet) error {\n\n\tvar desiredVolumeManagementStatefulSets []v1beta2.StatefulSet\n\n\ttemplate := exStatefulSet.Spec.Template\n\ttemplate.SetName(\"volume-management\")\n\n\t// Place the StatefulSet in the same namespace as the ExtendedStatefulSet\n\ttemplate.SetNamespace(exStatefulSet.Namespace)\n\n\tif exStatefulSet.Spec.ZoneNodeLabel == \"\" {\n\t\texStatefulSet.Spec.ZoneNodeLabel = essv1a1.DefaultZoneNodeLabel\n\t}\n\n\tif len(exStatefulSet.Spec.Zones) > 0 {\n\t\tfor zoneIndex, zoneName := range exStatefulSet.Spec.Zones {\n\t\t\tstatefulSet, err := r.generateVolumeManagementSingleStatefulSet(exStatefulSet, &template, zoneIndex, zoneName)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"Could not generate volumeManagement StatefulSet template for AZ '%d/%s'\", zoneIndex, zoneName)\n\t\t\t}\n\t\t\tdesiredVolumeManagementStatefulSets = append(desiredVolumeManagementStatefulSets, *statefulSet)\n\t\t}\n\t} else {\n\t\tstatefulSet, err := r.generateVolumeManagementSingleStatefulSet(exStatefulSet, &template, -1, \"\")\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Could not generate StatefulSet template for single zone\")\n\t\t}\n\t\tdesiredVolumeManagementStatefulSets = append(desiredVolumeManagementStatefulSets, *statefulSet)\n\t}\n\n\tfor _, desiredVolumeManagementStatefulSet := range desiredVolumeManagementStatefulSets {\n\n\t\toriginalTemplate := exStatefulSet.Spec.Template.DeepCopy()\n\t\t// Set the owner of the StatefulSet, so it's garbage collected,\n\t\t// and we can find it later\n\t\tctxlog.Info(ctx, \"Setting owner for StatefulSet '\", desiredVolumeManagementStatefulSet.Name, \"' to ExtendedStatefulSet '\", exStatefulSet.Name, \"' in namespace '\", exStatefulSet.Namespace, \"'.\")\n\t\tif err := r.setReference(exStatefulSet, &desiredVolumeManagementStatefulSet, r.scheme); err != nil {\n\t\t\treturn errors.Wrapf(err, \"could not set owner for volumeManagement StatefulSet '%s' to ExtendedStatefulSet '%s' in namespace '%s'\", desiredVolumeManagementStatefulSet.Name, exStatefulSet.Name, exStatefulSet.Namespace)\n\t\t}\n\n\t\t// Create the StatefulSet\n\t\tif err := r.client.Create(ctx, &desiredVolumeManagementStatefulSet); err != nil {\n\t\t\treturn errors.Wrapf(err, \"could not create volumeManagement StatefulSet '%s' for ExtendedStatefulSet '%s' in namespace '%s'\", desiredVolumeManagementStatefulSet.Name, exStatefulSet.Name, exStatefulSet.Namespace)\n\t\t}\n\n\t\tctxlog.Info(ctx, \"Created VolumeManagement StatefulSet '\", desiredVolumeManagementStatefulSet.Name, \"' for ExtendedStatefulSet '\", exStatefulSet.Name, \"' in namespace '\", exStatefulSet.Namespace, \"'.\")\n\n\t\texStatefulSet.Spec.Template = *originalTemplate\n\t}\n\treturn nil\n}", "func (c *AppsStacksCmd) Run() (err error) {\n\ts := NewSpinner(\"Looking up stacks\")\n\ts.Start()\n\tk, err := api.Stacks()\n\ts.Stop()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to look up stacks: %w\", err)\n\t}\n\n\ttable := NewTable(os.Stdout)\n\ttable.SetHeader([]string{\"Name\", \"Label\", \"Description\", \"Type\"})\n\n\tfor _, s := range k {\n\t\tr := []string{s.Name, s.Label, s.Description, s.Type}\n\t\ttable.Append(r)\n\t}\n\n\ttable.Render()\n\treturn err\n}", "func LookupStack(ctx *pulumi.Context, args *LookupStackArgs, opts ...pulumi.InvokeOption) (*LookupStackResult, error) {\n\topts = internal.PkgInvokeDefaultOpts(opts)\n\tvar rv LookupStackResult\n\terr := ctx.Invoke(\"aws-native:appstream:getStack\", args, &rv, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &rv, nil\n}", "func convergeStackState(cfTemplateURL string, ctx *workflowContext) (*cloudformation.Stack, error) {\n\tawsCloudFormation := cloudformation.New(ctx.awsSession)\n\n\t// Does it exist?\n\texists, err := stackExists(ctx.serviceName, awsCloudFormation, ctx.logger)\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\tstackID := \"\"\n\tif exists {\n\t\t// Update stack\n\t\tupdateStackInput := &cloudformation.UpdateStackInput{\n\t\t\tStackName: aws.String(ctx.serviceName),\n\t\t\tTemplateURL: aws.String(cfTemplateURL),\n\t\t\tCapabilities: []*string{aws.String(\"CAPABILITY_IAM\")},\n\t\t}\n\t\tupdateStackResponse, err := awsCloudFormation.UpdateStack(updateStackInput)\n\t\tif nil != err {\n\t\t\treturn nil, err\n\t\t}\n\t\tctx.logger.Info(\"Issued update request: \", *updateStackResponse.StackId)\n\t\tstackID = *updateStackResponse.StackId\n\t} else {\n\t\t// Create stack\n\t\tcreateStackInput := &cloudformation.CreateStackInput{\n\t\t\tStackName: aws.String(ctx.serviceName),\n\t\t\tTemplateURL: aws.String(cfTemplateURL),\n\t\t\tTimeoutInMinutes: aws.Int64(5),\n\t\t\tOnFailure: aws.String(cloudformation.OnFailureDelete),\n\t\t\tCapabilities: []*string{aws.String(\"CAPABILITY_IAM\")},\n\t\t}\n\t\tcreateStackResponse, err := awsCloudFormation.CreateStack(createStackInput)\n\t\tif nil != err {\n\t\t\treturn nil, err\n\t\t}\n\t\tctx.logger.Info(\"Creating stack: \", *createStackResponse.StackId)\n\t\tstackID = *createStackResponse.StackId\n\t}\n\n\t// Poll for the current stackID state\n\tdescribeStacksInput := &cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(stackID),\n\t}\n\n\tvar stackInfo *cloudformation.Stack\n\tstackOperationComplete := false\n\tctx.logger.Info(\"Waiting for stack to complete\")\n\tfor !stackOperationComplete {\n\t\ttime.Sleep(10 * time.Second)\n\t\tdescribeStacksOutput, err := awsCloudFormation.DescribeStacks(describeStacksInput)\n\t\tif nil != err {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(describeStacksOutput.Stacks) > 0 {\n\t\t\tstackInfo = describeStacksOutput.Stacks[0]\n\t\t\tctx.logger.Info(\"Current state: \", *stackInfo.StackStatus)\n\t\t\tswitch *stackInfo.StackStatus {\n\t\t\tcase cloudformation.StackStatusCreateInProgress,\n\t\t\t\tcloudformation.StackStatusDeleteInProgress,\n\t\t\t\tcloudformation.StackStatusUpdateInProgress,\n\t\t\t\tcloudformation.StackStatusRollbackInProgress,\n\t\t\t\tcloudformation.StackStatusUpdateCompleteCleanupInProgress,\n\t\t\t\tcloudformation.StackStatusUpdateRollbackCompleteCleanupInProgress,\n\t\t\t\tcloudformation.StackStatusUpdateRollbackInProgress:\n\t\t\t\ttime.Sleep(20 * time.Second)\n\t\t\tdefault:\n\t\t\t\tstackOperationComplete = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"More than one stack returned for: %s\", stackID)\n\t\t}\n\t}\n\t// What happened?\n\tsucceed := true\n\tswitch *stackInfo.StackStatus {\n\tcase cloudformation.StackStatusDeleteComplete, // Initial create failure\n\t\tcloudformation.StackStatusUpdateRollbackComplete: // Update failure\n\t\tsucceed = false\n\tdefault:\n\t\tsucceed = true\n\t}\n\n\t// If it didn't work, then output some failure information\n\tif !succeed {\n\t\t// Get the stack events and find the ones that failed.\n\t\tevents, err := stackEvents(stackID, awsCloudFormation)\n\t\tif nil != err {\n\t\t\treturn nil, err\n\t\t}\n\t\tctx.logger.Error(\"Stack provisioning failed.\")\n\t\tfor _, eachEvent := range events {\n\t\t\tswitch *eachEvent.ResourceStatus {\n\t\t\tcase cloudformation.ResourceStatusCreateFailed,\n\t\t\t\tcloudformation.ResourceStatusDeleteFailed,\n\t\t\t\tcloudformation.ResourceStatusUpdateFailed:\n\t\t\t\terrMsg := fmt.Sprintf(\"\\tError ensuring %s (%s): %s\",\n\t\t\t\t\t*eachEvent.ResourceType,\n\t\t\t\t\t*eachEvent.LogicalResourceId,\n\t\t\t\t\t*eachEvent.ResourceStatusReason)\n\t\t\t\tctx.logger.Error(errMsg)\n\t\t\tdefault:\n\t\t\t\t// NOP\n\t\t\t}\n\t\t}\n\t\treturn nil, fmt.Errorf(\"Failed to provision: %s\", ctx.serviceName)\n\t} else if nil != stackInfo.Outputs {\n\t\tctx.logger.Info(\"Stack Outputs:\")\n\t\tfor _, eachOutput := range stackInfo.Outputs {\n\t\t\tctx.logger.WithFields(logrus.Fields{\n\t\t\t\t\"Key\": *eachOutput.OutputKey,\n\t\t\t\t\"Value\": *eachOutput.OutputValue,\n\t\t\t\t\"Description\": *eachOutput.Description,\n\t\t\t}).Info(\"\\tOutput\")\n\t\t}\n\t}\n\treturn stackInfo, nil\n}", "func (client *CraneDockerClient) InspectStack(namespace string) (*model.Bundle, error) {\n\tservices, err := client.FilterServiceByStack(namespace, types.ServiceListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstackServices := make(map[string]model.CraneServiceSpec)\n\tfor _, swarmService := range services {\n\t\tstackServices[swarmService.Spec.Name] = client.ToCraneServiceSpec(swarmService.Spec)\n\t}\n\n\treturn &model.Bundle{\n\t\tNamespace: namespace,\n\t\tStack: model.BundleService{\n\t\t\t//TODO stack version is missing\n\t\t\tServices: stackServices,\n\t\t},\n\t}, nil\n}", "func (o *InstanceStatusKubernetes) GetSmartstack() SmartstackStatus {\n\tif o == nil || o.Smartstack == nil {\n\t\tvar ret SmartstackStatus\n\t\treturn ret\n\t}\n\treturn *o.Smartstack\n}", "func StackAnalyses(requestParams driver.RequestType, jsonOut bool, verboseOut bool) bool {\n\tlog.Debug().Msgf(\"Executing StackAnalyses.\")\n\tvar hasVul bool\n\tmatcher, err := GetMatcher(requestParams.RawManifestFile)\n\tif err != nil {\n\t\tlog.Fatal().Msgf(err.Error())\n\t}\n\tmc := NewController(matcher)\n\tmc.fileStats = mc.buildFileStats(requestParams.RawManifestFile)\n\tpostResponse := mc.postRequest(requestParams, mc.fileStats.DepsTreePath)\n\tgetResponse := mc.getRequest(requestParams, postResponse)\n\tverboseEligible := getResponse.RegistrationStatus == RegisteredStatus\n\tshowVerboseMsg := verboseOut && !verboseEligible\n\n\tif verboseOut && verboseEligible {\n\t\thasVul = verbose.ProcessVerbose(getResponse, jsonOut)\n\t} else {\n\t\thasVul = summary.ProcessSummary(getResponse, jsonOut, showVerboseMsg)\n\t}\n\n\tlog.Debug().Msgf(\"Success StackAnalyses.\")\n\treturn hasVul\n}", "func (client *CraneDockerClient) ListStackService(namespace string, opts types.ServiceListOptions) ([]ServiceStatus, error) {\n\tservices, err := client.FilterServiceByStack(namespace, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn client.GetServicesStatus(services)\n}", "func GetStack(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *StackState, opts ...pulumi.ResourceOption) (*Stack, error) {\n\tvar resource Stack\n\terr := ctx.ReadResource(\"aws-native:cloudformation:Stack\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (c *StackCollection) ListStacksWithStatuses(ctx context.Context, statusFilters ...types.StackStatus) ([]*Stack, error) {\n\treturn c.ListStacksMatching(ctx, fmtStacksRegexForCluster(c.spec.Metadata.Name), statusFilters...)\n}", "func NewMonitoringStackResources() *MonitoringStackResourcesBuilder {\n\treturn &MonitoringStackResourcesBuilder{}\n}", "func (clusterRequest *KibanaRequest) isManaged() bool {\n\treturn clusterRequest.cluster.Spec.ManagementState == kibana.ManagementStateManaged\n}", "func (s *Stack) Destroy() error {\n\t_, err := s.cfnconn.DeleteStack(&cloudformation.DeleteStackInput{\n\t\tStackName: aws.String(s.Name),\n\t})\n\treturn errors.Annotatef(err, \"DeleteStack failed for stack '%s'\", s.Name)\n}", "func NewManagementStatefulSet(cluster *v1alpha1.AtomixCluster) (*appsv1.StatefulSet, error) {\n\tclaims, err := newPersistentVolumeClaims(cluster.Spec.Storage.ClassName, cluster.Spec.Storage.Size)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &appsv1.StatefulSet{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: GetManagementStatefulSetName(cluster),\n\t\t\tNamespace: cluster.Namespace,\n\t\t\tLabels: newManagementLabels(cluster),\n\t\t},\n\t\tSpec: appsv1.StatefulSetSpec{\n\t\t\tServiceName: GetManagementServiceName(cluster),\n\t\t\tReplicas: &cluster.Spec.Size,\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: newManagementLabels(cluster),\n\t\t\t},\n\t\t\tUpdateStrategy: appsv1.StatefulSetUpdateStrategy{\n\t\t\t\tType: appsv1.RollingUpdateStatefulSetStrategyType,\n\t\t\t},\n\t\t\tPodManagementPolicy: appsv1.ParallelPodManagement,\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: newManagementLabels(cluster),\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tAffinity: newAffinity(cluster.Name),\n\t\t\t\t\tInitContainers: newInitContainers(cluster.Spec.Size),\n\t\t\t\t\tContainers: newPersistentContainers(cluster.Spec.Version, cluster.Spec.Env, cluster.Spec.Resources),\n\t\t\t\t\tVolumes: []corev1.Volume{\n\t\t\t\t\t\tnewInitScriptsVolume(GetManagementInitConfigMapName(cluster)),\n\t\t\t\t\t\tnewUserConfigVolume(GetManagementSystemConfigMapName(cluster)),\n\t\t\t\t\t\tnewSystemConfigVolume(),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tVolumeClaimTemplates: claims,\n\t\t},\n\t}, nil\n}", "func ListManagedInstances(c GCECloud, igm *compute.InstanceGroupManager) ([]*compute.ManagedInstance, error) {\n\tctx := context.Background()\n\tproject := c.Project()\n\n\tzoneName := LastComponent(igm.Zone)\n\n\t// TODO: Only select a subset of fields\n\t//\treq.Fields(\n\t//\t\tgoogleapi.Field(\"items/selfLink\"),\n\t//\t\tgoogleapi.Field(\"items/metadata/items[key='cluster-name']\"),\n\t//\t\tgoogleapi.Field(\"items/metadata/items[key='instance-template']\"),\n\t//\t)\n\n\tinstances, err := c.Compute().InstanceGroupManagers().ListManagedInstances(ctx, project, zoneName, igm.Name)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error listing ManagedInstances in %s: %v\", igm.Name, err)\n\t}\n\n\treturn instances, nil\n}", "func (c *AppsStacksCmd) Run(cli *CLI, logWriters *LogWriters) (err error) {\n\ts := NewSpinner(\"Looking up stacks\",logWriters)\n\ts.Start()\n\tk, err := api.Stacks()\n\ts.Stop()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to look up stacks: %w\", err)\n\t}\n\n\ttable := NewTable(cli, os.Stdout)\n\ttable.SetHeader([]string{\"Name\", \"Label\", \"Description\", \"Type\"})\n\n\tfor _, s := range k {\n\t\tr := []string{s.Name, s.Label, s.Description, s.Type}\n\t\ttable.Append(r)\n\t}\n\n\ttable.Render()\n\treturn err\n}", "func (client *CraneDockerClient) PretreatmentStack(bundle model.Bundle) (map[string]bool, error) {\n\t// create network map and convert to slice for distinct network\n\tnetworkMap := make(map[string]bool)\n\n\t// all the publish port in the stack\n\tpublishedPortMap := make(map[string]bool)\n\n\tfor _, serviceSpec := range bundle.Stack.Services {\n\t\tif err := ValidateCraneServiceSpec(&serviceSpec); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, network := range serviceSpec.Networks {\n\t\t\tnetworkMap[network] = true\n\t\t}\n\n\t\tif serviceSpec.EndpointSpec != nil {\n\t\t\tfor _, pc := range serviceSpec.EndpointSpec.Ports {\n\t\t\t\tif pc.PublishedPort > 0 {\n\t\t\t\t\tportConflictStr := PortConflictToString(pc)\n\t\t\t\t\t// have two service publish the same port\n\t\t\t\t\tif _, ok := publishedPortMap[portConflictStr]; ok {\n\t\t\t\t\t\tportConflictErr := &cranerror.ServicePortConflictError{\n\t\t\t\t\t\t\tName: serviceSpec.Name,\n\t\t\t\t\t\t\tNamespace: bundle.Namespace,\n\t\t\t\t\t\t\tPublishedPort: portConflictStr,\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn nil, &cranerror.CraneError{Code: CodeGetServicePortConflictError, Err: portConflictErr}\n\t\t\t\t\t}\n\n\t\t\t\t\tpublishedPortMap[portConflictStr] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// check stack need publish port is conflicted with exist services\n\tif len(publishedPortMap) > 0 {\n\t\texistingServices, err := client.ListServiceSpec(types.ServiceListOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := checkPortConflicts(publishedPortMap, \"\", existingServices); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// check if all network used by stack was exist, if not create it\n\tnewNetworkMap, err := client.updateNetworks(networkMap, bundle.Namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newNetworkMap, nil\n\n}", "func NewStackCollection(provider api.ClusterProvider, spec *api.ClusterConfig) StackManager {\n\ttags := []types.Tag{\n\t\tnewTag(api.ClusterNameTag, spec.Metadata.Name),\n\t\tnewTag(api.OldClusterNameTag, spec.Metadata.Name),\n\t\tnewTag(api.EksctlVersionTag, version.GetVersion()),\n\t}\n\tfor key, value := range spec.Metadata.Tags {\n\t\ttags = append(tags, newTag(key, value))\n\t}\n\treturn &StackCollection{\n\t\tspec: spec,\n\t\tsharedTags: tags,\n\t\tcloudformationAPI: provider.CloudFormation(),\n\t\tec2API: provider.EC2(),\n\t\teksAPI: provider.EKS(),\n\t\tiamAPI: provider.IAM(),\n\t\tcloudTrailAPI: provider.CloudTrail(),\n\t\tasgAPI: provider.ASG(),\n\t\tdisableRollback: provider.CloudFormationDisableRollback(),\n\t\troleARN: provider.CloudFormationRoleARN(),\n\t\tregion: provider.Region(),\n\t\twaitTimeout: provider.WaitTimeout(),\n\t}\n}", "func HasManagedNodesSG(stackResources *gjson.Result) bool {\n\treturn stackResources.Get(cfnIngressClusterToNodeSGResource).Exists()\n}", "func (v *infromerVersion) StatefulSets() v1beta1.StatefulSetLister {\n\treturn v.factory.Apps().V1beta1().StatefulSets().Lister()\n}", "func CfnStackSet_IsConstruct(x interface{}) *bool {\n\t_init_.Initialize()\n\n\tvar returns *bool\n\n\t_jsii_.StaticInvoke(\n\t\t\"aws-cdk-lib.aws_cloudformation.CfnStackSet\",\n\t\t\"isConstruct\",\n\t\t[]interface{}{x},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func GetStatefulSetContainers(item interface{}) []corev1.Container {\n\treturn item.(appsv1.StatefulSet).Spec.Template.Spec.Containers\n}", "func (mr *MockCfnClientMockRecorder) ListStacks(regexNameFilter, statusFilter interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListStacks\", reflect.TypeOf((*MockCfnClient)(nil).ListStacks), regexNameFilter, statusFilter)\n}", "func (s DescribeStacksOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *ResourceLimits) GetK8sClustersProvisionedOk() (*int32, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn o.K8sClustersProvisioned, true\n}", "func (o *ComputeBladeIdentityAllOf) GetManagedNodesOk() ([]ComputeBladeIdentityRelationship, bool) {\n\tif o == nil || o.ManagedNodes == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ManagedNodes, true\n}", "func ContainsStackStatus(slice []cloudformation.StackStatus, val cloudformation.ResourceStatus) bool {\n\tfor _, item := range slice {\n\t\t// aws::cloudformation::stack can have a resource status be a stack status\n\t\tif string(item) == string(val) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func listStatefulSets(ctx context.Context, client crc.Client, exStatefulSet *estsv1.ExtendedStatefulSet) ([]v1beta2.StatefulSet, error) {\n\tctxlog.Debug(ctx, \"Listing StatefulSets owned by ExtendedStatefulSet '\", exStatefulSet.Name, \"'.\")\n\n\t// Get owned resources\n\t// Go through each StatefulSet\n\tresult := []v1beta2.StatefulSet{}\n\tallStatefulSets := &v1beta2.StatefulSetList{}\n\terr := client.List(\n\t\tctx,\n\t\t&crc.ListOptions{\n\t\t\tNamespace: exStatefulSet.Namespace,\n\t\t\tLabelSelector: labels.Everything(),\n\t\t},\n\t\tallStatefulSets)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, statefulSet := range allStatefulSets.Items {\n\t\tif metav1.IsControlledBy(&statefulSet, exStatefulSet) {\n\t\t\tresult = append(result, statefulSet)\n\t\t\tctxlog.Debug(ctx, \"StatefulSet '\", statefulSet.Name, \"' owned by ExtendedStatefulSet '\", exStatefulSet.Name, \"'.\")\n\t\t} else {\n\t\t\tctxlog.Debug(ctx, \"StatefulSet '\", statefulSet.Name, \"' is not owned by ExtendedStatefulSet '\", exStatefulSet.Name, \"', ignoring.\")\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func (c *Client) ListOpenstack(i *ListOpenstackInput) ([]*Openstack, error) {\n\tif i.Service == \"\" {\n\t\treturn nil, ErrMissingService\n\t}\n\n\tif i.Version == 0 {\n\t\treturn nil, ErrMissingVersion\n\t}\n\n\tpath := fmt.Sprintf(\"/service/%s/version/%d/logging/openstack\", i.Service, i.Version)\n\tresp, err := c.Get(path, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar openstacks []*Openstack\n\tif err := decodeBodyMap(resp.Body, &openstacks); err != nil {\n\t\treturn nil, err\n\t}\n\tsort.Stable(openstacksByName(openstacks))\n\treturn openstacks, nil\n}", "func Find(c *gophercloud.ServiceClient, stackName string) (r FindResult) {\n\tresp, err := c.Get(findURL(c, stackName), &r.Body, nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func (c *StackCollection) DeleteTasksForDeprecatedStacks() (*tasks.TaskTree, error) {\n\tstacks, err := c.ListStacksMatching(fmtDeprecatedStacksRegexForCluster(c.spec.Metadata.Name))\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"describing deprecated CloudFormation stacks for %q\", c.spec.Metadata.Name)\n\t}\n\tif len(stacks) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tdeleteControlPlaneTask := &tasks.TaskWithoutParams{\n\t\tInfo: fmt.Sprintf(\"delete control plane %q\", c.spec.Metadata.Name),\n\t\tCall: func(errs chan error) error {\n\t\t\t_, err := c.eksAPI.DescribeCluster(&eks.DescribeClusterInput{\n\t\t\t\tName: &c.spec.Metadata.Name,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t_, err = c.eksAPI.DeleteCluster(&eks.DeleteClusterInput{\n\t\t\t\tName: &c.spec.Metadata.Name,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tnewRequest := func() *request.Request {\n\t\t\t\tinput := &eks.DescribeClusterInput{\n\t\t\t\t\tName: &c.spec.Metadata.Name,\n\t\t\t\t}\n\t\t\t\treq, _ := c.eksAPI.DescribeClusterRequest(input)\n\t\t\t\treturn req\n\t\t\t}\n\n\t\t\tmsg := fmt.Sprintf(\"waiting for control plane %q to be deleted\", c.spec.Metadata.Name)\n\n\t\t\tacceptors := waiters.MakeAcceptors(\n\t\t\t\t\"Cluster.Status\",\n\t\t\t\teks.ClusterStatusDeleting,\n\t\t\t\t[]string{\n\t\t\t\t\teks.ClusterStatusFailed,\n\t\t\t\t},\n\t\t\t)\n\n\t\t\treturn waiters.Wait(c.spec.Metadata.Name, msg, acceptors, newRequest, c.waitTimeout, nil)\n\t\t},\n\t}\n\n\tcpStackFound := false\n\tfor _, s := range stacks {\n\t\tif strings.HasSuffix(*s.StackName, \"-ControlPlane\") {\n\t\t\tcpStackFound = true\n\t\t}\n\t}\n\ttaskTree := &tasks.TaskTree{}\n\n\tfor _, suffix := range deprecatedStackSuffices() {\n\t\tfor _, s := range stacks {\n\t\t\tif strings.HasSuffix(*s.StackName, \"-\"+suffix) {\n\t\t\t\tif suffix == \"-ControlPlane\" && !cpStackFound {\n\t\t\t\t\ttaskTree.Append(deleteControlPlaneTask)\n\t\t\t\t} else {\n\t\t\t\t\ttaskTree.Append(&taskWithStackSpec{\n\t\t\t\t\t\tstack: s,\n\t\t\t\t\t\tcall: c.DeleteStackBySpecSync,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn taskTree, nil\n}", "func (rm *resourceManager) sdkFind(\n\tctx context.Context,\n\tr *resource,\n) (*resource, error) {\n\tinput, err := rm.newListRequestPayload(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, respErr := rm.sdkapi.DescribeReplicationGroupsWithContext(ctx, input)\n\trm.metrics.RecordAPICall(\"READ_MANY\", \"DescribeReplicationGroups\", respErr)\n\tif respErr != nil {\n\t\tif awsErr, ok := ackerr.AWSError(respErr); ok && awsErr.Code() == \"ReplicationGroupNotFoundFault\" {\n\t\t\treturn nil, ackerr.NotFound\n\t\t}\n\t\treturn nil, respErr\n\t}\n\n\t// Merge in the information we read from the API call above to the copy of\n\t// the original Kubernetes object we passed to the function\n\tko := r.ko.DeepCopy()\n\n\tfound := false\n\tfor _, elem := range resp.ReplicationGroups {\n\t\tif elem.ARN != nil {\n\t\t\tif ko.Status.ACKResourceMetadata == nil {\n\t\t\t\tko.Status.ACKResourceMetadata = &ackv1alpha1.ResourceMetadata{}\n\t\t\t}\n\t\t\ttmpARN := ackv1alpha1.AWSResourceName(*elem.ARN)\n\t\t\tko.Status.ACKResourceMetadata.ARN = &tmpARN\n\t\t}\n\t\tif elem.AtRestEncryptionEnabled != nil {\n\t\t\tko.Spec.AtRestEncryptionEnabled = elem.AtRestEncryptionEnabled\n\t\t}\n\t\tif elem.AuthTokenEnabled != nil {\n\t\t\tko.Status.AuthTokenEnabled = elem.AuthTokenEnabled\n\t\t}\n\t\tif elem.AuthTokenLastModifiedDate != nil {\n\t\t\tko.Status.AuthTokenLastModifiedDate = &metav1.Time{*elem.AuthTokenLastModifiedDate}\n\t\t}\n\t\tif elem.AutomaticFailover != nil {\n\t\t\tko.Status.AutomaticFailover = elem.AutomaticFailover\n\t\t}\n\t\tif elem.CacheNodeType != nil {\n\t\t\tko.Spec.CacheNodeType = elem.CacheNodeType\n\t\t}\n\t\tif elem.ClusterEnabled != nil {\n\t\t\tko.Status.ClusterEnabled = elem.ClusterEnabled\n\t\t}\n\t\tif elem.ConfigurationEndpoint != nil {\n\t\t\tf7 := &svcapitypes.Endpoint{}\n\t\t\tif elem.ConfigurationEndpoint.Address != nil {\n\t\t\t\tf7.Address = elem.ConfigurationEndpoint.Address\n\t\t\t}\n\t\t\tif elem.ConfigurationEndpoint.Port != nil {\n\t\t\t\tf7.Port = elem.ConfigurationEndpoint.Port\n\t\t\t}\n\t\t\tko.Status.ConfigurationEndpoint = f7\n\t\t}\n\t\tif elem.Description != nil {\n\t\t\tko.Status.Description = elem.Description\n\t\t}\n\t\tif elem.GlobalReplicationGroupInfo != nil {\n\t\t\tf9 := &svcapitypes.GlobalReplicationGroupInfo{}\n\t\t\tif elem.GlobalReplicationGroupInfo.GlobalReplicationGroupId != nil {\n\t\t\t\tf9.GlobalReplicationGroupID = elem.GlobalReplicationGroupInfo.GlobalReplicationGroupId\n\t\t\t}\n\t\t\tif elem.GlobalReplicationGroupInfo.GlobalReplicationGroupMemberRole != nil {\n\t\t\t\tf9.GlobalReplicationGroupMemberRole = elem.GlobalReplicationGroupInfo.GlobalReplicationGroupMemberRole\n\t\t\t}\n\t\t\tko.Status.GlobalReplicationGroupInfo = f9\n\t\t}\n\t\tif elem.KmsKeyId != nil {\n\t\t\tko.Spec.KMSKeyID = elem.KmsKeyId\n\t\t}\n\t\tif elem.MemberClusters != nil {\n\t\t\tf11 := []*string{}\n\t\t\tfor _, f11iter := range elem.MemberClusters {\n\t\t\t\tvar f11elem string\n\t\t\t\tf11elem = *f11iter\n\t\t\t\tf11 = append(f11, &f11elem)\n\t\t\t}\n\t\t\tko.Status.MemberClusters = f11\n\t\t}\n\t\tif elem.MemberClustersOutpostArns != nil {\n\t\t\tf12 := []*string{}\n\t\t\tfor _, f12iter := range elem.MemberClustersOutpostArns {\n\t\t\t\tvar f12elem string\n\t\t\t\tf12elem = *f12iter\n\t\t\t\tf12 = append(f12, &f12elem)\n\t\t\t}\n\t\t\tko.Status.MemberClustersOutpostARNs = f12\n\t\t}\n\t\tif elem.MultiAZ != nil {\n\t\t\tko.Status.MultiAZ = elem.MultiAZ\n\t\t}\n\t\tif elem.NodeGroups != nil {\n\t\t\tf14 := []*svcapitypes.NodeGroup{}\n\t\t\tfor _, f14iter := range elem.NodeGroups {\n\t\t\t\tf14elem := &svcapitypes.NodeGroup{}\n\t\t\t\tif f14iter.NodeGroupId != nil {\n\t\t\t\t\tf14elem.NodeGroupID = f14iter.NodeGroupId\n\t\t\t\t}\n\t\t\t\tif f14iter.NodeGroupMembers != nil {\n\t\t\t\t\tf14elemf1 := []*svcapitypes.NodeGroupMember{}\n\t\t\t\t\tfor _, f14elemf1iter := range f14iter.NodeGroupMembers {\n\t\t\t\t\t\tf14elemf1elem := &svcapitypes.NodeGroupMember{}\n\t\t\t\t\t\tif f14elemf1iter.CacheClusterId != nil {\n\t\t\t\t\t\t\tf14elemf1elem.CacheClusterID = f14elemf1iter.CacheClusterId\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif f14elemf1iter.CacheNodeId != nil {\n\t\t\t\t\t\t\tf14elemf1elem.CacheNodeID = f14elemf1iter.CacheNodeId\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif f14elemf1iter.CurrentRole != nil {\n\t\t\t\t\t\t\tf14elemf1elem.CurrentRole = f14elemf1iter.CurrentRole\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif f14elemf1iter.PreferredAvailabilityZone != nil {\n\t\t\t\t\t\t\tf14elemf1elem.PreferredAvailabilityZone = f14elemf1iter.PreferredAvailabilityZone\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif f14elemf1iter.PreferredOutpostArn != nil {\n\t\t\t\t\t\t\tf14elemf1elem.PreferredOutpostARN = f14elemf1iter.PreferredOutpostArn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif f14elemf1iter.ReadEndpoint != nil {\n\t\t\t\t\t\t\tf14elemf1elemf5 := &svcapitypes.Endpoint{}\n\t\t\t\t\t\t\tif f14elemf1iter.ReadEndpoint.Address != nil {\n\t\t\t\t\t\t\t\tf14elemf1elemf5.Address = f14elemf1iter.ReadEndpoint.Address\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif f14elemf1iter.ReadEndpoint.Port != nil {\n\t\t\t\t\t\t\t\tf14elemf1elemf5.Port = f14elemf1iter.ReadEndpoint.Port\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tf14elemf1elem.ReadEndpoint = f14elemf1elemf5\n\t\t\t\t\t\t}\n\t\t\t\t\t\tf14elemf1 = append(f14elemf1, f14elemf1elem)\n\t\t\t\t\t}\n\t\t\t\t\tf14elem.NodeGroupMembers = f14elemf1\n\t\t\t\t}\n\t\t\t\tif f14iter.PrimaryEndpoint != nil {\n\t\t\t\t\tf14elemf2 := &svcapitypes.Endpoint{}\n\t\t\t\t\tif f14iter.PrimaryEndpoint.Address != nil {\n\t\t\t\t\t\tf14elemf2.Address = f14iter.PrimaryEndpoint.Address\n\t\t\t\t\t}\n\t\t\t\t\tif f14iter.PrimaryEndpoint.Port != nil {\n\t\t\t\t\t\tf14elemf2.Port = f14iter.PrimaryEndpoint.Port\n\t\t\t\t\t}\n\t\t\t\t\tf14elem.PrimaryEndpoint = f14elemf2\n\t\t\t\t}\n\t\t\t\tif f14iter.ReaderEndpoint != nil {\n\t\t\t\t\tf14elemf3 := &svcapitypes.Endpoint{}\n\t\t\t\t\tif f14iter.ReaderEndpoint.Address != nil {\n\t\t\t\t\t\tf14elemf3.Address = f14iter.ReaderEndpoint.Address\n\t\t\t\t\t}\n\t\t\t\t\tif f14iter.ReaderEndpoint.Port != nil {\n\t\t\t\t\t\tf14elemf3.Port = f14iter.ReaderEndpoint.Port\n\t\t\t\t\t}\n\t\t\t\t\tf14elem.ReaderEndpoint = f14elemf3\n\t\t\t\t}\n\t\t\t\tif f14iter.Slots != nil {\n\t\t\t\t\tf14elem.Slots = f14iter.Slots\n\t\t\t\t}\n\t\t\t\tif f14iter.Status != nil {\n\t\t\t\t\tf14elem.Status = f14iter.Status\n\t\t\t\t}\n\t\t\t\tf14 = append(f14, f14elem)\n\t\t\t}\n\t\t\tko.Status.NodeGroups = f14\n\t\t}\n\t\tif elem.PendingModifiedValues != nil {\n\t\t\tf15 := &svcapitypes.ReplicationGroupPendingModifiedValues{}\n\t\t\tif elem.PendingModifiedValues.AuthTokenStatus != nil {\n\t\t\t\tf15.AuthTokenStatus = elem.PendingModifiedValues.AuthTokenStatus\n\t\t\t}\n\t\t\tif elem.PendingModifiedValues.AutomaticFailoverStatus != nil {\n\t\t\t\tf15.AutomaticFailoverStatus = elem.PendingModifiedValues.AutomaticFailoverStatus\n\t\t\t}\n\t\t\tif elem.PendingModifiedValues.PrimaryClusterId != nil {\n\t\t\t\tf15.PrimaryClusterID = elem.PendingModifiedValues.PrimaryClusterId\n\t\t\t}\n\t\t\tif elem.PendingModifiedValues.Resharding != nil {\n\t\t\t\tf15f3 := &svcapitypes.ReshardingStatus{}\n\t\t\t\tif elem.PendingModifiedValues.Resharding.SlotMigration != nil {\n\t\t\t\t\tf15f3f0 := &svcapitypes.SlotMigration{}\n\t\t\t\t\tif elem.PendingModifiedValues.Resharding.SlotMigration.ProgressPercentage != nil {\n\t\t\t\t\t\tf15f3f0.ProgressPercentage = elem.PendingModifiedValues.Resharding.SlotMigration.ProgressPercentage\n\t\t\t\t\t}\n\t\t\t\t\tf15f3.SlotMigration = f15f3f0\n\t\t\t\t}\n\t\t\t\tf15.Resharding = f15f3\n\t\t\t}\n\t\t\tif elem.PendingModifiedValues.UserGroups != nil {\n\t\t\t\tf15f4 := &svcapitypes.UserGroupsUpdateStatus{}\n\t\t\t\tif elem.PendingModifiedValues.UserGroups.UserGroupIdsToAdd != nil {\n\t\t\t\t\tf15f4f0 := []*string{}\n\t\t\t\t\tfor _, f15f4f0iter := range elem.PendingModifiedValues.UserGroups.UserGroupIdsToAdd {\n\t\t\t\t\t\tvar f15f4f0elem string\n\t\t\t\t\t\tf15f4f0elem = *f15f4f0iter\n\t\t\t\t\t\tf15f4f0 = append(f15f4f0, &f15f4f0elem)\n\t\t\t\t\t}\n\t\t\t\t\tf15f4.UserGroupIDsToAdd = f15f4f0\n\t\t\t\t}\n\t\t\t\tif elem.PendingModifiedValues.UserGroups.UserGroupIdsToRemove != nil {\n\t\t\t\t\tf15f4f1 := []*string{}\n\t\t\t\t\tfor _, f15f4f1iter := range elem.PendingModifiedValues.UserGroups.UserGroupIdsToRemove {\n\t\t\t\t\t\tvar f15f4f1elem string\n\t\t\t\t\t\tf15f4f1elem = *f15f4f1iter\n\t\t\t\t\t\tf15f4f1 = append(f15f4f1, &f15f4f1elem)\n\t\t\t\t\t}\n\t\t\t\t\tf15f4.UserGroupIDsToRemove = f15f4f1\n\t\t\t\t}\n\t\t\t\tf15.UserGroups = f15f4\n\t\t\t}\n\t\t\tko.Status.PendingModifiedValues = f15\n\t\t}\n\t\tif elem.ReplicationGroupId != nil {\n\t\t\tko.Spec.ReplicationGroupID = elem.ReplicationGroupId\n\t\t}\n\t\tif elem.SnapshotRetentionLimit != nil {\n\t\t\tko.Spec.SnapshotRetentionLimit = elem.SnapshotRetentionLimit\n\t\t}\n\t\tif elem.SnapshotWindow != nil {\n\t\t\tko.Spec.SnapshotWindow = elem.SnapshotWindow\n\t\t}\n\t\tif elem.SnapshottingClusterId != nil {\n\t\t\tko.Status.SnapshottingClusterID = elem.SnapshottingClusterId\n\t\t}\n\t\tif elem.Status != nil {\n\t\t\tko.Status.Status = elem.Status\n\t\t}\n\t\tif elem.TransitEncryptionEnabled != nil {\n\t\t\tko.Spec.TransitEncryptionEnabled = elem.TransitEncryptionEnabled\n\t\t}\n\t\tif elem.UserGroupIds != nil {\n\t\t\tf22 := []*string{}\n\t\t\tfor _, f22iter := range elem.UserGroupIds {\n\t\t\t\tvar f22elem string\n\t\t\t\tf22elem = *f22iter\n\t\t\t\tf22 = append(f22, &f22elem)\n\t\t\t}\n\t\t\tko.Spec.UserGroupIDs = f22\n\t\t}\n\t\tfound = true\n\t\tbreak\n\t}\n\tif !found {\n\t\treturn nil, ackerr.NotFound\n\t}\n\n\trm.setStatusDefaults(ko)\n\n\t// custom set output from response\n\tko, err = rm.CustomDescribeReplicationGroupsSetOutput(ctx, r, resp, ko)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &resource{ko}, nil\n}", "func (cf *Cloudformation) createStack() {\n\n\tcreateStack = &cobra.Command {\n\t\tUse: \"create-efs\",\n\t\tShort: \"Create stack\",\n\t\tLong: `Create stack based on template`,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\n\t\t\tparameters := make([]*cloudformation.Parameter, 0, 5)\n\n\t\t\tonFailure, err := cmd.Flags().GetString(\"onfailure\")\n\t\t\tverifyOnFailureArg(err, onFailure)\n\n\t\t\tcapabilities, err := cmd.Flags().GetStringArray(\"capabilities\")\n\t\t\tverifyCapability(err, capabilities)\n\n\t\t\tstackName, err := cmd.Flags().GetString(\"stackname\")\n\t\t\tverify(err, \"stackname\")\n\n\t\t\tinstanceType, err := cmd.Flags().GetString(\"instance-type\")\n\t\t\tverify(err, \"instance-type\")\n\t\t\taddParameter(&parameters, \"InstanceType\", instanceType)\n\n\t\t\tkeyPair, err := cmd.Flags().GetString(\"key-pair-name\")\n\t\t\tverify(err, \"key-pair-name\")\n\t\t\taddParameter(&parameters, \"KeyName\", keyPair)\n\n\t\t\tsubnets, err := cmd.Flags().GetStringArray(\"subnets\")\n\t\t\tverify(err, \"subnets\")\n\t\t\taddParameters(&parameters, \"Subnets\", subnets)\n\n\t\t\tvpc, err := cmd.Flags().GetString(\"vpc\")\n\t\t\tverify(err, \"vpc\")\n\t\t\taddParameter(&parameters, \"VPC\" ,vpc)\n\n\t\t\timage, err := cmd.Flags().GetString(\"image\")\n\t\t\tverify(err, \"image\")\n\t\t\taddParameter(&parameters, \"ImageId\", image)\n\n\t\t\tfor _, param := range parameters {\n\t\t\t\tfmt.Printf(\"----Param : %s ---- \\n\", param)\n\t\t\t}\n\n\t\t\tcfClient := cloudformation.New(cf.sess, cf.sess.Config)\n\n\t\t\tresp, err := cf.ec2Res.createKeyPair(keyPair)\n\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Create key pair err: %s \\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\n\t\t\tcreatePemFile(resp.KeyMaterial)\n\n\t\t\tfile := readFile(\"templates/distributed_file_system.yaml\")\n\n\t\t\tif _, err := cfClient.CreateStack(&cloudformation.CreateStackInput{\n\t\t\t\tCapabilities: aws.StringSlice(capabilities),\n\t\t\t\tClientRequestToken: nil,\n\t\t\t\tDisableRollback: nil,\n\t\t\t\tEnableTerminationProtection: nil,\n\t\t\t\tNotificationARNs: nil,\n\t\t\t\tOnFailure: &onFailure,\n\t\t\t\tParameters: parameters,\n\t\t\t\tResourceTypes: nil,\n\t\t\t\tRoleARN: nil,\n\t\t\t\tRollbackConfiguration: nil,\n\t\t\t\tStackName: &stackName,\n\t\t\t\tStackPolicyBody: nil,\n\t\t\t\tStackPolicyURL: nil,\n\t\t\t\tTags: nil,\n\t\t\t\tTemplateBody: &file,\n\t\t\t\tTemplateURL: nil,\n\t\t\t\tTimeoutInMinutes: nil,\n\t\t\t}); err != nil {\n\t\t\t\tdeleteKeyPair(cf, keyPair, err)\n\t\t\t}\n\n\t\t},\n\t}\n}", "func (sess *reconcileStackSession) GetStackOutputs() (pulumiv1alpha1.StackOutputs, error) {\n\tstdout, _, err := sess.pulumi(\"stack\", \"output\", \"--json\")\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"getting stack outputs\")\n\t}\n\n\t// Parse the JSON to ensure it's valid and then encode it as a raw message.\n\tvar outs pulumiv1alpha1.StackOutputs\n\tif err = json.Unmarshal([]byte(stdout), &outs); err != nil {\n\t\treturn nil, errors.Wrap(err, \"unmarshaling stack outputs (to map)\")\n\t}\n\n\treturn outs, nil\n}", "func (m *manager) List() ([]string, error) {\n\tvar igs []*compute.InstanceGroup\n\n\tzones, err := m.ListZones(utils.AllNodesPredicate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, zone := range zones {\n\t\tigsForZone, err := m.cloud.ListInstanceGroups(zone)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, ig := range igsForZone {\n\t\t\tigs = append(igs, ig)\n\t\t}\n\t}\n\n\tvar names []string\n\tfor _, ig := range igs {\n\t\tif m.namer.NameBelongsToCluster(ig.Name) {\n\t\t\tnames = append(names, ig.Name)\n\t\t}\n\t}\n\n\treturn names, nil\n}", "func stackExists(stackNameOrID string, cf *cloudformation.CloudFormation, logger *logrus.Logger) (bool, error) {\n\tdescribeStacksInput := &cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(stackNameOrID),\n\t}\n\tdescribeStacksOutput, err := cf.DescribeStacks(describeStacksInput)\n\tlogger.Debug(\"DescribeStackOutput: \", describeStacksOutput)\n\texists := false\n\tif err != nil {\n\t\tlogger.Info(\"DescribeStackOutputError: \", err)\n\t\t// If the stack doesn't exist, then no worries\n\t\tif strings.Contains(err.Error(), \"does not exist\") {\n\t\t\texists = false\n\t\t} else {\n\t\t\treturn false, err\n\t\t}\n\t} else {\n\t\texists = true\n\t}\n\treturn exists, nil\n}", "func (y *YogClient) DescribeStack(request DescribeStackRequest) (DescribeStackResponse, YogError) {\n\treturn DescribeStackResponse{}, YogError{}\n}", "func (clusterRequest *ClusterLoggingRequest) isManaged() bool {\n\treturn clusterRequest.cluster.Spec.ManagementState == logging.ManagementStateManaged\n}", "func Delete(ctx context.Context, serviceName string, logger *zerolog.Logger) error {\n\tawsConfig, awsConfigErr := spartaAWS.NewConfig(ctx, logger)\n\tif awsConfigErr != nil {\n\t\treturn awsConfigErr\n\t}\n\tawsCloudFormation := awsv2CF.NewFromConfig(awsConfig)\n\n\texists, err := spartaCF.StackExists(ctx, serviceName, awsConfig, logger)\n\tif nil != err {\n\t\treturn err\n\t}\n\tlogger.Info().\n\t\tBool(\"Exists\", exists).\n\t\tStr(\"Name\", serviceName).\n\t\tMsg(\"Stack existence check\")\n\n\tif exists {\n\n\t\tparams := &awsv2CF.DeleteStackInput{\n\t\t\tStackName: awsv2.String(serviceName),\n\t\t}\n\t\tresp, err := awsCloudFormation.DeleteStack(ctx, params)\n\t\tif nil != resp {\n\t\t\tlogger.Info().\n\t\t\t\tInterface(\"Response\", resp).\n\t\t\t\tMsg(\"Delete request submitted\")\n\t\t}\n\t\treturn err\n\t}\n\tlogger.Info().Msg(\"Stack does not exist\")\n\treturn nil\n}", "func (root *DSSRoot) ActiveStacks() []*Stack {\n\tdup := make([]*Stack, len(root.stacks))\n\tcopy(dup, root.stacks)\n\treturn dup\n}", "func (client *CraneDockerClient) FilterServiceByStack(namespace string, opts types.ServiceListOptions) ([]swarm.Service, error) {\n\tif opts.Filter.Len() == 0 {\n\t\topts.Filter = filters.NewArgs()\n\t}\n\topts.Filter.Add(\"label\", LabelNamespace)\n\tservices, err := client.ListServiceSpec(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar stackServices []swarm.Service\n\tfor _, service := range services {\n\t\tlabels := service.Spec.Labels\n\t\tname, ok := labels[LabelNamespace]\n\t\tif !ok {\n\t\t\tlog.Warnf(\"Cannot get label %s for service %s\", LabelNamespace, service.ID)\n\t\t\tcontinue\n\t\t}\n\n\t\tif name != namespace {\n\t\t\tcontinue\n\t\t}\n\n\t\tstackServices = append(stackServices, service)\n\t}\n\n\treturn stackServices, nil\n}", "func (r *Client) get(ctx context.Context, stack Stack) (*State, error) {\n\tdescribeOutput, err := r.Client.DescribeStacksWithContext(ctx, &DescribeStacksInput{\n\t\tStackName: aws.String(stack.GetStackName()),\n\t})\n\tif err != nil {\n\t\tif IsNotFoundError(err) {\n\t\t\treturn nil, ErrStackNotFound\n\t\t}\n\t\treturn nil, err\n\t}\n\tif describeOutput == nil {\n\t\treturn nil, fmt.Errorf(\"describeOutput was nil, potential issue with AWS Client\")\n\t}\n\tif len(describeOutput.Stacks) == 0 {\n\t\treturn nil, fmt.Errorf(\"describeOutput contained no Stacks, potential issue with AWS Client\")\n\t}\n\tif len(describeOutput.Stacks) > 1 {\n\t\treturn nil, fmt.Errorf(\"describeOutput contained multiple Stacks which is unexpected when calling with StackName, potential issue with AWS Client\")\n\t}\n\tstate := describeOutput.Stacks[0]\n\tif state.StackStatus == nil {\n\t\treturn nil, fmt.Errorf(\"describeOutput contained a nil StackStatus, potential issue with AWS Client\")\n\t}\n\treturn state, nil\n}", "func (o *ListStacksByWorkspaceParams) WithTimeout(timeout time.Duration) *ListStacksByWorkspaceParams {\n\to.SetTimeout(timeout)\n\treturn o\n}", "func (s *Cloudformation) DeleteStack() (err error) {\n\tsess := s.config.AWSSession\n\tsvc := cloudformation.New(sess)\n\n\tstackInputs := cloudformation.DeleteStackInput{}\n\tstackInputs.SetStackName(s.StackName())\n\n\t_, err = svc.DeleteStack(&stackInputs)\n\treturn\n}", "func (s *Stack) read() (*cloudformation.Stack, error) {\n\tout, err := s.cfnconn.DescribeStacks(&cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(s.Name),\n\t})\n\tif err != nil {\n\t\tif e, ok := err.(awserr.Error); ok && e.Code() == \"ValidationError\" {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, errors.Annotatef(err, \"cannot read stack\")\n\t}\n\tif out.Stacks == nil || len(out.Stacks) == 0 {\n\t\treturn nil, nil\n\t}\n\treturn out.Stacks[0], nil\n}", "func (c *Client) WaitForResources(timeout time.Duration, resources []*manifest.MappingResult) error {\n\treturn wait.Poll(5*time.Second, timeout, func() (bool, error) {\n\t\tstatefulSets := []appsv1.StatefulSet{}\n\t\tdeployments := []deployment{}\n\t\tfor _, r := range resources {\n\t\t\tswitch r.Metadata.Kind {\n\t\t\tcase \"ConfigMap\":\n\t\t\tcase \"Service\":\n\t\t\tcase \"ReplicationController\":\n\t\t\tcase \"Pod\":\n\t\t\tcase \"Deployment\":\n\t\t\t\tcurrentDeployment, err := c.clientset.AppsV1().Deployments(r.Metadata.ObjectMeta.Namespace).Get(context.TODO(), r.Metadata.ObjectMeta.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\t// Find RS associated with deployment\n\t\t\t\tnewReplicaSet, err := c.getNewReplicaSet(currentDeployment)\n\t\t\t\tif err != nil || newReplicaSet == nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tnewDeployment := deployment{\n\t\t\t\t\tnewReplicaSet,\n\t\t\t\t\tcurrentDeployment,\n\t\t\t\t}\n\t\t\t\tdeployments = append(deployments, newDeployment)\n\t\t\tcase \"StatefulSet\":\n\t\t\t\tsf, err := c.clientset.AppsV1().StatefulSets(r.Metadata.ObjectMeta.Namespace).Get(context.TODO(), r.Metadata.ObjectMeta.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tstatefulSets = append(statefulSets, *sf)\n\t\t\t}\n\t\t}\n\t\tisReady := c.statefulSetsReady(statefulSets) && c.deploymentsReady(deployments)\n\t\treturn isReady, nil\n\t})\n}", "func (client *CraneDockerClient) filterStackNetwork(namespace string) ([]docker.Network, error) {\n\tfilter := docker.NetworkFilterOpts{\"label\": map[string]bool{LabelNamespace: true}}\n\tnetworks, err := client.ListNetworks(filter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar stackNetwork []docker.Network\n\tfor _, network := range networks {\n\t\tif network.Labels == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif name, ok := network.Labels[LabelNamespace]; !ok || name != namespace {\n\t\t\tcontinue\n\t\t}\n\n\t\tstackNetwork = append(stackNetwork, network)\n\t}\n\n\treturn stackNetwork, nil\n}", "func (s DescribeStacksInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (m *kafkaConsumerGroupManagerImpl) IsManaged(groupId string) bool {\n\treturn m.getGroup(groupId) != nil\n}", "func (o NodeGroupDataOutput) CfnStack() cloudformation.StackOutput {\n\treturn o.ApplyT(func(v NodeGroupData) *cloudformation.Stack { return v.CfnStack }).(cloudformation.StackOutput)\n}", "func DumpStacks(dir string) (string, error) {\n\tvar (\n\t\tbuf []byte\n\t\tstackSize int\n\t)\n\tbufferLen := 16384\n\tfor stackSize == len(buf) {\n\t\tbuf = make([]byte, bufferLen)\n\t\tstackSize = runtime.Stack(buf, true)\n\t\tbufferLen *= 2\n\t}\n\tbuf = buf[:stackSize]\n\tvar f *os.File\n\tif dir != \"\" {\n\t\tpath := filepath.Join(dir, fmt.Sprintf(stacksLogNameTemplate, strings.Replace(time.Now().Format(time.RFC3339), \":\", \"\", -1)))\n\t\tvar err error\n\t\tf, err = os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0666)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"failed to open file to write the goroutine stacks\")\n\t\t}\n\t\tdefer f.Close()\n\t\tdefer f.Sync()\n\t} else {\n\t\tf = os.Stderr\n\t}\n\tif _, err := f.Write(buf); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to write goroutine stacks\")\n\t}\n\treturn f.Name(), nil\n}", "func (ms *MachinePlugin) ListMachines(ctx context.Context, req *cmi.ListMachinesRequest) (*cmi.ListMachinesResponse, error) {\n\t// Log messages to track start and end of request\n\tglog.V(2).Infof(\"List machines request has been recieved for %q\", req.ProviderSpec)\n\n\tproviderSpec, secrets, err := decodeProviderSpecAndSecret(req.ProviderSpec, req.Secrets, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclusterName := \"\"\n\tnodeRole := \"\"\n\n\tfor key := range providerSpec.Tags {\n\t\tif strings.Contains(key, \"kubernetes.io/cluster/\") {\n\t\t\tclusterName = key\n\t\t} else if strings.Contains(key, \"kubernetes.io/role/\") {\n\t\t\tnodeRole = key\n\t\t}\n\t}\n\n\tsvc, err := ms.createSVC(secrets, providerSpec.Region)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tinput := ec2.DescribeInstancesInput{\n\t\tFilters: []*ec2.Filter{\n\t\t\t&ec2.Filter{\n\t\t\t\tName: aws.String(\"tag-key\"),\n\t\t\t\tValues: []*string{\n\t\t\t\t\t&clusterName,\n\t\t\t\t},\n\t\t\t},\n\t\t\t&ec2.Filter{\n\t\t\t\tName: aws.String(\"tag-key\"),\n\t\t\t\tValues: []*string{\n\t\t\t\t\t&nodeRole,\n\t\t\t\t},\n\t\t\t},\n\t\t\t&ec2.Filter{\n\t\t\t\tName: aws.String(\"instance-state-name\"),\n\t\t\t\tValues: []*string{\n\t\t\t\t\taws.String(\"pending\"),\n\t\t\t\t\taws.String(\"running\"),\n\t\t\t\t\taws.String(\"stopping\"),\n\t\t\t\t\taws.String(\"stopped\"),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\trunResult, err := svc.DescribeInstances(&input)\n\tif err != nil {\n\t\tglog.Errorf(\"AWS plugin is returning error while describe instances request is sent: %s\", err)\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tlistOfVMs := make(map[string]string)\n\tfor _, reservation := range runResult.Reservations {\n\t\tfor _, instance := range reservation.Instances {\n\n\t\t\tmachineName := \"\"\n\t\t\tfor _, tag := range instance.Tags {\n\t\t\t\tif *tag.Key == \"Name\" {\n\t\t\t\t\tmachineName = *tag.Value\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tlistOfVMs[encodeProviderID(providerSpec.Region, *instance.InstanceId)] = machineName\n\t\t}\n\t}\n\n\tglog.V(2).Infof(\"List machines request has been processed successfully\")\n\t// Core logic ends here.\n\tResp := &cmi.ListMachinesResponse{\n\t\tMachineList: listOfVMs,\n\t}\n\treturn Resp, nil\n}", "func (c *StackCollection) DescribeNodeGroupStacksAndResources() (map[string]StackInfo, error) {\n\tstacks, err := c.DescribeNodeGroupStacks()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tallResources := make(map[string]StackInfo)\n\n\tfor _, s := range stacks {\n\t\tinput := &cfn.DescribeStackResourcesInput{\n\t\t\tStackName: s.StackName,\n\t\t}\n\t\ttemplate, err := c.GetStackTemplate(*s.StackName)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"getting template for %q stack\", *s.StackName)\n\t\t}\n\t\tresources, err := c.cloudformationAPI.DescribeStackResources(input)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"getting all resources for %q stack\", *s.StackName)\n\t\t}\n\t\tallResources[c.GetNodeGroupName(s)] = StackInfo{\n\t\t\tResources: resources.StackResources,\n\t\t\tTemplate: &template,\n\t\t\tStack: s,\n\t\t}\n\t}\n\n\treturn allResources, nil\n}", "func NewStack(ctx *pulumi.Context,\n\tname string, args *StackArgs, opts ...pulumi.ResourceOption) (*Stack, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.TemplateUrl == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'TemplateUrl'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Stack\n\terr := ctx.RegisterResource(\"aws-native:cloudformation:Stack\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (d *Double) ListStacksWithTags(tags map[string]string) ([]cfn.StackDescription, error) {\n\treturn d.ListStacksWithTagsFn(tags)\n}", "func New(capacity int) SetOfStacks {\n\treturn &setOfStacks{capacity: capacity}\n}", "func (c *Compiler) needsStackObjects() bool {\n\tif c.selectGC() != \"conservative\" {\n\t\treturn false\n\t}\n\tfor _, tag := range c.BuildTags {\n\t\tif tag == \"baremetal\" {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}" ]
[ "0.5754251", "0.54573864", "0.5245028", "0.5053429", "0.49962544", "0.4935037", "0.49084404", "0.4904233", "0.48626906", "0.48518154", "0.48450178", "0.4760185", "0.47336546", "0.4727369", "0.4725655", "0.47225136", "0.45577127", "0.45574242", "0.4549063", "0.4514616", "0.44926664", "0.44753167", "0.4472368", "0.44648415", "0.4453302", "0.44528726", "0.44009694", "0.43739283", "0.43532315", "0.4344922", "0.4320946", "0.431947", "0.4317713", "0.43105933", "0.43104616", "0.42863357", "0.42794374", "0.4268818", "0.42636308", "0.42614555", "0.4237213", "0.42264742", "0.42238802", "0.4222309", "0.4209366", "0.41983408", "0.4182213", "0.4179085", "0.41640612", "0.41634604", "0.41570017", "0.4147944", "0.41421726", "0.41401082", "0.41360793", "0.41243756", "0.41228262", "0.4112646", "0.40908054", "0.40897357", "0.40852785", "0.4069737", "0.40632463", "0.40579593", "0.4029774", "0.40266657", "0.40051976", "0.4001341", "0.39967075", "0.3994236", "0.39897788", "0.39835608", "0.39708242", "0.39691755", "0.3957803", "0.39487907", "0.3948738", "0.39397642", "0.39360625", "0.39357197", "0.3933174", "0.39226368", "0.39109388", "0.39018643", "0.38996872", "0.38962427", "0.38949585", "0.3887927", "0.38849914", "0.38841787", "0.38451424", "0.38432053", "0.3823774", "0.38153714", "0.38128763", "0.38093922", "0.3809182", "0.38088185", "0.38033545", "0.38032237" ]
0.7192245
0
CreateStack creates a new Application Load Balancer using CloudFormation. The stack name is derived from the Cluster ID and the certificate ARN (when available). All the required resources (listeners and target group) are created in a transactional fashion. Failure to create the stack causes it to be deleted automatically.
func (a *Adapter) CreateStack(certificateARN string, scheme string) (string, error) { spec := &stackSpec{ name: a.stackName(certificateARN), scheme: scheme, certificateARN: certificateARN, securityGroupID: a.SecurityGroupID(), subnets: a.PublicSubnetIDs(), vpcID: a.VpcID(), clusterID: a.ClusterID(), healthCheck: &healthCheck{ path: a.healthCheckPath, port: a.healthCheckPort, interval: a.healthCheckInterval, }, timeoutInMinutes: uint(a.creationTimeout.Minutes()), } return createStack(a.cloudformation, spec) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *Cloudformation) CreateStack() (output *cloudformation.CreateStackOutput, err error) {\n\tsess := s.config.AWSSession\n\tsvc := cloudformation.New(sess)\n\n\tcftemplate := helpers.GetCloudFormationTemplate(s.config, \"s3bucket\", s.S3Bucket.Spec.CloudFormationTemplateName, s.S3Bucket.Spec.CloudFormationTemplateNamespace)\n\n\tstackInputs := cloudformation.CreateStackInput{\n\t\tStackName: aws.String(s.StackName()),\n\t\tTemplateURL: aws.String(cftemplate),\n\t\tNotificationARNs: []*string{\n\t\t\taws.String(s.topicARN),\n\t\t},\n\t}\n\n\tresourceName := helpers.CreateParam(\"ResourceName\", s.S3Bucket.Name)\n\tresourceVersion := helpers.CreateParam(\"ResourceVersion\", s.S3Bucket.ResourceVersion)\n\tnamespace := helpers.CreateParam(\"Namespace\", s.S3Bucket.Namespace)\n\tclusterName := helpers.CreateParam(\"ClusterName\", s.config.ClusterName)\n\tbucketName := helpers.CreateParam(\"BucketName\", helpers.Stringify(s.S3Bucket.Name))\n\tversioningTemp := \"{{.Obj.Spec.Versioning}}\"\n\tversioningValue, err := helpers.Templatize(versioningTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tversioning := helpers.CreateParam(\"EnableVersioning\", helpers.Stringify(versioningValue))\n\taccessControlTemp := \"{{.Obj.Spec.AccessControl}}\"\n\taccessControlValue, err := helpers.Templatize(accessControlTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\taccessControl := helpers.CreateParam(\"BucketAccessControl\", helpers.Stringify(accessControlValue))\n\tloggingenabledTemp := \"{{.Obj.Spec.Logging.Enabled}}\"\n\tloggingenabledValue, err := helpers.Templatize(loggingenabledTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tloggingenabled := helpers.CreateParam(\"EnableLogging\", helpers.Stringify(loggingenabledValue))\n\tloggingprefixTemp := \"{{.Obj.Spec.Logging.Prefix}}\"\n\tloggingprefixValue, err := helpers.Templatize(loggingprefixTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tloggingprefix := helpers.CreateParam(\"LoggingPrefix\", helpers.Stringify(loggingprefixValue))\n\twebsiteenabledTemp := \"{{.Obj.Spec.Website.Enabled}}\"\n\twebsiteenabledValue, err := helpers.Templatize(websiteenabledTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteenabled := helpers.CreateParam(\"EnableStaticSite\", helpers.Stringify(websiteenabledValue))\n\twebsiteindexPageTemp := \"{{.Obj.Spec.Website.IndexPage}}\"\n\twebsiteindexPageValue, err := helpers.Templatize(websiteindexPageTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteindexPage := helpers.CreateParam(\"StaticSiteIndex\", helpers.Stringify(websiteindexPageValue))\n\twebsiteerrorPageTemp := \"{{.Obj.Spec.Website.ErrorPage}}\"\n\twebsiteerrorPageValue, err := helpers.Templatize(websiteerrorPageTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteerrorPage := helpers.CreateParam(\"StaticSiteError\", helpers.Stringify(websiteerrorPageValue))\n\n\tparameters := []*cloudformation.Parameter{}\n\tparameters = append(parameters, resourceName)\n\tparameters = append(parameters, resourceVersion)\n\tparameters = append(parameters, namespace)\n\tparameters = append(parameters, clusterName)\n\tparameters = append(parameters, bucketName)\n\tparameters = append(parameters, versioning)\n\tparameters = append(parameters, accessControl)\n\tparameters = append(parameters, loggingenabled)\n\tparameters = append(parameters, loggingprefix)\n\tparameters = append(parameters, websiteenabled)\n\tparameters = append(parameters, websiteindexPage)\n\tparameters = append(parameters, websiteerrorPage)\n\n\tstackInputs.SetParameters(parameters)\n\n\tresourceNameTag := helpers.CreateTag(\"ResourceName\", s.S3Bucket.Name)\n\tresourceVersionTag := helpers.CreateTag(\"ResourceVersion\", s.S3Bucket.ResourceVersion)\n\tnamespaceTag := helpers.CreateTag(\"Namespace\", s.S3Bucket.Namespace)\n\tclusterNameTag := helpers.CreateTag(\"ClusterName\", s.config.ClusterName)\n\n\ttags := []*cloudformation.Tag{}\n\ttags = append(tags, resourceNameTag)\n\ttags = append(tags, resourceVersionTag)\n\ttags = append(tags, namespaceTag)\n\ttags = append(tags, clusterNameTag)\n\n\tstackInputs.SetTags(tags)\n\n\toutput, err = svc.CreateStack(&stackInputs)\n\treturn\n}", "func CreateStack(r string, name string, uri string, params []*cloudformation.Parameter, capabilities []*string) {\n\tsvc := cloudformation.New(getSession(r))\n\tlog.Info(\"CreateStack\")\n\n\tlog.Debug(\"Using Parameters:\")\n\tlog.Debug(\"%v\", params)\n\n\ttemplate := cloudformation.CreateStackInput{\n\t\tStackName: &name,\n\t\tParameters: params,\n\t\tCapabilities: capabilities,\n\t}\n\tif pass, path := parseURI(uri); pass {\n\t\ttemplateBody := utils.LoadTemplate(path)\n\t\ttemplate.TemplateBody = &templateBody\n\t} else {\n\t\ttemplate.TemplateURL = &path\n\t}\n\n\tstack, err := svc.CreateStack(&template)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Print(\"%v\", stack)\n}", "func (client *Client) CreateStack(request *CreateStackRequest) (response *CreateStackResponse, err error) {\n\tresponse = CreateCreateStackResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func (c *CloudFormationTemplate) CreateStack(suffix string) {\n\tfmt.Printf(\"\\nRunning CloudFormation stack [%s]\", c.Name)\n\tsess := session.Must(session.NewSession(&aws.Config{\n\t\tRegion: aws.String(\"us-west-2\"),\n\t}))\n\tsvc := cloudformation.New(sess)\n\n\ttemplateBody := string(c.Bytes)\n\tc.StackName = c.Name + \"-\" + suffix\n\tcloudFormationValues := make(map[string]string)\n\n\tcreateStackParams := &cloudformation.CreateStackInput{\n\t\tStackName: aws.String(c.StackName),\n\t\tTemplateBody: aws.String(templateBody),\n\t}\n\n\tdescribeStacksParams := &cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(c.StackName),\n\t}\n\n\tout, err := svc.CreateStack(createStackParams)\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"AlreadyExistsException\") {\n\t\t\tfmt.Printf(\"\\nCloudFormation stack [%s] already exists. Skipping...\", c.Name)\n\t\t\tdescOut, err := svc.DescribeStacks(describeStacksParams)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tc.ParseOutput(descOut, cloudFormationValues)\n\t\t\treturn\n\t\t} else {\n\t\t\tfmt.Printf(\"%s\", err)\n\t\t\tpanic(err)\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"%s\", out)\n\t}\n\n\tstackReady := false\n\n\tfor stackReady != true {\n\n\t\tdescOut, err := svc.DescribeStacks(describeStacksParams)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%s\", err)\n\t\t\tpanic(err)\n\t\t} else {\n\t\t\tfmt.Printf(\"\\nCloudFormation stack [%s] is creating...\", c.Name)\n\t\t}\n\n\t\tif *descOut.Stacks[0].StackStatus == \"CREATE_COMPLETE\" {\n\t\t\tstackReady = true\n\t\t\tfmt.Printf(\"\\nCloudFormation stack [%s] ready...\\n\", c.Name)\n\t\t\tc.ParseOutput(descOut, cloudFormationValues)\n\t\t}\n\n\t\ttime.Sleep(time.Second * 7)\n\t}\n\n}", "func CreateStack(ctx context.Context, svc *cf.CloudFormation, opts *RequestOptions, timeout int64) (*cf.CreateStackOutput, error) {\n\tinput := &cf.CreateStackInput{\n\t\tStackName: aws.String(opts.StackName),\n\t\tCapabilities: []*string{\n\t\t\taws.String(\"CAPABILITY_IAM\"),\n\t\t},\n\t\tOnFailure: aws.String(opts.OnFailure),\n\t\tParameters: toParameters(opts.Params),\n\t\tTemplateURL: aws.String(opts.TemplateURL),\n\t\tTimeoutInMinutes: aws.Int64(timeout),\n\t}\n\n\treturn svc.CreateStackWithContext(ctx, input)\n}", "func NewStack(ctx *pulumi.Context,\n\tname string, args *StackArgs, opts ...pulumi.ResourceOption) (*Stack, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.TemplateUrl == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'TemplateUrl'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Stack\n\terr := ctx.RegisterResource(\"aws-native:cloudformation:Stack\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (c *CloudFormation) CreateStack(input *cfn.CreateStackInput) (*Stack, error) {\n\tresp, err := c.srv.CreateStack(input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.Stack(*resp.StackId)\n}", "func (y *YogClient) CreateStack(request CreateStackRequest) (CreateStackResponse, YogError) {\n\tcsi, err := parseTemplate(request.TemplateBody)\n\tif err != nil {\n\t\tye := YogError{\n\t\t\tCode: FailedToParseYaml,\n\t\t\tMessage: \"error while parsing template\",\n\t\t\tError: err,\n\t\t\tDropletErrors: []DropletError{},\n\t\t\tStackname: request.StackName,\n\t\t}\n\t\treturn CreateStackResponse{}, ye\n\t}\n\n\tresponse := CreateStackResponse{Name: request.StackName}\n\tbuiltResources := []Resource{}\n\tfor k, v := range csi.Resources {\n\t\tvar s Service\n\t\tif _, ok := v[\"Type\"]; !ok {\n\t\t\tmessage := fmt.Sprintf(\"no 'Type' provided for resource '%s'\", k)\n\t\t\tye := YogError{\n\t\t\t\tCode: NoTypeForResource,\n\t\t\t\tMessage: message,\n\t\t\t\tError: errors.New(message),\n\t\t\t\tDropletErrors: []DropletError{},\n\t\t\t\tStackname: request.StackName,\n\t\t\t}\n\t\t\treturn CreateStackResponse{}, ye\n\t\t}\n\t\td, err := buildResource(s.Service(v[\"Type\"].(string)))\n\t\t// Droplet doesn't yet have an ID. This will be updated once they are created.\n\t\tif err != nil {\n\t\t\tye := YogError{\n\t\t\t\tCode: UnknownResourceType,\n\t\t\t\tMessage: \"\",\n\t\t\t\tError: err,\n\t\t\t\tDropletErrors: []DropletError{},\n\t\t\t\tStackname: request.StackName,\n\t\t\t}\n\t\t\treturn CreateStackResponse{}, ye\n\t\t}\n\t\terr = d.buildRequest(request.StackName, v)\n\t\tif err != nil {\n\t\t\tye := YogError{\n\t\t\t\tCode: FailedToBuildRequest,\n\t\t\t\tMessage: \"\",\n\t\t\t\tError: err,\n\t\t\t\tDropletErrors: []DropletError{},\n\t\t\t\tStackname: request.StackName,\n\t\t\t}\n\t\t\treturn CreateStackResponse{}, ye\n\t\t}\n\t\tbuiltResources = append(builtResources, d)\n\t}\n\n\tde := y.launchAllDroplets(builtResources)\n\tif len(de) != 0 {\n\t\tye := YogError{\n\t\t\tCode: ErrorLaunchingDroplets,\n\t\t\tStackname: request.StackName,\n\t\t\tError: errors.New(\"error launching droplets. please see DropletErrors for more detail\"),\n\t\t\tMessage: \"\",\n\t\t\tDropletErrors: de,\n\t\t}\n\t\treturn CreateStackResponse{}, ye\n\t}\n\terr = y.setupDropletIDsForResources(builtResources)\n\tif err != nil {\n\t\tye := YogError{\n\t\t\tCode: ErrorSettingUpDropletIDSForResources,\n\t\t\tStackname: request.StackName,\n\t\t\tError: err,\n\t\t\tMessage: \"error setting up droplet ids for resource\",\n\t\t\tDropletErrors: []DropletError{},\n\t\t}\n\t\treturn CreateStackResponse{}, ye\n\t}\n\terr = y.launchTheRestOfTheResources(builtResources)\n\tif err != nil {\n\t\tye := YogError{\n\t\t\tCode: ErrorLaunchingResource,\n\t\t\tStackname: request.StackName,\n\t\t\tError: err,\n\t\t\tMessage: \"error while trying to launch the rest of the resources\",\n\t\t\tDropletErrors: []DropletError{},\n\t\t}\n\t\treturn CreateStackResponse{}, ye\n\t}\n\n\tresponse.Resources = builtResources\n\t// Save resources here.\n\treturn response, YogError{}\n}", "func (c *Client) CreateStack(ctx context.Context, params *CreateStackInput, optFns ...func(*Options)) (*CreateStackOutput, error) {\n\tif params == nil {\n\t\tparams = &CreateStackInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"CreateStack\", params, optFns, addOperationCreateStackMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*CreateStackOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (a *StacksApiService) CreateStack(ctx _context.Context) apiCreateStackRequest {\n\treturn apiCreateStackRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (c *StackCollection) CreateStack(ctx context.Context, stackName string, resourceSet builder.ResourceSetReader, tags, parameters map[string]string, errs chan error) error {\n\tstack, err := c.createStackRequest(ctx, stackName, resourceSet, tags, parameters)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo c.waitUntilStackIsCreated(ctx, stack, resourceSet, errs)\n\treturn nil\n}", "func (f *FakeReconcilerClient) CreateStack(stackSpec types.StackSpec) (types.StackCreateResponse, error) {\n\tif stackSpec.Annotations.Name == \"\" {\n\t\treturn types.StackCreateResponse{}, fmt.Errorf(\"StackSpec contains no name\")\n\t}\n\n\tid, err := f.FakeStackStore.AddStack(stackSpec)\n\tif err != nil {\n\t\treturn types.StackCreateResponse{}, fmt.Errorf(\"unable to store stack: %s\", err)\n\t}\n\n\treturn types.StackCreateResponse{\n\t\tID: id,\n\t}, err\n}", "func (m *MockCloudformationAPI) CreateStack(*cloudformation.CreateStackInput) (*cloudformation.CreateStackOutput, error) {\n\treturn &cloudformation.CreateStackOutput{}, nil\n}", "func CreateStackResources(stackID string, subscription dynamodb.APISubscription) error {\n\n\t// Create a new CloudFormation template\n\ttemplate := cloudformation.NewTemplate()\n\n\t//Generate GUID\n\tid := stackID\n\n\ttags := []tags.Tag{\n\t\ttags.Tag{\n\t\t\tKey: \"Product\",\n\t\t\tValue: \"MaxEdge\",\n\t\t},\n\t\t// tags.Tag{\n\t\t// \tKey: \"Subscription_ID\",\n\t\t// \tValue: subscription.Name,\n\t\t// },\n\t}\n\n\t// AWS ECS Prpoperties\n\tvarRequiresCompatibilities := []string{\"FARGATE\"}\n\n\t// Lambda Environment Variables //\n\n\t// AWS Account ID\n\tvar varAwsAccountID = os.Getenv(\"AWS_ACCOUNT_ID\")\n\n\t// Task Definition\n\tvar varExecutionRoleArn = os.Getenv(\"EXECUTION_ROLE\")\n\tvar varTaskRoleArn = os.Getenv(\"TASK_ROLE\")\n\tvar varEcsTaskDefinitionRef = os.Getenv(\"CLOUDFORMATION_TASK_DEFINITION_REF\")\n\n\t// Container Definition\n\tvar varImage = os.Getenv(\"CONTAINER_IMAGE\")\n\n\t//Network Definition\n\tvar varSecurityGroup = os.Getenv(\"SECURITY_GROUP\")\n\tvar varSubnet1 = os.Getenv(\"SUBNET_1\")\n\tvar varSubnet2 = os.Getenv(\"SUBNET_2\")\n\tvar varSubnet3 = os.Getenv(\"SUBNET_3\")\n\n\t//ECS Service\n\tvar varClusterName = os.Getenv(\"CLUSTER_NAME\")\n\tvar varEcsRef = os.Getenv(\"CLOUDFORMATION_ECS_SERVICE_REF\")\n\n\t//Secret\n\tvar varSecretRef = os.Getenv(\"CLOUDFORMATION_SECRET_REF\")\n\n\t// Create IAM User\n\ttemplate.Resources[\"IAMUSER\"] = &iam.User{\n\t\tUserName: string(id),\n\t\tTags: tags,\n\t}\n\n\t// Assigning the subscribers ID to a string so it can be added to the policy\n\tbucket := fmt.Sprintf(\"\\\"arn:aws:s3:::maxedgecloudtocloudpoc-sandbox/%s/*\\\"\", id)\n\tvar roleName string = \"ROLE_\" + id\n\tvar policyName string = \"Policy\" + id\n\n\t// S3 GetObject policy for the created IAM user for a subscription\n\t// User will assume the role\n\t// Action is to Assume the sts role\n\ttemplate.Resources[\"IAMPolicy\"] = &iam.Policy{\n\t\tPolicyName: policyName,\n\t\tPolicyDocument: (\"{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[{\\\"Effect\\\":\\\"Allow\\\",\\\"Action\\\":\\\"sts:AssumeRole\\\",\\\"Resource\\\":\\\"arn:aws:iam::\" + varAwsAccountID + \":role/\" + roleName + \"\\\"}]}\"),\n\t\tUsers: []string{id},\n\t\tAWSCloudFormationDependsOn: []string{\"IAMUSER\"},\n\t}\n\n\tp := iam.Role_Policy{\n\t\tPolicyDocument: (\"{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[{\\\"Effect\\\":\\\"Allow\\\",\\\"Action\\\":\\\"s3:GetObject\\\",\\\"Resource\\\":\" + bucket + \"}]}\"),\n\t\tPolicyName: id,\n\t}\n\n\t// Assume Role or Trust Policy\n\ttemplate.Resources[\"IAMROLE\"] = &iam.Role{\n\t\tAssumeRolePolicyDocument: (\"{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[{\\\"Effect\\\":\\\"Allow\\\",\\\"Principal\\\":{\\\"AWS\\\": \\\"arn:aws:iam::\" + varAwsAccountID + \":user/\" + id + \"\\\"},\\\"Action\\\":[\\\"sts:AssumeRole\\\"]}]}\"),\n\t\tRoleName: roleName,\n\t\tPolicies: []iam.Role_Policy{p},\n\t\tAWSCloudFormationDependsOn: []string{\"IAMUSER\"},\n\t\tTags: tags,\n\t}\n\n\t// Task Definition Secret - sets the value for the container based on what was\n\t// created in the template.\n\tTaskDefSecret := []ecs.TaskDefinition_Secret{}\n\tvarTaskDefSecret := ecs.TaskDefinition_Secret{\n\t\t//Referance to the ARNs created when the secret is created\n\t\tName: cloudformation.Ref(varSecretRef),\n\t\tValueFrom: cloudformation.Ref(varSecretRef),\n\t}\n\tTaskDefSecret = append(TaskDefSecret, varTaskDefSecret)\n\n\t// TargetName come from the DynamoDB table and stores the cloud platform\n\t// endpoint for the data destination\n\tgroup := \"/MaxEdge/CloudToCloud/\" + subscription.Target\n\n\tcwLog := &ecs.TaskDefinition_LogConfiguration{\n\t\tLogDriver: \"awslogs\",\n\t\tOptions: map[string]string{\"awslogs-create-group\": \"true\", \"awslogs-group\": group, \"awslogs-region\": \"us-east-1\", \"awslogs-stream-prefix\": id},\n\t}\n\n\t//Task Definition Container Definition - Setting properties\n\tTaskDefConDef := []ecs.TaskDefinition_ContainerDefinition{}\n\tvarTaskDef := ecs.TaskDefinition_ContainerDefinition{\n\t\tImage: varImage,\n\t\tName: id,\n\t\tSecrets: TaskDefSecret,\n\t\tLogConfiguration: cwLog,\n\t}\n\tTaskDefConDef = append(TaskDefConDef, varTaskDef)\n\n\t// Create an Amazon ECS Task Definition - Setting properties\n\ttemplate.Resources[varEcsTaskDefinitionRef] = &ecs.TaskDefinition{\n\t\tExecutionRoleArn: varExecutionRoleArn,\n\t\tTaskRoleArn: varTaskRoleArn,\n\t\tMemory: \"1024\",\n\t\tNetworkMode: \"awsvpc\",\n\t\tRequiresCompatibilities: varRequiresCompatibilities,\n\t\tCpu: \"512\",\n\t\tContainerDefinitions: TaskDefConDef,\n\t\tTags: tags,\n\t}\n\n\t// ECS Service Network configuration\n\tsnc := &ecs.Service_NetworkConfiguration{\n\t\tAwsvpcConfiguration: &ecs.Service_AwsVpcConfiguration{\n\n\t\t\t// Required to access ECR\n\t\t\tAssignPublicIp: \"ENABLED\",\n\t\t\t// The Security Group needs to allow traffic via port :443\n\t\t\tSecurityGroups: []string{varSecurityGroup},\n\t\t\tSubnets: []string{varSubnet1, varSubnet2, varSubnet3},\n\t\t},\n\t}\n\n\t// Create Amazon ECS Service\n\ttemplate.Resources[varEcsRef] = &ecs.Service{\n\t\tLaunchType: \"FARGATE\",\n\t\tCluster: varClusterName,\n\t\tTaskDefinition: cloudformation.Ref(varEcsTaskDefinitionRef),\n\t\tServiceName: id,\n\t\tDesiredCount: 1,\n\t\tNetworkConfiguration: snc,\n\t\tSchedulingStrategy: \"REPLICA\",\n\t\tTags: tags,\n\t\tPropagateTags: \"TASK_DEFINITION\",\n\t}\n\n\t// Create an Amazon Secret\n\ttemplate.Resources[varSecretRef] = &secretsmanager.Secret{\n\t\tName: id,\n\t\tDescription: \"Metadata for companies\",\n\t\tTags: tags,\n\t}\n\n\t// Get JSON form of AWS CloudFormation template\n\tj, err := template.JSON()\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to generate JSON: %s\\n\", err)\n\t\treturn err\n\t}\n\tfmt.Printf(\"Template creation for %s Done.\\n\", id)\n\tfmt.Println(\"=====\")\n\tfmt.Println(\"Generated template:\")\n\tfmt.Printf(\"%s\\n\", string(j))\n\tfmt.Println(\"=====\")\n\n\t// Initialize a session that the SDK uses to load\n\t// credentials from the shared credentials file ~/.aws/credentials\n\t// and configuration from the shared configuration file ~/.aws/config.\n\t// https://docs.aws.amazon.com/sdk-for-go/api/aws/session/\n\tsess := session.Must(session.NewSessionWithOptions(session.Options{\n\t\tSharedConfigState: session.SharedConfigEnable,\n\t}))\n\n\t// Create the stack\n\terr = createStackFromBody(sess, j, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func TestCFCreateStack(t *testing.T) {\n\tt.Parallel()\n\n\texpectedName := fmt.Sprintf(\"terratest-cf-example-%s\", random.UniqueId())\n\n\tCFOptions := &cloudformation.Options{\n\t\tCFFile: \"../examples/cloudformation-aws-example/cf_create_test.yml\",\n\t\tStackName: expectedName,\n\t\tAWSRegion: \"us-west-2\",\n\t}\n\tdefer cloudformation.DeleteStack(t, CFOptions)\n\n\tcloudformation.CreateStack(t, CFOptions)\n\tlist := cloudformation.ListResources(t, CFOptions)\n\tfilteredList := cloudformation.FilterResources(list, \"DummyResource\")\n\tassert.Contains(t, filteredList, \"cloudformation-waitcondition-\")\n}", "func (handler *Handler) stackCreate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {\n\tstackType, err := request.RetrieveNumericQueryParameter(r, \"type\", false)\n\tif err != nil {\n\t\treturn &httperror.HandlerError{http.StatusBadRequest, \"Invalid query parameter: type\", err}\n\t}\n\n\tmethod, err := request.RetrieveQueryParameter(r, \"method\", false)\n\tif err != nil {\n\t\treturn &httperror.HandlerError{http.StatusBadRequest, \"Invalid query parameter: method\", err}\n\t}\n\n\tendpointID, err := request.RetrieveNumericQueryParameter(r, \"endpointId\", false)\n\tif err != nil {\n\t\treturn &httperror.HandlerError{http.StatusBadRequest, \"Invalid query parameter: endpointId\", err}\n\t}\n\n\tendpoint, err := handler.EndpointService.Endpoint(portainer.EndpointID(endpointID))\n\tif err == portainer.ErrObjectNotFound {\n\t\treturn &httperror.HandlerError{http.StatusNotFound, \"Unable to find an endpoint with the specified identifier inside the database\", err}\n\t} else if err != nil {\n\t\treturn &httperror.HandlerError{http.StatusInternalServerError, \"Unable to find an endpoint with the specified identifier inside the database\", err}\n\t}\n\n\terr = handler.requestBouncer.EndpointAccess(r, endpoint)\n\tif err != nil {\n\t\treturn &httperror.HandlerError{http.StatusForbidden, \"Permission denied to access endpoint\", portainer.ErrEndpointAccessDenied}\n\t}\n\n\tswitch portainer.StackType(stackType) {\n\tcase portainer.DockerSwarmStack:\n\t\treturn handler.createSwarmStack(w, r, method, endpoint)\n\tcase portainer.DockerComposeStack:\n\t\treturn handler.createComposeStack(w, r, method, endpoint)\n\t}\n\n\treturn &httperror.HandlerError{http.StatusBadRequest, \"Invalid value for query parameter: type. Value must be one of: 1 (Swarm stack) or 2 (Compose stack)\", errors.New(request.ErrInvalidQueryParameter)}\n}", "func (a *Client) CreateNetworkSwitchStack(params *CreateNetworkSwitchStackParams, authInfo runtime.ClientAuthInfoWriter) (*CreateNetworkSwitchStackCreated, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewCreateNetworkSwitchStackParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"createNetworkSwitchStack\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/networks/{networkId}/switchStacks\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &CreateNetworkSwitchStackReader{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.(*CreateNetworkSwitchStackCreated)\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 createNetworkSwitchStack: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (c *Client) NewStack(stack *CreateStackInput) (int64, error) {\n\tdata, err := json.Marshal(stack)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tresult := struct {\n\t\tID int64 `json:\"id\"`\n\t}{}\n\n\terr = c.request(\"POST\", \"/api/instances\", nil, bytes.NewBuffer(data), &result)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn result.ID, nil\n}", "func (r *Client) create(ctx context.Context, stack Stack, params ...*Parameter) error {\n\t// fetch and validate template\n\tt, err := stack.GetStackTemplate()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = r.validateTemplateParams(t, params)\n\tif err != nil {\n\t\treturn err\n\t}\n\tyaml, err := t.YAML()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstackPolicy, err := getStackPolicy(stack)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = r.Client.CreateStackWithContext(ctx, &CreateStackInput{\n\t\tCapabilities: capabilities,\n\t\tTemplateBody: aws.String(string(yaml)),\n\t\tStackName: aws.String(stack.GetStackName()),\n\t\tStackPolicyBody: stackPolicy,\n\t\tParameters: params,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func NewStack(cfnconn cloudformationiface.CloudFormationAPI, name string) (*Stack, error) {\n\tstack := &Stack{Name: name, cfnconn: cfnconn}\n\tif err := stack.updateOnce(); err != nil {\n\t\treturn nil, errors.Annotatef(err, \"cannot create new stack\")\n\t}\n\treturn stack, nil\n}", "func (c *StackCollection) createClusterStack(ctx context.Context, stackName string, resourceSet builder.ResourceSetReader, errCh chan error) error {\n\tclusterTags := map[string]string{\n\t\tapi.ClusterOIDCEnabledTag: strconv.FormatBool(api.IsEnabled(c.spec.IAM.WithOIDC)),\n\t}\n\tstack, err := c.createStackRequest(ctx, stackName, resourceSet, clusterTags, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\tdefer close(errCh)\n\t\ttroubleshoot := func() {\n\t\t\tstack, err := c.DescribeStack(ctx, stack)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Info(\"error describing stack to troubleshoot the cause of the failure; \"+\n\t\t\t\t\t\"check the CloudFormation console for further details\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlogger.Critical(\"unexpected status %q while waiting for CloudFormation stack %q\", stack.StackStatus, *stack.StackName)\n\t\t\tc.troubleshootStackFailureCause(ctx, stack, string(types.StackStatusCreateComplete))\n\t\t}\n\n\t\tctx, cancelFunc := context.WithTimeout(context.Background(), c.waitTimeout)\n\t\tdefer cancelFunc()\n\n\t\tstack, err := waiter.WaitForStack(ctx, c.cloudformationAPI, *stack.StackId, *stack.StackName, func(attempts int) time.Duration {\n\t\t\t// Wait 30s for the first two requests, and 1m for subsequent requests.\n\t\t\tif attempts <= 2 {\n\t\t\t\treturn 30 * time.Second\n\t\t\t}\n\t\t\treturn 1 * time.Minute\n\t\t})\n\n\t\tif err != nil {\n\t\t\ttroubleshoot()\n\t\t\terrCh <- err\n\t\t\treturn\n\t\t}\n\n\t\tif err := resourceSet.GetAllOutputs(*stack); err != nil {\n\t\t\terrCh <- errors.Wrapf(err, \"getting stack %q outputs\", *stack.StackName)\n\t\t\treturn\n\t\t}\n\n\t\terrCh <- nil\n\t}()\n\n\treturn nil\n}", "func createStackFromBody(sess client.ConfigProvider, templateBody []byte, stackName string) error {\n\n\t// Tags for the CloudFormation stack\n\ttags := []*cfn.Tag{\n\t\t{\n\t\t\tKey: aws.String(\"Product\"),\n\t\t\tValue: aws.String(\"MaxEdge\"),\n\t\t},\n\t}\n\n\t//Creates CloudFormation stack\n\tsvc := cfn.New(sess)\n\tinput := &cfn.CreateStackInput{\n\t\tTemplateBody: aws.String(string(templateBody)),\n\t\tStackName: aws.String(stackName),\n\t\tTags: tags,\n\t\tCapabilities: []*string{aws.String(\"CAPABILITY_NAMED_IAM\")}, // Required because of creating a stack that is creating IAM resources\n\t}\n\n\tfmt.Println(\"Stack creation initiated...\")\n\n\t// Creates the stack\n\t_, err := svc.CreateStack(input)\n\tif err != nil {\n\t\tfmt.Println(\"Got error creating stack:\")\n\t\tfmt.Println(err.Error())\n\t\treturn err\n\t}\n\treturn nil\n}", "func CreateStackResources(stackID string, subscription dynamodb.APISubscription) error {\n\n\t// Lamba environment variables\n\n\tvar amiID = os.Getenv(\"AMI_ID\")\n\tvar securityGroup = os.Getenv(\"SECURITY_GROUP\")\n\tvar subNet = os.Getenv(\"SUBNET\")\n\tvar keyName = os.Getenv(\"KEY_NAME\")\n\tvar instanceType = os.Getenv(\"INSTANCE_TYPE\")\n\tvar iamRole = os.Getenv(\"IAM_ROLE\")\n\n\t// Create a new CloudFormation template\n\ttemplate := cloudformation.NewTemplate()\n\n\t// StackID with 'PI' as a prefix to avoid\n\t// duplicate stack names in CloudFormation\n\tid := stackID\n\n\ttags := []tags.Tag{\n\t\ttags.Tag{\n\t\t\tKey: \"Product\",\n\t\t\tValue: \"MaxEdge\",\n\t\t},\n\t\t// This tag is used to display the \"Name\" in the console\n\t\ttags.Tag{\n\t\t\tKey: \"Name\",\n\t\t\tValue: id,\n\t\t},\n\t}\n\n\t// Declaring the PI .exe for teh service to deal with the qoutes\n\t// being stripped off and not workign in PowerShell\n\tpiToPi := `C:\\Program Files (x86)\\PIPC\\Interfaces\\PItoPI\\PItoPI.exe`\n\n\t// Pi .bat file needed for the Pi interface service\n\t// The source, destination and ports are added to this string and passed in as parameters\n\t// from the user.\n\t// The PowerShell commands that updates the .bat file that is on the AMI\n\t// with the client passed in parameters.\n\t// PowerShell command and the \"<powershell></powershell>\" is required when\n\t// using UserDate in EC2 and using PowerShell commands\n\t// Then changes the directory to the location of the nssm program to start the PItoPIInt service.\n\t// Services will restart on reboot or instance restart\n\tuserData := fmt.Sprintf(`<powershell> \n\tSet-Content -Path \"C:\\Program Files (x86)\\PIPC\\Interfaces\\PItoPI\\PItoPIInt.bat\" -Value '\"`+piToPi+`\" Int /src_host=%s:%s /PS=%s /ID=%s /host=%s:%s /pisdk=0 /maxstoptime=120 /PercentUp=100 /sio /perf=8 /f=00:00:01'\n\tcd \"C:\\Program Files (x86)\\PIPC\\Interfaces\\PItoPI\\\"; .\\nssm start PItoPIInt \n\t</powershell>\n\t<persist>true</persist>`, subscription.SourceIP, subscription.SourcePort, id, id, subscription.DestinationIP, subscription.DestinationPort)\n\n\t// Required base64 encoding\n\t// If you are using a command line tool, base64-encoding is performed\n\t// for you, and you can load the text from a file. Otherwise, you must provide\n\t// base64-encoded text. User data is limited to 16 KB.\n\tencodeUserDate := e64.StdEncoding.EncodeToString([]byte(userData))\n\n\t// CloudFormation E2 properties\n\ttemplate.Resources[\"EC2Pi\"] = &ec2.Instance{\n\t\tImageId: (amiID),\n\t\tKeyName: (keyName),\n\t\tInstanceType: (instanceType),\n\t\tSecurityGroupIds: []string{securityGroup},\n\t\tSubnetId: (subNet),\n\t\tIamInstanceProfile: (iamRole),\n\t\tUserData: encodeUserDate,\n\t\tTags: (tags),\n\t}\n\n\t// Get JSON form of AWS CloudFormation template\n\tj, err := template.JSON()\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to generate JSON: %s\\n\", err)\n\t\treturn err\n\t}\n\tfmt.Printf(\"Template creation for %s Done.\\n\", id)\n\tfmt.Println(\"=====\")\n\tfmt.Println(\"Generated template:\")\n\tfmt.Printf(\"%s\\n\", string(j))\n\tfmt.Println(\"=====\")\n\n\t// Initialize a session that the SDK uses to load\n\t// credentials from the shared credentials file ~/.aws/credentials\n\t// and configuration from the shared configuration file ~/.aws/config.\n\t// https://docs.aws.amazon.com/sdk-for-go/api/aws/session/\n\tsess := session.Must(session.NewSessionWithOptions(session.Options{\n\t\tSharedConfigState: session.SharedConfigEnable,\n\t}))\n\n\t// Create the stack\n\terr = createStackFromBody(sess, j, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (f *FakeReconcilerClient) GenerateStackDependencies(stackID string) error {\n\tsnapshot, err := f.FakeStackStore.GetSnapshotStack(stackID)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstackSpec := CopyStackSpec(snapshot.CurrentSpec)\n\n\tfor _, secret := range stackSpec.Secrets {\n\t\tsecret = *CopySecretSpec(secret)\n\t\tif secret.Annotations.Labels == nil {\n\t\t\tsecret.Annotations.Labels = map[string]string{}\n\t\t}\n\t\tsecret.Annotations.Labels[types.StackLabel] = stackID\n\t\t_, secretError := f.CreateSecret(secret)\n\n\t\tif secretError != nil {\n\t\t\terr = secretError\n\t\t\tbreak\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, config := range stackSpec.Configs {\n\t\tconfig = *CopyConfigSpec(config)\n\t\tif config.Annotations.Labels == nil {\n\t\t\tconfig.Annotations.Labels = map[string]string{}\n\t\t}\n\t\tconfig.Annotations.Labels[types.StackLabel] = stackID\n\t\t_, configError := f.CreateConfig(config)\n\n\t\tif configError != nil {\n\t\t\terr = configError\n\t\t\tbreak\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor name, network := range stackSpec.Networks {\n\t\tnetwork = *CopyNetworkCreate(network)\n\t\tif network.Labels == nil {\n\t\t\tnetwork.Labels = map[string]string{}\n\t\t}\n\t\tnetwork.Labels[types.StackLabel] = stackID\n\t\tnetworkCreate := dockerTypes.NetworkCreateRequest{\n\t\t\tName: name,\n\t\t\tNetworkCreate: network,\n\t\t}\n\t\t_, networkError := f.CreateNetwork(networkCreate)\n\n\t\tif networkError != nil {\n\t\t\terr = networkError\n\t\t\tbreak\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, service := range stackSpec.Services {\n\t\tservice = *CopyServiceSpec(service)\n\t\tif service.Annotations.Labels == nil {\n\t\t\tservice.Annotations.Labels = map[string]string{}\n\t\t}\n\t\tservice.Annotations.Labels[types.StackLabel] = stackID\n\t\t_, serviceError := f.CreateService(service, \"\", false)\n\n\t\tif serviceError != nil {\n\t\t\terr = serviceError\n\t\t\tbreak\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (cf *Cloudformation) createStack() {\n\n\tcreateStack = &cobra.Command {\n\t\tUse: \"create-efs\",\n\t\tShort: \"Create stack\",\n\t\tLong: `Create stack based on template`,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\n\t\t\tparameters := make([]*cloudformation.Parameter, 0, 5)\n\n\t\t\tonFailure, err := cmd.Flags().GetString(\"onfailure\")\n\t\t\tverifyOnFailureArg(err, onFailure)\n\n\t\t\tcapabilities, err := cmd.Flags().GetStringArray(\"capabilities\")\n\t\t\tverifyCapability(err, capabilities)\n\n\t\t\tstackName, err := cmd.Flags().GetString(\"stackname\")\n\t\t\tverify(err, \"stackname\")\n\n\t\t\tinstanceType, err := cmd.Flags().GetString(\"instance-type\")\n\t\t\tverify(err, \"instance-type\")\n\t\t\taddParameter(&parameters, \"InstanceType\", instanceType)\n\n\t\t\tkeyPair, err := cmd.Flags().GetString(\"key-pair-name\")\n\t\t\tverify(err, \"key-pair-name\")\n\t\t\taddParameter(&parameters, \"KeyName\", keyPair)\n\n\t\t\tsubnets, err := cmd.Flags().GetStringArray(\"subnets\")\n\t\t\tverify(err, \"subnets\")\n\t\t\taddParameters(&parameters, \"Subnets\", subnets)\n\n\t\t\tvpc, err := cmd.Flags().GetString(\"vpc\")\n\t\t\tverify(err, \"vpc\")\n\t\t\taddParameter(&parameters, \"VPC\" ,vpc)\n\n\t\t\timage, err := cmd.Flags().GetString(\"image\")\n\t\t\tverify(err, \"image\")\n\t\t\taddParameter(&parameters, \"ImageId\", image)\n\n\t\t\tfor _, param := range parameters {\n\t\t\t\tfmt.Printf(\"----Param : %s ---- \\n\", param)\n\t\t\t}\n\n\t\t\tcfClient := cloudformation.New(cf.sess, cf.sess.Config)\n\n\t\t\tresp, err := cf.ec2Res.createKeyPair(keyPair)\n\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Create key pair err: %s \\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\n\t\t\tcreatePemFile(resp.KeyMaterial)\n\n\t\t\tfile := readFile(\"templates/distributed_file_system.yaml\")\n\n\t\t\tif _, err := cfClient.CreateStack(&cloudformation.CreateStackInput{\n\t\t\t\tCapabilities: aws.StringSlice(capabilities),\n\t\t\t\tClientRequestToken: nil,\n\t\t\t\tDisableRollback: nil,\n\t\t\t\tEnableTerminationProtection: nil,\n\t\t\t\tNotificationARNs: nil,\n\t\t\t\tOnFailure: &onFailure,\n\t\t\t\tParameters: parameters,\n\t\t\t\tResourceTypes: nil,\n\t\t\t\tRoleARN: nil,\n\t\t\t\tRollbackConfiguration: nil,\n\t\t\t\tStackName: &stackName,\n\t\t\t\tStackPolicyBody: nil,\n\t\t\t\tStackPolicyURL: nil,\n\t\t\t\tTags: nil,\n\t\t\t\tTemplateBody: &file,\n\t\t\t\tTemplateURL: nil,\n\t\t\t\tTimeoutInMinutes: nil,\n\t\t\t}); err != nil {\n\t\t\t\tdeleteKeyPair(cf, keyPair, err)\n\t\t\t}\n\n\t\t},\n\t}\n}", "func NewCfnStack(scope constructs.Construct, id *string, props *CfnStackProps) CfnStack {\n\t_init_.Initialize()\n\n\tj := jsiiProxy_CfnStack{}\n\n\t_jsii_.Create(\n\t\t\"aws-cdk-lib.aws_cloudformation.CfnStack\",\n\t\t[]interface{}{scope, id, props},\n\t\t&j,\n\t)\n\n\treturn &j\n}", "func CreateCreateStackRequest() (request *CreateStackRequest) {\n\trequest = &CreateStackRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"ROS\", \"2019-09-10\", \"CreateStack\", \"ros\", \"openAPI\")\n\treturn\n}", "func CreateStackName(namespace string, stackType StackType, names ...string) string {\n\treturn fmt.Sprintf(\"%s-%s-%s\", namespace, stackType, strings.Join(names, \"-\"))\n}", "func CreateTerraformStack(t *testing.T, terraformDir string) {\n terraformOptions := test_structure.LoadTerraformOptions(t, terraformDir)\n terraform.InitAndApply(t, terraformOptions)\n}", "func NewCfnStack(scope awscdk.Construct, id *string, props *CfnStackProps) CfnStack {\n\t_init_.Initialize()\n\n\tj := jsiiProxy_CfnStack{}\n\n\t_jsii_.Create(\n\t\t\"monocdk.aws_opsworks.CfnStack\",\n\t\t[]interface{}{scope, id, props},\n\t\t&j,\n\t)\n\n\treturn &j\n}", "func LoadStack(api cloudformationiface.CloudFormationAPI, config *StackConfig) (*Stack, error) {\n\tstack := &Stack{\n\t\tapi: api,\n\t\tconfig: config,\n\t\twaitAttempts: maxWaitAttempts,\n\t\twaiter: waiterFunc(sleepWaiter),\n\t\teventLoader: &stackEvents{\n\t\t\tapi: api,\n\t\t\tstackName: aws.String(config.Name),\n\t\t},\n\n\t\ttemplateReader: fileReaderFunc(ioutil.ReadFile),\n\t}\n\n\terr := stack.load()\n\tif err == nil {\n\t\terr = stack.storeLastEvent()\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn stack, nil\n}", "func (a *Client) CreateCertificate(params *CreateCertificateParams, authInfo runtime.ClientAuthInfoWriter) (*CreateCertificateOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewCreateCertificateParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"CreateCertificate\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/cdn/v1/stacks/{stack_id}/certificates\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &CreateCertificateReader{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.(*CreateCertificateOK), nil\n\n}", "func (client *CraneDockerClient) DeployStack(bundle *model.Bundle) error {\n\tif bundle.Namespace == \"\" || !isValidName.MatchString(bundle.Namespace) {\n\t\treturn cranerror.NewError(CodeInvalidStackName, \"invalid name, only [a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]\")\n\t}\n\n\tnewNetworkMap, err := client.PretreatmentStack(*bundle)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn client.deployServices(bundle.Stack.Services, bundle.Namespace, newNetworkMap)\n}", "func NewCfnStack_Override(c CfnStack, scope constructs.Construct, id *string, props *CfnStackProps) {\n\t_init_.Initialize()\n\n\t_jsii_.Create(\n\t\t\"aws-cdk-lib.aws_cloudformation.CfnStack\",\n\t\t[]interface{}{scope, id, props},\n\t\tc,\n\t)\n}", "func CreateLoadBalancer(ctx context.Context, lbName, pipName string) (lb network.LoadBalancer, err error) {\n\tprobeName := \"probe\"\n\tfrontEndIPConfigName := \"fip\"\n\tbackEndAddressPoolName := \"backEndPool\"\n\tidPrefix := fmt.Sprintf(\"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/loadBalancers\", config.SubscriptionID(), config.GroupName())\n\n\tpip, err := GetPublicIP(ctx, pipName)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tlbClient := getLBClient()\n\tfuture, err := lbClient.CreateOrUpdate(ctx,\n\t\tconfig.GroupName(),\n\t\tlbName,\n\t\tnetwork.LoadBalancer{\n\t\t\tLocation: to.StringPtr(config.Location()),\n\t\t\tLoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{\n\t\t\t\tFrontendIPConfigurations: &[]network.FrontendIPConfiguration{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: &frontEndIPConfigName,\n\t\t\t\t\t\tFrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{\n\t\t\t\t\t\t\tPrivateIPAllocationMethod: network.Dynamic,\n\t\t\t\t\t\t\tPublicIPAddress: &pip,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tBackendAddressPools: &[]network.BackendAddressPool{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: &backEndAddressPoolName,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tProbes: &[]network.Probe{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: &probeName,\n\t\t\t\t\t\tProbePropertiesFormat: &network.ProbePropertiesFormat{\n\t\t\t\t\t\t\tProtocol: network.ProbeProtocolHTTP,\n\t\t\t\t\t\t\tPort: to.Int32Ptr(80),\n\t\t\t\t\t\t\tIntervalInSeconds: to.Int32Ptr(15),\n\t\t\t\t\t\t\tNumberOfProbes: to.Int32Ptr(4),\n\t\t\t\t\t\t\tRequestPath: to.StringPtr(\"healthprobe.aspx\"),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tLoadBalancingRules: &[]network.LoadBalancingRule{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: to.StringPtr(\"lbRule\"),\n\t\t\t\t\t\tLoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{\n\t\t\t\t\t\t\tProtocol: network.TransportProtocolTCP,\n\t\t\t\t\t\t\tFrontendPort: to.Int32Ptr(80),\n\t\t\t\t\t\t\tBackendPort: to.Int32Ptr(80),\n\t\t\t\t\t\t\tIdleTimeoutInMinutes: to.Int32Ptr(4),\n\t\t\t\t\t\t\tEnableFloatingIP: to.BoolPtr(false),\n\t\t\t\t\t\t\tLoadDistribution: network.Default,\n\t\t\t\t\t\t\tFrontendIPConfiguration: &network.SubResource{\n\t\t\t\t\t\t\t\tID: to.StringPtr(fmt.Sprintf(\"/%s/%s/frontendIPConfigurations/%s\", idPrefix, lbName, frontEndIPConfigName)),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tBackendAddressPool: &network.SubResource{\n\t\t\t\t\t\t\t\tID: to.StringPtr(fmt.Sprintf(\"/%s/%s/backendAddressPools/%s\", idPrefix, lbName, backEndAddressPoolName)),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tProbe: &network.SubResource{\n\t\t\t\t\t\t\t\tID: to.StringPtr(fmt.Sprintf(\"/%s/%s/probes/%s\", idPrefix, lbName, probeName)),\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\tInboundNatRules: &[]network.InboundNatRule{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: to.StringPtr(\"natRule1\"),\n\t\t\t\t\t\tInboundNatRulePropertiesFormat: &network.InboundNatRulePropertiesFormat{\n\t\t\t\t\t\t\tProtocol: network.TransportProtocolTCP,\n\t\t\t\t\t\t\tFrontendPort: to.Int32Ptr(21),\n\t\t\t\t\t\t\tBackendPort: to.Int32Ptr(22),\n\t\t\t\t\t\t\tEnableFloatingIP: to.BoolPtr(false),\n\t\t\t\t\t\t\tIdleTimeoutInMinutes: to.Int32Ptr(4),\n\t\t\t\t\t\t\tFrontendIPConfiguration: &network.SubResource{\n\t\t\t\t\t\t\t\tID: to.StringPtr(fmt.Sprintf(\"/%s/%s/frontendIPConfigurations/%s\", idPrefix, lbName, frontEndIPConfigName)),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tName: to.StringPtr(\"natRule2\"),\n\t\t\t\t\t\tInboundNatRulePropertiesFormat: &network.InboundNatRulePropertiesFormat{\n\t\t\t\t\t\t\tProtocol: network.TransportProtocolTCP,\n\t\t\t\t\t\t\tFrontendPort: to.Int32Ptr(23),\n\t\t\t\t\t\t\tBackendPort: to.Int32Ptr(22),\n\t\t\t\t\t\t\tEnableFloatingIP: to.BoolPtr(false),\n\t\t\t\t\t\t\tIdleTimeoutInMinutes: to.Int32Ptr(4),\n\t\t\t\t\t\t\tFrontendIPConfiguration: &network.SubResource{\n\t\t\t\t\t\t\t\tID: to.StringPtr(fmt.Sprintf(\"/%s/%s/frontendIPConfigurations/%s\", idPrefix, lbName, frontEndIPConfigName)),\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\n\tif err != nil {\n\t\treturn lb, fmt.Errorf(\"cannot create load balancer: %v\", err)\n\t}\n\n\terr = future.WaitForCompletion(ctx, lbClient.Client)\n\tif err != nil {\n\t\treturn lb, fmt.Errorf(\"cannot get load balancer create or update future response: %v\", err)\n\t}\n\n\treturn future.Result(lbClient)\n}", "func Delete(ctx context.Context, serviceName string, logger *zerolog.Logger) error {\n\tawsConfig, awsConfigErr := spartaAWS.NewConfig(ctx, logger)\n\tif awsConfigErr != nil {\n\t\treturn awsConfigErr\n\t}\n\tawsCloudFormation := awsv2CF.NewFromConfig(awsConfig)\n\n\texists, err := spartaCF.StackExists(ctx, serviceName, awsConfig, logger)\n\tif nil != err {\n\t\treturn err\n\t}\n\tlogger.Info().\n\t\tBool(\"Exists\", exists).\n\t\tStr(\"Name\", serviceName).\n\t\tMsg(\"Stack existence check\")\n\n\tif exists {\n\n\t\tparams := &awsv2CF.DeleteStackInput{\n\t\t\tStackName: awsv2.String(serviceName),\n\t\t}\n\t\tresp, err := awsCloudFormation.DeleteStack(ctx, params)\n\t\tif nil != resp {\n\t\t\tlogger.Info().\n\t\t\t\tInterface(\"Response\", resp).\n\t\t\t\tMsg(\"Delete request submitted\")\n\t\t}\n\t\treturn err\n\t}\n\tlogger.Info().Msg(\"Stack does not exist\")\n\treturn nil\n}", "func Create(client *golangsdk.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToLoadBalancerCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\t_, r.Err = client.Post(rootURL(client), b, &r.Body, nil)\n\treturn\n}", "func CreateCreateStackResponse() (response *CreateStackResponse) {\n\tresponse = &CreateStackResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (c *Client) CreateOpenstack(i *CreateOpenstackInput) (*Openstack, error) {\n\tif i.Service == \"\" {\n\t\treturn nil, ErrMissingService\n\t}\n\n\tif i.Version == 0 {\n\t\treturn nil, ErrMissingVersion\n\t}\n\n\tpath := fmt.Sprintf(\"/service/%s/version/%d/logging/openstack\", i.Service, i.Version)\n\tresp, err := c.PostForm(path, i, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar openstack *Openstack\n\tif err := decodeBodyMap(resp.Body, &openstack); err != nil {\n\t\treturn nil, err\n\t}\n\treturn openstack, nil\n}", "func (c *CloudFormation) Stack(name string) (*Stack, error) {\n\tparams := &cfn.DescribeStacksInput{\n\t\tNextToken: aws.String(\"NextToken\"),\n\t\tStackName: aws.String(name),\n\t}\n\tresp, err := c.srv.DescribeStacks(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(resp.Stacks) != 1 {\n\t\treturn nil, fmt.Errorf(\"Reseived %v stacks, expected one\", len(resp.Stacks))\n\t}\n\n\treturn &Stack{srv: c.srv, Stack: resp.Stacks[0]}, nil\n}", "func NewCfnStack_Override(c CfnStack, scope awscdk.Construct, id *string, props *CfnStackProps) {\n\t_init_.Initialize()\n\n\t_jsii_.Create(\n\t\t\"monocdk.aws_opsworks.CfnStack\",\n\t\t[]interface{}{scope, id, props},\n\t\tc,\n\t)\n}", "func (s *Stack) CreateNetwork(req abstract.NetworkRequest) (*abstract.Network, fail.Error) {\n\t// disable subnetwork auto-creation\n\tne := compute.Network{\n\t\tName: s.GcpConfig.NetworkName,\n\t\tAutoCreateSubnetworks: false,\n\t\tForceSendFields: []string{\"AutoCreateSubnetworks\"},\n\t}\n\n\tcompuService := s.ComputeService\n\n\trecreateSafescaleNetwork := true\n\trecnet, err := compuService.Networks.Get(s.GcpConfig.ProjectID, ne.Name).Do()\n\tif recnet != nil && err == nil {\n\t\trecreateSafescaleNetwork = false\n\t} else if err != nil {\n\t\tif gerr, ok := err.(*googleapi.Error); ok {\n\t\t\tif gerr.Code != 404 {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif recreateSafescaleNetwork {\n\t\topp, err := compuService.Networks.Insert(s.GcpConfig.ProjectID, &ne).Context(context.Background()).Do()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\toco := OpContext{\n\t\t\tOperation: opp,\n\t\t\tProjectID: s.GcpConfig.ProjectID,\n\t\t\tService: compuService,\n\t\t\tDesiredState: \"DONE\",\n\t\t}\n\n\t\terr = waitUntilOperationIsSuccessfulOrTimeout(oco, temporal.GetMinDelay(), 2*temporal.GetContextTimeout())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tnecreated, err := compuService.Networks.Get(s.GcpConfig.ProjectID, ne.Name).Do()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnet := abstract.NewNetwork()\n\tnet.ID = strconv.FormatUint(necreated.Id, 10)\n\tnet.Name = necreated.Name\n\n\t// Create subnetwork\n\n\ttheRegion := s.GcpConfig.Region\n\n\tsubnetReq := compute.Subnetwork{\n\t\tIpCidrRange: req.CIDR,\n\t\tName: req.Name,\n\t\tNetwork: fmt.Sprintf(\"projects/%s/global/networks/%s\", s.GcpConfig.ProjectID, s.GcpConfig.NetworkName),\n\t\tRegion: theRegion,\n\t}\n\n\topp, err := compuService.Subnetworks.Insert(\n\t\ts.GcpConfig.ProjectID, theRegion, &subnetReq,\n\t).Context(context.Background()).Do()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toco := OpContext{\n\t\tOperation: opp,\n\t\tProjectID: s.GcpConfig.ProjectID,\n\t\tService: compuService,\n\t\tDesiredState: \"DONE\",\n\t}\n\n\terr = waitUntilOperationIsSuccessfulOrTimeout(oco, temporal.GetMinDelay(), 2*temporal.GetContextTimeout())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgcpSubNet, err := compuService.Subnetworks.Get(s.GcpConfig.ProjectID, theRegion, req.Name).Do()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// FIXME: Add properties and GatewayID\n\tsubnet := abstract.NewNetwork()\n\tsubnet.ID = strconv.FormatUint(gcpSubNet.Id, 10)\n\tsubnet.Name = gcpSubNet.Name\n\tsubnet.CIDR = gcpSubNet.IpCidrRange\n\tsubnet.IPVersion = ipversion.IPv4\n\n\tbuildNewRule := true\n\tfirewallRuleName := fmt.Sprintf(\"%s-%s-all-in\", s.GcpConfig.NetworkName, gcpSubNet.Name)\n\n\tfws, err := compuService.Firewalls.Get(s.GcpConfig.ProjectID, firewallRuleName).Do()\n\tif fws != nil && err == nil {\n\t\tbuildNewRule = false\n\t} else if err != nil {\n\t\tif gerr, ok := err.(*googleapi.Error); ok {\n\t\t\tif gerr.Code != 404 {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif buildNewRule {\n\t\tfiw := compute.Firewall{\n\t\t\tAllowed: []*compute.FirewallAllowed{\n\t\t\t\t{\n\t\t\t\t\tIPProtocol: \"all\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tDirection: \"INGRESS\",\n\t\t\tDisabled: false,\n\t\t\tName: firewallRuleName,\n\t\t\tNetwork: fmt.Sprintf(\n\t\t\t\t\"https://www.googleapis.com/compute/v1/projects/%s/global/networks/%s\", s.GcpConfig.ProjectID,\n\t\t\t\ts.GcpConfig.NetworkName,\n\t\t\t),\n\t\t\tPriority: 999,\n\t\t\tSourceRanges: []string{\"0.0.0.0/0\"},\n\t\t}\n\n\t\topp, err = compuService.Firewalls.Insert(s.GcpConfig.ProjectID, &fiw).Do()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\toco = OpContext{\n\t\t\tOperation: opp,\n\t\t\tProjectID: s.GcpConfig.ProjectID,\n\t\t\tService: compuService,\n\t\t\tDesiredState: \"DONE\",\n\t\t}\n\n\t\terr = waitUntilOperationIsSuccessfulOrTimeout(oco, temporal.GetMinDelay(), temporal.GetHostTimeout())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbuildNewNATRule := true\n\tnatRuleName := fmt.Sprintf(\"%s-%s-nat-allowed\", s.GcpConfig.NetworkName, gcpSubNet.Name)\n\n\trfs, err := compuService.Routes.Get(s.GcpConfig.ProjectID, natRuleName).Do()\n\tif rfs != nil && err == nil {\n\t\tbuildNewNATRule = false\n\t} else if err != nil {\n\t\tif gerr, ok := err.(*googleapi.Error); ok {\n\t\t\tif gerr.Code != 404 {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif buildNewNATRule {\n\t\troute := &compute.Route{\n\t\t\tDestRange: \"0.0.0.0/0\",\n\t\t\tName: natRuleName,\n\t\t\tNetwork: fmt.Sprintf(\n\t\t\t\t\"https://www.googleapis.com/compute/v1/projects/%s/global/networks/%s\", s.GcpConfig.ProjectID,\n\t\t\t\ts.GcpConfig.NetworkName,\n\t\t\t),\n\t\t\tNextHopInstance: fmt.Sprintf(\n\t\t\t\t\"projects/%s/zones/%s/instances/gw-%s\", s.GcpConfig.ProjectID, s.GcpConfig.Zone, req.Name,\n\t\t\t),\n\t\t\tPriority: 800,\n\t\t\tTags: []string{fmt.Sprintf(\"no-ip-%s\", gcpSubNet.Name)},\n\t\t}\n\t\topp, err := compuService.Routes.Insert(s.GcpConfig.ProjectID, route).Do()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\toco = OpContext{\n\t\t\tOperation: opp,\n\t\t\tProjectID: s.GcpConfig.ProjectID,\n\t\t\tService: compuService,\n\t\t\tDesiredState: \"DONE\",\n\t\t}\n\n\t\terr = waitUntilOperationIsSuccessfulOrTimeout(oco, temporal.GetMinDelay(), 2*temporal.GetContextTimeout())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t}\n\n\t// FIXME: Validation before return...\n\treturn subnet, nil\n}", "func (s stack) CreateNetwork(req abstract.NetworkRequest) (res *abstract.Network, ferr fail.Error) {\n\tnullAN := abstract.NewNetwork()\n\tif s.IsNull() {\n\t\treturn nullAN, fail.InvalidInstanceError()\n\t}\n\n\tdefer debug.NewTracer(nil, tracing.ShouldTrace(\"stack.aws\") || tracing.ShouldTrace(\"stacks.network\"), \"(%v)\", req).WithStopwatch().Entering().Exiting()\n\n\t// Check if network already there\n\tvar xerr fail.Error\n\tif _, xerr = s.rpcDescribeVpcByName(aws.String(req.Name)); xerr != nil {\n\t\tswitch xerr.(type) {\n\t\tcase *fail.ErrNotFound:\n\t\t\tdebug.IgnoreError(xerr)\n\t\t\t// continue\n\t\tdefault:\n\t\t\treturn nullAN, xerr\n\t\t}\n\t} else {\n\t\treturn nullAN, fail.DuplicateError(\"a Network/VPC named '%s' already exists\")\n\t}\n\n\t// if not, create the network/VPC\n\ttheVpc, xerr := s.rpcCreateVpc(aws.String(req.Name), aws.String(req.CIDR))\n\tif xerr != nil {\n\t\treturn nullAN, fail.Wrap(xerr, \"failed to create VPC\")\n\t}\n\n\t// wait until available status\n\tif IsOperation(theVpc, \"State\", reflect.TypeOf(\"\")) {\n\t\tretryErr := retry.WhileUnsuccessful(\n\t\t\tfunc() error {\n\t\t\t\tvpcTmp, innerXErr := s.rpcDescribeVpcByID(theVpc.VpcId)\n\t\t\t\tif innerXErr != nil {\n\t\t\t\t\treturn innerXErr\n\t\t\t\t}\n\t\t\t\tif aws.StringValue(vpcTmp.State) != \"available\" {\n\t\t\t\t\treturn fail.NewError(\"not ready\")\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\ttemporal.GetMinDelay(),\n\t\t\ttemporal.GetDefaultDelay(),\n\t\t)\n\t\tif retryErr != nil {\n\t\t\tswitch retryErr.(type) {\n\t\t\tcase *retry.ErrStopRetry:\n\t\t\t\treturn nullAN, fail.Wrap(fail.Cause(retryErr), \"stopping retries\")\n\t\t\tcase *fail.ErrTimeout:\n\t\t\t\treturn nullAN, fail.Wrap(fail.Cause(retryErr), \"timeout\")\n\t\t\tdefault:\n\t\t\t\treturn nullAN, retryErr\n\t\t\t}\n\t\t}\n\t}\n\n\tdefer func() {\n\t\tif ferr != nil && !req.KeepOnFailure {\n\t\t\tif theVpc != nil {\n\t\t\t\tderr := s.DeleteNetwork(aws.StringValue(theVpc.VpcId))\n\t\t\t\tif derr != nil {\n\t\t\t\t\t_ = ferr.AddConsequence(derr)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\tgw, xerr := s.rpcCreateInternetGateway()\n\tif xerr != nil {\n\t\treturn nullAN, fail.Wrap(xerr, \"failed to create internet gateway\")\n\t}\n\n\tif xerr = s.rpcAttachInternetGateway(theVpc.VpcId, gw.InternetGatewayId); xerr != nil {\n\t\treturn nullAN, fail.Wrap(xerr, \"failed to attach internet gateway to Network\")\n\t}\n\n\tdefer func() {\n\t\tif ferr != nil && !req.KeepOnFailure {\n\t\t\tif derr := s.rpcDetachInternetGateway(theVpc.VpcId, gw.InternetGatewayId); derr != nil {\n\t\t\t\t_ = ferr.AddConsequence(normalizeError(derr))\n\t\t\t}\n\t\t}\n\t}()\n\n\ttables, xerr := s.rpcDescribeRouteTables(aws.String(\"vpc-id\"), []*string{theVpc.VpcId})\n\tif xerr != nil {\n\t\treturn nullAN, xerr\n\t}\n\tif len(tables) < 1 {\n\t\treturn nullAN, fail.InconsistentError(\"no Route Tables\")\n\t}\n\n\tif xerr = s.rpcCreateRoute(gw.InternetGatewayId, tables[0].RouteTableId, aws.String(\"0.0.0.0/0\")); xerr != nil {\n\t\treturn nullAN, fail.Wrap(xerr, \"failed to create route\")\n\t}\n\n\tdefer func() {\n\t\tif ferr != nil && !req.KeepOnFailure {\n\t\t\tif derr := s.rpcDeleteRoute(tables[0].RouteTableId, aws.String(\"0.0.0.0/0\")); derr != nil {\n\t\t\t\t_ = ferr.AddConsequence(normalizeError(derr))\n\t\t\t}\n\t\t}\n\t}()\n\n\tanet := abstract.NewNetwork()\n\tanet.ID = aws.StringValue(theVpc.VpcId)\n\tanet.Name = req.Name\n\tanet.CIDR = req.CIDR\n\tanet.DNSServers = req.DNSServers\n\n\t// Make sure we log warnings\n\t_ = anet.OK()\n\n\treturn anet, nil\n}", "func (s stack) CreateKeyPair(ctx context.Context, name string) (_ *abstract.KeyPair, ferr fail.Error) {\n\tif valid.IsNil(s) {\n\t\treturn nil, fail.InvalidInstanceError()\n\t}\n\tif name == \"\" {\n\t\treturn nil, fail.InvalidParameterError(\"name\", \"cannot be empty string\")\n\t}\n\n\treturn abstract.NewKeyPair(name)\n}", "func (a *Client) CreateScope(params *CreateScopeParams, authInfo runtime.ClientAuthInfoWriter) (*CreateScopeOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewCreateScopeParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"CreateScope\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/cdn/v1/stacks/{stack_id}/sites/{site_id}/scopes\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &CreateScopeReader{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.(*CreateScopeOK), nil\n\n}", "func New(auth stacks.AuthenticationOptions, localCfg stacks.AWSConfiguration, cfg stacks.ConfigurationOptions) (*stack, error) { // nolint\n\tif localCfg.Ec2Endpoint == \"\" {\n\t\tlocalCfg.Ec2Endpoint = fmt.Sprintf(\"https://ec2.%s.amazonaws.com\", localCfg.Region)\n\t}\n\tif localCfg.SsmEndpoint == \"\" {\n\t\tlocalCfg.SsmEndpoint = fmt.Sprintf(\"https://ssm.%s.amazonaws.com\", localCfg.Region)\n\t}\n\n\tstack := &stack{\n\t\tConfig: &cfg,\n\t\tAuthOptions: &auth,\n\t\tAwsConfig: &localCfg,\n\t}\n\n\taccessKeyID := auth.AccessKeyID\n\tsecretAccessKey := auth.SecretAccessKey\n\n\tss3 := session.Must(session.NewSession(&aws.Config{\n\t\tCredentials: credentials.NewStaticCredentials(accessKeyID, secretAccessKey, \"\"),\n\t\tS3ForcePathStyle: aws.Bool(true),\n\t\tRegion: aws.String(localCfg.Region),\n\t\tEndpoint: aws.String(localCfg.S3Endpoint),\n\t}))\n\n\tsec2 := session.Must(session.NewSession(&aws.Config{\n\t\tCredentials: credentials.NewStaticCredentials(accessKeyID, secretAccessKey, \"\"),\n\t\tS3ForcePathStyle: aws.Bool(true),\n\t\tRegion: aws.String(localCfg.Region),\n\t\tEndpoint: aws.String(localCfg.Ec2Endpoint),\n\t}))\n\n\tsssm := session.Must(session.NewSession(&aws.Config{\n\t\tCredentials: credentials.NewStaticCredentials(accessKeyID, secretAccessKey, \"\"),\n\t\tS3ForcePathStyle: aws.Bool(true),\n\t\tRegion: aws.String(localCfg.Region),\n\t\tEndpoint: aws.String(localCfg.SsmEndpoint),\n\t}))\n\n\tspricing := session.Must(session.NewSession(&aws.Config{\n\t\tCredentials: credentials.NewStaticCredentials(accessKeyID, secretAccessKey, \"\"),\n\t\tS3ForcePathStyle: aws.Bool(true),\n\t\tRegion: aws.String(endpoints.UsEast1RegionID),\n\t}))\n\n\tstack.S3Service = s3.New(ss3, &aws.Config{})\n\tstack.EC2Service = ec2.New(sec2, &aws.Config{})\n\tstack.SSMService = ssm.New(sssm, &aws.Config{})\n\tstack.PricingService = pricing.New(spricing, &aws.Config{})\n\n\tif cfg.Timings != nil {\n\t\tstack.MutableTimings = cfg.Timings\n\t} else {\n\t\tstack.MutableTimings = temporal.NewTimings()\n\t}\n\n\treturn stack, nil\n}", "func (p EksProvisioner) Create(dryRun bool) error {\n\n\tclusterExists, err := p.clusterExists()\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif clusterExists {\n\t\tlog.Logger.Debugf(\"An EKS cluster already exists called '%s'. Won't recreate it...\",\n\t\t\tp.GetStack().GetConfig().GetCluster())\n\t\treturn nil\n\t}\n\n\ttemplatedVars, err := p.stack.GetTemplatedVars(nil, map[string]interface{}{})\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\tlog.Logger.Debugf(\"Templated stack config vars: %#v\", templatedVars)\n\n\targs := []string{\"create\", \"cluster\"}\n\targs = parameteriseValues(args, p.eksConfig.Params.Global)\n\targs = parameteriseValues(args, p.eksConfig.Params.CreateCluster)\n\n\tconfigFilePath, err := p.writeConfigFile()\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif configFilePath != \"\" {\n\t\targs = append(args, []string{\"-f\", configFilePath}...)\n\t}\n\n\t_, err = printer.Fprintf(\"Creating EKS cluster (this may take some time)...\\n\")\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\terr = utils.ExecCommandUnbuffered(p.eksConfig.Binary, args, map[string]string{},\n\t\tos.Stdout, os.Stderr, \"\", 0, 0, dryRun)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif !dryRun {\n\t\tlog.Logger.Infof(\"EKS cluster created\")\n\n\t\terr = p.renameKubeContext()\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t}\n\n\tp.stack.GetStatus().SetStartedThisRun(true)\n\t// only sleep before checking the cluster fo readiness if we started it\n\tp.stack.GetStatus().SetSleepBeforeReadyCheck(eksSleepSecondsBeforeReadyCheck)\n\n\treturn nil\n}", "func (s *ClusterBackupsService) Create(req api.CreateBackupRequest) error {\n\tdeployment, err := s.deployments.GetActiveDeployment()\n\tif err != nil {\n\t\treturn errors.WrapIf(err, \"error getting active deployment\")\n\t}\n\n\tclient, err := s.deployments.GetClient()\n\tif err != nil {\n\t\treturn errors.WrapIf(err, \"error getting ark client\")\n\t}\n\n\tif req.Labels == nil {\n\t\treq.Labels = make(labels.Set)\n\t}\n\treq.Labels[api.LabelKeyDistribution] = s.cluster.GetDistribution()\n\treq.Labels[api.LabelKeyCloud] = s.cluster.GetCloud()\n\n\tbackup, err := client.CreateBackup(req)\n\tif err != nil {\n\t\treturn errors.WrapIf(err, \"error creating backup\")\n\t}\n\n\tif backup.Status.Phase == \"\" {\n\t\tbackup.Status.Phase = \"Creating\"\n\t}\n\n\tpreq := &api.PersistBackupRequest{\n\t\tBucketID: deployment.BucketID,\n\n\t\tCloud: s.cluster.GetCloud(),\n\t\tDistribution: s.cluster.GetDistribution(),\n\n\t\tClusterID: s.cluster.GetID(),\n\t\tDeploymentID: deployment.ID,\n\n\t\tBackup: backup,\n\t}\n\t_, err = s.Persist(preq)\n\tif err != nil {\n\t\treturn errors.WrapIf(err, \"error persisting backup\")\n\t}\n\n\treturn nil\n}", "func LoadStack(name string, cfg composetypes.Config) (*apiv1beta1.Stack, error) {\n\tres, err := yaml.Marshal(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &apiv1beta1.Stack{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t},\n\t\tSpec: apiv1beta1.StackSpec{\n\t\t\tComposeFile: string(res),\n\t\t},\n\t}, nil\n}", "func NewStack() *Stack {\n\n\tdata := make([]interface{}, 0, 16)\n\treturn &Stack{data}\n}", "func NewStackPackage() *StackPackage {\n\t// create a Stack record and populate it with the relevant package contents\n\tv, k := v1alpha1.StackGroupVersionKind.ToAPIVersionAndKind()\n\n\tsp := &StackPackage{\n\t\tStack: v1alpha1.Stack{\n\t\t\tTypeMeta: metav1.TypeMeta{APIVersion: v, Kind: k},\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tAnnotations: map[string]string{},\n\t\t\t},\n\t\t},\n\t\tCRDs: map[string]apiextensions.CustomResourceDefinition{},\n\t\tCRDPaths: map[string]string{},\n\t\tGroups: map[string]StackGroup{},\n\t\tIcons: map[string]*v1alpha1.IconSpec{},\n\t\tResources: map[string]StackResource{},\n\t\tUISpecs: map[string]string{},\n\t}\n\n\treturn sp\n}", "func (c *StackCollection) DoCreateStackRequest(ctx context.Context, i *Stack, templateData TemplateData, tags, parameters map[string]string, withIAM bool, withNamedIAM bool) error {\n\tinput := &cloudformation.CreateStackInput{\n\t\tStackName: i.StackName,\n\t\tDisableRollback: aws.Bool(c.disableRollback),\n\t}\n\tinput.Tags = append(input.Tags, c.sharedTags...)\n\tfor k, v := range tags {\n\t\tinput.Tags = append(input.Tags, newTag(k, v))\n\t}\n\n\tswitch data := templateData.(type) {\n\tcase TemplateBody:\n\t\tinput.TemplateBody = aws.String(string(data))\n\tcase TemplateURL:\n\t\tinput.TemplateURL = aws.String(string(data))\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown template data type: %T\", templateData)\n\t}\n\n\tif withIAM {\n\t\tinput.Capabilities = stackCapabilitiesIAM\n\t}\n\n\tif withNamedIAM {\n\t\tinput.Capabilities = stackCapabilitiesNamedIAM\n\t}\n\n\tif cfnRole := c.roleARN; cfnRole != \"\" {\n\t\tinput.RoleARN = aws.String(cfnRole)\n\t}\n\n\tfor k, v := range parameters {\n\t\tinput.Parameters = append(input.Parameters, types.Parameter{\n\t\t\tParameterKey: aws.String(k),\n\t\t\tParameterValue: aws.String(v),\n\t\t})\n\t}\n\n\tlogger.Debug(\"CreateStackInput = %#v\", input)\n\ts, err := c.cloudformationAPI.CreateStack(ctx, input)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"creating CloudFormation stack %q\", *i.StackName)\n\t}\n\ti.StackId = s.StackId\n\treturn nil\n}", "func contractCreate(ic *interop.Context) error {\n\tnewcontract, err := createContractStateFromVM(ic)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcontract, err := ic.DAO.GetContractState(newcontract.ScriptHash())\n\tif contract != nil && err == nil {\n\t\treturn errors.New(\"contract already exists\")\n\t}\n\tid, err := ic.DAO.GetAndUpdateNextContractID()\n\tif err != nil {\n\t\treturn err\n\t}\n\tnewcontract.ID = id\n\tif !newcontract.Manifest.IsValid(newcontract.ScriptHash()) {\n\t\treturn errors.New(\"failed to check contract script hash against manifest\")\n\t}\n\tif err := ic.DAO.PutContractState(newcontract); err != nil {\n\t\treturn err\n\t}\n\tcs, err := contractToStackItem(newcontract)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot convert contract to stack item: %w\", err)\n\t}\n\tic.VM.Estack().PushVal(cs)\n\treturn callDeploy(ic, newcontract, false)\n}", "func (a *LoadBalancerApiService) CreateLoadBalancerTags(ctx _context.Context) ApiCreateLoadBalancerTagsRequest {\n\treturn ApiCreateLoadBalancerTagsRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func NewStack() *Stack {\n\treturn &Stack{}\n}", "func NewStack() *Stack {\n\treturn &Stack{}\n}", "func NewStack() *Stack {\n\treturn &Stack{}\n}", "func NewStack() *Stack {\n\treturn &Stack{}\n}", "func NewStack() *Stack {\n\treturn &Stack{}\n}", "func (action *CreateVPCAction) ExecuteAction(input interface{}) (output interface{}, err error) {\n\tlog.Infoln(\"EXECUTE CreateVPCAction, stack name:\", action.stackName)\n\n\tlog.Infoln(\"Getting CloudFormation template for creating VPC for EKS cluster\")\n\ttemplateBody, err := pkgEks.GetVPCTemplate()\n\tif err != nil {\n\t\tlog.Errorln(\"Getting CloudFormation template for VPC failed: \", err.Error())\n\t\treturn nil, err\n\t}\n\n\tcloudformationSrv := cloudformation.New(action.context.Session)\n\tcreateStackInput := &cloudformation.CreateStackInput{\n\t\t//Capabilities: []*string{},\n\t\tClientRequestToken: aws.String(uuid.NewV4().String()),\n\t\tDisableRollback: aws.Bool(false),\n\n\t\tStackName: aws.String(action.stackName),\n\t\tTags: []*cloudformation.Tag{{Key: aws.String(\"pipeline-created\"), Value: aws.String(\"true\")}},\n\t\tTemplateBody: aws.String(templateBody),\n\t\tTimeoutInMinutes: aws.Int64(10),\n\t}\n\t//startTime := time.Now()\n\t_, err = cloudformationSrv.CreateStack(createStackInput)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t//action.context.VpcID = createStackOutput.StackId\n\t//completed := false\n\t//for time.Now().Before(startTime.Add(action.stackCreationTimeout)) {\n\t//\tstackStatuses, err := cloudformationSrv.DescribeStacks(&cloudformation.DescribeStacksInput{StackName: aws.String(action.stackName)})\n\t//\tif err != nil {\n\t//\t\treturn nil, err\n\t//\t}\n\t//\n\t//\tif len(stackStatuses.Stacks) != 1 {\n\t//\t\treturn nil, errors.New(fmt.Sprintf(\"Got %d stack(s) instead of 1 after stack creation\", len(stackStatuses.Stacks)))\n\t//\t}\n\t//\tstack := stackStatuses.Stacks[0]\n\t//\tfmt.Printf(\"stackStatus: %s\\n\", *stack.StackStatus)\n\t//\tif *stack.StackStatus == cloudformation.StackStatusCreateComplete {\n\t//\t\tcompleted = true\n\t//\t\tbreak\n\t//\t}\n\t//\ttime.Sleep(action.describeStacksTimeInterval)\n\t//}\n\n\t//if !completed {\n\t//\treturn nil, errors.New(\"Timeout occurred during eks stack creation\")\n\t//}\n\n\tdescribeStacksInput := &cloudformation.DescribeStacksInput{StackName: aws.String(action.stackName)}\n\terr = cloudformationSrv.WaitUntilStackCreateComplete(describeStacksInput)\n\n\treturn nil, err\n}", "func NewStack() *stack {\n\treturn &stack{nil, 0}\n}", "func NewStack() *Stack {\n\ts := &Stack{}\n\ts.mutex = &sync.Mutex{}\n\treturn s\n}", "func NewStack() *Stack {\n\tlist := list.New()\n\treturn &Stack{list}\n}", "func CreateContract(rpcURL string, sk string, data []byte, gasPrice uint64, gasLimit uint64) (common.Hash, error) {\n\treturn SendTx(rpcURL, sk, \"\", 0, data, gasPrice, gasLimit)\n}", "func Create(c *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToLBPoolCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\tresp, err := c.Post(rootURL(c), b, &r.Body, nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func Create(logger *zap.SugaredLogger, tfDir, bucket, attackTag string) error {\n\terr := InitIfNeeded(logger, tfDir, bucket, attackTag)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogger.Info(\"Running terraform plan\")\n\t_, err = Terraform(tfDir, \"plan\", bucket)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogger.Info(\"Running terraform apply\")\n\t_, err = Terraform(tfDir, \"apply\", bucket)\n\treturn err\n}", "func New() *Stack {\n\treturn &Stack{\n\t\tTables: []*symboltable.Table{\n\t\t\tsymboltable.NewTable(),\n\t\t},\n\t\tSize: 0,\n\t\tImports: make(map[string]*gotypes.SymbolDef, 0),\n\t}\n}", "func (client *Client) CreateStackWithCallback(request *CreateStackRequest, callback func(response *CreateStackResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateStackResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateStack(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func New(threadSafe ...bool) Stack {\n\tif len(threadSafe) >= 1 && threadSafe[0] {\n\t\treturn newThreadSafeStack()\n\t}\n\n\treturn newSimpleStack()\n}", "func (s *Stack) Create() (*ListItem, string, error) {\n\tclient, err := _client.New(s.ClientConfig)\n\tif err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"failed to get client: %s\", err)\n\t}\n\n\tclient.Endpoint = s.Endpoint\n\n\tdata := createDocument{\n\t\tName: s.Name,\n\t\tStackSlug: s.StackSlug,\n\t}\n\n\tbody, statusCode, err := client.Post(data)\n\tif err != nil {\n\t\tif statusCode == 409 {\n\t\t\treturn nil, \"\", fmt.Errorf(\"stack with this name already exists: %s\", err)\n\t\t}\n\n\t\treturn nil, \"\", err\n\t}\n\n\tvar jsonData ListItem\n\tif err := json.Unmarshal(body, &jsonData); err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"cannot parse API response as JSON: %s\", err)\n\t}\n\n\treturn &jsonData, string(body), nil\n}", "func (r *ProjectsTraceSinksService) Create(parent string, tracesink *TraceSink) *ProjectsTraceSinksCreateCall {\n\tc := &ProjectsTraceSinksCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.parent = parent\n\tc.tracesink = tracesink\n\treturn c\n}", "func convergeStackState(cfTemplateURL string, ctx *workflowContext) (*cloudformation.Stack, error) {\n\tawsCloudFormation := cloudformation.New(ctx.awsSession)\n\n\t// Does it exist?\n\texists, err := stackExists(ctx.serviceName, awsCloudFormation, ctx.logger)\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\tstackID := \"\"\n\tif exists {\n\t\t// Update stack\n\t\tupdateStackInput := &cloudformation.UpdateStackInput{\n\t\t\tStackName: aws.String(ctx.serviceName),\n\t\t\tTemplateURL: aws.String(cfTemplateURL),\n\t\t\tCapabilities: []*string{aws.String(\"CAPABILITY_IAM\")},\n\t\t}\n\t\tupdateStackResponse, err := awsCloudFormation.UpdateStack(updateStackInput)\n\t\tif nil != err {\n\t\t\treturn nil, err\n\t\t}\n\t\tctx.logger.Info(\"Issued update request: \", *updateStackResponse.StackId)\n\t\tstackID = *updateStackResponse.StackId\n\t} else {\n\t\t// Create stack\n\t\tcreateStackInput := &cloudformation.CreateStackInput{\n\t\t\tStackName: aws.String(ctx.serviceName),\n\t\t\tTemplateURL: aws.String(cfTemplateURL),\n\t\t\tTimeoutInMinutes: aws.Int64(5),\n\t\t\tOnFailure: aws.String(cloudformation.OnFailureDelete),\n\t\t\tCapabilities: []*string{aws.String(\"CAPABILITY_IAM\")},\n\t\t}\n\t\tcreateStackResponse, err := awsCloudFormation.CreateStack(createStackInput)\n\t\tif nil != err {\n\t\t\treturn nil, err\n\t\t}\n\t\tctx.logger.Info(\"Creating stack: \", *createStackResponse.StackId)\n\t\tstackID = *createStackResponse.StackId\n\t}\n\n\t// Poll for the current stackID state\n\tdescribeStacksInput := &cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(stackID),\n\t}\n\n\tvar stackInfo *cloudformation.Stack\n\tstackOperationComplete := false\n\tctx.logger.Info(\"Waiting for stack to complete\")\n\tfor !stackOperationComplete {\n\t\ttime.Sleep(10 * time.Second)\n\t\tdescribeStacksOutput, err := awsCloudFormation.DescribeStacks(describeStacksInput)\n\t\tif nil != err {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(describeStacksOutput.Stacks) > 0 {\n\t\t\tstackInfo = describeStacksOutput.Stacks[0]\n\t\t\tctx.logger.Info(\"Current state: \", *stackInfo.StackStatus)\n\t\t\tswitch *stackInfo.StackStatus {\n\t\t\tcase cloudformation.StackStatusCreateInProgress,\n\t\t\t\tcloudformation.StackStatusDeleteInProgress,\n\t\t\t\tcloudformation.StackStatusUpdateInProgress,\n\t\t\t\tcloudformation.StackStatusRollbackInProgress,\n\t\t\t\tcloudformation.StackStatusUpdateCompleteCleanupInProgress,\n\t\t\t\tcloudformation.StackStatusUpdateRollbackCompleteCleanupInProgress,\n\t\t\t\tcloudformation.StackStatusUpdateRollbackInProgress:\n\t\t\t\ttime.Sleep(20 * time.Second)\n\t\t\tdefault:\n\t\t\t\tstackOperationComplete = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"More than one stack returned for: %s\", stackID)\n\t\t}\n\t}\n\t// What happened?\n\tsucceed := true\n\tswitch *stackInfo.StackStatus {\n\tcase cloudformation.StackStatusDeleteComplete, // Initial create failure\n\t\tcloudformation.StackStatusUpdateRollbackComplete: // Update failure\n\t\tsucceed = false\n\tdefault:\n\t\tsucceed = true\n\t}\n\n\t// If it didn't work, then output some failure information\n\tif !succeed {\n\t\t// Get the stack events and find the ones that failed.\n\t\tevents, err := stackEvents(stackID, awsCloudFormation)\n\t\tif nil != err {\n\t\t\treturn nil, err\n\t\t}\n\t\tctx.logger.Error(\"Stack provisioning failed.\")\n\t\tfor _, eachEvent := range events {\n\t\t\tswitch *eachEvent.ResourceStatus {\n\t\t\tcase cloudformation.ResourceStatusCreateFailed,\n\t\t\t\tcloudformation.ResourceStatusDeleteFailed,\n\t\t\t\tcloudformation.ResourceStatusUpdateFailed:\n\t\t\t\terrMsg := fmt.Sprintf(\"\\tError ensuring %s (%s): %s\",\n\t\t\t\t\t*eachEvent.ResourceType,\n\t\t\t\t\t*eachEvent.LogicalResourceId,\n\t\t\t\t\t*eachEvent.ResourceStatusReason)\n\t\t\t\tctx.logger.Error(errMsg)\n\t\t\tdefault:\n\t\t\t\t// NOP\n\t\t\t}\n\t\t}\n\t\treturn nil, fmt.Errorf(\"Failed to provision: %s\", ctx.serviceName)\n\t} else if nil != stackInfo.Outputs {\n\t\tctx.logger.Info(\"Stack Outputs:\")\n\t\tfor _, eachOutput := range stackInfo.Outputs {\n\t\t\tctx.logger.WithFields(logrus.Fields{\n\t\t\t\t\"Key\": *eachOutput.OutputKey,\n\t\t\t\t\"Value\": *eachOutput.OutputValue,\n\t\t\t\t\"Description\": *eachOutput.Description,\n\t\t\t}).Info(\"\\tOutput\")\n\t\t}\n\t}\n\treturn stackInfo, nil\n}", "func NewStack() *Stack {\n\treturn &Stack{nil, 0, &sync.RWMutex{}}\n}", "func CreateVpc(ec2Svc *ec2.EC2) {\n\tlogrus.Info(\"Creating VPC\")\n\tvpcResponse, err := ec2Svc.CreateDefaultVpc(&ec2.CreateDefaultVpcInput{})\n\tif err != nil {\n\t\tlogrus.Fatalf(\"Couldn't create a VPC: %s\", err)\n\t}\n\tlogrus.Info(\"Waiting for VPC to be created\")\n\tec2Svc.WaitUntilVpcExists(vpcInput)\n\tlogrus.Infof(\"VPC: %s has been created\", *vpcResponse.Vpc.VpcId)\n\t_, err = ec2Svc.CreateTags(&ec2.CreateTagsInput{\n\t\tResources: []*string{vpcResponse.Vpc.VpcId},\n\t\tTags: []*ec2.Tag{\n\t\t\t{\n\t\t\t\tKey: aws.String(\"Name\"),\n\t\t\t\tValue: aws.String(vpcName),\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tlogrus.Fatalf(\"Unable to tag VPC: %s\", err)\n\t}\n}", "func NewStack() *Stack {\n\tq := &Stack{}\n\tq.lock = &sync.Mutex{}\n\treturn q\n}", "func NewStack(root *DSSRoot) *Stack {\n\ts := &Stack{root: root, tos: root.bottom}\n\ts.root.stacks = append(s.root.stacks, s)\n\treturn s\n}", "func (s *Cloudformation) DeleteStack() (err error) {\n\tsess := s.config.AWSSession\n\tsvc := cloudformation.New(sess)\n\n\tstackInputs := cloudformation.DeleteStackInput{}\n\tstackInputs.SetStackName(s.StackName())\n\n\t_, err = svc.DeleteStack(&stackInputs)\n\treturn\n}", "func (c *CaptainClient) CreateFormation(name string, flightID, CPU, RAM, disk int, baseName, domain string, targetCount int, preflightPlaybook string) (Formation, error) {\n\tresult, err := c.restPOST(\"formation\", map[string]interface{}{\n\t\t\"FlightID\": flightID,\n\t\t\"Name\": name,\n\t\t\"CPU\": CPU,\n\t\t\"RAM\": RAM,\n\t\t\"Disk\": disk,\n\t\t\"BaseName\": baseName,\n\t\t\"Domain\": domain,\n\t\t\"TargetCount\": targetCount,\n\t\t\"PreflightPlaybook\": preflightPlaybook,\n\t})\n\tif err != nil {\n\t\treturn Formation{}, fmt.Errorf(\"unable to create Formation:\\n%w\", err)\n\t}\n\tvar formation Formation\n\terr = json.Unmarshal(result, &formation)\n\tif err != nil {\n\t\treturn Formation{}, fmt.Errorf(\"unable to format response as Formation:\\n%w\", err)\n\t}\n\treturn formation, nil\n}", "func CreateLoadBalancer(t *testing.T, client *gophercloud.ServiceClient, subnetID string) (*loadbalancers.LoadBalancer, error) {\n\tlbName := tools.RandomString(\"TESTACCT-\", 8)\n\tlbDescription := tools.RandomString(\"TESTACCT-DESC-\", 8)\n\n\tt.Logf(\"Attempting to create loadbalancer %s on subnet %s\", lbName, subnetID)\n\n\tcreateOpts := loadbalancers.CreateOpts{\n\t\tName: lbName,\n\t\tDescription: lbDescription,\n\t\tVipSubnetID: subnetID,\n\t\tAdminStateUp: gophercloud.Enabled,\n\t}\n\n\tlb, err := loadbalancers.Create(client, createOpts).Extract()\n\tif err != nil {\n\t\treturn lb, err\n\t}\n\n\tt.Logf(\"Successfully created loadbalancer %s on subnet %s\", lbName, subnetID)\n\tt.Logf(\"Waiting for loadbalancer %s to become active\", lbName)\n\n\tif err := WaitForLoadBalancerState(client, lb.ID, \"ACTIVE\"); err != nil {\n\t\treturn lb, err\n\t}\n\n\tt.Logf(\"LoadBalancer %s is active\", lbName)\n\n\tth.AssertEquals(t, lb.Name, lbName)\n\tth.AssertEquals(t, lb.Description, lbDescription)\n\tth.AssertEquals(t, lb.VipSubnetID, subnetID)\n\tth.AssertEquals(t, lb.AdminStateUp, true)\n\n\treturn lb, nil\n}", "func DeleteStack(stackName, profile, region string) {\n\tcf := GetCloudformationClient(profile, region)\n\tprinter.Step(fmt.Sprintf(\"Delete Stack %s:\", stackName))\n\n\t//See if the stack exists to begin with\n\t_, err := cf.DescribeStacks(&cloudformation.DescribeStacksInput{StackName: aws.String(stackName)})\n\tcheckError(err)\n\n\t_, err = cf.DeleteStack(&cloudformation.DeleteStackInput{StackName: aws.String(stackName)})\n\tcheckError(err)\n\n\t// status polling\n\tPrintStackEventHeader()\n\n\tfor {\n\t\tprinter.Progress(\"Deleting\")\n\t\ttime.Sleep(2 * time.Second)\n\t\tstatus, err := cf.DescribeStacks(&cloudformation.DescribeStacksInput{StackName: aws.String(stackName)})\n\t\tcheckErrorDeletePoll(err)\n\n\t\tevents, _ := cf.DescribeStackEvents(&cloudformation.DescribeStackEventsInput{StackName: aws.String(stackName)})\n\n\t\tif len(status.Stacks) > 0 {\n\t\t\tstackStatus := *status.Stacks[0].StackStatus\n\n\t\t\tif len(events.StackEvents) > 0 {\n\t\t\t\tPrintStackEvent(events.StackEvents[0], false)\n\t\t\t}\n\t\t\tif stackStatus == cloudformation.StackStatusDeleteInProgress {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tbreak\n\t}\n\n\t// Make sure delete worked\n\t_, err = cf.DescribeStacks(&cloudformation.DescribeStacksInput{StackName: aws.String(stackName)})\n\tif err != nil {\n\t\tcheckErrorDeletePoll(err)\n\t} else {\n\t\tprinter.SubStep(\n\t\t\tfmt.Sprintf(\"Success Delete Stack %s\", stackName),\n\t\t\t1,\n\t\t\ttrue,\n\t\t\ttrue,\n\t\t)\n\t\tos.Exit(0)\n\t}\n}", "func (cardStack *CardStack) CreateRenderStack() []graphic.Instance {\n\tinstances := make([]graphic.Instance, len(cardStack.Cards))\n\n\tfor n, i := range cardStack.Cards {\n\t\tinstances[n] = i.GetCardInstance()\n\t\tinstances[n].NewPositionCorner(sdl.FPoint{(float32)(n) * (i.GetCardInstance().GetBaseWitdth()), 0})\n\t\tinstances[n].Show()\n\t}\n\n\treturn instances\n}", "func NewStack() *Stack {\n\treturn &Stack{nil, 0}\n}", "func NewStack() *Stack {\n\treturn &Stack{nil, 0}\n}", "func (a *Client) CreateSite(params *CreateSiteParams, authInfo runtime.ClientAuthInfoWriter) (*CreateSiteOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewCreateSiteParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"CreateSite\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/cdn/v1/stacks/{stack_id}/sites\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &CreateSiteReader{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.(*CreateSiteOK), nil\n\n}", "func CreateService(ctx *gin.Context) {\n\tlog := logger.RuntimeLog\n\tvar svcModel *model.Service\n\tif err := ctx.BindJSON(&svcModel); err != nil {\n\t\tSendResponse(ctx, err, \"Request Body Invalid\")\n\t}\n\n\tsvcNamespace := strings.ToLower(svcModel.SvcMeta.Namespace)\n\tsvcZone := svcModel.SvcMeta.AppMeta.ZoneName\n\tsvcName := svcModel.SvcMeta.Name\n\n\t// fetch k8s-client hander by zoneName\n\tkclient, err := GetClientByAzCode(svcZone)\n\tif err != nil {\n\t\tlog.WithError(err)\n\t\tSendResponse(ctx, errno.ErrTokenInvalid, nil)\n\t\treturn\n\t}\n\n\tstartAt := time.Now() // used to record operation time cost\n\t_, err = kclient.CoreV1().Services(svcNamespace).Create(makeupServiceData(ctx, svcModel))\n\tif err != nil {\n\t\tSendResponse(ctx, err, \"create Service fail.\")\n\t\treturn\n\t}\n\tlogger.MetricsEmit(\n\t\tSVC_CONST.K8S_LOG_Method_CreateService,\n\t\tutil.GetReqID(ctx),\n\t\tfloat32(time.Since(startAt)/time.Millisecond),\n\t\terr == err,\n\t)\n\tSendResponse(ctx, errno.OK, fmt.Sprintf(\"Create Service %s success.\", svcName))\n}", "func (service *SQSService) Create(attributes map[string]*string) (string, error) {\n\tinput := &sqs.CreateQueueInput{\n\t\tAttributes: attributes,\n\t\tQueueName: &service.QueueName,\n\t}\n\n\toutput, err := service.CreateQueue(input)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif output.QueueUrl == nil {\n\t\treturn \"\", errors.New(\"QueueUrl is null\")\n\t}\n\n\treturn *output.QueueUrl, nil\n}", "func (r apiCreateStackRequest) Execute() (StackCreateStackResponse, *_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 StackCreateStackResponse\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"StacksApiService.CreateStack\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/stack/v1/stacks\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\t\n\tif r.stackCreateStackRequest == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"stackCreateStackRequest is required and must be specified\")\n\t}\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\"}\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 = r.stackCreateStackRequest\n\treq, err := r.apiService.client.prepareRequest(r.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 := r.apiService.client.callAPI(req)\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 == 401 {\n\t\t\tvar v StackpathapiStatus\n\t\t\terr = r.apiService.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 StackpathapiStatus\n\t\t\terr = r.apiService.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\t\tvar v StackpathapiStatus\n\t\t\terr = r.apiService.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\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.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 NewStack() *Stack {\n\treturn &Stack{Items: list.New()}\n}", "func (w *workerpool) CreateWorkerPool(workerPoolReq WorkerPoolRequest, target ClusterTargetHeader) (WorkerPoolResponse, error) {\n\tvar successV WorkerPoolResponse\n\t_, err := w.client.Post(\"/v2/vpc/createWorkerPool\", workerPoolReq, &successV, target.ToMap())\n\treturn successV, err\n}", "func (a *Azure) CreateNetworkSecurityGroup(ctx context.Context, location string, nsgName string, c *types.Config) (nsg *network.SecurityGroup, err error) {\n\tnsgClient, err := a.getNsgClient()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar securityRules []network.SecurityRule\n\n\tfor _, ports := range c.RunConfig.Ports {\n\t\tvar rule = a.buildFirewallRule(network.SecurityRuleProtocolTCP, ports)\n\t\tsecurityRules = append(securityRules, rule)\n\t}\n\n\tfor _, ports := range c.RunConfig.UDPPorts {\n\t\tvar rule = a.buildFirewallRule(network.SecurityRuleProtocolUDP, ports)\n\t\tsecurityRules = append(securityRules, rule)\n\t}\n\n\tfuture, err := nsgClient.CreateOrUpdate(\n\t\tctx,\n\t\ta.groupName,\n\t\tnsgName,\n\t\tnetwork.SecurityGroup{\n\t\t\tLocation: to.StringPtr(location),\n\t\t\tSecurityGroupPropertiesFormat: &network.SecurityGroupPropertiesFormat{\n\t\t\t\tSecurityRules: &securityRules,\n\t\t\t},\n\t\t\tTags: getAzureDefaultTags(),\n\t\t},\n\t)\n\n\tif err != nil {\n\t\treturn nsg, fmt.Errorf(\"cannot create nsg: %v\", err)\n\t}\n\n\terr = future.WaitForCompletionRef(ctx, nsgClient.Client)\n\tif err != nil {\n\t\treturn nsg, fmt.Errorf(\"cannot get nsg create or update future response: %v\", err)\n\t}\n\n\tnsgValue, err := future.Result(*nsgClient)\n\tnsg = &nsgValue\n\treturn\n}", "func (c *LoadBalancerClient) Create(params LoadBalancerParams) (*LoadBalancer, error) {\n\tvar result LoadBalancer\n\terr := c.Backend.CallIntoInterface(\"v1/Network/LoadBalancer/create\", params, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &result, nil\n}", "func NewCreate(name, desc string) *CreateSecurityTagAPI {\n\tthis := new(CreateSecurityTagAPI)\n\trequestPayload := new(SecurityTag)\n\trequestPayload.Name = name\n\trequestPayload.Description = desc\n\t// TODO: need to make it argument\n\trequestPayload.TypeName = \"SecurityTag\"\n\tthis.BaseAPI = api.NewBaseAPI(http.MethodPost, \"/api/2.0/services/securitytags/tag\", requestPayload, new(string))\n\treturn this\n}", "func (a *LoadBalancerApiService) CreateLoadBalancer(ctx _context.Context) ApiCreateLoadBalancerRequest {\n\treturn ApiCreateLoadBalancerRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (command HelloWorldResource) Create(ctx context.Context, awsConfig awsv2.Config,\n\tevent *CloudFormationLambdaEvent,\n\tlogger *zerolog.Logger) (map[string]interface{}, error) {\n\trequest := HelloWorldResourceRequest{}\n\trequestPropsErr := json.Unmarshal(event.ResourceProperties, &request)\n\tif requestPropsErr != nil {\n\t\treturn nil, requestPropsErr\n\t}\n\tlogger.Info().Msgf(\"create: Hello %s\", request.Message)\n\treturn map[string]interface{}{\n\t\t\"Resource\": \"Created message: \" + request.Message,\n\t}, nil\n}", "func (net *NetworkComponentInput) CreateSecurityGroup(con aws.EstablishConnectionInput) (NetworkComponentResponse, error) {\n\n\tec2, seserr := con.EstablishConnection()\n\tif seserr != nil {\n\t\treturn NetworkComponentResponse{}, seserr\n\t}\n\tsecurity, secerr := ec2.CreateSecurityGroup(\n\t\t&aws.CreateNetworkInput{\n\t\t\tVpcId: net.VpcIds[0],\n\t\t\tName: net.Name + \"_sec\",\n\t\t},\n\t)\n\tif secerr != nil {\n\t\treturn NetworkComponentResponse{}, secerr\n\t}\n\n\tsctags := new(Tag)\n\tsctags.Resource = *security.GroupId\n\tsctags.Name = \"Name\"\n\tsctags.Value = net.Name + \"_sec\"\n\t_, sctagerr := sctags.CreateTags(con)\n\tif sctagerr != nil {\n\t\treturn NetworkComponentResponse{}, sctagerr\n\t}\n\n\t//creating egree and ingres rules for the security group which I created just now\n\tfor _, port := range net.Ports {\n\t\tintport, _ := strconv.ParseInt(port, 10, 64)\n\t\tingreserr := ec2.CreateIngressRule(\n\t\t\t&aws.IngressEgressInput{\n\t\t\t\tPort: intport,\n\t\t\t\tSecId: *security.GroupId,\n\t\t\t},\n\t\t)\n\t\tif ingreserr != nil {\n\t\t\treturn NetworkComponentResponse{}, ingreserr\n\t\t}\n\t}\n\tegreserr := ec2.CreateEgressRule(\n\t\t&aws.IngressEgressInput{\n\t\t\tSecId: *security.GroupId,\n\t\t},\n\t)\n\tif egreserr != nil {\n\t\treturn NetworkComponentResponse{}, egreserr\n\t}\n\n\tif net.GetRaw == true {\n\t\treturn NetworkComponentResponse{CreateSecurityRaw: security}, nil\n\t}\n\treturn NetworkComponentResponse{SecGroupIds: []string{*security.GroupId}}, nil\n}", "func (c *Canary) CreateCanaryLoadBalancer(region schemas.RegionConfig, groupID *string) (*elbv2.LoadBalancer, error) {\n\tclient, err := selectClientFromList(c.AWSClients, region.Region)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnewLBName := c.GenerateCanaryLoadBalancerName(region.Region)\n\n\tavailabilityZones, err := client.EC2Service.GetAvailabilityZones(region.VPC, region.AvailabilityZones)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsubnets, err := client.EC2Service.GetSubnets(region.VPC, region.UsePublicSubnets, availabilityZones)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlb, err := client.ELBV2Service.CreateLoadBalancer(newLBName, subnets, groupID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn lb, nil\n}", "func NewStack(n int) (*Stack, error) {\n\tif n < 1 {\n\t\treturn nil, fmt.Errorf(\"stack size must be larger than 0\")\n\t}\n\ts := &Stack{\n\t\tdata: make([]Elem, 0, n),\n\t\ttop: -1,\n\t}\n\n\treturn s, nil\n}", "func New() Stack {\n\treturn &stack{}\n}", "func lookupStack(clustername string) (string, string, error) {\n\tcfg, err := external.LoadDefaultAWSConfig()\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tsvc := cloudformation.New(cfg)\n\tvar activeStacks = []cloudformation.StackStatus{\"CREATE_COMPLETE\"}\n\tlsreq := svc.ListStacksRequest(&cloudformation.ListStacksInput{StackStatusFilter: activeStacks})\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tlsresp, err := lsreq.Send(context.TODO())\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\t// iterate over active stacks to find the two eksctl created, by label\n\tcpstack, dpstack := \"\", \"\"\n\tfor _, stack := range lsresp.StackSummaries {\n\t\tdsreq := svc.DescribeStacksRequest(&cloudformation.DescribeStacksInput{StackName: stack.StackName})\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", err\n\t\t}\n\t\tdsresp, err := dsreq.Send(context.TODO())\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", err\n\t\t}\n\t\t// fmt.Printf(\"DEBUG:: checking stack %v if it has label with cluster name %v\\n\", *dsresp.Stacks[0].StackName, clustername)\n\t\tcnofstack := tagValueOf(dsresp.Stacks[0], \"eksctl.cluster.k8s.io/v1alpha1/cluster-name\")\n\t\tif cnofstack != \"\" && cnofstack == clustername {\n\t\t\tswitch {\n\t\t\tcase tagValueOf(dsresp.Stacks[0], \"alpha.eksctl.io/nodegroup-name\") != \"\":\n\t\t\t\tdpstack = *dsresp.Stacks[0].StackName\n\t\t\tdefault:\n\t\t\t\tcpstack = *dsresp.Stacks[0].StackName\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Printf(\"DEBUG:: found control plane stack [%v] and data plane stack [%v] for cluster %v\\n\", cpstack, dpstack, clustername)\n\treturn cpstack, dpstack, nil\n}", "func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToAddressScopeCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\tresp, err := client.Post(createURL(client), b, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{201},\n\t})\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}" ]
[ "0.71047324", "0.6875082", "0.68076223", "0.6794135", "0.679078", "0.6751174", "0.6712775", "0.66567725", "0.66023535", "0.6595654", "0.6490512", "0.62750256", "0.62704486", "0.60571676", "0.605478", "0.59436655", "0.5935414", "0.5841742", "0.58413035", "0.5837066", "0.5765792", "0.57359904", "0.56689155", "0.55838966", "0.5551551", "0.5532969", "0.54530954", "0.54199123", "0.5387313", "0.5298438", "0.5283694", "0.52135646", "0.5099999", "0.5093779", "0.49949494", "0.49949214", "0.49781558", "0.49771446", "0.49741974", "0.495631", "0.49434125", "0.4937035", "0.4933767", "0.4932947", "0.49173164", "0.4916523", "0.4914573", "0.4853663", "0.48334512", "0.4815726", "0.48104128", "0.48058593", "0.47861195", "0.4771646", "0.47578186", "0.47578186", "0.47578186", "0.47578186", "0.47578186", "0.47576818", "0.47328654", "0.47325245", "0.4724283", "0.4710268", "0.4692099", "0.46841916", "0.468128", "0.46550488", "0.46495554", "0.46406904", "0.46402654", "0.4622974", "0.4620183", "0.4618741", "0.46184996", "0.460759", "0.46011215", "0.460095", "0.45987213", "0.45892262", "0.45848128", "0.45722386", "0.45722386", "0.4562697", "0.45386967", "0.453778", "0.45374003", "0.45276853", "0.45272908", "0.45258716", "0.4523776", "0.4511218", "0.45105913", "0.45083445", "0.45024052", "0.44983035", "0.44972903", "0.44917417", "0.44792035", "0.44601044" ]
0.7167785
0
GetStack returns the CloudFormation stack details with the name or ID from the argument
func (a *Adapter) GetStack(stackID string) (*Stack, error) { return getStack(a.cloudformation, stackID) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetStack(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *StackState, opts ...pulumi.ResourceOption) (*Stack, error) {\n\tvar resource Stack\n\terr := ctx.ReadResource(\"aws-native:cloudformation:Stack\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (a *StacksApiService) GetStack(ctx _context.Context, stackId string) apiGetStackRequest {\n\treturn apiGetStackRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t\tstackId: stackId,\n\t}\n}", "func (c *CloudFormation) Stack(name string) (*Stack, error) {\n\tparams := &cfn.DescribeStacksInput{\n\t\tNextToken: aws.String(\"NextToken\"),\n\t\tStackName: aws.String(name),\n\t}\n\tresp, err := c.srv.DescribeStacks(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(resp.Stacks) != 1 {\n\t\treturn nil, fmt.Errorf(\"Reseived %v stacks, expected one\", len(resp.Stacks))\n\t}\n\n\treturn &Stack{srv: c.srv, Stack: resp.Stacks[0]}, nil\n}", "func (r *Client) get(ctx context.Context, stack Stack) (*State, error) {\n\tdescribeOutput, err := r.Client.DescribeStacksWithContext(ctx, &DescribeStacksInput{\n\t\tStackName: aws.String(stack.GetStackName()),\n\t})\n\tif err != nil {\n\t\tif IsNotFoundError(err) {\n\t\t\treturn nil, ErrStackNotFound\n\t\t}\n\t\treturn nil, err\n\t}\n\tif describeOutput == nil {\n\t\treturn nil, fmt.Errorf(\"describeOutput was nil, potential issue with AWS Client\")\n\t}\n\tif len(describeOutput.Stacks) == 0 {\n\t\treturn nil, fmt.Errorf(\"describeOutput contained no Stacks, potential issue with AWS Client\")\n\t}\n\tif len(describeOutput.Stacks) > 1 {\n\t\treturn nil, fmt.Errorf(\"describeOutput contained multiple Stacks which is unexpected when calling with StackName, potential issue with AWS Client\")\n\t}\n\tstate := describeOutput.Stacks[0]\n\tif state.StackStatus == nil {\n\t\treturn nil, fmt.Errorf(\"describeOutput contained a nil StackStatus, potential issue with AWS Client\")\n\t}\n\treturn state, nil\n}", "func Get(c *gophercloud.ServiceClient, stackName, stackID string) GetResult {\n\tvar res GetResult\n\t_, res.Err = c.Request(\"GET\", getURL(c, stackName, stackID), gophercloud.RequestOpts{\n\t\tJSONResponse: &res.Body,\n\t})\n\treturn res\n}", "func (s *Stack) read() (*cloudformation.Stack, error) {\n\tout, err := s.cfnconn.DescribeStacks(&cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(s.Name),\n\t})\n\tif err != nil {\n\t\tif e, ok := err.(awserr.Error); ok && e.Code() == \"ValidationError\" {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, errors.Annotatef(err, \"cannot read stack\")\n\t}\n\tif out.Stacks == nil || len(out.Stacks) == 0 {\n\t\treturn nil, nil\n\t}\n\treturn out.Stacks[0], nil\n}", "func StacksGet(w http.ResponseWriter, r *http.Request) {\n\tresp, err := goreq.Request{\n\t\tMethod: \"GET\",\n\t\tUri: remoteURL + \"/stacks\",\n\t}.Do()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer resp.Body.Close()\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(resp.StatusCode)\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tw.Write(body)\n}", "func InfoStack(ctx context.Context, svc *cf.CloudFormation, opts *RequestOptions) ([]StackOutput, error) {\n\tinput := &cf.DescribeStacksInput{\n\t\tStackName: aws.String(opts.StackName),\n\t\tNextToken: aws.String(strconv.Itoa(opts.Page)),\n\t}\n\toutput, err := svc.DescribeStacksWithContext(ctx, input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar stack *cf.Stack\n\tfor _, stack = range output.Stacks {\n\t\t//if stack.StackName == input.StackName {\n\t\tif aws.StringValue(stack.StackName) == opts.StackName {\n\t\t\tbreak\n\t\t}\n\t\tstack = nil\n\t}\n\n\tif stack == nil {\n\t\treturn nil, errors.New(\"stack not found: \" + opts.StackName)\n\t}\n\n\tstackOutputs := []StackOutput{}\n\tfor _, o := range stack.Outputs {\n\t\tstackOutputs = append(stackOutputs, StackOutput{\n\t\t\tDescription: aws.StringValue(o.Description),\n\t\t\tOutputKey: aws.StringValue(o.OutputKey),\n\t\t\tOutputValue: aws.StringValue(o.OutputValue),\n\t\t})\n\t}\n\n\treturn stackOutputs, nil\n}", "func LookupSolutionStack(ctx *pulumi.Context, args *GetSolutionStackArgs) (*GetSolutionStackResult, error) {\n\tinputs := make(map[string]interface{})\n\tif args != nil {\n\t\tinputs[\"mostRecent\"] = args.MostRecent\n\t\tinputs[\"nameRegex\"] = args.NameRegex\n\t}\n\toutputs, err := ctx.Invoke(\"aws:elasticbeanstalk/getSolutionStack:getSolutionStack\", inputs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &GetSolutionStackResult{\n\t\tMostRecent: outputs[\"mostRecent\"],\n\t\tName: outputs[\"name\"],\n\t\tNameRegex: outputs[\"nameRegex\"],\n\t\tId: outputs[\"id\"],\n\t}, nil\n}", "func lookupStack(clustername string) (string, string, error) {\n\tcfg, err := external.LoadDefaultAWSConfig()\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tsvc := cloudformation.New(cfg)\n\tvar activeStacks = []cloudformation.StackStatus{\"CREATE_COMPLETE\"}\n\tlsreq := svc.ListStacksRequest(&cloudformation.ListStacksInput{StackStatusFilter: activeStacks})\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tlsresp, err := lsreq.Send(context.TODO())\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\t// iterate over active stacks to find the two eksctl created, by label\n\tcpstack, dpstack := \"\", \"\"\n\tfor _, stack := range lsresp.StackSummaries {\n\t\tdsreq := svc.DescribeStacksRequest(&cloudformation.DescribeStacksInput{StackName: stack.StackName})\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", err\n\t\t}\n\t\tdsresp, err := dsreq.Send(context.TODO())\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", err\n\t\t}\n\t\t// fmt.Printf(\"DEBUG:: checking stack %v if it has label with cluster name %v\\n\", *dsresp.Stacks[0].StackName, clustername)\n\t\tcnofstack := tagValueOf(dsresp.Stacks[0], \"eksctl.cluster.k8s.io/v1alpha1/cluster-name\")\n\t\tif cnofstack != \"\" && cnofstack == clustername {\n\t\t\tswitch {\n\t\t\tcase tagValueOf(dsresp.Stacks[0], \"alpha.eksctl.io/nodegroup-name\") != \"\":\n\t\t\t\tdpstack = *dsresp.Stacks[0].StackName\n\t\t\tdefault:\n\t\t\t\tcpstack = *dsresp.Stacks[0].StackName\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Printf(\"DEBUG:: found control plane stack [%v] and data plane stack [%v] for cluster %v\\n\", cpstack, dpstack, clustername)\n\treturn cpstack, dpstack, nil\n}", "func Get(c *gophercloud.ServiceClient, stackName, stackID, resourceName, eventID string) (r GetResult) {\n\tresp, err := c.Get(getURL(c, stackName, stackID, resourceName, eventID), &r.Body, nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func (client *BuildServiceClient) getSupportedStackCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, stackName string, options *BuildServiceClientGetSupportedStackOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/supportedStacks/{stackName}\"\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\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 serviceName == \"\" {\n\t\treturn nil, errors.New(\"parameter serviceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{serviceName}\", url.PathEscape(serviceName))\n\tif buildServiceName == \"\" {\n\t\treturn nil, errors.New(\"parameter buildServiceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{buildServiceName}\", url.PathEscape(buildServiceName))\n\tif stackName == \"\" {\n\t\treturn nil, errors.New(\"parameter stackName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{stackName}\", url.PathEscape(stackName))\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-01-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func LookupStack(ctx *pulumi.Context, args *LookupStackArgs, opts ...pulumi.InvokeOption) (*LookupStackResult, error) {\n\topts = internal.PkgInvokeDefaultOpts(opts)\n\tvar rv LookupStackResult\n\terr := ctx.Invoke(\"aws-native:appstream:getStack\", args, &rv, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &rv, nil\n}", "func (a *StacksApiService) GetStacks(ctx _context.Context) apiGetStacksRequest {\n\treturn apiGetStacksRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (o *V1VolumeClaim) GetStackId() string {\n\tif o == nil || o.StackId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.StackId\n}", "func (e *NotFoundError) GetStack() stack { return e.stack }", "func (a *Client) GetNetworkSwitchStack(params *GetNetworkSwitchStackParams, authInfo runtime.ClientAuthInfoWriter) (*GetNetworkSwitchStackOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetNetworkSwitchStackParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getNetworkSwitchStack\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/networks/{networkId}/switchStacks/{switchStackId}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetNetworkSwitchStackReader{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.(*GetNetworkSwitchStackOK)\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 getNetworkSwitchStack: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (client *CraneDockerClient) getStackFilter(namespace string) filters.Args {\n\tfilter := filters.NewArgs()\n\tfilter.Add(\"label\", LabelNamespace+\"=\"+namespace)\n\treturn filter\n}", "func (in *RecordSetGroup) GetStackID() string {\n\treturn in.Status.StackID\n}", "func (in *RecordSetGroup) GetStackName() string {\n\treturn in.Spec.StackName\n}", "func (e *GalaxyBaseError) GetStack() string {\n\treturn e.Stack\n}", "func (c *StackCollection) DescribeStack(ctx context.Context, i *Stack) (*Stack, error) {\n\tinput := &cloudformation.DescribeStacksInput{\n\t\tStackName: i.StackName,\n\t}\n\tif api.IsSetAndNonEmptyString(i.StackId) {\n\t\tinput.StackName = i.StackId\n\t}\n\tresp, err := c.cloudformationAPI.DescribeStacks(ctx, input)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"describing CloudFormation stack %q\", *i.StackName)\n\t}\n\tif len(resp.Stacks) == 0 {\n\t\treturn nil, fmt.Errorf(\"no CloudFormation stack found for %s\", *i.StackName)\n\t}\n\treturn &resp.Stacks[0], nil\n}", "func (c *StackCollection) GetFargateStack(ctx context.Context) (*Stack, error) {\n\tstacks, err := c.ListStacks(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, s := range stacks {\n\t\tif s.StackStatus == types.StackStatusDeleteComplete {\n\t\t\tcontinue\n\t\t}\n\t\tif isFargateStack(s) {\n\t\t\treturn s, nil\n\t\t}\n\t}\n\n\treturn nil, nil\n}", "func GetStack(err error) string {\n\tif e, ok := err.(*goerrors.Error); ok {\n\t\treturn string(e.Stack())\n\t}\n\treturn \"\"\n}", "func (r apiGetStackRequest) Execute() (StackStack, *_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 StackStack\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"StacksApiService.GetStack\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/stack/v1/stacks/{stack_id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"stack_id\"+\"}\", _neturl.QueryEscape(parameterToString(r.stackId, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\t\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\treq, err := r.apiService.client.prepareRequest(r.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 := r.apiService.client.callAPI(req)\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 == 401 {\n\t\t\tvar v StackpathapiStatus\n\t\t\terr = r.apiService.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 StackpathapiStatus\n\t\t\terr = r.apiService.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\t\tvar v StackpathapiStatus\n\t\t\terr = r.apiService.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\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.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 *YogClient) DescribeStack(request DescribeStackRequest) (DescribeStackResponse, YogError) {\n\treturn DescribeStackResponse{}, YogError{}\n}", "func (s stack) GetStackName() (string, fail.Error) {\n\treturn \"aws\", nil\n}", "func (o *ZoneZone) GetStackId() string {\n\tif o == nil || o.StackId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.StackId\n}", "func LoadStack(api cloudformationiface.CloudFormationAPI, config *StackConfig) (*Stack, error) {\n\tstack := &Stack{\n\t\tapi: api,\n\t\tconfig: config,\n\t\twaitAttempts: maxWaitAttempts,\n\t\twaiter: waiterFunc(sleepWaiter),\n\t\teventLoader: &stackEvents{\n\t\t\tapi: api,\n\t\t\tstackName: aws.String(config.Name),\n\t\t},\n\n\t\ttemplateReader: fileReaderFunc(ioutil.ReadFile),\n\t}\n\n\terr := stack.load()\n\tif err == nil {\n\t\terr = stack.storeLastEvent()\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn stack, nil\n}", "func NewStack(ctx *pulumi.Context,\n\tname string, args *StackArgs, opts ...pulumi.ResourceOption) (*Stack, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.TemplateUrl == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'TemplateUrl'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Stack\n\terr := ctx.RegisterResource(\"aws-native:cloudformation:Stack\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (s *Cloudformation) CreateStack() (output *cloudformation.CreateStackOutput, err error) {\n\tsess := s.config.AWSSession\n\tsvc := cloudformation.New(sess)\n\n\tcftemplate := helpers.GetCloudFormationTemplate(s.config, \"s3bucket\", s.S3Bucket.Spec.CloudFormationTemplateName, s.S3Bucket.Spec.CloudFormationTemplateNamespace)\n\n\tstackInputs := cloudformation.CreateStackInput{\n\t\tStackName: aws.String(s.StackName()),\n\t\tTemplateURL: aws.String(cftemplate),\n\t\tNotificationARNs: []*string{\n\t\t\taws.String(s.topicARN),\n\t\t},\n\t}\n\n\tresourceName := helpers.CreateParam(\"ResourceName\", s.S3Bucket.Name)\n\tresourceVersion := helpers.CreateParam(\"ResourceVersion\", s.S3Bucket.ResourceVersion)\n\tnamespace := helpers.CreateParam(\"Namespace\", s.S3Bucket.Namespace)\n\tclusterName := helpers.CreateParam(\"ClusterName\", s.config.ClusterName)\n\tbucketName := helpers.CreateParam(\"BucketName\", helpers.Stringify(s.S3Bucket.Name))\n\tversioningTemp := \"{{.Obj.Spec.Versioning}}\"\n\tversioningValue, err := helpers.Templatize(versioningTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tversioning := helpers.CreateParam(\"EnableVersioning\", helpers.Stringify(versioningValue))\n\taccessControlTemp := \"{{.Obj.Spec.AccessControl}}\"\n\taccessControlValue, err := helpers.Templatize(accessControlTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\taccessControl := helpers.CreateParam(\"BucketAccessControl\", helpers.Stringify(accessControlValue))\n\tloggingenabledTemp := \"{{.Obj.Spec.Logging.Enabled}}\"\n\tloggingenabledValue, err := helpers.Templatize(loggingenabledTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tloggingenabled := helpers.CreateParam(\"EnableLogging\", helpers.Stringify(loggingenabledValue))\n\tloggingprefixTemp := \"{{.Obj.Spec.Logging.Prefix}}\"\n\tloggingprefixValue, err := helpers.Templatize(loggingprefixTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tloggingprefix := helpers.CreateParam(\"LoggingPrefix\", helpers.Stringify(loggingprefixValue))\n\twebsiteenabledTemp := \"{{.Obj.Spec.Website.Enabled}}\"\n\twebsiteenabledValue, err := helpers.Templatize(websiteenabledTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteenabled := helpers.CreateParam(\"EnableStaticSite\", helpers.Stringify(websiteenabledValue))\n\twebsiteindexPageTemp := \"{{.Obj.Spec.Website.IndexPage}}\"\n\twebsiteindexPageValue, err := helpers.Templatize(websiteindexPageTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteindexPage := helpers.CreateParam(\"StaticSiteIndex\", helpers.Stringify(websiteindexPageValue))\n\twebsiteerrorPageTemp := \"{{.Obj.Spec.Website.ErrorPage}}\"\n\twebsiteerrorPageValue, err := helpers.Templatize(websiteerrorPageTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteerrorPage := helpers.CreateParam(\"StaticSiteError\", helpers.Stringify(websiteerrorPageValue))\n\n\tparameters := []*cloudformation.Parameter{}\n\tparameters = append(parameters, resourceName)\n\tparameters = append(parameters, resourceVersion)\n\tparameters = append(parameters, namespace)\n\tparameters = append(parameters, clusterName)\n\tparameters = append(parameters, bucketName)\n\tparameters = append(parameters, versioning)\n\tparameters = append(parameters, accessControl)\n\tparameters = append(parameters, loggingenabled)\n\tparameters = append(parameters, loggingprefix)\n\tparameters = append(parameters, websiteenabled)\n\tparameters = append(parameters, websiteindexPage)\n\tparameters = append(parameters, websiteerrorPage)\n\n\tstackInputs.SetParameters(parameters)\n\n\tresourceNameTag := helpers.CreateTag(\"ResourceName\", s.S3Bucket.Name)\n\tresourceVersionTag := helpers.CreateTag(\"ResourceVersion\", s.S3Bucket.ResourceVersion)\n\tnamespaceTag := helpers.CreateTag(\"Namespace\", s.S3Bucket.Namespace)\n\tclusterNameTag := helpers.CreateTag(\"ClusterName\", s.config.ClusterName)\n\n\ttags := []*cloudformation.Tag{}\n\ttags = append(tags, resourceNameTag)\n\ttags = append(tags, resourceVersionTag)\n\ttags = append(tags, namespaceTag)\n\ttags = append(tags, clusterNameTag)\n\n\tstackInputs.SetTags(tags)\n\n\toutput, err = svc.CreateStack(&stackInputs)\n\treturn\n}", "func (m *RPN) GetStack() []int {\n\treturn m.stack\n}", "func (c *Client) GetOpenstack(i *GetOpenstackInput) (*Openstack, error) {\n\tif i.Service == \"\" {\n\t\treturn nil, ErrMissingService\n\t}\n\n\tif i.Version == 0 {\n\t\treturn nil, ErrMissingVersion\n\t}\n\n\tif i.Name == \"\" {\n\t\treturn nil, ErrMissingName\n\t}\n\n\tpath := fmt.Sprintf(\"/service/%s/version/%d/logging/openstack/%s\", i.Service, i.Version, url.PathEscape(i.Name))\n\tresp, err := c.Get(path, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar openstack *Openstack\n\tif err := decodeBodyMap(resp.Body, &openstack); err != nil {\n\t\treturn nil, err\n\t}\n\treturn openstack, nil\n}", "func (c *Client) NewStack(stack *CreateStackInput) (int64, error) {\n\tdata, err := json.Marshal(stack)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tresult := struct {\n\t\tID int64 `json:\"id\"`\n\t}{}\n\n\terr = c.request(\"POST\", \"/api/instances\", nil, bytes.NewBuffer(data), &result)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn result.ID, nil\n}", "func (b *localBackend) GetStackTags(ctx context.Context,\n\tstack backend.Stack) (map[apitype.StackTagName]string, error) {\n\n\t// The local backend does not currently persist tags.\n\treturn nil, errors.New(\"stack tags not supported in --local mode\")\n}", "func (e *InvalidArgumentError) GetStack() stack { return e.stack }", "func (c *Client) StackByID(id int64) (Stack, error) {\n\tstack := Stack{}\n\terr := c.request(\"GET\", fmt.Sprintf(\"/api/instances/%d\", id), nil, nil, &stack)\n\n\tif err != nil {\n\t\treturn stack, err\n\t}\n\n\treturn stack, err\n}", "func (e *Ex) StackString() string {\n\treturn fmt.Sprintf(\"%v\", e.stack)\n}", "func (e *Ex) StackString() string {\n\treturn fmt.Sprintf(\"%v\", e.stack)\n}", "func (m *MockCloudformationAPI) DescribeStacks(input *cloudformation.DescribeStacksInput) (*cloudformation.DescribeStacksOutput, error) {\n\tif m.FailDescribe {\n\t\treturn nil, m.Err\n\t}\n\n\treturn &cloudformation.DescribeStacksOutput{\n\t\tStacks: []*cloudformation.Stack{\n\t\t\t&cloudformation.Stack{\n\t\t\t\tStackName: aws.String(\"foo\"),\n\t\t\t\tStackStatus: aws.String(m.Status),\n\t\t\t\tOutputs: []*cloudformation.Output{\n\t\t\t\t\t&cloudformation.Output{\n\t\t\t\t\t\tOutputKey: aws.String(\"CustomerGateway0\"),\n\t\t\t\t\t\tOutputValue: aws.String(\"test-CustomerGatewayID\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, nil\n}", "func (b *cloudBackend) getCloudStackIdentifier(stackRef backend.StackReference) (client.StackIdentifier, error) {\n\tcloudBackendStackRef, ok := stackRef.(cloudBackendReference)\n\tif !ok {\n\t\treturn client.StackIdentifier{}, errors.New(\"bad stack reference type\")\n\t}\n\n\treturn client.StackIdentifier{\n\t\tOwner: cloudBackendStackRef.owner,\n\t\tProject: cleanProjectName(string(cloudBackendStackRef.project)),\n\t\tStack: string(cloudBackendStackRef.name),\n\t}, nil\n}", "func StackExists(r string, name string) (bool, *cloudformation.Stack) {\n\tsvc := cloudformation.New(getSession(r))\n\tlog.Debug(\"Getting stack information for %v\", name)\n\n\tstackDetails, _ := svc.DescribeStacks(&cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(name),\n\t})\n\n\tif len(stackDetails.Stacks) == 1 {\n\t\treturn true, stackDetails.Stacks[0]\n\t}\n\n\treturn false, nil\n}", "func (r *Route) Stack() *Stack {\n\treturn r.outgoingNIC.stack\n}", "func (o CustomLayerOutput) StackId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *CustomLayer) pulumi.StringOutput { return v.StackId }).(pulumi.StringOutput)\n}", "func (client *CraneDockerClient) InspectStack(namespace string) (*model.Bundle, error) {\n\tservices, err := client.FilterServiceByStack(namespace, types.ServiceListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstackServices := make(map[string]model.CraneServiceSpec)\n\tfor _, swarmService := range services {\n\t\tstackServices[swarmService.Spec.Name] = client.ToCraneServiceSpec(swarmService.Spec)\n\t}\n\n\treturn &model.Bundle{\n\t\tNamespace: namespace,\n\t\tStack: model.BundleService{\n\t\t\t//TODO stack version is missing\n\t\t\tServices: stackServices,\n\t\t},\n\t}, nil\n}", "func (c *Client) StackBySlug(slug string) (Stack, error) {\n\tstack := Stack{}\n\terr := c.request(\"GET\", fmt.Sprintf(\"/api/instances/%s\", slug), nil, nil, &stack)\n\n\tif err != nil {\n\t\treturn stack, err\n\t}\n\n\treturn stack, err\n}", "func CreateStack(r string, name string, uri string, params []*cloudformation.Parameter, capabilities []*string) {\n\tsvc := cloudformation.New(getSession(r))\n\tlog.Info(\"CreateStack\")\n\n\tlog.Debug(\"Using Parameters:\")\n\tlog.Debug(\"%v\", params)\n\n\ttemplate := cloudformation.CreateStackInput{\n\t\tStackName: &name,\n\t\tParameters: params,\n\t\tCapabilities: capabilities,\n\t}\n\tif pass, path := parseURI(uri); pass {\n\t\ttemplateBody := utils.LoadTemplate(path)\n\t\ttemplate.TemplateBody = &templateBody\n\t} else {\n\t\ttemplate.TemplateURL = &path\n\t}\n\n\tstack, err := svc.CreateStack(&template)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Print(\"%v\", stack)\n}", "func (a *API) Stacks() string {\n\ta.logger.Debug(\"debug_stacks\")\n\tbuf := new(bytes.Buffer)\n\terr := pprof.Lookup(\"goroutine\").WriteTo(buf, 2)\n\tif err != nil {\n\t\ta.logger.Error(\"Failed to create stacks\", \"error\", err.Error())\n\t}\n\treturn buf.String()\n}", "func (err *StackableError) Stack() string {\n\tbuf := bytes.Buffer{}\n\n\tfor _, frame := range err.StackFrames() {\n\t\tbuf.WriteString(frame.String())\n\t\tbuf.WriteString(\"\\n\")\n\t}\n\n\treturn buf.String()\n}", "func (o PhpAppLayerOutput) StackId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *PhpAppLayer) pulumi.StringOutput { return v.StackId }).(pulumi.StringOutput)\n}", "func Stack(err error) string {\n\tif err == nil {\n\t\treturn \"\"\n\t}\n\tif e, ok := err.(iStack); ok {\n\t\treturn e.Stack()\n\t}\n\treturn err.Error()\n}", "func convergeStackState(cfTemplateURL string, ctx *workflowContext) (*cloudformation.Stack, error) {\n\tawsCloudFormation := cloudformation.New(ctx.awsSession)\n\n\t// Does it exist?\n\texists, err := stackExists(ctx.serviceName, awsCloudFormation, ctx.logger)\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\tstackID := \"\"\n\tif exists {\n\t\t// Update stack\n\t\tupdateStackInput := &cloudformation.UpdateStackInput{\n\t\t\tStackName: aws.String(ctx.serviceName),\n\t\t\tTemplateURL: aws.String(cfTemplateURL),\n\t\t\tCapabilities: []*string{aws.String(\"CAPABILITY_IAM\")},\n\t\t}\n\t\tupdateStackResponse, err := awsCloudFormation.UpdateStack(updateStackInput)\n\t\tif nil != err {\n\t\t\treturn nil, err\n\t\t}\n\t\tctx.logger.Info(\"Issued update request: \", *updateStackResponse.StackId)\n\t\tstackID = *updateStackResponse.StackId\n\t} else {\n\t\t// Create stack\n\t\tcreateStackInput := &cloudformation.CreateStackInput{\n\t\t\tStackName: aws.String(ctx.serviceName),\n\t\t\tTemplateURL: aws.String(cfTemplateURL),\n\t\t\tTimeoutInMinutes: aws.Int64(5),\n\t\t\tOnFailure: aws.String(cloudformation.OnFailureDelete),\n\t\t\tCapabilities: []*string{aws.String(\"CAPABILITY_IAM\")},\n\t\t}\n\t\tcreateStackResponse, err := awsCloudFormation.CreateStack(createStackInput)\n\t\tif nil != err {\n\t\t\treturn nil, err\n\t\t}\n\t\tctx.logger.Info(\"Creating stack: \", *createStackResponse.StackId)\n\t\tstackID = *createStackResponse.StackId\n\t}\n\n\t// Poll for the current stackID state\n\tdescribeStacksInput := &cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(stackID),\n\t}\n\n\tvar stackInfo *cloudformation.Stack\n\tstackOperationComplete := false\n\tctx.logger.Info(\"Waiting for stack to complete\")\n\tfor !stackOperationComplete {\n\t\ttime.Sleep(10 * time.Second)\n\t\tdescribeStacksOutput, err := awsCloudFormation.DescribeStacks(describeStacksInput)\n\t\tif nil != err {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(describeStacksOutput.Stacks) > 0 {\n\t\t\tstackInfo = describeStacksOutput.Stacks[0]\n\t\t\tctx.logger.Info(\"Current state: \", *stackInfo.StackStatus)\n\t\t\tswitch *stackInfo.StackStatus {\n\t\t\tcase cloudformation.StackStatusCreateInProgress,\n\t\t\t\tcloudformation.StackStatusDeleteInProgress,\n\t\t\t\tcloudformation.StackStatusUpdateInProgress,\n\t\t\t\tcloudformation.StackStatusRollbackInProgress,\n\t\t\t\tcloudformation.StackStatusUpdateCompleteCleanupInProgress,\n\t\t\t\tcloudformation.StackStatusUpdateRollbackCompleteCleanupInProgress,\n\t\t\t\tcloudformation.StackStatusUpdateRollbackInProgress:\n\t\t\t\ttime.Sleep(20 * time.Second)\n\t\t\tdefault:\n\t\t\t\tstackOperationComplete = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"More than one stack returned for: %s\", stackID)\n\t\t}\n\t}\n\t// What happened?\n\tsucceed := true\n\tswitch *stackInfo.StackStatus {\n\tcase cloudformation.StackStatusDeleteComplete, // Initial create failure\n\t\tcloudformation.StackStatusUpdateRollbackComplete: // Update failure\n\t\tsucceed = false\n\tdefault:\n\t\tsucceed = true\n\t}\n\n\t// If it didn't work, then output some failure information\n\tif !succeed {\n\t\t// Get the stack events and find the ones that failed.\n\t\tevents, err := stackEvents(stackID, awsCloudFormation)\n\t\tif nil != err {\n\t\t\treturn nil, err\n\t\t}\n\t\tctx.logger.Error(\"Stack provisioning failed.\")\n\t\tfor _, eachEvent := range events {\n\t\t\tswitch *eachEvent.ResourceStatus {\n\t\t\tcase cloudformation.ResourceStatusCreateFailed,\n\t\t\t\tcloudformation.ResourceStatusDeleteFailed,\n\t\t\t\tcloudformation.ResourceStatusUpdateFailed:\n\t\t\t\terrMsg := fmt.Sprintf(\"\\tError ensuring %s (%s): %s\",\n\t\t\t\t\t*eachEvent.ResourceType,\n\t\t\t\t\t*eachEvent.LogicalResourceId,\n\t\t\t\t\t*eachEvent.ResourceStatusReason)\n\t\t\t\tctx.logger.Error(errMsg)\n\t\t\tdefault:\n\t\t\t\t// NOP\n\t\t\t}\n\t\t}\n\t\treturn nil, fmt.Errorf(\"Failed to provision: %s\", ctx.serviceName)\n\t} else if nil != stackInfo.Outputs {\n\t\tctx.logger.Info(\"Stack Outputs:\")\n\t\tfor _, eachOutput := range stackInfo.Outputs {\n\t\t\tctx.logger.WithFields(logrus.Fields{\n\t\t\t\t\"Key\": *eachOutput.OutputKey,\n\t\t\t\t\"Value\": *eachOutput.OutputValue,\n\t\t\t\t\"Description\": *eachOutput.Description,\n\t\t\t}).Info(\"\\tOutput\")\n\t\t}\n\t}\n\treturn stackInfo, nil\n}", "func (c *Client) Stacks() (StackItems, error) {\n\tstacks := StackItems{}\n\terr := c.request(\"GET\", \"/api/instances\", nil, nil, &stacks)\n\tif err != nil {\n\t\treturn stacks, err\n\t}\n\n\treturn stacks, err\n}", "func DescribeStacks(r string) {\n\tsvc := cloudformation.New(getSession(r))\n\n\tstatii := []*string{\n\t\taws.String(\"CREATE_COMPLETE\"),\n\t\taws.String(\"CREATE_IN_PROGRESS\"),\n\t\taws.String(\"UPDATE_COMPLETE\"),\n\t\taws.String(\"UPDATE_IN_PROGRESS\"),\n\t}\n\n\tstackSummaries, err := svc.ListStacks(&cloudformation.ListStacksInput{\n\t\tStackStatusFilter: statii,\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor _, stack := range stackSummaries.StackSummaries {\n\t\tlog.Print(\"%-52v %-40v %-20v\", *stack.StackName,\n\t\t\tstack.CreationTime.Format(\"Mon Jan 2 15:04:05 MST 2006\"),\n\t\t\t*stack.StackStatus,\n\t\t)\n\t\t// List change sets:\n\t\tchangeSets := DescribeChangeSets(r, *stack.StackName)\n\t\tfor _, change := range changeSets.Summaries {\n\t\t\tlog.Print(\"\\tchange set -> %-30v %-40v %-20v\", *change.ChangeSetName,\n\t\t\t\tchange.CreationTime.Format(\"Mon Jan 2 15:04:05 MST 2006\"),\n\t\t\t\t*change.ExecutionStatus,\n\t\t\t)\n\t\t}\n\t}\n}", "func (e *PermissionDeniedError) GetStack() stack { return e.stack }", "func (handler *Handler) stackCreate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {\n\tstackType, err := request.RetrieveNumericQueryParameter(r, \"type\", false)\n\tif err != nil {\n\t\treturn &httperror.HandlerError{http.StatusBadRequest, \"Invalid query parameter: type\", err}\n\t}\n\n\tmethod, err := request.RetrieveQueryParameter(r, \"method\", false)\n\tif err != nil {\n\t\treturn &httperror.HandlerError{http.StatusBadRequest, \"Invalid query parameter: method\", err}\n\t}\n\n\tendpointID, err := request.RetrieveNumericQueryParameter(r, \"endpointId\", false)\n\tif err != nil {\n\t\treturn &httperror.HandlerError{http.StatusBadRequest, \"Invalid query parameter: endpointId\", err}\n\t}\n\n\tendpoint, err := handler.EndpointService.Endpoint(portainer.EndpointID(endpointID))\n\tif err == portainer.ErrObjectNotFound {\n\t\treturn &httperror.HandlerError{http.StatusNotFound, \"Unable to find an endpoint with the specified identifier inside the database\", err}\n\t} else if err != nil {\n\t\treturn &httperror.HandlerError{http.StatusInternalServerError, \"Unable to find an endpoint with the specified identifier inside the database\", err}\n\t}\n\n\terr = handler.requestBouncer.EndpointAccess(r, endpoint)\n\tif err != nil {\n\t\treturn &httperror.HandlerError{http.StatusForbidden, \"Permission denied to access endpoint\", portainer.ErrEndpointAccessDenied}\n\t}\n\n\tswitch portainer.StackType(stackType) {\n\tcase portainer.DockerSwarmStack:\n\t\treturn handler.createSwarmStack(w, r, method, endpoint)\n\tcase portainer.DockerComposeStack:\n\t\treturn handler.createComposeStack(w, r, method, endpoint)\n\t}\n\n\treturn &httperror.HandlerError{http.StatusBadRequest, \"Invalid value for query parameter: type. Value must be one of: 1 (Swarm stack) or 2 (Compose stack)\", errors.New(request.ErrInvalidQueryParameter)}\n}", "func GetStackOverrides(stackName string) interface{} {\n\tif stackOverrides == nil {\n\t\treturn nil\n\t}\n\n\treturn stackOverrides[stackName]\n}", "func getStackName(input *commands.DNSInput) string {\n\treturn strings.Replace(input.HostedZone, \".\", \"-\", -1)\n}", "func (a *Client) GetNetworkSwitchStacks(params *GetNetworkSwitchStacksParams, authInfo runtime.ClientAuthInfoWriter) (*GetNetworkSwitchStacksOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetNetworkSwitchStacksParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getNetworkSwitchStacks\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/networks/{networkId}/switchStacks\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetNetworkSwitchStacksReader{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.(*GetNetworkSwitchStacksOK)\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 getNetworkSwitchStacks: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (c *CloudFormationTemplate) CreateStack(suffix string) {\n\tfmt.Printf(\"\\nRunning CloudFormation stack [%s]\", c.Name)\n\tsess := session.Must(session.NewSession(&aws.Config{\n\t\tRegion: aws.String(\"us-west-2\"),\n\t}))\n\tsvc := cloudformation.New(sess)\n\n\ttemplateBody := string(c.Bytes)\n\tc.StackName = c.Name + \"-\" + suffix\n\tcloudFormationValues := make(map[string]string)\n\n\tcreateStackParams := &cloudformation.CreateStackInput{\n\t\tStackName: aws.String(c.StackName),\n\t\tTemplateBody: aws.String(templateBody),\n\t}\n\n\tdescribeStacksParams := &cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(c.StackName),\n\t}\n\n\tout, err := svc.CreateStack(createStackParams)\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"AlreadyExistsException\") {\n\t\t\tfmt.Printf(\"\\nCloudFormation stack [%s] already exists. Skipping...\", c.Name)\n\t\t\tdescOut, err := svc.DescribeStacks(describeStacksParams)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tc.ParseOutput(descOut, cloudFormationValues)\n\t\t\treturn\n\t\t} else {\n\t\t\tfmt.Printf(\"%s\", err)\n\t\t\tpanic(err)\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"%s\", out)\n\t}\n\n\tstackReady := false\n\n\tfor stackReady != true {\n\n\t\tdescOut, err := svc.DescribeStacks(describeStacksParams)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%s\", err)\n\t\t\tpanic(err)\n\t\t} else {\n\t\t\tfmt.Printf(\"\\nCloudFormation stack [%s] is creating...\", c.Name)\n\t\t}\n\n\t\tif *descOut.Stacks[0].StackStatus == \"CREATE_COMPLETE\" {\n\t\t\tstackReady = true\n\t\t\tfmt.Printf(\"\\nCloudFormation stack [%s] ready...\\n\", c.Name)\n\t\t\tc.ParseOutput(descOut, cloudFormationValues)\n\t\t}\n\n\t\ttime.Sleep(time.Second * 7)\n\t}\n\n}", "func (o ChangeSetOutput) StackId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ChangeSet) pulumi.StringOutput { return v.StackId }).(pulumi.StringOutput)\n}", "func UpdateStack(r string, currentStack *cloudformation.Stack,\n\turi string, name string, params []*cloudformation.Parameter,\n\tcapabilities []*string) {\n\tsvc := cloudformation.New(getSession(r))\n\tlog.Info(\"UpdateStack\")\n\n\tgetUpdatedParameters(&currentStack.Parameters, params)\n\ttemplate := cloudformation.UpdateStackInput{\n\t\tStackName: &name,\n\t\tParameters: currentStack.Parameters,\n\t\tCapabilities: capabilities,\n\t}\n\n\tif pass, path := parseURI(uri); pass {\n\t\ttemplateBody := utils.LoadTemplate(path)\n\t\ttemplate.TemplateBody = &templateBody\n\t} else {\n\t\ttemplate.TemplateURL = &path\n\t}\n\n\tstack, err := svc.UpdateStack(&template)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Print(\"%v\", stack)\n}", "func NewCfnStack(scope constructs.Construct, id *string, props *CfnStackProps) CfnStack {\n\t_init_.Initialize()\n\n\tj := jsiiProxy_CfnStack{}\n\n\t_jsii_.Create(\n\t\t\"aws-cdk-lib.aws_cloudformation.CfnStack\",\n\t\t[]interface{}{scope, id, props},\n\t\t&j,\n\t)\n\n\treturn &j\n}", "func GetStackInfo(stackDepth int) (string, string, string) {\n\tresultFile := \"?\"\n\tresultFunc := \"?()\"\n\tresultLine := \"0\"\n\n\tif pc, file, line, ok := runtime.Caller(stackDepth + 1); ok {\n\t\tresultFile = filepath.Base(file)\n\t\tresultLine = Int(line)\n\t\tif fn := runtime.FuncForPC(pc); fn != nil {\n\t\t\tdotName := filepath.Ext(fn.Name())\n\t\t\tresultFunc = strings.TrimLeft(dotName, \".\") + \"()\"\n\t\t}\n\t}\n\treturn resultFile, resultFunc, resultLine\n}", "func (e *Ex) Stack() StackTrace {\n\treturn e.stack\n}", "func (ge *GenericError) StackToString() string {\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"StackTrace:\\n\")\n\tfor i, v := range ge.Stack {\n\t\tsep := fmt.Sprintf(\"ST%d: \", i)\n\t\tbuffer.WriteString(sep + v.String() + \"\\n\")\n\t}\n\treturn buffer.String()\n}", "func (es *ErrorStack) Stack() string {\n\tstack := \"\"\n\tif es.Inner != nil {\n\t\tif s, ok := es.Inner.(stackable); ok {\n\t\t\tstack = s.Stack()\n\t\t} else {\n\t\t\tstack = es.Inner.Error() + \"\\n\"\n\t\t}\n\t}\n\treturn stack + es.format() + \"\\n\"\n}", "func NewCfnStack(scope awscdk.Construct, id *string, props *CfnStackProps) CfnStack {\n\t_init_.Initialize()\n\n\tj := jsiiProxy_CfnStack{}\n\n\t_jsii_.Create(\n\t\t\"monocdk.aws_opsworks.CfnStack\",\n\t\t[]interface{}{scope, id, props},\n\t\t&j,\n\t)\n\n\treturn &j\n}", "func stackExists(stackNameOrID string, cf *cloudformation.CloudFormation, logger *logrus.Logger) (bool, error) {\n\tdescribeStacksInput := &cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(stackNameOrID),\n\t}\n\tdescribeStacksOutput, err := cf.DescribeStacks(describeStacksInput)\n\tlogger.Debug(\"DescribeStackOutput: \", describeStacksOutput)\n\texists := false\n\tif err != nil {\n\t\tlogger.Info(\"DescribeStackOutputError: \", err)\n\t\t// If the stack doesn't exist, then no worries\n\t\tif strings.Contains(err.Error(), \"does not exist\") {\n\t\t\texists = false\n\t\t} else {\n\t\t\treturn false, err\n\t\t}\n\t} else {\n\t\texists = true\n\t}\n\treturn exists, nil\n}", "func (y *YogClient) CreateStack(request CreateStackRequest) (CreateStackResponse, YogError) {\n\tcsi, err := parseTemplate(request.TemplateBody)\n\tif err != nil {\n\t\tye := YogError{\n\t\t\tCode: FailedToParseYaml,\n\t\t\tMessage: \"error while parsing template\",\n\t\t\tError: err,\n\t\t\tDropletErrors: []DropletError{},\n\t\t\tStackname: request.StackName,\n\t\t}\n\t\treturn CreateStackResponse{}, ye\n\t}\n\n\tresponse := CreateStackResponse{Name: request.StackName}\n\tbuiltResources := []Resource{}\n\tfor k, v := range csi.Resources {\n\t\tvar s Service\n\t\tif _, ok := v[\"Type\"]; !ok {\n\t\t\tmessage := fmt.Sprintf(\"no 'Type' provided for resource '%s'\", k)\n\t\t\tye := YogError{\n\t\t\t\tCode: NoTypeForResource,\n\t\t\t\tMessage: message,\n\t\t\t\tError: errors.New(message),\n\t\t\t\tDropletErrors: []DropletError{},\n\t\t\t\tStackname: request.StackName,\n\t\t\t}\n\t\t\treturn CreateStackResponse{}, ye\n\t\t}\n\t\td, err := buildResource(s.Service(v[\"Type\"].(string)))\n\t\t// Droplet doesn't yet have an ID. This will be updated once they are created.\n\t\tif err != nil {\n\t\t\tye := YogError{\n\t\t\t\tCode: UnknownResourceType,\n\t\t\t\tMessage: \"\",\n\t\t\t\tError: err,\n\t\t\t\tDropletErrors: []DropletError{},\n\t\t\t\tStackname: request.StackName,\n\t\t\t}\n\t\t\treturn CreateStackResponse{}, ye\n\t\t}\n\t\terr = d.buildRequest(request.StackName, v)\n\t\tif err != nil {\n\t\t\tye := YogError{\n\t\t\t\tCode: FailedToBuildRequest,\n\t\t\t\tMessage: \"\",\n\t\t\t\tError: err,\n\t\t\t\tDropletErrors: []DropletError{},\n\t\t\t\tStackname: request.StackName,\n\t\t\t}\n\t\t\treturn CreateStackResponse{}, ye\n\t\t}\n\t\tbuiltResources = append(builtResources, d)\n\t}\n\n\tde := y.launchAllDroplets(builtResources)\n\tif len(de) != 0 {\n\t\tye := YogError{\n\t\t\tCode: ErrorLaunchingDroplets,\n\t\t\tStackname: request.StackName,\n\t\t\tError: errors.New(\"error launching droplets. please see DropletErrors for more detail\"),\n\t\t\tMessage: \"\",\n\t\t\tDropletErrors: de,\n\t\t}\n\t\treturn CreateStackResponse{}, ye\n\t}\n\terr = y.setupDropletIDsForResources(builtResources)\n\tif err != nil {\n\t\tye := YogError{\n\t\t\tCode: ErrorSettingUpDropletIDSForResources,\n\t\t\tStackname: request.StackName,\n\t\t\tError: err,\n\t\t\tMessage: \"error setting up droplet ids for resource\",\n\t\t\tDropletErrors: []DropletError{},\n\t\t}\n\t\treturn CreateStackResponse{}, ye\n\t}\n\terr = y.launchTheRestOfTheResources(builtResources)\n\tif err != nil {\n\t\tye := YogError{\n\t\t\tCode: ErrorLaunchingResource,\n\t\t\tStackname: request.StackName,\n\t\t\tError: err,\n\t\t\tMessage: \"error while trying to launch the rest of the resources\",\n\t\t\tDropletErrors: []DropletError{},\n\t\t}\n\t\treturn CreateStackResponse{}, ye\n\t}\n\n\tresponse.Resources = builtResources\n\t// Save resources here.\n\treturn response, YogError{}\n}", "func (a *StacksApiService) CreateStack(ctx _context.Context) apiCreateStackRequest {\n\treturn apiCreateStackRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (s *Cloudformation) StackName() string {\n\treturn helpers.StackName(s.config.ClusterName, \"s3bucket\", s.S3Bucket.Name, s.S3Bucket.Namespace)\n}", "func Stack(err error) CallStack {\n\tif withCode, ok := err.(Error); ok {\n\t\treturn withCode.stack\n\t}\n\n\treturn nil\n}", "func NewStack(cfnconn cloudformationiface.CloudFormationAPI, name string) (*Stack, error) {\n\tstack := &Stack{Name: name, cfnconn: cfnconn}\n\tif err := stack.updateOnce(); err != nil {\n\t\treturn nil, errors.Annotatef(err, \"cannot create new stack\")\n\t}\n\treturn stack, nil\n}", "func (m *MockCloudformationAPI) CreateStack(*cloudformation.CreateStackInput) (*cloudformation.CreateStackOutput, error) {\n\treturn &cloudformation.CreateStackOutput{}, nil\n}", "func Status(ctx context.Context,\n\tserviceName string,\n\tserviceDescription string,\n\tredact bool,\n\tlogger *zerolog.Logger) error {\n\n\tawsConfig, awsConfigErr := spartaAWS.NewConfig(ctx, logger)\n\tif awsConfigErr != nil {\n\t\treturn awsConfigErr\n\t}\n\tcfSvc := awsv2CF.NewFromConfig(awsConfig)\n\n\tparams := &awsv2CF.DescribeStacksInput{\n\t\tStackName: aws.String(serviceName),\n\t}\n\tdescribeStacksResponse, describeStacksResponseErr := cfSvc.DescribeStacks(ctx, params)\n\n\tif describeStacksResponseErr != nil {\n\t\tif strings.Contains(describeStacksResponseErr.Error(), \"does not exist\") {\n\t\t\tlogger.Info().Str(\"Region\", awsConfig.Region).Msg(\"Stack does not exist\")\n\t\t\treturn nil\n\t\t}\n\t\treturn describeStacksResponseErr\n\t}\n\tif len(describeStacksResponse.Stacks) > 1 {\n\t\treturn errors.Errorf(\"More than 1 stack returned for %s. Count: %d\",\n\t\t\tserviceName,\n\t\t\tlen(describeStacksResponse.Stacks))\n\t}\n\n\t// What's the current accountID?\n\tredactor := func(stringValue string) string {\n\t\treturn stringValue\n\t}\n\tif redact {\n\t\tinput := &awsv2STS.GetCallerIdentityInput{}\n\n\t\tstsSvc := awsv2STS.NewFromConfig(awsConfig)\n\t\tidentityResponse, identityResponseErr := stsSvc.GetCallerIdentity(ctx, input)\n\t\tif identityResponseErr != nil {\n\t\t\treturn identityResponseErr\n\t\t}\n\t\tredactedValue := strings.Repeat(\"*\", len(*identityResponse.Account))\n\t\tredactor = func(stringValue string) string {\n\t\t\treturn strings.Replace(stringValue,\n\t\t\t\t*identityResponse.Account,\n\t\t\t\tredactedValue,\n\t\t\t\t-1)\n\t\t}\n\t}\n\n\t// Report on what's up with the stack...\n\tlogSectionHeader(\"Stack Summary\", dividerLength, logger)\n\tstackInfo := describeStacksResponse.Stacks[0]\n\tlogger.Info().Str(\"Id\", redactor(*stackInfo.StackId)).Msg(\"StackId\")\n\tlogger.Info().Str(\"Description\", redactor(*stackInfo.Description)).Msg(\"Description\")\n\tlogger.Info().Str(\"State\", string(stackInfo.StackStatus)).Msg(\"Status\")\n\tif stackInfo.StackStatusReason != nil {\n\t\tlogger.Info().Str(\"Reason\", *stackInfo.StackStatusReason).Msg(\"Reason\")\n\t}\n\tlogger.Info().Str(\"Time\", stackInfo.CreationTime.UTC().String()).Msg(\"Created\")\n\tif stackInfo.LastUpdatedTime != nil {\n\t\tlogger.Info().Str(\"Time\", stackInfo.LastUpdatedTime.UTC().String()).Msg(\"Last Update\")\n\t}\n\tif stackInfo.DeletionTime != nil {\n\t\tlogger.Info().Str(\"Time\", stackInfo.DeletionTime.UTC().String()).Msg(\"Deleted\")\n\t}\n\n\tlogger.Info()\n\tif len(stackInfo.Parameters) != 0 {\n\t\tlogSectionHeader(\"Parameters\", dividerLength, logger)\n\t\tfor _, eachParam := range stackInfo.Parameters {\n\t\t\tlogger.Info().Str(\"Value\",\n\t\t\t\tredactor(*eachParam.ParameterValue)).Msg(*eachParam.ParameterKey)\n\t\t}\n\t\tlogger.Info().Msg(\"\")\n\t}\n\tif len(stackInfo.Tags) != 0 {\n\t\tlogSectionHeader(\"Tags\", dividerLength, logger)\n\t\tfor _, eachTag := range stackInfo.Tags {\n\t\t\tlogger.Info().Str(\"Value\",\n\t\t\t\tredactor(*eachTag.Value)).Msg(*eachTag.Key)\n\t\t}\n\t\tlogger.Info().Msg(\"\")\n\t}\n\tif len(stackInfo.Outputs) != 0 {\n\t\tlogSectionHeader(\"Outputs\", dividerLength, logger)\n\t\tfor _, eachOutput := range stackInfo.Outputs {\n\t\t\tstatement := logger.Info().Str(\"Value\",\n\t\t\t\tredactor(*eachOutput.OutputValue))\n\t\t\tif eachOutput.ExportName != nil {\n\t\t\t\tstatement.Str(\"ExportName\", *eachOutput.ExportName)\n\t\t\t}\n\t\t\tstatement.Msg(*eachOutput.OutputKey)\n\t\t}\n\t\tlogger.Info()\n\t}\n\treturn nil\n}", "func deleteStack(name string) error {\n\tfmt.Printf(\"DEBUG:: deleting stack %v\\n\", name)\n\tcfg, err := external.LoadDefaultAWSConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\tsvc := cloudformation.New(cfg)\n\tdsreq := svc.DeleteStackRequest(&cloudformation.DeleteStackInput{StackName: aws.String(name)})\n\t_, err = dsreq.Send(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func GetStacktracer(ctx context.Context) Stacktracer {\n\tout, _ := ctx.Value(stacktracerKey).(Stacktracer)\n\treturn out\n}", "func (m *MockCfnClient) GetStackTags(stackName string) (map[string]string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetStackTags\", stackName)\n\tret0, _ := ret[0].(map[string]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func Stack() string {\n\ttrace := make([]byte, 2048)\n\tcount := runtime.Stack(trace, false)\n\treturn fmt.Sprintf(\"\\nStack of %d bytes: %s\\n\", count, trace)\n}", "func (cf *Cloudformation) createStack() {\n\n\tcreateStack = &cobra.Command {\n\t\tUse: \"create-efs\",\n\t\tShort: \"Create stack\",\n\t\tLong: `Create stack based on template`,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\n\t\t\tparameters := make([]*cloudformation.Parameter, 0, 5)\n\n\t\t\tonFailure, err := cmd.Flags().GetString(\"onfailure\")\n\t\t\tverifyOnFailureArg(err, onFailure)\n\n\t\t\tcapabilities, err := cmd.Flags().GetStringArray(\"capabilities\")\n\t\t\tverifyCapability(err, capabilities)\n\n\t\t\tstackName, err := cmd.Flags().GetString(\"stackname\")\n\t\t\tverify(err, \"stackname\")\n\n\t\t\tinstanceType, err := cmd.Flags().GetString(\"instance-type\")\n\t\t\tverify(err, \"instance-type\")\n\t\t\taddParameter(&parameters, \"InstanceType\", instanceType)\n\n\t\t\tkeyPair, err := cmd.Flags().GetString(\"key-pair-name\")\n\t\t\tverify(err, \"key-pair-name\")\n\t\t\taddParameter(&parameters, \"KeyName\", keyPair)\n\n\t\t\tsubnets, err := cmd.Flags().GetStringArray(\"subnets\")\n\t\t\tverify(err, \"subnets\")\n\t\t\taddParameters(&parameters, \"Subnets\", subnets)\n\n\t\t\tvpc, err := cmd.Flags().GetString(\"vpc\")\n\t\t\tverify(err, \"vpc\")\n\t\t\taddParameter(&parameters, \"VPC\" ,vpc)\n\n\t\t\timage, err := cmd.Flags().GetString(\"image\")\n\t\t\tverify(err, \"image\")\n\t\t\taddParameter(&parameters, \"ImageId\", image)\n\n\t\t\tfor _, param := range parameters {\n\t\t\t\tfmt.Printf(\"----Param : %s ---- \\n\", param)\n\t\t\t}\n\n\t\t\tcfClient := cloudformation.New(cf.sess, cf.sess.Config)\n\n\t\t\tresp, err := cf.ec2Res.createKeyPair(keyPair)\n\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Create key pair err: %s \\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\n\t\t\tcreatePemFile(resp.KeyMaterial)\n\n\t\t\tfile := readFile(\"templates/distributed_file_system.yaml\")\n\n\t\t\tif _, err := cfClient.CreateStack(&cloudformation.CreateStackInput{\n\t\t\t\tCapabilities: aws.StringSlice(capabilities),\n\t\t\t\tClientRequestToken: nil,\n\t\t\t\tDisableRollback: nil,\n\t\t\t\tEnableTerminationProtection: nil,\n\t\t\t\tNotificationARNs: nil,\n\t\t\t\tOnFailure: &onFailure,\n\t\t\t\tParameters: parameters,\n\t\t\t\tResourceTypes: nil,\n\t\t\t\tRoleARN: nil,\n\t\t\t\tRollbackConfiguration: nil,\n\t\t\t\tStackName: &stackName,\n\t\t\t\tStackPolicyBody: nil,\n\t\t\t\tStackPolicyURL: nil,\n\t\t\t\tTags: nil,\n\t\t\t\tTemplateBody: &file,\n\t\t\t\tTemplateURL: nil,\n\t\t\t\tTimeoutInMinutes: nil,\n\t\t\t}); err != nil {\n\t\t\t\tdeleteKeyPair(cf, keyPair, err)\n\t\t\t}\n\n\t\t},\n\t}\n}", "func Stack(skip ...int) string {\n\tnumber := 1\n\tif len(skip) > 0 {\n\t\tnumber = skip[0] + 1\n\t}\n\treturn debug.Stack(number)\n}", "func (s *Spike) Stack() (sp uint64, stack []byte, err error) {\n\tsp = s.Reg[SP]\n\tfor addr := sp; ; addr += 8 {\n\t\tv, err := s.Memory(addr)\n\t\tif IsInvlidAddr(err) {\n\t\t\treturn sp, stack, nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn 0, nil, fmt.Errorf(\"can't read Spike stack: %#v\", err)\n\t\t}\n\t\tstack = append(stack, byte(v), byte(v>>8), byte(v>>16), byte(v>>24), byte(v>>32), byte(v>>40), byte(v>>48), byte(v>>56))\n\t}\n}", "func (c *client) Stacks() ([]string, error) {\n\tcfg, err := c.fetchConfig()\n\tif err != nil || cfg == nil {\n\t\treturn nil, err\n\t}\n\n\tvar stack struct {\n\t\tStack struct {\n\t\t\tRunImage struct {\n\t\t\t\tImage string `json:\"image\"`\n\t\t\t} `json:\"runImage\"`\n\t\t} `json:\"stack\"`\n\t}\n\n\tif err := json.NewDecoder(strings.NewReader(cfg.Config.Labels[metadataLabel])).Decode(&stack); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn []string{stack.Stack.RunImage.Image}, nil\n}", "func (err StackTraceError) Stack() []byte {\n\tbuf := bytes.Buffer{}\n\n\tfor _, frame := range err.StackFrames() {\n\t\tbuf.WriteString(frame.String())\n\t}\n\n\treturn buf.Bytes()\n}", "func (e *detailedError) Stack() []uintptr {\n\treturn e.stack\n}", "func CreateStack(ctx context.Context, svc *cf.CloudFormation, opts *RequestOptions, timeout int64) (*cf.CreateStackOutput, error) {\n\tinput := &cf.CreateStackInput{\n\t\tStackName: aws.String(opts.StackName),\n\t\tCapabilities: []*string{\n\t\t\taws.String(\"CAPABILITY_IAM\"),\n\t\t},\n\t\tOnFailure: aws.String(opts.OnFailure),\n\t\tParameters: toParameters(opts.Params),\n\t\tTemplateURL: aws.String(opts.TemplateURL),\n\t\tTimeoutInMinutes: aws.Int64(timeout),\n\t}\n\n\treturn svc.CreateStackWithContext(ctx, input)\n}", "func stackEvents(stackID string, cfService *cloudformation.CloudFormation) ([]*cloudformation.StackEvent, error) {\n\tvar events []*cloudformation.StackEvent\n\n\tnextToken := \"\"\n\tfor {\n\t\tparams := &cloudformation.DescribeStackEventsInput{\n\t\t\tStackName: aws.String(stackID),\n\t\t}\n\t\tif len(nextToken) > 0 {\n\t\t\tparams.NextToken = aws.String(nextToken)\n\t\t}\n\n\t\tresp, err := cfService.DescribeStackEvents(params)\n\t\tif nil != err {\n\t\t\treturn nil, err\n\t\t}\n\t\tevents = append(events, resp.StackEvents...)\n\t\tif nil == resp.NextToken {\n\t\t\tbreak\n\t\t} else {\n\t\t\tnextToken = *resp.NextToken\n\t\t}\n\t}\n\treturn events, nil\n}", "func (c *CloudFormation) CreateStack(input *cfn.CreateStackInput) (*Stack, error) {\n\tresp, err := c.srv.CreateStack(input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.Stack(*resp.StackId)\n}", "func (s *IntStack) Get(n int) int{\n\treturn s.stack[n]\n}", "func (p *Chip) popStack() uint8 {\n\tp.S++\n\treturn p.ram.Read(0x0100 + uint16(p.S))\n}", "func Get() *Stacktrace {\n\tstacktrace := &Stacktrace{}\n\tpc := make([]uintptr, FrameCap)\n\tn := runtime.Callers(1, pc)\n\tif n == 0 {\n\t\treturn stacktrace\n\t}\n\n\tpc = pc[:n]\n\tframes := runtime.CallersFrames(pc)\n\n\tvar skipFile, skipPkg string\n\tfor {\n\t\tframe, more := frames.Next()\n\t\tpkg := strings.Split(filepath.Base(frame.Func.Name()), \".\")[0]\n\n\t\t// Skip our own path\n\t\tif skipFile == \"\" {\n\t\t\tskipFile = filepath.Dir(frame.File)\n\t\t\tskipPkg = pkg\n\t\t}\n\t\tif strings.Contains(frame.File, skipFile) && pkg == skipPkg {\n\t\t\tcontinue\n\t\t}\n\n\t\tstacktrace.Frames = append(stacktrace.Frames, Frame{\n\t\t\tFunc: frame.Func.Name(),\n\t\t\tLine: frame.Line,\n\t\t\tPath: frame.File,\n\t\t\tPackage: pkg,\n\t\t})\n\n\t\tif !more {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn stacktrace\n}", "func (cs CallStack) String() string {\n\treturn fmt.Sprint(cs)\n}", "func (s *Cloudformation) DeleteStack() (err error) {\n\tsess := s.config.AWSSession\n\tsvc := cloudformation.New(sess)\n\n\tstackInputs := cloudformation.DeleteStackInput{}\n\tstackInputs.SetStackName(s.StackName())\n\n\t_, err = svc.DeleteStack(&stackInputs)\n\treturn\n}", "func UpdateStack(ctx context.Context, svc *cf.CloudFormation, opts *RequestOptions) (*cf.UpdateStackOutput, error) {\n\tinput := &cf.UpdateStackInput{\n\t\tStackName: aws.String(opts.StackName),\n\t\tCapabilities: []*string{\n\t\t\taws.String(\"CAPABILITY_IAM\"),\n\t\t},\n\t\tParameters: toParameters(opts.Params),\n\t\tTemplateURL: aws.String(opts.TemplateURL),\n\t}\n\n\treturn svc.UpdateStackWithContext(ctx, input)\n}", "func (client *BuildServiceClient) listSupportedStacksCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, options *BuildServiceClientListSupportedStacksOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/supportedStacks\"\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\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 serviceName == \"\" {\n\t\treturn nil, errors.New(\"parameter serviceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{serviceName}\", url.PathEscape(serviceName))\n\tif buildServiceName == \"\" {\n\t\treturn nil, errors.New(\"parameter buildServiceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{buildServiceName}\", url.PathEscape(buildServiceName))\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-01-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func LoadStack(name string, cfg composetypes.Config) (*apiv1beta1.Stack, error) {\n\tres, err := yaml.Marshal(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &apiv1beta1.Stack{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t},\n\t\tSpec: apiv1beta1.StackSpec{\n\t\t\tComposeFile: string(res),\n\t\t},\n\t}, nil\n}", "func ShowStack(err error) string {\n\treturn NewErr(err, 1).(*Error).ErrorWithStack()\n}", "func (f *FakeReconcilerClient) CreateStack(stackSpec types.StackSpec) (types.StackCreateResponse, error) {\n\tif stackSpec.Annotations.Name == \"\" {\n\t\treturn types.StackCreateResponse{}, fmt.Errorf(\"StackSpec contains no name\")\n\t}\n\n\tid, err := f.FakeStackStore.AddStack(stackSpec)\n\tif err != nil {\n\t\treturn types.StackCreateResponse{}, fmt.Errorf(\"unable to store stack: %s\", err)\n\t}\n\n\treturn types.StackCreateResponse{\n\t\tID: id,\n\t}, err\n}", "func (m *MockCfnClient) GetStackInfo(stackName string) (cfn.StackInfo, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetStackInfo\", stackName)\n\tret0, _ := ret[0].(cfn.StackInfo)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}" ]
[ "0.8298661", "0.72698605", "0.7154262", "0.6917696", "0.66157544", "0.6453903", "0.6377056", "0.6247309", "0.61395586", "0.60342014", "0.59907895", "0.5941389", "0.58851993", "0.584781", "0.5842104", "0.58073467", "0.580492", "0.5800194", "0.57823026", "0.571775", "0.5689168", "0.56700355", "0.5651942", "0.56472284", "0.5642756", "0.56276846", "0.5625189", "0.560323", "0.5578819", "0.55786216", "0.55272794", "0.54981166", "0.546801", "0.54265815", "0.54213595", "0.54110813", "0.5382846", "0.5378098", "0.5378098", "0.5373668", "0.53600454", "0.5323117", "0.52948964", "0.5290488", "0.52888715", "0.52880186", "0.52879643", "0.52743655", "0.52582866", "0.52490634", "0.522642", "0.52213836", "0.5220995", "0.5194187", "0.51844716", "0.5177552", "0.5163107", "0.5160713", "0.51383847", "0.5128374", "0.51250947", "0.50961226", "0.5093819", "0.50723267", "0.50671774", "0.50572366", "0.50546247", "0.50543547", "0.5050364", "0.5046265", "0.5044015", "0.50384974", "0.50364286", "0.5030729", "0.5011995", "0.50100803", "0.49836487", "0.49777222", "0.49699983", "0.49620938", "0.49572152", "0.49565715", "0.4943602", "0.49345887", "0.4931869", "0.4903794", "0.4902176", "0.48972532", "0.4892269", "0.4882413", "0.48789424", "0.48763183", "0.48670706", "0.48659864", "0.48553905", "0.4848202", "0.48419434", "0.48414505", "0.48345038", "0.48268867" ]
0.7326961
1
MarkToDeleteStack adds a "deleteScheduled" Tag to the CloudFormation stack with the given name
func (a *Adapter) MarkToDeleteStack(stack *Stack) (time.Time, error) { t0 := time.Now().Add(a.stackTTL) return t0, markToDeleteStack(a.cloudformation, a.stackName(stack.CertificateARN()), t0.Format(time.RFC3339)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func deleteStack(name string) error {\n\tfmt.Printf(\"DEBUG:: deleting stack %v\\n\", name)\n\tcfg, err := external.LoadDefaultAWSConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\tsvc := cloudformation.New(cfg)\n\tdsreq := svc.DeleteStackRequest(&cloudformation.DeleteStackInput{StackName: aws.String(name)})\n\t_, err = dsreq.Send(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func DeleteStack(stackName, profile, region string) {\n\tcf := GetCloudformationClient(profile, region)\n\tprinter.Step(fmt.Sprintf(\"Delete Stack %s:\", stackName))\n\n\t//See if the stack exists to begin with\n\t_, err := cf.DescribeStacks(&cloudformation.DescribeStacksInput{StackName: aws.String(stackName)})\n\tcheckError(err)\n\n\t_, err = cf.DeleteStack(&cloudformation.DeleteStackInput{StackName: aws.String(stackName)})\n\tcheckError(err)\n\n\t// status polling\n\tPrintStackEventHeader()\n\n\tfor {\n\t\tprinter.Progress(\"Deleting\")\n\t\ttime.Sleep(2 * time.Second)\n\t\tstatus, err := cf.DescribeStacks(&cloudformation.DescribeStacksInput{StackName: aws.String(stackName)})\n\t\tcheckErrorDeletePoll(err)\n\n\t\tevents, _ := cf.DescribeStackEvents(&cloudformation.DescribeStackEventsInput{StackName: aws.String(stackName)})\n\n\t\tif len(status.Stacks) > 0 {\n\t\t\tstackStatus := *status.Stacks[0].StackStatus\n\n\t\t\tif len(events.StackEvents) > 0 {\n\t\t\t\tPrintStackEvent(events.StackEvents[0], false)\n\t\t\t}\n\t\t\tif stackStatus == cloudformation.StackStatusDeleteInProgress {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tbreak\n\t}\n\n\t// Make sure delete worked\n\t_, err = cf.DescribeStacks(&cloudformation.DescribeStacksInput{StackName: aws.String(stackName)})\n\tif err != nil {\n\t\tcheckErrorDeletePoll(err)\n\t} else {\n\t\tprinter.SubStep(\n\t\t\tfmt.Sprintf(\"Success Delete Stack %s\", stackName),\n\t\t\t1,\n\t\t\ttrue,\n\t\t\ttrue,\n\t\t)\n\t\tos.Exit(0)\n\t}\n}", "func Delete(ctx context.Context, serviceName string, logger *zerolog.Logger) error {\n\tawsConfig, awsConfigErr := spartaAWS.NewConfig(ctx, logger)\n\tif awsConfigErr != nil {\n\t\treturn awsConfigErr\n\t}\n\tawsCloudFormation := awsv2CF.NewFromConfig(awsConfig)\n\n\texists, err := spartaCF.StackExists(ctx, serviceName, awsConfig, logger)\n\tif nil != err {\n\t\treturn err\n\t}\n\tlogger.Info().\n\t\tBool(\"Exists\", exists).\n\t\tStr(\"Name\", serviceName).\n\t\tMsg(\"Stack existence check\")\n\n\tif exists {\n\n\t\tparams := &awsv2CF.DeleteStackInput{\n\t\t\tStackName: awsv2.String(serviceName),\n\t\t}\n\t\tresp, err := awsCloudFormation.DeleteStack(ctx, params)\n\t\tif nil != resp {\n\t\t\tlogger.Info().\n\t\t\t\tInterface(\"Response\", resp).\n\t\t\t\tMsg(\"Delete request submitted\")\n\t\t}\n\t\treturn err\n\t}\n\tlogger.Info().Msg(\"Stack does not exist\")\n\treturn nil\n}", "func (s *Cloudformation) DeleteStack() (err error) {\n\tsess := s.config.AWSSession\n\tsvc := cloudformation.New(sess)\n\n\tstackInputs := cloudformation.DeleteStackInput{}\n\tstackInputs.SetStackName(s.StackName())\n\n\t_, err = svc.DeleteStack(&stackInputs)\n\treturn\n}", "func (a *Adapter) DeleteStack(stack *Stack) error {\n\tif err := detachTargetGroupFromAutoScalingGroup(a.autoscaling, stack.TargetGroupARN(), a.AutoScalingGroupName()); err != nil {\n\t\treturn fmt.Errorf(\"DeleteStack failed to detach: %v\", err)\n\t}\n\n\treturn deleteStack(a.cloudformation, stack.Name())\n}", "func (c *Client) DeleteStack(stackSlug string) error {\n\treturn c.request(\"DELETE\", fmt.Sprintf(\"/api/instances/%s\", stackSlug), nil, nil, nil)\n}", "func Delete(c *cli.Context) {\n\tprinter.Progress(\"Kombusting\")\n\n\tfileName := c.Args().Get(0)\n\tif fileName == \"\" {\n\t\tprinter.Fatal(\n\t\t\tfmt.Errorf(\"Can't upsert file, no source template provided\"),\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"Add the path to the source template file you want to generate like: `kombustion upsert template.yaml`.\",\n\t\t\t),\n\t\t\t\"https://www.kombustion.io/api/manifest/\",\n\t\t)\n\t}\n\n\tmanifestFile := manifest.FindAndLoadManifest()\n\n\tenvironment := c.String(\"environment\")\n\n\tstackName := cloudformation.GetStackName(manifestFile, fileName, environment, c.String(\"stack-name\"))\n\n\tregion := c.String(\"region\")\n\tif region == \"\" {\n\t\t// If no region was provided by the cli flag, check for the default in the manifest\n\t\tif manifestFile.Region != \"\" {\n\t\t\tregion = manifestFile.Region\n\t\t}\n\t}\n\n\ttasks.DeleteStack(\n\t\tstackName,\n\t\tc.GlobalString(\"profile\"),\n\t\tregion,\n\t)\n}", "func (y *YogClient) DeleteStack(request DeleteStackRequest) (DeleteStackResponse, YogError) {\n\tret := DeleteStackResponse{}\n\n\treturn ret, YogError{}\n}", "func (s *Server) MarkForDeletion(ctx context.Context, now func() time.Time) error {\n\tmarkTimeSeconds := fmt.Sprint(now().Unix())\n\n\t// Get all brokers from ZK.\n\tbrokers, errs := s.ZK.GetAllBrokerMeta(false)\n\tif errs != nil {\n\t\treturn ErrFetchingBrokers\n\t}\n\n\t// Lock.\n\tif err := s.Locking.Lock(ctx); err != nil {\n\t\treturn err\n\t}\n\tdefer s.Locking.UnlockLogError(ctx)\n\n\t// Get all topics from ZK\n\ttopics, err := s.ZK.GetTopics([]*regexp.Regexp{topicRegex})\n\ttopicSet := TopicSetFromSlice(topics)\n\tif err != nil {\n\t\treturn ErrFetchingTopics\n\t}\n\n\t// Get all tag sets.\n\tallTags, err := s.Tags.Store.GetAllTags()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Add a marker tag with timestamp to any dangling tagset whose associated kafka\n\t// resource no longer exists.\n\tfor kafkaObject, tagSet := range allTags {\n\t\tvar objectExists bool\n\n\t\t// Check whether the object currently exists.\n\t\tswitch kafkaObject.Type {\n\t\tcase \"broker\":\n\t\t\tbrokerId, err := strconv.Atoi(kafkaObject.ID)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"found non int broker ID %s in tag cleanup\\n\", kafkaObject.ID)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t_, objectExists = brokers[brokerId]\n\t\tcase \"topic\":\n\t\t\t_, objectExists = topicSet[kafkaObject.ID]\n\t\t}\n\n\t\t// Check if the object has already been marked.\n\t\t_, marked := tagSet[TagMarkTimeKey]\n\n\t\t// If the object doesn't exist and hasn't already been marked, do so.\n\t\tif !objectExists && !marked {\n\t\t\tlog.Printf(\"marking %s:%s for cleanup\\n\", kafkaObject.Type, kafkaObject.ID)\n\t\t\ttagSet[TagMarkTimeKey] = markTimeSeconds\n\t\t\tif err := s.Tags.Store.SetTags(kafkaObject, tagSet); err != nil {\n\t\t\t\tlog.Printf(\"failed to update TagSet for %s %s: %s\\n\", kafkaObject.Type, kafkaObject.ID, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// If the object exists but has been marked, remove the mark.\n\t\tif objectExists && marked {\n\t\t\tlog.Printf(\"unmarking existing %s:%s to avoid cleanup\\n\", kafkaObject.Type, kafkaObject.ID)\n\t\t\tif err := s.Tags.Store.DeleteTags(kafkaObject, []string{TagMarkTimeKey}); err != nil {\n\t\t\t\tlog.Printf(\"failed to remove %s tag for %s %s: %s\\n\", TagMarkTimeKey, kafkaObject.Type, kafkaObject.ID, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t}\n\n\treturn nil\n}", "func (d *Double) Delete(stackName string) error {\n\treturn d.DeleteFn(stackName)\n}", "func (c *StackCollection) DeleteStackSync(ctx context.Context, s *Stack) error {\n\ti, err := c.DeleteStackBySpec(ctx, s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogger.Info(\"waiting for stack %q to get deleted\", *i.StackName)\n\treturn c.doWaitUntilStackIsDeleted(ctx, s)\n}", "func (m *MockCloudformationAPI) DeleteStack(*cloudformation.DeleteStackInput) (*cloudformation.DeleteStackOutput, error) {\n\treturn &cloudformation.DeleteStackOutput{}, nil\n}", "func (s *Cloudformation) WaitUntilStackDeleted() (err error) {\n\tsess := s.config.AWSSession\n\tsvc := cloudformation.New(sess)\n\n\tstackInputs := cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(s.StackName()),\n\t}\n\n\terr = svc.WaitUntilStackDeleteComplete(&stackInputs)\n\treturn\n}", "func (c *StackCollection) DeleteTasksForDeprecatedStacks() (*tasks.TaskTree, error) {\n\tstacks, err := c.ListStacksMatching(fmtDeprecatedStacksRegexForCluster(c.spec.Metadata.Name))\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"describing deprecated CloudFormation stacks for %q\", c.spec.Metadata.Name)\n\t}\n\tif len(stacks) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tdeleteControlPlaneTask := &tasks.TaskWithoutParams{\n\t\tInfo: fmt.Sprintf(\"delete control plane %q\", c.spec.Metadata.Name),\n\t\tCall: func(errs chan error) error {\n\t\t\t_, err := c.eksAPI.DescribeCluster(&eks.DescribeClusterInput{\n\t\t\t\tName: &c.spec.Metadata.Name,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t_, err = c.eksAPI.DeleteCluster(&eks.DeleteClusterInput{\n\t\t\t\tName: &c.spec.Metadata.Name,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tnewRequest := func() *request.Request {\n\t\t\t\tinput := &eks.DescribeClusterInput{\n\t\t\t\t\tName: &c.spec.Metadata.Name,\n\t\t\t\t}\n\t\t\t\treq, _ := c.eksAPI.DescribeClusterRequest(input)\n\t\t\t\treturn req\n\t\t\t}\n\n\t\t\tmsg := fmt.Sprintf(\"waiting for control plane %q to be deleted\", c.spec.Metadata.Name)\n\n\t\t\tacceptors := waiters.MakeAcceptors(\n\t\t\t\t\"Cluster.Status\",\n\t\t\t\teks.ClusterStatusDeleting,\n\t\t\t\t[]string{\n\t\t\t\t\teks.ClusterStatusFailed,\n\t\t\t\t},\n\t\t\t)\n\n\t\t\treturn waiters.Wait(c.spec.Metadata.Name, msg, acceptors, newRequest, c.waitTimeout, nil)\n\t\t},\n\t}\n\n\tcpStackFound := false\n\tfor _, s := range stacks {\n\t\tif strings.HasSuffix(*s.StackName, \"-ControlPlane\") {\n\t\t\tcpStackFound = true\n\t\t}\n\t}\n\ttaskTree := &tasks.TaskTree{}\n\n\tfor _, suffix := range deprecatedStackSuffices() {\n\t\tfor _, s := range stacks {\n\t\t\tif strings.HasSuffix(*s.StackName, \"-\"+suffix) {\n\t\t\t\tif suffix == \"-ControlPlane\" && !cpStackFound {\n\t\t\t\t\ttaskTree.Append(deleteControlPlaneTask)\n\t\t\t\t} else {\n\t\t\t\t\ttaskTree.Append(&taskWithStackSpec{\n\t\t\t\t\t\tstack: s,\n\t\t\t\t\t\tcall: c.DeleteStackBySpecSync,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn taskTree, nil\n}", "func (mr *MockProviderClientMockRecorder) DeleteCloudformationStack(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteCloudformationStack\", reflect.TypeOf((*MockProviderClient)(nil).DeleteCloudformationStack), arg0, arg1, arg2)\n}", "func (o *deleteEnvOpts) deleteStack() bool {\n\to.prog.Start(fmt.Sprintf(fmtDeleteEnvStart, o.EnvName, o.ProjectName()))\n\tif err := o.deployClient.DeleteEnvironment(o.ProjectName(), o.EnvName); err != nil {\n\t\to.prog.Stop(fmt.Sprintf(fmtDeleteEnvFailed, o.EnvName, o.ProjectName(), err))\n\t\treturn false\n\t}\n\to.prog.Stop(fmt.Sprintf(fmtDeleteEnvComplete, o.EnvName, o.ProjectName()))\n\treturn true\n}", "func (cf *Cloudformation) deleteEFS() {\n\n\tdeleteStack = &cobra.Command {\n\t\tUse: \"delete-efs\",\n\t\tShort: \"Delete stack\",\n\t\tLong: `Delete efs stack resources`,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\n\t\t\tstackName, err := cmd.Flags().GetString(\"stackname\")\n\t\t\tverify(err, \"stackname\")\n\n\t\t\tkeyPair, err := cmd.Flags().GetString(\"key-pair-name\")\n\t\t\tverify(err, \"key-pair-name\")\n\n\t\t\tcfClient := cloudformation.New(cf.sess, cf.sess.Config)\n\n\t\t\tif _, err := cfClient.DeleteStack(&cloudformation.DeleteStackInput{\n\t\t\t\tClientRequestToken: nil,\n\t\t\t\tRetainResources: nil,\n\t\t\t\tRoleARN: nil,\n\t\t\t\tStackName: &stackName,\n\t\t\t}); err != nil {\n\t\t\t\tfmt.Printf(\"Stack failed to delete with err: %s \\n\", err)\n\t\t\t}\n\n\t\t\tdeleteKeyPair(cf, keyPair, err)\n\n\t\t\tdeletePemFile()\n\n\t\t},\n\t}\n}", "func (r *Client) Destroy(ctx context.Context, stack Stack) error {\n\t// always update stack status\n\tdefer r.updateStatus(stack)\n\t// fetch current state\n\tstate, err := r.get(ctx, stack)\n\tif err == ErrStackNotFound {\n\t\t// resource is already deleted (or never existsed)\n\t\t// so we're done here\n\t\treturn nil\n\t} else if err != nil {\n\t\t// failed to get stack status\n\t\treturn err\n\t}\n\tif *state.StackStatus == DeleteComplete {\n\t\t// resource already deleted\n\t\treturn nil\n\t}\n\t// trigger a delete unless we're already in a deleting state\n\tif *state.StackStatus != DeleteInProgress {\n\t\t_, err := r.Client.DeleteStackWithContext(ctx, &DeleteStackInput{\n\t\t\tStackName: aws.String(stack.GetStackName()),\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t_, err = r.waitUntilDestroyedState(ctx, stack)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (mr *MockCfnClientMockRecorder) DeleteStack(stackId interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteStack\", reflect.TypeOf((*MockCfnClient)(nil).DeleteStack), stackId)\n}", "func Delete(c *cli.Context) {\n\tobjectStore := core.NewFilesystemStore(\".\")\n\n\tfileName := c.Args().Get(0)\n\tif fileName == \"\" {\n\t\tprinter.Fatal(\n\t\t\tfmt.Errorf(\"Can't upsert file, no source template provided\"),\n\t\t\t\"Add the path to the source template file you want to generate like: `kombustion upsert template.yaml`.\",\n\t\t\t\"https://www.kombustion.io/api/manifest/\",\n\t\t)\n\t}\n\n\tclient := &cloudformation.Wrapper{}\n\tprofile := c.GlobalString(\"profile\")\n\tregion := c.String(\"region\")\n\tenvName := c.String(\"environment\")\n\tstackName := c.String(\"stack-name\")\n\tmanifestFile := c.GlobalString(\"manifest-file\")\n\n\ttaskDelete(\n\t\tclient,\n\t\tobjectStore,\n\t\tfileName,\n\t\tprofile,\n\t\tstackName,\n\t\tregion,\n\t\tenvName,\n\t\tmanifestFile,\n\t)\n}", "func markEnvironmentForDeletion(name, kubeContext string, force, print bool) error {\n\tif !force {\n\t\tif err := lockEnvironment(name, kubeContext, print); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tannotations := map[string]string{stateAnnotation: deleteState}\n\terr := utils.UpdateNamespace(name, kubeContext, annotations, map[string]string{}, print)\n\n\treturn err\n}", "func (mr *MockapiMockRecorder) DeleteStack(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteStack\", reflect.TypeOf((*Mockapi)(nil).DeleteStack), arg0)\n}", "func (m *Mockapi) DeleteStack(arg0 *cloudformation.DeleteStackInput) (*cloudformation.DeleteStackOutput, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteStack\", arg0)\n\tret0, _ := ret[0].(*cloudformation.DeleteStackOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (s *Stack) Destroy() error {\n\t_, err := s.cfnconn.DeleteStack(&cloudformation.DeleteStackInput{\n\t\tStackName: aws.String(s.Name),\n\t})\n\treturn errors.Annotatef(err, \"DeleteStack failed for stack '%s'\", s.Name)\n}", "func (c *StackCollection) DeleteStackBySpec(ctx context.Context, s *Stack) (*Stack, error) {\n\tif !matchesCluster(c.spec.Metadata.Name, s.Tags) {\n\t\treturn nil, fmt.Errorf(\"cannot delete stack %q as it doesn't bear our %q, %q tags\", *s.StackName,\n\t\t\tfmt.Sprintf(\"%s:%s\", api.OldClusterNameTag, c.spec.Metadata.Name),\n\t\t\tfmt.Sprintf(\"%s:%s\", api.ClusterNameTag, c.spec.Metadata.Name))\n\t}\n\n\tinput := &cloudformation.DeleteStackInput{\n\t\tStackName: s.StackId,\n\t}\n\n\tif cfnRole := c.roleARN; cfnRole != \"\" {\n\t\tinput.RoleARN = &cfnRole\n\t}\n\n\tif _, err := c.cloudformationAPI.DeleteStack(ctx, input); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"not able to delete stack %q\", *s.StackName)\n\t}\n\tlogger.Info(\"will delete stack %q\", *s.StackName)\n\treturn s, nil\n}", "func (s *Cloudformation) CreateStack() (output *cloudformation.CreateStackOutput, err error) {\n\tsess := s.config.AWSSession\n\tsvc := cloudformation.New(sess)\n\n\tcftemplate := helpers.GetCloudFormationTemplate(s.config, \"s3bucket\", s.S3Bucket.Spec.CloudFormationTemplateName, s.S3Bucket.Spec.CloudFormationTemplateNamespace)\n\n\tstackInputs := cloudformation.CreateStackInput{\n\t\tStackName: aws.String(s.StackName()),\n\t\tTemplateURL: aws.String(cftemplate),\n\t\tNotificationARNs: []*string{\n\t\t\taws.String(s.topicARN),\n\t\t},\n\t}\n\n\tresourceName := helpers.CreateParam(\"ResourceName\", s.S3Bucket.Name)\n\tresourceVersion := helpers.CreateParam(\"ResourceVersion\", s.S3Bucket.ResourceVersion)\n\tnamespace := helpers.CreateParam(\"Namespace\", s.S3Bucket.Namespace)\n\tclusterName := helpers.CreateParam(\"ClusterName\", s.config.ClusterName)\n\tbucketName := helpers.CreateParam(\"BucketName\", helpers.Stringify(s.S3Bucket.Name))\n\tversioningTemp := \"{{.Obj.Spec.Versioning}}\"\n\tversioningValue, err := helpers.Templatize(versioningTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tversioning := helpers.CreateParam(\"EnableVersioning\", helpers.Stringify(versioningValue))\n\taccessControlTemp := \"{{.Obj.Spec.AccessControl}}\"\n\taccessControlValue, err := helpers.Templatize(accessControlTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\taccessControl := helpers.CreateParam(\"BucketAccessControl\", helpers.Stringify(accessControlValue))\n\tloggingenabledTemp := \"{{.Obj.Spec.Logging.Enabled}}\"\n\tloggingenabledValue, err := helpers.Templatize(loggingenabledTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tloggingenabled := helpers.CreateParam(\"EnableLogging\", helpers.Stringify(loggingenabledValue))\n\tloggingprefixTemp := \"{{.Obj.Spec.Logging.Prefix}}\"\n\tloggingprefixValue, err := helpers.Templatize(loggingprefixTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tloggingprefix := helpers.CreateParam(\"LoggingPrefix\", helpers.Stringify(loggingprefixValue))\n\twebsiteenabledTemp := \"{{.Obj.Spec.Website.Enabled}}\"\n\twebsiteenabledValue, err := helpers.Templatize(websiteenabledTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteenabled := helpers.CreateParam(\"EnableStaticSite\", helpers.Stringify(websiteenabledValue))\n\twebsiteindexPageTemp := \"{{.Obj.Spec.Website.IndexPage}}\"\n\twebsiteindexPageValue, err := helpers.Templatize(websiteindexPageTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteindexPage := helpers.CreateParam(\"StaticSiteIndex\", helpers.Stringify(websiteindexPageValue))\n\twebsiteerrorPageTemp := \"{{.Obj.Spec.Website.ErrorPage}}\"\n\twebsiteerrorPageValue, err := helpers.Templatize(websiteerrorPageTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteerrorPage := helpers.CreateParam(\"StaticSiteError\", helpers.Stringify(websiteerrorPageValue))\n\n\tparameters := []*cloudformation.Parameter{}\n\tparameters = append(parameters, resourceName)\n\tparameters = append(parameters, resourceVersion)\n\tparameters = append(parameters, namespace)\n\tparameters = append(parameters, clusterName)\n\tparameters = append(parameters, bucketName)\n\tparameters = append(parameters, versioning)\n\tparameters = append(parameters, accessControl)\n\tparameters = append(parameters, loggingenabled)\n\tparameters = append(parameters, loggingprefix)\n\tparameters = append(parameters, websiteenabled)\n\tparameters = append(parameters, websiteindexPage)\n\tparameters = append(parameters, websiteerrorPage)\n\n\tstackInputs.SetParameters(parameters)\n\n\tresourceNameTag := helpers.CreateTag(\"ResourceName\", s.S3Bucket.Name)\n\tresourceVersionTag := helpers.CreateTag(\"ResourceVersion\", s.S3Bucket.ResourceVersion)\n\tnamespaceTag := helpers.CreateTag(\"Namespace\", s.S3Bucket.Namespace)\n\tclusterNameTag := helpers.CreateTag(\"ClusterName\", s.config.ClusterName)\n\n\ttags := []*cloudformation.Tag{}\n\ttags = append(tags, resourceNameTag)\n\ttags = append(tags, resourceVersionTag)\n\ttags = append(tags, namespaceTag)\n\ttags = append(tags, clusterNameTag)\n\n\tstackInputs.SetTags(tags)\n\n\toutput, err = svc.CreateStack(&stackInputs)\n\treturn\n}", "func (s *Scheduler) Remove(app string) error {\n\treturn s.stackBuilder.Remove(app)\n}", "func (c *StackCollection) DeleteStackBySpecSync(ctx context.Context, s *Stack, errs chan error) error {\n\ti, err := c.DeleteStackBySpec(ctx, s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogger.Info(\"waiting for stack %q to get deleted\", *i.StackName)\n\n\tgo c.waitUntilStackIsDeleted(ctx, i, errs)\n\n\treturn nil\n}", "func (c *CloudFormationTemplate) CreateStack(suffix string) {\n\tfmt.Printf(\"\\nRunning CloudFormation stack [%s]\", c.Name)\n\tsess := session.Must(session.NewSession(&aws.Config{\n\t\tRegion: aws.String(\"us-west-2\"),\n\t}))\n\tsvc := cloudformation.New(sess)\n\n\ttemplateBody := string(c.Bytes)\n\tc.StackName = c.Name + \"-\" + suffix\n\tcloudFormationValues := make(map[string]string)\n\n\tcreateStackParams := &cloudformation.CreateStackInput{\n\t\tStackName: aws.String(c.StackName),\n\t\tTemplateBody: aws.String(templateBody),\n\t}\n\n\tdescribeStacksParams := &cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(c.StackName),\n\t}\n\n\tout, err := svc.CreateStack(createStackParams)\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"AlreadyExistsException\") {\n\t\t\tfmt.Printf(\"\\nCloudFormation stack [%s] already exists. Skipping...\", c.Name)\n\t\t\tdescOut, err := svc.DescribeStacks(describeStacksParams)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tc.ParseOutput(descOut, cloudFormationValues)\n\t\t\treturn\n\t\t} else {\n\t\t\tfmt.Printf(\"%s\", err)\n\t\t\tpanic(err)\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"%s\", out)\n\t}\n\n\tstackReady := false\n\n\tfor stackReady != true {\n\n\t\tdescOut, err := svc.DescribeStacks(describeStacksParams)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%s\", err)\n\t\t\tpanic(err)\n\t\t} else {\n\t\t\tfmt.Printf(\"\\nCloudFormation stack [%s] is creating...\", c.Name)\n\t\t}\n\n\t\tif *descOut.Stacks[0].StackStatus == \"CREATE_COMPLETE\" {\n\t\t\tstackReady = true\n\t\t\tfmt.Printf(\"\\nCloudFormation stack [%s] ready...\\n\", c.Name)\n\t\t\tc.ParseOutput(descOut, cloudFormationValues)\n\t\t}\n\n\t\ttime.Sleep(time.Second * 7)\n\t}\n\n}", "func DeleteStack(ctx context.Context, svc *cf.CloudFormation, opts *RequestOptions) (*cf.DeleteStackOutput, error) {\n\tinput := &cf.DeleteStackInput{\n\t\tStackName: aws.String(opts.StackName),\n\t}\n\n\treturn svc.DeleteStackWithContext(ctx, input)\n}", "func (s *TattooStorage) DeleteTag(tagName string) {\n\treturn\n}", "func (d *defaultJobRepository) MarkDeleted(ctxIn context.Context, id string) error {\n _, span := trace.StartSpan(ctxIn, \"(*defaultJobRepository).MarkDeleted\")\n defer span.End()\n\n job := &Job{\n ID: id,\n Status: JobDeleted,\n EntityAudit: EntityAudit{\n UpdatedTimestamp: time.Now(),\n DeletedTimestamp: time.Now(),\n },\n }\n\n _, err := d.storageService.DB().\n Model(job).\n Column(\"status\", \"audit_updated_timestamp\", \"audit_deleted_timestamp\").\n WherePK().\n Where(\"audit_deleted_timestamp IS NULL\").\n Update()\n\n if err != nil {\n return fmt.Errorf(\"error during executing updating job statemant: %s\", err)\n }\n\n return nil\n}", "func (c *grafana) MarkDeleted() {}", "func (m *MockProviderClient) DeleteCloudformationStack(arg0 context.Context, arg1 map[string]string, arg2 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteCloudformationStack\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (q *Queue) StackReorder(uuids []string) error {\n\tq.Lock()\n\n\t// Check all the UUIDs before we do anything\n\tl := len(uuids)\n\tif l != len(q.stack) {\n\t\tq.Unlock()\n\t\treturn errors.New(\"The wrong number of UUIDs were provided.\")\n\t}\n\n\t// Get the UUIDs in the check map\n\tuuidCheck := make(map[string]common.Job)\n\tfor _, v := range uuids {\n\t\tuuidCheck[v] = common.Job{}\n\t}\n\n\t// Loop through the stack and check for bad UUIDs\n\tfor i, _ := range q.stack {\n\t\tj := q.stack[i]\n\t\tlog.WithField(\"uuid\", j.UUID).Debug(\"Checking UUID on reorder stack.\")\n\t\tif _, ok := uuidCheck[j.UUID]; !ok {\n\t\t\tq.Unlock()\n\t\t\treturn errors.New(\"All Job UUIDs must be provided!\")\n\t\t}\n\t}\n\n\t// UUIDs are good so pause the queue (we will return the errors at the end)\n\tq.Unlock()\n\terr := q.PauseQueue()\n\tq.Lock()\n\n\t// Get Job information to build new stack\n\tfor i, _ := range q.stack {\n\t\tlog.WithField(\"uuid\", q.stack[i].UUID).Debug(\"Building new job stack.\")\n\t\tuuidCheck[q.stack[i].UUID] = q.stack[i]\n\t}\n\n\tnewStack := []common.Job{}\n\tfor _, v := range uuids {\n\t\tnewStack = append(newStack, uuidCheck[v])\n\t}\n\n\t// If no errors were given we now have a new stack so lets assign it and finally unlock the Queue\n\tlog.Debug(\"Assigning new stack to queue stack\")\n\tq.stack = newStack\n\n\t// Resume the Queue\n\tq.Unlock()\n\tq.ResumeQueue()\n\n\t// Return the errors from the QueuePause if there were any\n\tif err != nil {\n\t\treturn errors.New(\"There was an error pausing jobs.\")\n\t}\n\n\tgo HookOnQueueReorder(Hooks.QueueReorder, q.stack)\n\n\treturn nil\n}", "func (in *RecordSetGroup) SetStackID(input string) {\n\tin.Status.StackID = input\n\treturn\n}", "func TestCFCreateStack(t *testing.T) {\n\tt.Parallel()\n\n\texpectedName := fmt.Sprintf(\"terratest-cf-example-%s\", random.UniqueId())\n\n\tCFOptions := &cloudformation.Options{\n\t\tCFFile: \"../examples/cloudformation-aws-example/cf_create_test.yml\",\n\t\tStackName: expectedName,\n\t\tAWSRegion: \"us-west-2\",\n\t}\n\tdefer cloudformation.DeleteStack(t, CFOptions)\n\n\tcloudformation.CreateStack(t, CFOptions)\n\tlist := cloudformation.ListResources(t, CFOptions)\n\tfilteredList := cloudformation.FilterResources(list, \"DummyResource\")\n\tassert.Contains(t, filteredList, \"cloudformation-waitcondition-\")\n}", "func (s *Cloudformation) StackName() string {\n\treturn helpers.StackName(s.config.ClusterName, \"s3bucket\", s.S3Bucket.Name, s.S3Bucket.Namespace)\n}", "func (d *Deployment) MarkDone(addr string) error {\n\treturn attempts.Run(func() error {\n\t\tif err := d.update(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdeploymentMeta, err := d.decode(d.meta)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdeploymentMeta.States[addr] = DeploymentStateDone\n\n\t\treturn d.set(d.meta, deploymentMeta)\n\t})\n}", "func (s *SQLiteStore) deleteAllResourcesForStack(stackname string) error {\n\treturn nil\n}", "func (dq *deleteQueue) deleteFromPending() {\n\tdq.Lock()\n\tdefer dq.Unlock()\n\n\tn := len(dq.entries)\n\tif n > awsBatchSizeLimit {\n\t\tn = awsBatchSizeLimit\n\t}\n\tfails, err := dq.deleteBatch(dq.entries[:n])\n\tif err != nil {\n\t\tdq.svc.Logger(\"Error deleting batch: %s\", err)\n\t\treturn\n\t}\n\n\tdq.entries = dq.entries[n:]\n\n\tif len(fails) > 0 {\n\t\tdq.entries = append(dq.entries, fails...)\n\t}\n}", "func (root *DSSRoot) removeStack(stack *Stack) {\n\tfor i, s := range root.stacks {\n\t\tif s == stack {\n\t\t\troot.stacks[i] = root.stacks[len(root.stacks)-1]\n\t\t\troot.stacks[len(root.stacks)-1] = nil\n\t\t\troot.stacks = root.stacks[:len(root.stacks)-1]\n\t\t}\n\t}\n}", "func (a *Client) DeleteNetworkSwitchStack(params *DeleteNetworkSwitchStackParams, authInfo runtime.ClientAuthInfoWriter) (*DeleteNetworkSwitchStackNoContent, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewDeleteNetworkSwitchStackParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"deleteNetworkSwitchStack\",\n\t\tMethod: \"DELETE\",\n\t\tPathPattern: \"/networks/{networkId}/switchStacks/{switchStackId}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &DeleteNetworkSwitchStackReader{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.(*DeleteNetworkSwitchStackNoContent)\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 deleteNetworkSwitchStack: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func NewDeleteStackActivity(awsSessionFactory AWSFactory) *DeleteStackActivity {\n\treturn &DeleteStackActivity{\n\t\tawsSessionFactory: awsSessionFactory,\n\t}\n}", "func (o *GetPurgeStatusParams) SetStackID(stackID string) {\n\to.StackID = stackID\n}", "func NewDeleteStackAction(context *EksClusterDeletionContext, stackName string) *DeleteStackAction {\n\treturn &DeleteStackAction{\n\t\tcontext: context,\n\t\tStackName: stackName,\n\t}\n}", "func (cf *Cloudformation) createStack() {\n\n\tcreateStack = &cobra.Command {\n\t\tUse: \"create-efs\",\n\t\tShort: \"Create stack\",\n\t\tLong: `Create stack based on template`,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\n\t\t\tparameters := make([]*cloudformation.Parameter, 0, 5)\n\n\t\t\tonFailure, err := cmd.Flags().GetString(\"onfailure\")\n\t\t\tverifyOnFailureArg(err, onFailure)\n\n\t\t\tcapabilities, err := cmd.Flags().GetStringArray(\"capabilities\")\n\t\t\tverifyCapability(err, capabilities)\n\n\t\t\tstackName, err := cmd.Flags().GetString(\"stackname\")\n\t\t\tverify(err, \"stackname\")\n\n\t\t\tinstanceType, err := cmd.Flags().GetString(\"instance-type\")\n\t\t\tverify(err, \"instance-type\")\n\t\t\taddParameter(&parameters, \"InstanceType\", instanceType)\n\n\t\t\tkeyPair, err := cmd.Flags().GetString(\"key-pair-name\")\n\t\t\tverify(err, \"key-pair-name\")\n\t\t\taddParameter(&parameters, \"KeyName\", keyPair)\n\n\t\t\tsubnets, err := cmd.Flags().GetStringArray(\"subnets\")\n\t\t\tverify(err, \"subnets\")\n\t\t\taddParameters(&parameters, \"Subnets\", subnets)\n\n\t\t\tvpc, err := cmd.Flags().GetString(\"vpc\")\n\t\t\tverify(err, \"vpc\")\n\t\t\taddParameter(&parameters, \"VPC\" ,vpc)\n\n\t\t\timage, err := cmd.Flags().GetString(\"image\")\n\t\t\tverify(err, \"image\")\n\t\t\taddParameter(&parameters, \"ImageId\", image)\n\n\t\t\tfor _, param := range parameters {\n\t\t\t\tfmt.Printf(\"----Param : %s ---- \\n\", param)\n\t\t\t}\n\n\t\t\tcfClient := cloudformation.New(cf.sess, cf.sess.Config)\n\n\t\t\tresp, err := cf.ec2Res.createKeyPair(keyPair)\n\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Create key pair err: %s \\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\n\t\t\tcreatePemFile(resp.KeyMaterial)\n\n\t\t\tfile := readFile(\"templates/distributed_file_system.yaml\")\n\n\t\t\tif _, err := cfClient.CreateStack(&cloudformation.CreateStackInput{\n\t\t\t\tCapabilities: aws.StringSlice(capabilities),\n\t\t\t\tClientRequestToken: nil,\n\t\t\t\tDisableRollback: nil,\n\t\t\t\tEnableTerminationProtection: nil,\n\t\t\t\tNotificationARNs: nil,\n\t\t\t\tOnFailure: &onFailure,\n\t\t\t\tParameters: parameters,\n\t\t\t\tResourceTypes: nil,\n\t\t\t\tRoleARN: nil,\n\t\t\t\tRollbackConfiguration: nil,\n\t\t\t\tStackName: &stackName,\n\t\t\t\tStackPolicyBody: nil,\n\t\t\t\tStackPolicyURL: nil,\n\t\t\t\tTags: nil,\n\t\t\t\tTemplateBody: &file,\n\t\t\t\tTemplateURL: nil,\n\t\t\t\tTimeoutInMinutes: nil,\n\t\t\t}); err != nil {\n\t\t\t\tdeleteKeyPair(cf, keyPair, err)\n\t\t\t}\n\n\t\t},\n\t}\n}", "func (s *Subtitle) MarkAsDeleted() {\n\ts.Num = -1\n}", "func (o *ZoneZone) SetStackId(v string) {\n\to.StackId = &v\n}", "func (s *Cloudformation) UpdateStack(updated *awsV1alpha1.S3Bucket) (output *cloudformation.UpdateStackOutput, err error) {\n\tsess := s.config.AWSSession\n\tsvc := cloudformation.New(sess)\n\n\tcftemplate := helpers.GetCloudFormationTemplate(s.config, \"s3bucket\", updated.Spec.CloudFormationTemplateName, updated.Spec.CloudFormationTemplateNamespace)\n\n\tstackInputs := cloudformation.UpdateStackInput{\n\t\tStackName: aws.String(s.StackName()),\n\t\tTemplateURL: aws.String(cftemplate),\n\t\tNotificationARNs: []*string{\n\t\t\taws.String(s.topicARN),\n\t\t},\n\t}\n\n\tresourceName := helpers.CreateParam(\"ResourceName\", s.S3Bucket.Name)\n\tresourceVersion := helpers.CreateParam(\"ResourceVersion\", s.S3Bucket.ResourceVersion)\n\tnamespace := helpers.CreateParam(\"Namespace\", s.S3Bucket.Namespace)\n\tclusterName := helpers.CreateParam(\"ClusterName\", s.config.ClusterName)\n\tbucketName := helpers.CreateParam(\"BucketName\", helpers.Stringify(s.S3Bucket.Name))\n\tversioningTemp := \"{{.Obj.Spec.Versioning}}\"\n\tversioningValue, err := helpers.Templatize(versioningTemp, helpers.Data{Obj: updated, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tversioning := helpers.CreateParam(\"EnableVersioning\", helpers.Stringify(versioningValue))\n\taccessControlTemp := \"{{.Obj.Spec.AccessControl}}\"\n\taccessControlValue, err := helpers.Templatize(accessControlTemp, helpers.Data{Obj: updated, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\taccessControl := helpers.CreateParam(\"BucketAccessControl\", helpers.Stringify(accessControlValue))\n\tloggingenabledTemp := \"{{.Obj.Spec.Logging.Enabled}}\"\n\tloggingenabledValue, err := helpers.Templatize(loggingenabledTemp, helpers.Data{Obj: updated, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tloggingenabled := helpers.CreateParam(\"EnableLogging\", helpers.Stringify(loggingenabledValue))\n\tloggingprefixTemp := \"{{.Obj.Spec.Logging.Prefix}}\"\n\tloggingprefixValue, err := helpers.Templatize(loggingprefixTemp, helpers.Data{Obj: updated, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tloggingprefix := helpers.CreateParam(\"LoggingPrefix\", helpers.Stringify(loggingprefixValue))\n\twebsiteenabledTemp := \"{{.Obj.Spec.Website.Enabled}}\"\n\twebsiteenabledValue, err := helpers.Templatize(websiteenabledTemp, helpers.Data{Obj: updated, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteenabled := helpers.CreateParam(\"EnableStaticSite\", helpers.Stringify(websiteenabledValue))\n\twebsiteindexPageTemp := \"{{.Obj.Spec.Website.IndexPage}}\"\n\twebsiteindexPageValue, err := helpers.Templatize(websiteindexPageTemp, helpers.Data{Obj: updated, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteindexPage := helpers.CreateParam(\"StaticSiteIndex\", helpers.Stringify(websiteindexPageValue))\n\twebsiteerrorPageTemp := \"{{.Obj.Spec.Website.ErrorPage}}\"\n\twebsiteerrorPageValue, err := helpers.Templatize(websiteerrorPageTemp, helpers.Data{Obj: updated, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteerrorPage := helpers.CreateParam(\"StaticSiteError\", helpers.Stringify(websiteerrorPageValue))\n\n\tparameters := []*cloudformation.Parameter{}\n\tparameters = append(parameters, resourceName)\n\tparameters = append(parameters, resourceVersion)\n\tparameters = append(parameters, namespace)\n\tparameters = append(parameters, clusterName)\n\tparameters = append(parameters, bucketName)\n\tparameters = append(parameters, versioning)\n\tparameters = append(parameters, accessControl)\n\tparameters = append(parameters, loggingenabled)\n\tparameters = append(parameters, loggingprefix)\n\tparameters = append(parameters, websiteenabled)\n\tparameters = append(parameters, websiteindexPage)\n\tparameters = append(parameters, websiteerrorPage)\n\n\tstackInputs.SetParameters(parameters)\n\n\tresourceNameTag := helpers.CreateTag(\"ResourceName\", s.S3Bucket.Name)\n\tresourceVersionTag := helpers.CreateTag(\"ResourceVersion\", s.S3Bucket.ResourceVersion)\n\tnamespaceTag := helpers.CreateTag(\"Namespace\", s.S3Bucket.Namespace)\n\tclusterNameTag := helpers.CreateTag(\"ClusterName\", s.config.ClusterName)\n\n\ttags := []*cloudformation.Tag{}\n\ttags = append(tags, resourceNameTag)\n\ttags = append(tags, resourceVersionTag)\n\ttags = append(tags, namespaceTag)\n\ttags = append(tags, clusterNameTag)\n\n\tstackInputs.SetTags(tags)\n\n\toutput, err = svc.UpdateStack(&stackInputs)\n\treturn\n}", "func (client *CraneDockerClient) DeployStack(bundle *model.Bundle) error {\n\tif bundle.Namespace == \"\" || !isValidName.MatchString(bundle.Namespace) {\n\t\treturn cranerror.NewError(CodeInvalidStackName, \"invalid name, only [a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]\")\n\t}\n\n\tnewNetworkMap, err := client.PretreatmentStack(*bundle)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn client.deployServices(bundle.Stack.Services, bundle.Namespace, newNetworkMap)\n}", "func (t *TokenTransactionObject) MarkDelete() {\n\tt.deleted = true\n}", "func getStackName(input *commands.DNSInput) string {\n\treturn strings.Replace(input.HostedZone, \".\", \"-\", -1)\n}", "func Remove(name string) error", "func (m *MockCfnClient) DeleteStack(stackId string) (chan cfn.DeletionResult, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteStack\", stackId)\n\tret0, _ := ret[0].(chan cfn.DeletionResult)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func stackExists(stackNameOrID string, cf *cloudformation.CloudFormation, logger *logrus.Logger) (bool, error) {\n\tdescribeStacksInput := &cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(stackNameOrID),\n\t}\n\tdescribeStacksOutput, err := cf.DescribeStacks(describeStacksInput)\n\tlogger.Debug(\"DescribeStackOutput: \", describeStacksOutput)\n\texists := false\n\tif err != nil {\n\t\tlogger.Info(\"DescribeStackOutputError: \", err)\n\t\t// If the stack doesn't exist, then no worries\n\t\tif strings.Contains(err.Error(), \"does not exist\") {\n\t\t\texists = false\n\t\t} else {\n\t\t\treturn false, err\n\t\t}\n\t} else {\n\t\texists = true\n\t}\n\treturn exists, nil\n}", "func awsMockStackID(stackName string) string {\n\tnh := sha1.Sum([]byte(stackName))\n\treturn fmt.Sprintf(\"arn:aws:cloudformation:mock:%012d:stack/%s/%x-%x-%x-%x-%x\",\n\t\tbinary.BigEndian.Uint32(nh[16:20]), stackName, nh[0:4], nh[4:6], nh[6:8], nh[8:10], nh[10:16])\n}", "func DestroyTerraformStack(t *testing.T, terraformDir string) {\n terraformOptions := test_structure.LoadTerraformOptions(t, terraformDir)\n terraform.Destroy(t, terraformOptions)\n\n kubectlOptions := test_structure.LoadKubectlOptions(t, terraformDir)\n err := os.Remove(kubectlOptions.ConfigPath)\n require.NoError(t, err)\n}", "func (action *DeleteStackAction) GetName() string {\n\treturn \"DeleteStackAction\"\n}", "func (c *StakerObject) MarkDelete() {\n\tc.deleted = true\n}", "func (in *RecordSetGroup) SetStackName(input string) {\n\tin.Spec.StackName = input\n\treturn\n}", "func TestMarkForDelete(t *testing.T) {\n\tif !testutil.ShouldRunIntegrationTests() {\n\t\tt.Skip(\"Skipping integration test. Set ENV var RUN_EXCHANGE_INTEGRATION=true if you want to run them.\")\n\t}\n\tconfigFile := filepath.Join(\"config\", \"integration.json\")\n\tconfig, err := models.LoadConfigFile(configFile)\n\trequire.Nil(t, err)\n\t_context := context.NewContext(config)\n\n\tinstResp := _context.PharosClient.InstitutionGet(\"test.edu\")\n\trequire.Nil(t, instResp.Error)\n\tinstitution := instResp.Institution()\n\trequire.NotNil(t, institution)\n\n\t// Mark one object in standard storage for deletion\n\ts3Key := testutil.INTEGRATION_GOOD_BAGS[9]\n\tidentifier := strings.Replace(s3Key, \"aptrust.integration.test\", \"test.edu\", 1)\n\tidentifier = strings.Replace(identifier, \".tar\", \"\", 1)\n\tmarkObjectForDeletion(t, _context, identifier, institution.Id)\n\n\t// Mark one object in Glacier-only storage for deletion\n\ts3Key = testutil.INTEGRATION_GLACIER_BAGS[0]\n\tidentifier = strings.Replace(s3Key, \"aptrust.integration.test\", \"test.edu\", 1)\n\tidentifier = strings.Replace(identifier, \".tar\", \"\", 1)\n\tmarkObjectForDeletion(t, _context, identifier, institution.Id)\n}", "func (client DeploymentsClient) DeleteSender(req *http.Request) (future DeploymentsDeleteFuture, err error) {\n\tvar resp *http.Response\n\tfuture.FutureAPI = &azure.Future{}\n\tresp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))\n\tif err != nil {\n\t\treturn\n\t}\n\tvar azf azure.Future\n\tazf, err = azure.NewFutureFromResponse(resp)\n\tfuture.FutureAPI = &azf\n\tfuture.Result = future.result\n\treturn\n}", "func (tb *tableManager) markRemove(keyIn uint64) error {\n\tvar err error\n\tvar entry *tableEntry\n\tentry, err = tb.getEntry(keyIn)\n\tif err != nil {\n\t\tlog.Println(\"Could not obtain entry.\")\n\t\treturn errors.New(\"Could not obtain entry.\")\n\t}\n\terr = tb.write(keyIn, nil)\n\tif err != nil {\n\t\tlog.Println(\"Could not write nil to entry for removal.\")\n\t\treturn errors.New(\"Marking for removal failed.\")\n\t}\n\tentry.flags = flagDirty | flagRemove\n\treturn nil\n}", "func (task SchTask) Delete(taskname string, own, force bool) string {\n\tcmd := &exec.Cmd{}\n\n\tif Debug {\n\t\treturn dbgMessage\n\t}\n\n\tif own {\n\t\ttaskname = task.prefix + taskname\n\t}\n\n\tif !force {\n\t\tcmd = exec.Command(task.bin, _Delete.Command, _Delete.taskname, taskname)\n\t} else {\n\t\tcmd = exec.Command(task.bin, _Delete.Command, _Delete.taskname, taskname, _Delete.force)\n\t}\n\n\toutput, err := cmd.CombinedOutput()\n\tcatch(output, err)\n\n\treturn string(output)\n}", "func (f *FinalExchangeRatesStateObject) MarkDelete() {\n\tf.deleted = true\n}", "func CreateStackResources(stackID string, subscription dynamodb.APISubscription) error {\n\n\t// Create a new CloudFormation template\n\ttemplate := cloudformation.NewTemplate()\n\n\t//Generate GUID\n\tid := stackID\n\n\ttags := []tags.Tag{\n\t\ttags.Tag{\n\t\t\tKey: \"Product\",\n\t\t\tValue: \"MaxEdge\",\n\t\t},\n\t\t// tags.Tag{\n\t\t// \tKey: \"Subscription_ID\",\n\t\t// \tValue: subscription.Name,\n\t\t// },\n\t}\n\n\t// AWS ECS Prpoperties\n\tvarRequiresCompatibilities := []string{\"FARGATE\"}\n\n\t// Lambda Environment Variables //\n\n\t// AWS Account ID\n\tvar varAwsAccountID = os.Getenv(\"AWS_ACCOUNT_ID\")\n\n\t// Task Definition\n\tvar varExecutionRoleArn = os.Getenv(\"EXECUTION_ROLE\")\n\tvar varTaskRoleArn = os.Getenv(\"TASK_ROLE\")\n\tvar varEcsTaskDefinitionRef = os.Getenv(\"CLOUDFORMATION_TASK_DEFINITION_REF\")\n\n\t// Container Definition\n\tvar varImage = os.Getenv(\"CONTAINER_IMAGE\")\n\n\t//Network Definition\n\tvar varSecurityGroup = os.Getenv(\"SECURITY_GROUP\")\n\tvar varSubnet1 = os.Getenv(\"SUBNET_1\")\n\tvar varSubnet2 = os.Getenv(\"SUBNET_2\")\n\tvar varSubnet3 = os.Getenv(\"SUBNET_3\")\n\n\t//ECS Service\n\tvar varClusterName = os.Getenv(\"CLUSTER_NAME\")\n\tvar varEcsRef = os.Getenv(\"CLOUDFORMATION_ECS_SERVICE_REF\")\n\n\t//Secret\n\tvar varSecretRef = os.Getenv(\"CLOUDFORMATION_SECRET_REF\")\n\n\t// Create IAM User\n\ttemplate.Resources[\"IAMUSER\"] = &iam.User{\n\t\tUserName: string(id),\n\t\tTags: tags,\n\t}\n\n\t// Assigning the subscribers ID to a string so it can be added to the policy\n\tbucket := fmt.Sprintf(\"\\\"arn:aws:s3:::maxedgecloudtocloudpoc-sandbox/%s/*\\\"\", id)\n\tvar roleName string = \"ROLE_\" + id\n\tvar policyName string = \"Policy\" + id\n\n\t// S3 GetObject policy for the created IAM user for a subscription\n\t// User will assume the role\n\t// Action is to Assume the sts role\n\ttemplate.Resources[\"IAMPolicy\"] = &iam.Policy{\n\t\tPolicyName: policyName,\n\t\tPolicyDocument: (\"{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[{\\\"Effect\\\":\\\"Allow\\\",\\\"Action\\\":\\\"sts:AssumeRole\\\",\\\"Resource\\\":\\\"arn:aws:iam::\" + varAwsAccountID + \":role/\" + roleName + \"\\\"}]}\"),\n\t\tUsers: []string{id},\n\t\tAWSCloudFormationDependsOn: []string{\"IAMUSER\"},\n\t}\n\n\tp := iam.Role_Policy{\n\t\tPolicyDocument: (\"{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[{\\\"Effect\\\":\\\"Allow\\\",\\\"Action\\\":\\\"s3:GetObject\\\",\\\"Resource\\\":\" + bucket + \"}]}\"),\n\t\tPolicyName: id,\n\t}\n\n\t// Assume Role or Trust Policy\n\ttemplate.Resources[\"IAMROLE\"] = &iam.Role{\n\t\tAssumeRolePolicyDocument: (\"{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[{\\\"Effect\\\":\\\"Allow\\\",\\\"Principal\\\":{\\\"AWS\\\": \\\"arn:aws:iam::\" + varAwsAccountID + \":user/\" + id + \"\\\"},\\\"Action\\\":[\\\"sts:AssumeRole\\\"]}]}\"),\n\t\tRoleName: roleName,\n\t\tPolicies: []iam.Role_Policy{p},\n\t\tAWSCloudFormationDependsOn: []string{\"IAMUSER\"},\n\t\tTags: tags,\n\t}\n\n\t// Task Definition Secret - sets the value for the container based on what was\n\t// created in the template.\n\tTaskDefSecret := []ecs.TaskDefinition_Secret{}\n\tvarTaskDefSecret := ecs.TaskDefinition_Secret{\n\t\t//Referance to the ARNs created when the secret is created\n\t\tName: cloudformation.Ref(varSecretRef),\n\t\tValueFrom: cloudformation.Ref(varSecretRef),\n\t}\n\tTaskDefSecret = append(TaskDefSecret, varTaskDefSecret)\n\n\t// TargetName come from the DynamoDB table and stores the cloud platform\n\t// endpoint for the data destination\n\tgroup := \"/MaxEdge/CloudToCloud/\" + subscription.Target\n\n\tcwLog := &ecs.TaskDefinition_LogConfiguration{\n\t\tLogDriver: \"awslogs\",\n\t\tOptions: map[string]string{\"awslogs-create-group\": \"true\", \"awslogs-group\": group, \"awslogs-region\": \"us-east-1\", \"awslogs-stream-prefix\": id},\n\t}\n\n\t//Task Definition Container Definition - Setting properties\n\tTaskDefConDef := []ecs.TaskDefinition_ContainerDefinition{}\n\tvarTaskDef := ecs.TaskDefinition_ContainerDefinition{\n\t\tImage: varImage,\n\t\tName: id,\n\t\tSecrets: TaskDefSecret,\n\t\tLogConfiguration: cwLog,\n\t}\n\tTaskDefConDef = append(TaskDefConDef, varTaskDef)\n\n\t// Create an Amazon ECS Task Definition - Setting properties\n\ttemplate.Resources[varEcsTaskDefinitionRef] = &ecs.TaskDefinition{\n\t\tExecutionRoleArn: varExecutionRoleArn,\n\t\tTaskRoleArn: varTaskRoleArn,\n\t\tMemory: \"1024\",\n\t\tNetworkMode: \"awsvpc\",\n\t\tRequiresCompatibilities: varRequiresCompatibilities,\n\t\tCpu: \"512\",\n\t\tContainerDefinitions: TaskDefConDef,\n\t\tTags: tags,\n\t}\n\n\t// ECS Service Network configuration\n\tsnc := &ecs.Service_NetworkConfiguration{\n\t\tAwsvpcConfiguration: &ecs.Service_AwsVpcConfiguration{\n\n\t\t\t// Required to access ECR\n\t\t\tAssignPublicIp: \"ENABLED\",\n\t\t\t// The Security Group needs to allow traffic via port :443\n\t\t\tSecurityGroups: []string{varSecurityGroup},\n\t\t\tSubnets: []string{varSubnet1, varSubnet2, varSubnet3},\n\t\t},\n\t}\n\n\t// Create Amazon ECS Service\n\ttemplate.Resources[varEcsRef] = &ecs.Service{\n\t\tLaunchType: \"FARGATE\",\n\t\tCluster: varClusterName,\n\t\tTaskDefinition: cloudformation.Ref(varEcsTaskDefinitionRef),\n\t\tServiceName: id,\n\t\tDesiredCount: 1,\n\t\tNetworkConfiguration: snc,\n\t\tSchedulingStrategy: \"REPLICA\",\n\t\tTags: tags,\n\t\tPropagateTags: \"TASK_DEFINITION\",\n\t}\n\n\t// Create an Amazon Secret\n\ttemplate.Resources[varSecretRef] = &secretsmanager.Secret{\n\t\tName: id,\n\t\tDescription: \"Metadata for companies\",\n\t\tTags: tags,\n\t}\n\n\t// Get JSON form of AWS CloudFormation template\n\tj, err := template.JSON()\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to generate JSON: %s\\n\", err)\n\t\treturn err\n\t}\n\tfmt.Printf(\"Template creation for %s Done.\\n\", id)\n\tfmt.Println(\"=====\")\n\tfmt.Println(\"Generated template:\")\n\tfmt.Printf(\"%s\\n\", string(j))\n\tfmt.Println(\"=====\")\n\n\t// Initialize a session that the SDK uses to load\n\t// credentials from the shared credentials file ~/.aws/credentials\n\t// and configuration from the shared configuration file ~/.aws/config.\n\t// https://docs.aws.amazon.com/sdk-for-go/api/aws/session/\n\tsess := session.Must(session.NewSessionWithOptions(session.Options{\n\t\tSharedConfigState: session.SharedConfigEnable,\n\t}))\n\n\t// Create the stack\n\terr = createStackFromBody(sess, j, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *AntreaIPAMController) enqueueStatefulSetDeleteEvent(obj interface{}) {\n\tss := obj.(*appsv1.StatefulSet)\n\tklog.V(2).InfoS(\"Delete notification\", \"Namespace\", ss.Namespace, \"StatefulSet\", ss.Name)\n\n\tkey := k8s.NamespacedName(ss.Namespace, ss.Name)\n\tc.statefulSetQueue.Add(key)\n}", "func (in *RecordSetGroup) GenerateStackName() string {\n\treturn strings.Join([]string{\"route53\", \"recordsetgroup\", in.GetName(), in.GetNamespace()}, \"-\")\n}", "func (r *Release) mark(storageBackend string) {\n\tr.label(storageBackend, \"MANAGED-BY=HELMSMAN\", \"NAMESPACE=\"+r.Namespace, \"HELMSMAN_CONTEXT=\"+curContext)\n}", "func (c *ResourcesHandler) Delete(event.DeleteEvent, workqueue.RateLimitingInterface) {}", "func (c *stewards) Delete(name string, options *metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"stewards\").\n\t\tName(name).\n\t\tBody(options).\n\t\tDo().\n\t\tError()\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 (c *quarksStatefulSets) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"quarksstatefulsets\").\n\t\tName(name).\n\t\tBody(&opts).\n\t\tDo(ctx).\n\t\tError()\n}", "func deleteTaskMeta(db *leveldb.DB, name string) error {\n\tif db == nil {\n\t\treturn terror.ErrWorkerLogInvalidHandler.Generate()\n\t}\n\n\terr := db.Delete(encodeTaskMetaKey(name), nil)\n\tif err != nil {\n\t\treturn terror.ErrWorkerLogDeleteTaskMeta.Delegate(err, name)\n\t}\n\n\treturn nil\n}", "func (o *V1VolumeClaim) SetStackId(v string) {\n\to.StackId = &v\n}", "func (c *billing) MarkForDeletion(ctx context.Context, id string) (*api.BillingDocument, error) {\n\treturn c.patch(ctx, id, func(billingdoc *api.BillingDocument) error {\n\t\treturn nil\n\t}, &cosmosdb.Options{PreTriggers: []string{\"setDeletionBillingTimeStamp\"}})\n}", "func (q *Queue) Fix(name string, when time.Time, later bool) error {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\tdefer q.rouse()\n\n\tit, ok := q.items[name]\n\tif !ok {\n\t\treturn errors.New(\"not found\")\n\t}\n\tlog := q.log.WithFields(logrus.Fields{\n\t\t\"group\": name,\n\t\t\"when\": when,\n\t})\n\tif when.Before(it.when) {\n\t\tlog = log.WithField(\"reduced minutes\", it.when.Sub(when).Round(time.Second).Minutes())\n\t} else if later && !when.Equal(it.when) {\n\t\tlog = log.WithField(\"delayed minutes\", when.Sub(it.when).Round(time.Second).Minutes())\n\t} else {\n\t\treturn nil\n\t}\n\tit.when = when\n\theap.Fix(&q.queue, it.index)\n\tlog.Info(\"Fixed names\")\n\treturn nil\n}", "func (t *CustodianStateObject) MarkDelete() {\n\tt.deleted = true\n}", "func (action *DeleteStackAction) ExecuteAction(input interface{}) (output interface{}, err error) {\n\tlog.Info(\"EXECUTE DeleteStackAction\")\n\n\t//TODO handle non existing stack\n\tcloudformationSrv := cloudformation.New(action.context.Session)\n\tdeleteStackInput := &cloudformation.DeleteStackInput{\n\t\tClientRequestToken: aws.String(uuid.NewV4().String()),\n\t\tStackName: aws.String(action.StackName),\n\t}\n\treturn cloudformationSrv.DeleteStack(deleteStackInput)\n}", "func (s *LaunchDetails) SetStackId(v string) *LaunchDetails {\n\ts.StackId = &v\n\treturn s\n}", "func (f *FakeReconcilerClient) CreateStack(stackSpec types.StackSpec) (types.StackCreateResponse, error) {\n\tif stackSpec.Annotations.Name == \"\" {\n\t\treturn types.StackCreateResponse{}, fmt.Errorf(\"StackSpec contains no name\")\n\t}\n\n\tid, err := f.FakeStackStore.AddStack(stackSpec)\n\tif err != nil {\n\t\treturn types.StackCreateResponse{}, fmt.Errorf(\"unable to store stack: %s\", err)\n\t}\n\n\treturn types.StackCreateResponse{\n\t\tID: id,\n\t}, err\n}", "func (s *Service) Delete(ctx context.Context) error {\n\tfor _, bastionSpec := range s.Scope.BastionSpecs() {\n\n\t\ts.Scope.V(2).Info(\"deleting bastion host\", \"bastion\", bastionSpec.Name)\n\n\t\terr := s.Client.Delete(ctx, s.Scope.ResourceGroup(), bastionSpec.Name)\n\t\tif err != nil && azure.ResourceNotFound(err) {\n\t\t\t// already deleted\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to delete Bastion Host %s in resource group %s\", bastionSpec.Name, s.Scope.ResourceGroup())\n\t\t}\n\n\t\ts.Scope.V(2).Info(\"successfully deleted bastion host\", \"bastion\", bastionSpec.Name)\n\t}\n\treturn nil\n}", "func (client *LocalRulestacksClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, localRulestackName string, options *LocalRulestacksClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/PaloAltoNetworks.Cloudngfw/localRulestacks/{localRulestackName}\"\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\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 localRulestackName == \"\" {\n\t\treturn nil, errors.New(\"parameter localRulestackName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{localRulestackName}\", url.PathEscape(localRulestackName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, 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-29\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (c *StackCollection) createClusterStack(ctx context.Context, stackName string, resourceSet builder.ResourceSetReader, errCh chan error) error {\n\tclusterTags := map[string]string{\n\t\tapi.ClusterOIDCEnabledTag: strconv.FormatBool(api.IsEnabled(c.spec.IAM.WithOIDC)),\n\t}\n\tstack, err := c.createStackRequest(ctx, stackName, resourceSet, clusterTags, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\tdefer close(errCh)\n\t\ttroubleshoot := func() {\n\t\t\tstack, err := c.DescribeStack(ctx, stack)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Info(\"error describing stack to troubleshoot the cause of the failure; \"+\n\t\t\t\t\t\"check the CloudFormation console for further details\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlogger.Critical(\"unexpected status %q while waiting for CloudFormation stack %q\", stack.StackStatus, *stack.StackName)\n\t\t\tc.troubleshootStackFailureCause(ctx, stack, string(types.StackStatusCreateComplete))\n\t\t}\n\n\t\tctx, cancelFunc := context.WithTimeout(context.Background(), c.waitTimeout)\n\t\tdefer cancelFunc()\n\n\t\tstack, err := waiter.WaitForStack(ctx, c.cloudformationAPI, *stack.StackId, *stack.StackName, func(attempts int) time.Duration {\n\t\t\t// Wait 30s for the first two requests, and 1m for subsequent requests.\n\t\t\tif attempts <= 2 {\n\t\t\t\treturn 30 * time.Second\n\t\t\t}\n\t\t\treturn 1 * time.Minute\n\t\t})\n\n\t\tif err != nil {\n\t\t\ttroubleshoot()\n\t\t\terrCh <- err\n\t\t\treturn\n\t\t}\n\n\t\tif err := resourceSet.GetAllOutputs(*stack); err != nil {\n\t\t\terrCh <- errors.Wrapf(err, \"getting stack %q outputs\", *stack.StackName)\n\t\t\treturn\n\t\t}\n\n\t\terrCh <- nil\n\t}()\n\n\treturn nil\n}", "func (c *volumeSnapshotSchedules) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"volumesnapshotschedules\").\n\t\tName(name).\n\t\tBody(&opts).\n\t\tDo(ctx).\n\t\tError()\n}", "func UpdateStack(r string, currentStack *cloudformation.Stack,\n\turi string, name string, params []*cloudformation.Parameter,\n\tcapabilities []*string) {\n\tsvc := cloudformation.New(getSession(r))\n\tlog.Info(\"UpdateStack\")\n\n\tgetUpdatedParameters(&currentStack.Parameters, params)\n\ttemplate := cloudformation.UpdateStackInput{\n\t\tStackName: &name,\n\t\tParameters: currentStack.Parameters,\n\t\tCapabilities: capabilities,\n\t}\n\n\tif pass, path := parseURI(uri); pass {\n\t\ttemplateBody := utils.LoadTemplate(path)\n\t\ttemplate.TemplateBody = &templateBody\n\t} else {\n\t\ttemplate.TemplateURL = &path\n\t}\n\n\tstack, err := svc.UpdateStack(&template)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Print(\"%v\", stack)\n}", "func (action *CreateVPCAction) UndoAction() (err error) {\n\tlog.Infoln(\"EXECUTE UNDO CreateVPCAction, deleting stack:\", action.stackName)\n\tcloudformationSrv := cloudformation.New(action.context.Session)\n\tdeleteStackInput := &cloudformation.DeleteStackInput{\n\t\tClientRequestToken: aws.String(uuid.NewV4().String()),\n\t\tStackName: aws.String(action.stackName),\n\t}\n\t_, err = cloudformationSrv.DeleteStack(deleteStackInput)\n\treturn err\n}", "func (o ChangeSetOutput) StackName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ChangeSet) pulumi.StringPtrOutput { return v.StackName }).(pulumi.StringPtrOutput)\n}", "func (d *Double) DeleteAndWait(stackName string) error {\n\treturn d.DeleteAndWaitFn(stackName)\n}", "func Delete(name string) {\n\tkt.Remove(name)\n}", "func (c *MockVMScaleSetsClient) Delete(ctx context.Context, resourceGroupName, vmssName string) error {\n\t// Ignore resourceGroupName for simplicity.\n\tif _, ok := c.VMSSes[vmssName]; !ok {\n\t\treturn fmt.Errorf(\"%s does not exist\", vmssName)\n\t}\n\tdelete(c.VMSSes, vmssName)\n\treturn nil\n}", "func (command HelloWorldResource) Delete(ctx context.Context, awsConfig awsv2.Config,\n\tevent *CloudFormationLambdaEvent,\n\tlogger *zerolog.Logger) (map[string]interface{}, error) {\n\trequest := HelloWorldResourceRequest{}\n\n\trequestPropsErr := json.Unmarshal(event.ResourceProperties, &request)\n\tif requestPropsErr != nil {\n\t\treturn nil, requestPropsErr\n\t}\n\tlogger.Info().Msgf(\"delete: %s\", request.Message)\n\treturn nil, nil\n}", "func FormatQueueName(service, entity, action, event string) string {\n\treturn service + \".\" + entity + \".\" + action + \"_on_\" + event\n}", "func deleteTask(writer http.ResponseWriter, req *http.Request) {\n\tvars := mux.Vars(req)\n\tcreatedAt, err := time.Parse(time.RFC3339, vars[\"createdAt\"])\n\tif err != nil {\n\t\tlog.Print(\"error:\", err)\n\t\thttp.Error(writer, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdatabase, err := loadJsonFile()\n\tif err != nil {\n\t\tlog.Print(\"error:\", err)\n\t\thttp.Error(writer, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tfor i, _ := range database.Tasks {\n\t\tif database.Tasks[i].CreatedAt.Equal(createdAt) {\n\t\t\tdatabase.Tasks = append(database.Tasks[:i], database.Tasks[i+1:]...)\n\t\t\treturnJson(database, writer)\n\t\t\treturn\n\t\t}\n\t}\n\t//this code runs only if no taks was found with the correct createdAt timestamp\n\thttp.Error(writer, err.Error(), http.StatusBadRequest)\n}", "func (d *Double) CancelUpdateStack(stackName string) error {\n\treturn d.CancelUpdateStackFn(stackName)\n}", "func (connector *DbConnector) RemoveTag(tagName string) error {\n\tc := connector.pool.Get()\n\tdefer c.Close()\n\n\tc.Send(\"MULTI\")\n\tc.Send(\"SREM\", tagsKey, tagName)\n\tc.Send(\"DEL\", tagSubscriptionKey(tagName))\n\tc.Send(\"DEL\", tagTriggersKey(tagName))\n\t_, err := c.Do(\"EXEC\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to EXEC: %s\", err.Error())\n\t}\n\treturn nil\n}", "func (l *LinkedList) DeleteStock(name string) {\n\t//fmt.Printf(\"length = %d\", l.count)\n\tif l.count == 0 {\n\t\tfmt.Println(\"Delete not possible, add stock details\") //if there are no elements in List\n\t} else if l.count == 1 { //if Only one element in the list\n\t\tl.head = nil\n\t\tl.count--\n\t\tfmt.Println(\"Delete successful..\")\n\t} else if l.head.Name == name {\n\t\tl.head = l.head.next\n\t\tl.count--\n\t\tfmt.Println(\"Delete successful..\")\n\t} else {\n\t\tcurrent := l.head\n\t\tprev := current\n\t\tfor current.Name != name {\n\t\t\tprev = current\n\t\t\tcurrent = current.next\n\t\t}\n\t\tprev.next = current.next\n\t\tl.count--\n\t\tfmt.Println(\"Delete successful..\")\n\t}\n}", "func DeleteStatisticDefinition(settings *playfab.Settings, postData *DeleteStatisticDefinitionRequestModel, entityToken string) (*EmptyResponseModel, error) {\n if entityToken == \"\" {\n return nil, playfab.NewCustomError(\"entityToken should not be an empty string\", playfab.ErrorGeneric)\n }\n b, errMarshal := json.Marshal(postData)\n if errMarshal != nil {\n return nil, playfab.NewCustomError(errMarshal.Error(), playfab.ErrorMarshal)\n }\n\n sourceMap, err := playfab.Request(settings, b, \"/Statistic/DeleteStatisticDefinition\", \"X-EntityToken\", entityToken)\n if err != nil {\n return nil, err\n }\n \n result := &EmptyResponseModel{}\n\n config := mapstructure.DecoderConfig{\n DecodeHook: playfab.StringToDateTimeHook,\n Result: result,\n }\n \n decoder, errDecoding := mapstructure.NewDecoder(&config)\n if errDecoding != nil {\n return nil, playfab.NewCustomError(errDecoding.Error(), playfab.ErrorDecoding)\n }\n \n errDecoding = decoder.Decode(sourceMap)\n if errDecoding != nil {\n return nil, playfab.NewCustomError(errDecoding.Error(), playfab.ErrorDecoding)\n }\n\n return result, nil\n}", "func (*DeleteScanTemplate) Name() string {\n\treturn \"delete-scan-template\"\n}" ]
[ "0.6744801", "0.608052", "0.58702874", "0.57997805", "0.5764414", "0.56866527", "0.54130113", "0.5200751", "0.51474035", "0.4966605", "0.49617893", "0.49286732", "0.49198192", "0.4913417", "0.49053788", "0.48483595", "0.48267484", "0.4805724", "0.47534278", "0.473707", "0.4732654", "0.4700005", "0.46952775", "0.4693247", "0.46721762", "0.4654283", "0.46415588", "0.45822808", "0.45676342", "0.45307466", "0.45152044", "0.4503363", "0.449746", "0.44898647", "0.44872743", "0.44677076", "0.4456113", "0.44360274", "0.44303226", "0.44141144", "0.43566465", "0.43496162", "0.4348622", "0.43405592", "0.43180338", "0.4298187", "0.427565", "0.42711222", "0.4259436", "0.42452312", "0.42356917", "0.42319295", "0.4205644", "0.42010015", "0.41881236", "0.4173417", "0.4173", "0.4168675", "0.41549373", "0.4146504", "0.41278338", "0.41271088", "0.41183698", "0.4114085", "0.41080308", "0.4106769", "0.41025895", "0.40982047", "0.40963966", "0.40946501", "0.40900764", "0.40810567", "0.40738177", "0.40732914", "0.4066843", "0.40653676", "0.4062369", "0.40602547", "0.40404853", "0.4033573", "0.402934", "0.40216774", "0.40206507", "0.40178177", "0.40072352", "0.40066466", "0.39980614", "0.39961448", "0.39955702", "0.39920232", "0.39907074", "0.39827904", "0.39768475", "0.3975199", "0.39735135", "0.3970756", "0.39601427", "0.39555982", "0.39503694", "0.39501098" ]
0.74567723
0
DeleteStack deletes the CloudFormation stack with the given name
func (a *Adapter) DeleteStack(stack *Stack) error { if err := detachTargetGroupFromAutoScalingGroup(a.autoscaling, stack.TargetGroupARN(), a.AutoScalingGroupName()); err != nil { return fmt.Errorf("DeleteStack failed to detach: %v", err) } return deleteStack(a.cloudformation, stack.Name()) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func deleteStack(name string) error {\n\tfmt.Printf(\"DEBUG:: deleting stack %v\\n\", name)\n\tcfg, err := external.LoadDefaultAWSConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\tsvc := cloudformation.New(cfg)\n\tdsreq := svc.DeleteStackRequest(&cloudformation.DeleteStackInput{StackName: aws.String(name)})\n\t_, err = dsreq.Send(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *Cloudformation) DeleteStack() (err error) {\n\tsess := s.config.AWSSession\n\tsvc := cloudformation.New(sess)\n\n\tstackInputs := cloudformation.DeleteStackInput{}\n\tstackInputs.SetStackName(s.StackName())\n\n\t_, err = svc.DeleteStack(&stackInputs)\n\treturn\n}", "func DeleteStack(stackName, profile, region string) {\n\tcf := GetCloudformationClient(profile, region)\n\tprinter.Step(fmt.Sprintf(\"Delete Stack %s:\", stackName))\n\n\t//See if the stack exists to begin with\n\t_, err := cf.DescribeStacks(&cloudformation.DescribeStacksInput{StackName: aws.String(stackName)})\n\tcheckError(err)\n\n\t_, err = cf.DeleteStack(&cloudformation.DeleteStackInput{StackName: aws.String(stackName)})\n\tcheckError(err)\n\n\t// status polling\n\tPrintStackEventHeader()\n\n\tfor {\n\t\tprinter.Progress(\"Deleting\")\n\t\ttime.Sleep(2 * time.Second)\n\t\tstatus, err := cf.DescribeStacks(&cloudformation.DescribeStacksInput{StackName: aws.String(stackName)})\n\t\tcheckErrorDeletePoll(err)\n\n\t\tevents, _ := cf.DescribeStackEvents(&cloudformation.DescribeStackEventsInput{StackName: aws.String(stackName)})\n\n\t\tif len(status.Stacks) > 0 {\n\t\t\tstackStatus := *status.Stacks[0].StackStatus\n\n\t\t\tif len(events.StackEvents) > 0 {\n\t\t\t\tPrintStackEvent(events.StackEvents[0], false)\n\t\t\t}\n\t\t\tif stackStatus == cloudformation.StackStatusDeleteInProgress {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tbreak\n\t}\n\n\t// Make sure delete worked\n\t_, err = cf.DescribeStacks(&cloudformation.DescribeStacksInput{StackName: aws.String(stackName)})\n\tif err != nil {\n\t\tcheckErrorDeletePoll(err)\n\t} else {\n\t\tprinter.SubStep(\n\t\t\tfmt.Sprintf(\"Success Delete Stack %s\", stackName),\n\t\t\t1,\n\t\t\ttrue,\n\t\t\ttrue,\n\t\t)\n\t\tos.Exit(0)\n\t}\n}", "func (c *Client) DeleteStack(stackSlug string) error {\n\treturn c.request(\"DELETE\", fmt.Sprintf(\"/api/instances/%s\", stackSlug), nil, nil, nil)\n}", "func Delete(ctx context.Context, serviceName string, logger *zerolog.Logger) error {\n\tawsConfig, awsConfigErr := spartaAWS.NewConfig(ctx, logger)\n\tif awsConfigErr != nil {\n\t\treturn awsConfigErr\n\t}\n\tawsCloudFormation := awsv2CF.NewFromConfig(awsConfig)\n\n\texists, err := spartaCF.StackExists(ctx, serviceName, awsConfig, logger)\n\tif nil != err {\n\t\treturn err\n\t}\n\tlogger.Info().\n\t\tBool(\"Exists\", exists).\n\t\tStr(\"Name\", serviceName).\n\t\tMsg(\"Stack existence check\")\n\n\tif exists {\n\n\t\tparams := &awsv2CF.DeleteStackInput{\n\t\t\tStackName: awsv2.String(serviceName),\n\t\t}\n\t\tresp, err := awsCloudFormation.DeleteStack(ctx, params)\n\t\tif nil != resp {\n\t\t\tlogger.Info().\n\t\t\t\tInterface(\"Response\", resp).\n\t\t\t\tMsg(\"Delete request submitted\")\n\t\t}\n\t\treturn err\n\t}\n\tlogger.Info().Msg(\"Stack does not exist\")\n\treturn nil\n}", "func (y *YogClient) DeleteStack(request DeleteStackRequest) (DeleteStackResponse, YogError) {\n\tret := DeleteStackResponse{}\n\n\treturn ret, YogError{}\n}", "func (m *MockCloudformationAPI) DeleteStack(*cloudformation.DeleteStackInput) (*cloudformation.DeleteStackOutput, error) {\n\treturn &cloudformation.DeleteStackOutput{}, nil\n}", "func (s *Stack) Destroy() error {\n\t_, err := s.cfnconn.DeleteStack(&cloudformation.DeleteStackInput{\n\t\tStackName: aws.String(s.Name),\n\t})\n\treturn errors.Annotatef(err, \"DeleteStack failed for stack '%s'\", s.Name)\n}", "func DeleteStack(ctx context.Context, svc *cf.CloudFormation, opts *RequestOptions) (*cf.DeleteStackOutput, error) {\n\tinput := &cf.DeleteStackInput{\n\t\tStackName: aws.String(opts.StackName),\n\t}\n\n\treturn svc.DeleteStackWithContext(ctx, input)\n}", "func (client *CraneDockerClient) RemoveStack(namespace string) error {\n\tservices, err := client.FilterServiceByStack(namespace, types.ServiceListOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, service := range services {\n\t\tlog.Info(\"begin to remove service \", service.Spec.Name)\n\t\tif err := client.RemoveService(service.ID); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tnetworks, err := client.filterStackNetwork(namespace)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, network := range networks {\n\t\tlog.Info(\"begin to remove network \", network.Name)\n\t\tif err := client.RemoveNetwork(network.ID); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(services) == 0 && len(networks) == 0 {\n\t\treturn cranerror.NewError(CodeStackUnavailable, fmt.Sprintf(\"stack or network can't be empty %s \", namespace))\n\t}\n\n\treturn nil\n}", "func (cf *Cloudformation) deleteEFS() {\n\n\tdeleteStack = &cobra.Command {\n\t\tUse: \"delete-efs\",\n\t\tShort: \"Delete stack\",\n\t\tLong: `Delete efs stack resources`,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\n\t\t\tstackName, err := cmd.Flags().GetString(\"stackname\")\n\t\t\tverify(err, \"stackname\")\n\n\t\t\tkeyPair, err := cmd.Flags().GetString(\"key-pair-name\")\n\t\t\tverify(err, \"key-pair-name\")\n\n\t\t\tcfClient := cloudformation.New(cf.sess, cf.sess.Config)\n\n\t\t\tif _, err := cfClient.DeleteStack(&cloudformation.DeleteStackInput{\n\t\t\t\tClientRequestToken: nil,\n\t\t\t\tRetainResources: nil,\n\t\t\t\tRoleARN: nil,\n\t\t\t\tStackName: &stackName,\n\t\t\t}); err != nil {\n\t\t\t\tfmt.Printf(\"Stack failed to delete with err: %s \\n\", err)\n\t\t\t}\n\n\t\t\tdeleteKeyPair(cf, keyPair, err)\n\n\t\t\tdeletePemFile()\n\n\t\t},\n\t}\n}", "func (c *StackCollection) DeleteStackBySpec(ctx context.Context, s *Stack) (*Stack, error) {\n\tif !matchesCluster(c.spec.Metadata.Name, s.Tags) {\n\t\treturn nil, fmt.Errorf(\"cannot delete stack %q as it doesn't bear our %q, %q tags\", *s.StackName,\n\t\t\tfmt.Sprintf(\"%s:%s\", api.OldClusterNameTag, c.spec.Metadata.Name),\n\t\t\tfmt.Sprintf(\"%s:%s\", api.ClusterNameTag, c.spec.Metadata.Name))\n\t}\n\n\tinput := &cloudformation.DeleteStackInput{\n\t\tStackName: s.StackId,\n\t}\n\n\tif cfnRole := c.roleARN; cfnRole != \"\" {\n\t\tinput.RoleARN = &cfnRole\n\t}\n\n\tif _, err := c.cloudformationAPI.DeleteStack(ctx, input); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"not able to delete stack %q\", *s.StackName)\n\t}\n\tlogger.Info(\"will delete stack %q\", *s.StackName)\n\treturn s, nil\n}", "func (m *Mockapi) DeleteStack(arg0 *cloudformation.DeleteStackInput) (*cloudformation.DeleteStackOutput, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteStack\", arg0)\n\tret0, _ := ret[0].(*cloudformation.DeleteStackOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (a *Client) DeleteNetworkSwitchStack(params *DeleteNetworkSwitchStackParams, authInfo runtime.ClientAuthInfoWriter) (*DeleteNetworkSwitchStackNoContent, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewDeleteNetworkSwitchStackParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"deleteNetworkSwitchStack\",\n\t\tMethod: \"DELETE\",\n\t\tPathPattern: \"/networks/{networkId}/switchStacks/{switchStackId}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &DeleteNetworkSwitchStackReader{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.(*DeleteNetworkSwitchStackNoContent)\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 deleteNetworkSwitchStack: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (r *Client) Destroy(ctx context.Context, stack Stack) error {\n\t// always update stack status\n\tdefer r.updateStatus(stack)\n\t// fetch current state\n\tstate, err := r.get(ctx, stack)\n\tif err == ErrStackNotFound {\n\t\t// resource is already deleted (or never existsed)\n\t\t// so we're done here\n\t\treturn nil\n\t} else if err != nil {\n\t\t// failed to get stack status\n\t\treturn err\n\t}\n\tif *state.StackStatus == DeleteComplete {\n\t\t// resource already deleted\n\t\treturn nil\n\t}\n\t// trigger a delete unless we're already in a deleting state\n\tif *state.StackStatus != DeleteInProgress {\n\t\t_, err := r.Client.DeleteStackWithContext(ctx, &DeleteStackInput{\n\t\t\tStackName: aws.String(stack.GetStackName()),\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t_, err = r.waitUntilDestroyedState(ctx, stack)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (d *Double) Delete(stackName string) error {\n\treturn d.DeleteFn(stackName)\n}", "func (c *CloudFormation) Stack(name string) (*Stack, error) {\n\tparams := &cfn.DescribeStacksInput{\n\t\tNextToken: aws.String(\"NextToken\"),\n\t\tStackName: aws.String(name),\n\t}\n\tresp, err := c.srv.DescribeStacks(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(resp.Stacks) != 1 {\n\t\treturn nil, fmt.Errorf(\"Reseived %v stacks, expected one\", len(resp.Stacks))\n\t}\n\n\treturn &Stack{srv: c.srv, Stack: resp.Stacks[0]}, nil\n}", "func Delete(c *cli.Context) {\n\tprinter.Progress(\"Kombusting\")\n\n\tfileName := c.Args().Get(0)\n\tif fileName == \"\" {\n\t\tprinter.Fatal(\n\t\t\tfmt.Errorf(\"Can't upsert file, no source template provided\"),\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"Add the path to the source template file you want to generate like: `kombustion upsert template.yaml`.\",\n\t\t\t),\n\t\t\t\"https://www.kombustion.io/api/manifest/\",\n\t\t)\n\t}\n\n\tmanifestFile := manifest.FindAndLoadManifest()\n\n\tenvironment := c.String(\"environment\")\n\n\tstackName := cloudformation.GetStackName(manifestFile, fileName, environment, c.String(\"stack-name\"))\n\n\tregion := c.String(\"region\")\n\tif region == \"\" {\n\t\t// If no region was provided by the cli flag, check for the default in the manifest\n\t\tif manifestFile.Region != \"\" {\n\t\t\tregion = manifestFile.Region\n\t\t}\n\t}\n\n\ttasks.DeleteStack(\n\t\tstackName,\n\t\tc.GlobalString(\"profile\"),\n\t\tregion,\n\t)\n}", "func (m *MockProviderClient) DeleteCloudformationStack(arg0 context.Context, arg1 map[string]string, arg2 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteCloudformationStack\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (mr *MockProviderClientMockRecorder) DeleteCloudformationStack(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteCloudformationStack\", reflect.TypeOf((*MockProviderClient)(nil).DeleteCloudformationStack), arg0, arg1, arg2)\n}", "func (o *deleteEnvOpts) deleteStack() bool {\n\to.prog.Start(fmt.Sprintf(fmtDeleteEnvStart, o.EnvName, o.ProjectName()))\n\tif err := o.deployClient.DeleteEnvironment(o.ProjectName(), o.EnvName); err != nil {\n\t\to.prog.Stop(fmt.Sprintf(fmtDeleteEnvFailed, o.EnvName, o.ProjectName(), err))\n\t\treturn false\n\t}\n\to.prog.Stop(fmt.Sprintf(fmtDeleteEnvComplete, o.EnvName, o.ProjectName()))\n\treturn true\n}", "func DestroyTerraformStack(t *testing.T, terraformDir string) {\n terraformOptions := test_structure.LoadTerraformOptions(t, terraformDir)\n terraform.Destroy(t, terraformOptions)\n\n kubectlOptions := test_structure.LoadKubectlOptions(t, terraformDir)\n err := os.Remove(kubectlOptions.ConfigPath)\n require.NoError(t, err)\n}", "func (c *StackCollection) DeleteStackSync(ctx context.Context, s *Stack) error {\n\ti, err := c.DeleteStackBySpec(ctx, s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogger.Info(\"waiting for stack %q to get deleted\", *i.StackName)\n\treturn c.doWaitUntilStackIsDeleted(ctx, s)\n}", "func (a *Adapter) MarkToDeleteStack(stack *Stack) (time.Time, error) {\n\tt0 := time.Now().Add(a.stackTTL)\n\n\treturn t0, markToDeleteStack(a.cloudformation, a.stackName(stack.CertificateARN()), t0.Format(time.RFC3339))\n}", "func (root *DSSRoot) removeStack(stack *Stack) {\n\tfor i, s := range root.stacks {\n\t\tif s == stack {\n\t\t\troot.stacks[i] = root.stacks[len(root.stacks)-1]\n\t\t\troot.stacks[len(root.stacks)-1] = nil\n\t\t\troot.stacks = root.stacks[:len(root.stacks)-1]\n\t\t}\n\t}\n}", "func (s *Cloudformation) CreateStack() (output *cloudformation.CreateStackOutput, err error) {\n\tsess := s.config.AWSSession\n\tsvc := cloudformation.New(sess)\n\n\tcftemplate := helpers.GetCloudFormationTemplate(s.config, \"s3bucket\", s.S3Bucket.Spec.CloudFormationTemplateName, s.S3Bucket.Spec.CloudFormationTemplateNamespace)\n\n\tstackInputs := cloudformation.CreateStackInput{\n\t\tStackName: aws.String(s.StackName()),\n\t\tTemplateURL: aws.String(cftemplate),\n\t\tNotificationARNs: []*string{\n\t\t\taws.String(s.topicARN),\n\t\t},\n\t}\n\n\tresourceName := helpers.CreateParam(\"ResourceName\", s.S3Bucket.Name)\n\tresourceVersion := helpers.CreateParam(\"ResourceVersion\", s.S3Bucket.ResourceVersion)\n\tnamespace := helpers.CreateParam(\"Namespace\", s.S3Bucket.Namespace)\n\tclusterName := helpers.CreateParam(\"ClusterName\", s.config.ClusterName)\n\tbucketName := helpers.CreateParam(\"BucketName\", helpers.Stringify(s.S3Bucket.Name))\n\tversioningTemp := \"{{.Obj.Spec.Versioning}}\"\n\tversioningValue, err := helpers.Templatize(versioningTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tversioning := helpers.CreateParam(\"EnableVersioning\", helpers.Stringify(versioningValue))\n\taccessControlTemp := \"{{.Obj.Spec.AccessControl}}\"\n\taccessControlValue, err := helpers.Templatize(accessControlTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\taccessControl := helpers.CreateParam(\"BucketAccessControl\", helpers.Stringify(accessControlValue))\n\tloggingenabledTemp := \"{{.Obj.Spec.Logging.Enabled}}\"\n\tloggingenabledValue, err := helpers.Templatize(loggingenabledTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tloggingenabled := helpers.CreateParam(\"EnableLogging\", helpers.Stringify(loggingenabledValue))\n\tloggingprefixTemp := \"{{.Obj.Spec.Logging.Prefix}}\"\n\tloggingprefixValue, err := helpers.Templatize(loggingprefixTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tloggingprefix := helpers.CreateParam(\"LoggingPrefix\", helpers.Stringify(loggingprefixValue))\n\twebsiteenabledTemp := \"{{.Obj.Spec.Website.Enabled}}\"\n\twebsiteenabledValue, err := helpers.Templatize(websiteenabledTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteenabled := helpers.CreateParam(\"EnableStaticSite\", helpers.Stringify(websiteenabledValue))\n\twebsiteindexPageTemp := \"{{.Obj.Spec.Website.IndexPage}}\"\n\twebsiteindexPageValue, err := helpers.Templatize(websiteindexPageTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteindexPage := helpers.CreateParam(\"StaticSiteIndex\", helpers.Stringify(websiteindexPageValue))\n\twebsiteerrorPageTemp := \"{{.Obj.Spec.Website.ErrorPage}}\"\n\twebsiteerrorPageValue, err := helpers.Templatize(websiteerrorPageTemp, helpers.Data{Obj: s.S3Bucket, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteerrorPage := helpers.CreateParam(\"StaticSiteError\", helpers.Stringify(websiteerrorPageValue))\n\n\tparameters := []*cloudformation.Parameter{}\n\tparameters = append(parameters, resourceName)\n\tparameters = append(parameters, resourceVersion)\n\tparameters = append(parameters, namespace)\n\tparameters = append(parameters, clusterName)\n\tparameters = append(parameters, bucketName)\n\tparameters = append(parameters, versioning)\n\tparameters = append(parameters, accessControl)\n\tparameters = append(parameters, loggingenabled)\n\tparameters = append(parameters, loggingprefix)\n\tparameters = append(parameters, websiteenabled)\n\tparameters = append(parameters, websiteindexPage)\n\tparameters = append(parameters, websiteerrorPage)\n\n\tstackInputs.SetParameters(parameters)\n\n\tresourceNameTag := helpers.CreateTag(\"ResourceName\", s.S3Bucket.Name)\n\tresourceVersionTag := helpers.CreateTag(\"ResourceVersion\", s.S3Bucket.ResourceVersion)\n\tnamespaceTag := helpers.CreateTag(\"Namespace\", s.S3Bucket.Namespace)\n\tclusterNameTag := helpers.CreateTag(\"ClusterName\", s.config.ClusterName)\n\n\ttags := []*cloudformation.Tag{}\n\ttags = append(tags, resourceNameTag)\n\ttags = append(tags, resourceVersionTag)\n\ttags = append(tags, namespaceTag)\n\ttags = append(tags, clusterNameTag)\n\n\tstackInputs.SetTags(tags)\n\n\toutput, err = svc.CreateStack(&stackInputs)\n\treturn\n}", "func (mr *MockCfnClientMockRecorder) DeleteStack(stackId interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteStack\", reflect.TypeOf((*MockCfnClient)(nil).DeleteStack), stackId)\n}", "func (action *DeleteStackAction) ExecuteAction(input interface{}) (output interface{}, err error) {\n\tlog.Info(\"EXECUTE DeleteStackAction\")\n\n\t//TODO handle non existing stack\n\tcloudformationSrv := cloudformation.New(action.context.Session)\n\tdeleteStackInput := &cloudformation.DeleteStackInput{\n\t\tClientRequestToken: aws.String(uuid.NewV4().String()),\n\t\tStackName: aws.String(action.StackName),\n\t}\n\treturn cloudformationSrv.DeleteStack(deleteStackInput)\n}", "func (s *Cloudformation) StackName() string {\n\treturn helpers.StackName(s.config.ClusterName, \"s3bucket\", s.S3Bucket.Name, s.S3Bucket.Namespace)\n}", "func (c *Client) DeleteOpenstack(i *DeleteOpenstackInput) error {\n\tif i.Service == \"\" {\n\t\treturn ErrMissingService\n\t}\n\n\tif i.Version == 0 {\n\t\treturn ErrMissingVersion\n\t}\n\n\tif i.Name == \"\" {\n\t\treturn ErrMissingName\n\t}\n\n\tpath := fmt.Sprintf(\"/service/%s/version/%d/logging/openstack/%s\", i.Service, i.Version, url.PathEscape(i.Name))\n\tresp, err := c.Delete(path, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar r *statusResp\n\tif err := decodeBodyMap(resp.Body, &r); err != nil {\n\t\treturn err\n\t}\n\tif !r.Ok() {\n\t\treturn ErrStatusNotOk\n\t}\n\treturn nil\n}", "func (r DeleteStackRequest) Send(ctx context.Context) (*DeleteStackResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &DeleteStackResponse{\n\t\tDeleteStackOutput: r.Request.Data.(*DeleteStackOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (s *SQLiteStore) deleteAllResourcesForStack(stackname string) error {\n\treturn nil\n}", "func NewDeleteStackAction(context *EksClusterDeletionContext, stackName string) *DeleteStackAction {\n\treturn &DeleteStackAction{\n\t\tcontext: context,\n\t\tStackName: stackName,\n\t}\n}", "func (c *CloudFormationTemplate) CreateStack(suffix string) {\n\tfmt.Printf(\"\\nRunning CloudFormation stack [%s]\", c.Name)\n\tsess := session.Must(session.NewSession(&aws.Config{\n\t\tRegion: aws.String(\"us-west-2\"),\n\t}))\n\tsvc := cloudformation.New(sess)\n\n\ttemplateBody := string(c.Bytes)\n\tc.StackName = c.Name + \"-\" + suffix\n\tcloudFormationValues := make(map[string]string)\n\n\tcreateStackParams := &cloudformation.CreateStackInput{\n\t\tStackName: aws.String(c.StackName),\n\t\tTemplateBody: aws.String(templateBody),\n\t}\n\n\tdescribeStacksParams := &cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(c.StackName),\n\t}\n\n\tout, err := svc.CreateStack(createStackParams)\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"AlreadyExistsException\") {\n\t\t\tfmt.Printf(\"\\nCloudFormation stack [%s] already exists. Skipping...\", c.Name)\n\t\t\tdescOut, err := svc.DescribeStacks(describeStacksParams)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tc.ParseOutput(descOut, cloudFormationValues)\n\t\t\treturn\n\t\t} else {\n\t\t\tfmt.Printf(\"%s\", err)\n\t\t\tpanic(err)\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"%s\", out)\n\t}\n\n\tstackReady := false\n\n\tfor stackReady != true {\n\n\t\tdescOut, err := svc.DescribeStacks(describeStacksParams)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%s\", err)\n\t\t\tpanic(err)\n\t\t} else {\n\t\t\tfmt.Printf(\"\\nCloudFormation stack [%s] is creating...\", c.Name)\n\t\t}\n\n\t\tif *descOut.Stacks[0].StackStatus == \"CREATE_COMPLETE\" {\n\t\t\tstackReady = true\n\t\t\tfmt.Printf(\"\\nCloudFormation stack [%s] ready...\\n\", c.Name)\n\t\t\tc.ParseOutput(descOut, cloudFormationValues)\n\t\t}\n\n\t\ttime.Sleep(time.Second * 7)\n\t}\n\n}", "func CreateStack(r string, name string, uri string, params []*cloudformation.Parameter, capabilities []*string) {\n\tsvc := cloudformation.New(getSession(r))\n\tlog.Info(\"CreateStack\")\n\n\tlog.Debug(\"Using Parameters:\")\n\tlog.Debug(\"%v\", params)\n\n\ttemplate := cloudformation.CreateStackInput{\n\t\tStackName: &name,\n\t\tParameters: params,\n\t\tCapabilities: capabilities,\n\t}\n\tif pass, path := parseURI(uri); pass {\n\t\ttemplateBody := utils.LoadTemplate(path)\n\t\ttemplate.TemplateBody = &templateBody\n\t} else {\n\t\ttemplate.TemplateURL = &path\n\t}\n\n\tstack, err := svc.CreateStack(&template)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Print(\"%v\", stack)\n}", "func TestCFCreateStack(t *testing.T) {\n\tt.Parallel()\n\n\texpectedName := fmt.Sprintf(\"terratest-cf-example-%s\", random.UniqueId())\n\n\tCFOptions := &cloudformation.Options{\n\t\tCFFile: \"../examples/cloudformation-aws-example/cf_create_test.yml\",\n\t\tStackName: expectedName,\n\t\tAWSRegion: \"us-west-2\",\n\t}\n\tdefer cloudformation.DeleteStack(t, CFOptions)\n\n\tcloudformation.CreateStack(t, CFOptions)\n\tlist := cloudformation.ListResources(t, CFOptions)\n\tfilteredList := cloudformation.FilterResources(list, \"DummyResource\")\n\tassert.Contains(t, filteredList, \"cloudformation-waitcondition-\")\n}", "func (mr *MockapiMockRecorder) DeleteStack(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteStack\", reflect.TypeOf((*Mockapi)(nil).DeleteStack), arg0)\n}", "func UpdateStack(r string, currentStack *cloudformation.Stack,\n\turi string, name string, params []*cloudformation.Parameter,\n\tcapabilities []*string) {\n\tsvc := cloudformation.New(getSession(r))\n\tlog.Info(\"UpdateStack\")\n\n\tgetUpdatedParameters(&currentStack.Parameters, params)\n\ttemplate := cloudformation.UpdateStackInput{\n\t\tStackName: &name,\n\t\tParameters: currentStack.Parameters,\n\t\tCapabilities: capabilities,\n\t}\n\n\tif pass, path := parseURI(uri); pass {\n\t\ttemplateBody := utils.LoadTemplate(path)\n\t\ttemplate.TemplateBody = &templateBody\n\t} else {\n\t\ttemplate.TemplateURL = &path\n\t}\n\n\tstack, err := svc.UpdateStack(&template)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Print(\"%v\", stack)\n}", "func (a *Client) RemoveNetworkSwitchStack(params *RemoveNetworkSwitchStackParams, authInfo runtime.ClientAuthInfoWriter) (*RemoveNetworkSwitchStackOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewRemoveNetworkSwitchStackParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"removeNetworkSwitchStack\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/networks/{networkId}/switchStacks/{switchStackId}/remove\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &RemoveNetworkSwitchStackReader{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.(*RemoveNetworkSwitchStackOK)\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 removeNetworkSwitchStack: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (s *Cloudformation) WaitUntilStackDeleted() (err error) {\n\tsess := s.config.AWSSession\n\tsvc := cloudformation.New(sess)\n\n\tstackInputs := cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(s.StackName()),\n\t}\n\n\terr = svc.WaitUntilStackDeleteComplete(&stackInputs)\n\treturn\n}", "func (m *MockCfnClient) DeleteStack(stackId string) (chan cfn.DeletionResult, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteStack\", stackId)\n\tret0, _ := ret[0].(chan cfn.DeletionResult)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (cf *Cloudformation) createStack() {\n\n\tcreateStack = &cobra.Command {\n\t\tUse: \"create-efs\",\n\t\tShort: \"Create stack\",\n\t\tLong: `Create stack based on template`,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\n\t\t\tparameters := make([]*cloudformation.Parameter, 0, 5)\n\n\t\t\tonFailure, err := cmd.Flags().GetString(\"onfailure\")\n\t\t\tverifyOnFailureArg(err, onFailure)\n\n\t\t\tcapabilities, err := cmd.Flags().GetStringArray(\"capabilities\")\n\t\t\tverifyCapability(err, capabilities)\n\n\t\t\tstackName, err := cmd.Flags().GetString(\"stackname\")\n\t\t\tverify(err, \"stackname\")\n\n\t\t\tinstanceType, err := cmd.Flags().GetString(\"instance-type\")\n\t\t\tverify(err, \"instance-type\")\n\t\t\taddParameter(&parameters, \"InstanceType\", instanceType)\n\n\t\t\tkeyPair, err := cmd.Flags().GetString(\"key-pair-name\")\n\t\t\tverify(err, \"key-pair-name\")\n\t\t\taddParameter(&parameters, \"KeyName\", keyPair)\n\n\t\t\tsubnets, err := cmd.Flags().GetStringArray(\"subnets\")\n\t\t\tverify(err, \"subnets\")\n\t\t\taddParameters(&parameters, \"Subnets\", subnets)\n\n\t\t\tvpc, err := cmd.Flags().GetString(\"vpc\")\n\t\t\tverify(err, \"vpc\")\n\t\t\taddParameter(&parameters, \"VPC\" ,vpc)\n\n\t\t\timage, err := cmd.Flags().GetString(\"image\")\n\t\t\tverify(err, \"image\")\n\t\t\taddParameter(&parameters, \"ImageId\", image)\n\n\t\t\tfor _, param := range parameters {\n\t\t\t\tfmt.Printf(\"----Param : %s ---- \\n\", param)\n\t\t\t}\n\n\t\t\tcfClient := cloudformation.New(cf.sess, cf.sess.Config)\n\n\t\t\tresp, err := cf.ec2Res.createKeyPair(keyPair)\n\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Create key pair err: %s \\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\n\t\t\tcreatePemFile(resp.KeyMaterial)\n\n\t\t\tfile := readFile(\"templates/distributed_file_system.yaml\")\n\n\t\t\tif _, err := cfClient.CreateStack(&cloudformation.CreateStackInput{\n\t\t\t\tCapabilities: aws.StringSlice(capabilities),\n\t\t\t\tClientRequestToken: nil,\n\t\t\t\tDisableRollback: nil,\n\t\t\t\tEnableTerminationProtection: nil,\n\t\t\t\tNotificationARNs: nil,\n\t\t\t\tOnFailure: &onFailure,\n\t\t\t\tParameters: parameters,\n\t\t\t\tResourceTypes: nil,\n\t\t\t\tRoleARN: nil,\n\t\t\t\tRollbackConfiguration: nil,\n\t\t\t\tStackName: &stackName,\n\t\t\t\tStackPolicyBody: nil,\n\t\t\t\tStackPolicyURL: nil,\n\t\t\t\tTags: nil,\n\t\t\t\tTemplateBody: &file,\n\t\t\t\tTemplateURL: nil,\n\t\t\t\tTimeoutInMinutes: nil,\n\t\t\t}); err != nil {\n\t\t\t\tdeleteKeyPair(cf, keyPair, err)\n\t\t\t}\n\n\t\t},\n\t}\n}", "func NewStack(ctx *pulumi.Context,\n\tname string, args *StackArgs, opts ...pulumi.ResourceOption) (*Stack, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.TemplateUrl == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'TemplateUrl'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Stack\n\terr := ctx.RegisterResource(\"aws-native:cloudformation:Stack\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (s *Stack) DeleteNetwork(ref string) (err error) {\n\ttheNetwork, err := s.GetNetwork(ref)\n\tif err != nil {\n\t\tif gerr, ok := err.(*googleapi.Error); ok {\n\t\t\tif gerr.Code != 404 {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif theNetwork == nil {\n\t\treturn fail.Errorf(\n\t\t\tfmt.Sprintf(\"delete network failed: unexpected nil network when looking for [%s]\", ref), err,\n\t\t)\n\t}\n\n\tif !theNetwork.OK() {\n\t\tlogrus.Warnf(\"Missing data in network: %s\", spew.Sdump(theNetwork))\n\t}\n\n\tcompuService := s.ComputeService\n\tsubnetwork, err := compuService.Subnetworks.Get(s.GcpConfig.ProjectID, s.GcpConfig.Region, theNetwork.Name).Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\topp, err := compuService.Subnetworks.Delete(s.GcpConfig.ProjectID, s.GcpConfig.Region, subnetwork.Name).Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toco := OpContext{\n\t\tOperation: opp,\n\t\tProjectID: s.GcpConfig.ProjectID,\n\t\tService: compuService,\n\t\tDesiredState: \"DONE\",\n\t}\n\n\terr = waitUntilOperationIsSuccessfulOrTimeout(oco, temporal.GetMinDelay(), temporal.GetHostCleanupTimeout())\n\tif err != nil {\n\t\tswitch err.(type) {\n\t\tcase fail.ErrTimeout:\n\t\t\tlogrus.Warnf(\"Timeout waiting for subnetwork deletion\")\n\t\t\treturn err\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Delete routes and firewall\n\tfirewallRuleName := fmt.Sprintf(\"%s-%s-all-in\", s.GcpConfig.NetworkName, subnetwork.Name)\n\tfws, err := compuService.Firewalls.Get(s.GcpConfig.ProjectID, firewallRuleName).Do()\n\tif fws != nil && err == nil {\n\t\topp, operr := compuService.Firewalls.Delete(s.GcpConfig.ProjectID, firewallRuleName).Do()\n\t\tif operr == nil {\n\t\t\toco := OpContext{\n\t\t\t\tOperation: opp,\n\t\t\t\tProjectID: s.GcpConfig.ProjectID,\n\t\t\t\tService: compuService,\n\t\t\t\tDesiredState: \"DONE\",\n\t\t\t}\n\n\t\t\toperr = waitUntilOperationIsSuccessfulOrTimeout(\n\t\t\t\toco, temporal.GetMinDelay(), temporal.GetHostCleanupTimeout(),\n\t\t\t)\n\t\t\tif operr != nil {\n\t\t\t\tlogrus.Warn(operr)\n\t\t\t}\n\t\t}\n\t}\n\tif err != nil {\n\t\tlogrus.Warn(err)\n\t}\n\n\tnatRuleName := fmt.Sprintf(\"%s-%s-nat-allowed\", s.GcpConfig.NetworkName, subnetwork.Name)\n\tnws, err := compuService.Routes.Get(s.GcpConfig.ProjectID, natRuleName).Do()\n\tif nws != nil && err == nil {\n\t\topp, operr := compuService.Routes.Delete(s.GcpConfig.ProjectID, natRuleName).Do()\n\t\tif operr == nil {\n\t\t\toco := OpContext{\n\t\t\t\tOperation: opp,\n\t\t\t\tProjectID: s.GcpConfig.ProjectID,\n\t\t\t\tService: compuService,\n\t\t\t\tDesiredState: \"DONE\",\n\t\t\t}\n\n\t\t\toperr = waitUntilOperationIsSuccessfulOrTimeout(\n\t\t\t\toco, temporal.GetMinDelay(), temporal.GetHostCleanupTimeout(),\n\t\t\t)\n\t\t\tif operr != nil {\n\t\t\t\tlogrus.Warn(operr)\n\t\t\t}\n\t\t}\n\t}\n\tif err != nil {\n\t\tlogrus.Warn(err)\n\t}\n\n\treturn nil\n}", "func (y *YogClient) CreateStack(request CreateStackRequest) (CreateStackResponse, YogError) {\n\tcsi, err := parseTemplate(request.TemplateBody)\n\tif err != nil {\n\t\tye := YogError{\n\t\t\tCode: FailedToParseYaml,\n\t\t\tMessage: \"error while parsing template\",\n\t\t\tError: err,\n\t\t\tDropletErrors: []DropletError{},\n\t\t\tStackname: request.StackName,\n\t\t}\n\t\treturn CreateStackResponse{}, ye\n\t}\n\n\tresponse := CreateStackResponse{Name: request.StackName}\n\tbuiltResources := []Resource{}\n\tfor k, v := range csi.Resources {\n\t\tvar s Service\n\t\tif _, ok := v[\"Type\"]; !ok {\n\t\t\tmessage := fmt.Sprintf(\"no 'Type' provided for resource '%s'\", k)\n\t\t\tye := YogError{\n\t\t\t\tCode: NoTypeForResource,\n\t\t\t\tMessage: message,\n\t\t\t\tError: errors.New(message),\n\t\t\t\tDropletErrors: []DropletError{},\n\t\t\t\tStackname: request.StackName,\n\t\t\t}\n\t\t\treturn CreateStackResponse{}, ye\n\t\t}\n\t\td, err := buildResource(s.Service(v[\"Type\"].(string)))\n\t\t// Droplet doesn't yet have an ID. This will be updated once they are created.\n\t\tif err != nil {\n\t\t\tye := YogError{\n\t\t\t\tCode: UnknownResourceType,\n\t\t\t\tMessage: \"\",\n\t\t\t\tError: err,\n\t\t\t\tDropletErrors: []DropletError{},\n\t\t\t\tStackname: request.StackName,\n\t\t\t}\n\t\t\treturn CreateStackResponse{}, ye\n\t\t}\n\t\terr = d.buildRequest(request.StackName, v)\n\t\tif err != nil {\n\t\t\tye := YogError{\n\t\t\t\tCode: FailedToBuildRequest,\n\t\t\t\tMessage: \"\",\n\t\t\t\tError: err,\n\t\t\t\tDropletErrors: []DropletError{},\n\t\t\t\tStackname: request.StackName,\n\t\t\t}\n\t\t\treturn CreateStackResponse{}, ye\n\t\t}\n\t\tbuiltResources = append(builtResources, d)\n\t}\n\n\tde := y.launchAllDroplets(builtResources)\n\tif len(de) != 0 {\n\t\tye := YogError{\n\t\t\tCode: ErrorLaunchingDroplets,\n\t\t\tStackname: request.StackName,\n\t\t\tError: errors.New(\"error launching droplets. please see DropletErrors for more detail\"),\n\t\t\tMessage: \"\",\n\t\t\tDropletErrors: de,\n\t\t}\n\t\treturn CreateStackResponse{}, ye\n\t}\n\terr = y.setupDropletIDsForResources(builtResources)\n\tif err != nil {\n\t\tye := YogError{\n\t\t\tCode: ErrorSettingUpDropletIDSForResources,\n\t\t\tStackname: request.StackName,\n\t\t\tError: err,\n\t\t\tMessage: \"error setting up droplet ids for resource\",\n\t\t\tDropletErrors: []DropletError{},\n\t\t}\n\t\treturn CreateStackResponse{}, ye\n\t}\n\terr = y.launchTheRestOfTheResources(builtResources)\n\tif err != nil {\n\t\tye := YogError{\n\t\t\tCode: ErrorLaunchingResource,\n\t\t\tStackname: request.StackName,\n\t\t\tError: err,\n\t\t\tMessage: \"error while trying to launch the rest of the resources\",\n\t\t\tDropletErrors: []DropletError{},\n\t\t}\n\t\treturn CreateStackResponse{}, ye\n\t}\n\n\tresponse.Resources = builtResources\n\t// Save resources here.\n\treturn response, YogError{}\n}", "func (client *CraneDockerClient) DeployStack(bundle *model.Bundle) error {\n\tif bundle.Namespace == \"\" || !isValidName.MatchString(bundle.Namespace) {\n\t\treturn cranerror.NewError(CodeInvalidStackName, \"invalid name, only [a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]\")\n\t}\n\n\tnewNetworkMap, err := client.PretreatmentStack(*bundle)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn client.deployServices(bundle.Stack.Services, bundle.Namespace, newNetworkMap)\n}", "func (c *StackCollection) DeleteStackBySpecSync(ctx context.Context, s *Stack, errs chan error) error {\n\ti, err := c.DeleteStackBySpec(ctx, s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogger.Info(\"waiting for stack %q to get deleted\", *i.StackName)\n\n\tgo c.waitUntilStackIsDeleted(ctx, i, errs)\n\n\treturn nil\n}", "func GetStack(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *StackState, opts ...pulumi.ResourceOption) (*Stack, error) {\n\tvar resource Stack\n\terr := ctx.ReadResource(\"aws-native:cloudformation:Stack\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func stackExists(stackNameOrID string, cf *cloudformation.CloudFormation, logger *logrus.Logger) (bool, error) {\n\tdescribeStacksInput := &cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(stackNameOrID),\n\t}\n\tdescribeStacksOutput, err := cf.DescribeStacks(describeStacksInput)\n\tlogger.Debug(\"DescribeStackOutput: \", describeStacksOutput)\n\texists := false\n\tif err != nil {\n\t\tlogger.Info(\"DescribeStackOutputError: \", err)\n\t\t// If the stack doesn't exist, then no worries\n\t\tif strings.Contains(err.Error(), \"does not exist\") {\n\t\t\texists = false\n\t\t} else {\n\t\t\treturn false, err\n\t\t}\n\t} else {\n\t\texists = true\n\t}\n\treturn exists, nil\n}", "func (s stack) GetStackName() (string, fail.Error) {\n\treturn \"aws\", nil\n}", "func (action *CreateVPCAction) UndoAction() (err error) {\n\tlog.Infoln(\"EXECUTE UNDO CreateVPCAction, deleting stack:\", action.stackName)\n\tcloudformationSrv := cloudformation.New(action.context.Session)\n\tdeleteStackInput := &cloudformation.DeleteStackInput{\n\t\tClientRequestToken: aws.String(uuid.NewV4().String()),\n\t\tStackName: aws.String(action.stackName),\n\t}\n\t_, err = cloudformationSrv.DeleteStack(deleteStackInput)\n\treturn err\n}", "func (m *MockCloudformationAPI) CreateStack(*cloudformation.CreateStackInput) (*cloudformation.CreateStackOutput, error) {\n\treturn &cloudformation.CreateStackOutput{}, nil\n}", "func Delete(c *cli.Context) {\n\tobjectStore := core.NewFilesystemStore(\".\")\n\n\tfileName := c.Args().Get(0)\n\tif fileName == \"\" {\n\t\tprinter.Fatal(\n\t\t\tfmt.Errorf(\"Can't upsert file, no source template provided\"),\n\t\t\t\"Add the path to the source template file you want to generate like: `kombustion upsert template.yaml`.\",\n\t\t\t\"https://www.kombustion.io/api/manifest/\",\n\t\t)\n\t}\n\n\tclient := &cloudformation.Wrapper{}\n\tprofile := c.GlobalString(\"profile\")\n\tregion := c.String(\"region\")\n\tenvName := c.String(\"environment\")\n\tstackName := c.String(\"stack-name\")\n\tmanifestFile := c.GlobalString(\"manifest-file\")\n\n\ttaskDelete(\n\t\tclient,\n\t\tobjectStore,\n\t\tfileName,\n\t\tprofile,\n\t\tstackName,\n\t\tregion,\n\t\tenvName,\n\t\tmanifestFile,\n\t)\n}", "func createStackFromBody(sess client.ConfigProvider, templateBody []byte, stackName string) error {\n\n\t// Tags for the CloudFormation stack\n\ttags := []*cfn.Tag{\n\t\t{\n\t\t\tKey: aws.String(\"Product\"),\n\t\t\tValue: aws.String(\"MaxEdge\"),\n\t\t},\n\t}\n\n\t//Creates CloudFormation stack\n\tsvc := cfn.New(sess)\n\tinput := &cfn.CreateStackInput{\n\t\tTemplateBody: aws.String(string(templateBody)),\n\t\tStackName: aws.String(stackName),\n\t\tTags: tags,\n\t\tCapabilities: []*string{aws.String(\"CAPABILITY_NAMED_IAM\")}, // Required because of creating a stack that is creating IAM resources\n\t}\n\n\tfmt.Println(\"Stack creation initiated...\")\n\n\t// Creates the stack\n\t_, err := svc.CreateStack(input)\n\tif err != nil {\n\t\tfmt.Println(\"Got error creating stack:\")\n\t\tfmt.Println(err.Error())\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *bdCommon) destroy(ctx context.Context, stack *thrapb.Stack) []*thrapb.ActionResult {\n\tar := make([]*thrapb.ActionResult, 0, len(stack.Components))\n\n\tfor _, comp := range stack.Components {\n\t\tr := &thrapb.ActionResult{\n\t\t\tAction: \"destroy\",\n\t\t\tResource: comp.ID,\n\t\t\tError: c.crt.Remove(ctx, comp.ID+\".\"+stack.ID),\n\t\t}\n\t\tar = append(ar, r)\n\t}\n\n\treturn ar\n}", "func (c *CaptainClient) DeleteFormation(id int) error {\n\t_, err := c.restDELETE(fmt.Sprintf(\"formation/%d\", id))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to delete Formation with ID %d:\\n%w\", id, err)\n\t}\n\treturn nil\n}", "func DescribeStacks(r string) {\n\tsvc := cloudformation.New(getSession(r))\n\n\tstatii := []*string{\n\t\taws.String(\"CREATE_COMPLETE\"),\n\t\taws.String(\"CREATE_IN_PROGRESS\"),\n\t\taws.String(\"UPDATE_COMPLETE\"),\n\t\taws.String(\"UPDATE_IN_PROGRESS\"),\n\t}\n\n\tstackSummaries, err := svc.ListStacks(&cloudformation.ListStacksInput{\n\t\tStackStatusFilter: statii,\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor _, stack := range stackSummaries.StackSummaries {\n\t\tlog.Print(\"%-52v %-40v %-20v\", *stack.StackName,\n\t\t\tstack.CreationTime.Format(\"Mon Jan 2 15:04:05 MST 2006\"),\n\t\t\t*stack.StackStatus,\n\t\t)\n\t\t// List change sets:\n\t\tchangeSets := DescribeChangeSets(r, *stack.StackName)\n\t\tfor _, change := range changeSets.Summaries {\n\t\t\tlog.Print(\"\\tchange set -> %-30v %-40v %-20v\", *change.ChangeSetName,\n\t\t\t\tchange.CreationTime.Format(\"Mon Jan 2 15:04:05 MST 2006\"),\n\t\t\t\t*change.ExecutionStatus,\n\t\t\t)\n\t\t}\n\t}\n}", "func StackExists(r string, name string) (bool, *cloudformation.Stack) {\n\tsvc := cloudformation.New(getSession(r))\n\tlog.Debug(\"Getting stack information for %v\", name)\n\n\tstackDetails, _ := svc.DescribeStacks(&cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(name),\n\t})\n\n\tif len(stackDetails.Stacks) == 1 {\n\t\treturn true, stackDetails.Stacks[0]\n\t}\n\n\treturn false, nil\n}", "func NewStack(cfnconn cloudformationiface.CloudFormationAPI, name string) (*Stack, error) {\n\tstack := &Stack{Name: name, cfnconn: cfnconn}\n\tif err := stack.updateOnce(); err != nil {\n\t\treturn nil, errors.Annotatef(err, \"cannot create new stack\")\n\t}\n\treturn stack, nil\n}", "func (c *Client) NewStack(stack *CreateStackInput) (int64, error) {\n\tdata, err := json.Marshal(stack)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tresult := struct {\n\t\tID int64 `json:\"id\"`\n\t}{}\n\n\terr = c.request(\"POST\", \"/api/instances\", nil, bytes.NewBuffer(data), &result)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn result.ID, nil\n}", "func NewCfnStack(scope constructs.Construct, id *string, props *CfnStackProps) CfnStack {\n\t_init_.Initialize()\n\n\tj := jsiiProxy_CfnStack{}\n\n\t_jsii_.Create(\n\t\t\"aws-cdk-lib.aws_cloudformation.CfnStack\",\n\t\t[]interface{}{scope, id, props},\n\t\t&j,\n\t)\n\n\treturn &j\n}", "func (manager *ComposeStackManager) Down(ctx context.Context, stack *portainer.Stack, endpoint *portainer.Endpoint) error {\n\turl, proxy, err := manager.fetchEndpointProxy(endpoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif proxy != nil {\n\t\tdefer proxy.Close()\n\t}\n\n\tenvFilePath, err := createEnvFile(stack)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to create env file\")\n\t}\n\n\terr = manager.deployer.Remove(ctx, stack.Name, nil, libstack.Options{\n\t\tWorkingDir: stack.ProjectPath,\n\t\tEnvFilePath: envFilePath,\n\t\tHost: url,\n\t})\n\n\treturn errors.Wrap(err, \"failed to remove a stack\")\n}", "func (c *sandboxes) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"sandboxes\").\n\t\tName(name).\n\t\tBody(&opts).\n\t\tDo(ctx).\n\t\tError()\n}", "func (m *MockCloudformationAPI) DescribeStacks(input *cloudformation.DescribeStacksInput) (*cloudformation.DescribeStacksOutput, error) {\n\tif m.FailDescribe {\n\t\treturn nil, m.Err\n\t}\n\n\treturn &cloudformation.DescribeStacksOutput{\n\t\tStacks: []*cloudformation.Stack{\n\t\t\t&cloudformation.Stack{\n\t\t\t\tStackName: aws.String(\"foo\"),\n\t\t\t\tStackStatus: aws.String(m.Status),\n\t\t\t\tOutputs: []*cloudformation.Output{\n\t\t\t\t\t&cloudformation.Output{\n\t\t\t\t\t\tOutputKey: aws.String(\"CustomerGateway0\"),\n\t\t\t\t\t\tOutputValue: aws.String(\"test-CustomerGatewayID\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, nil\n}", "func (f *FakeReconcilerClient) CreateStack(stackSpec types.StackSpec) (types.StackCreateResponse, error) {\n\tif stackSpec.Annotations.Name == \"\" {\n\t\treturn types.StackCreateResponse{}, fmt.Errorf(\"StackSpec contains no name\")\n\t}\n\n\tid, err := f.FakeStackStore.AddStack(stackSpec)\n\tif err != nil {\n\t\treturn types.StackCreateResponse{}, fmt.Errorf(\"unable to store stack: %s\", err)\n\t}\n\n\treturn types.StackCreateResponse{\n\t\tID: id,\n\t}, err\n}", "func (e *ComponentStackConfig) StackName() string {\n\tconst maxLen = 128\n\tstackName := fmt.Sprintf(\"oam-ecs-%s-%s\", e.ApplicationConfiguration.Name, e.ComponentConfiguration.InstanceName)\n\tif len(stackName) > maxLen {\n\t\treturn stackName[len(stackName)-maxLen:]\n\t}\n\treturn stackName\n}", "func (c *Client) UpdateStack(id int64, stack *UpdateStackInput) error {\n\tdata, err := json.Marshal(stack)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.request(\"POST\", fmt.Sprintf(\"/api/instances/%d\", id), nil, bytes.NewBuffer(data), nil)\n}", "func (a *Adapter) GetStack(stackID string) (*Stack, error) {\n\treturn getStack(a.cloudformation, stackID)\n}", "func (a *StacksApiService) GetStack(ctx _context.Context, stackId string) apiGetStackRequest {\n\treturn apiGetStackRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t\tstackId: stackId,\n\t}\n}", "func getStackName(input *commands.DNSInput) string {\n\treturn strings.Replace(input.HostedZone, \".\", \"-\", -1)\n}", "func (s *Stack) read() (*cloudformation.Stack, error) {\n\tout, err := s.cfnconn.DescribeStacks(&cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(s.Name),\n\t})\n\tif err != nil {\n\t\tif e, ok := err.(awserr.Error); ok && e.Code() == \"ValidationError\" {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, errors.Annotatef(err, \"cannot read stack\")\n\t}\n\tif out.Stacks == nil || len(out.Stacks) == 0 {\n\t\treturn nil, nil\n\t}\n\treturn out.Stacks[0], nil\n}", "func (d *Double) CancelUpdateStack(stackName string) error {\n\treturn d.CancelUpdateStackFn(stackName)\n}", "func DeleteSecurityGroup(s resources.SecurityGroup) {\n\tif s.Name == \"\" {\n\t\tfmt.Println(\"Empty security group name. Skipping deletion.\")\n\t\treturn\n\t}\n\tEventually(CF(\"delete-security-group\", s.Name, \"-f\")).Should(Exit(0))\n}", "func (c *stewards) Delete(name string, options *metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"stewards\").\n\t\tName(name).\n\t\tBody(options).\n\t\tDo().\n\t\tError()\n}", "func deleteKeyPair(cf *Cloudformation, keyPair string, err error) {\n\tif err != nil {\n\t\tfmt.Printf(\"Key pair deleted %s because stack failed with err: \\n %s \\n\", keyPair, err)\n\t\tos.Exit(1)\n\t}\n\t_, keyErr := cf.ec2Res.deleteKeyPair(keyPair)\n\tif keyErr != nil {\n\t\tfmt.Printf(\"Delete key pair err: %s \\n\", keyErr)\n\t}\n}", "func Delete(ctx context.Context, name string) error {\n\tname, ok := extractName(ctx)\n\tif !ok {\n\t\treturn ErrNoTreeAttached\n\t}\n\tmu.Lock()\n\tsvr, ok := trees[name]\n\tmu.Unlock()\n\tif !ok {\n\t\tpanic(\"oversight tree not found\")\n\t}\n\tsvr.Delete(name)\n\treturn nil\n}", "func (s *Cloudformation) UpdateStack(updated *awsV1alpha1.S3Bucket) (output *cloudformation.UpdateStackOutput, err error) {\n\tsess := s.config.AWSSession\n\tsvc := cloudformation.New(sess)\n\n\tcftemplate := helpers.GetCloudFormationTemplate(s.config, \"s3bucket\", updated.Spec.CloudFormationTemplateName, updated.Spec.CloudFormationTemplateNamespace)\n\n\tstackInputs := cloudformation.UpdateStackInput{\n\t\tStackName: aws.String(s.StackName()),\n\t\tTemplateURL: aws.String(cftemplate),\n\t\tNotificationARNs: []*string{\n\t\t\taws.String(s.topicARN),\n\t\t},\n\t}\n\n\tresourceName := helpers.CreateParam(\"ResourceName\", s.S3Bucket.Name)\n\tresourceVersion := helpers.CreateParam(\"ResourceVersion\", s.S3Bucket.ResourceVersion)\n\tnamespace := helpers.CreateParam(\"Namespace\", s.S3Bucket.Namespace)\n\tclusterName := helpers.CreateParam(\"ClusterName\", s.config.ClusterName)\n\tbucketName := helpers.CreateParam(\"BucketName\", helpers.Stringify(s.S3Bucket.Name))\n\tversioningTemp := \"{{.Obj.Spec.Versioning}}\"\n\tversioningValue, err := helpers.Templatize(versioningTemp, helpers.Data{Obj: updated, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tversioning := helpers.CreateParam(\"EnableVersioning\", helpers.Stringify(versioningValue))\n\taccessControlTemp := \"{{.Obj.Spec.AccessControl}}\"\n\taccessControlValue, err := helpers.Templatize(accessControlTemp, helpers.Data{Obj: updated, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\taccessControl := helpers.CreateParam(\"BucketAccessControl\", helpers.Stringify(accessControlValue))\n\tloggingenabledTemp := \"{{.Obj.Spec.Logging.Enabled}}\"\n\tloggingenabledValue, err := helpers.Templatize(loggingenabledTemp, helpers.Data{Obj: updated, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tloggingenabled := helpers.CreateParam(\"EnableLogging\", helpers.Stringify(loggingenabledValue))\n\tloggingprefixTemp := \"{{.Obj.Spec.Logging.Prefix}}\"\n\tloggingprefixValue, err := helpers.Templatize(loggingprefixTemp, helpers.Data{Obj: updated, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\tloggingprefix := helpers.CreateParam(\"LoggingPrefix\", helpers.Stringify(loggingprefixValue))\n\twebsiteenabledTemp := \"{{.Obj.Spec.Website.Enabled}}\"\n\twebsiteenabledValue, err := helpers.Templatize(websiteenabledTemp, helpers.Data{Obj: updated, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteenabled := helpers.CreateParam(\"EnableStaticSite\", helpers.Stringify(websiteenabledValue))\n\twebsiteindexPageTemp := \"{{.Obj.Spec.Website.IndexPage}}\"\n\twebsiteindexPageValue, err := helpers.Templatize(websiteindexPageTemp, helpers.Data{Obj: updated, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteindexPage := helpers.CreateParam(\"StaticSiteIndex\", helpers.Stringify(websiteindexPageValue))\n\twebsiteerrorPageTemp := \"{{.Obj.Spec.Website.ErrorPage}}\"\n\twebsiteerrorPageValue, err := helpers.Templatize(websiteerrorPageTemp, helpers.Data{Obj: updated, Config: s.config, Helpers: helpers.New()})\n\tif err != nil {\n\t\treturn output, err\n\t}\n\twebsiteerrorPage := helpers.CreateParam(\"StaticSiteError\", helpers.Stringify(websiteerrorPageValue))\n\n\tparameters := []*cloudformation.Parameter{}\n\tparameters = append(parameters, resourceName)\n\tparameters = append(parameters, resourceVersion)\n\tparameters = append(parameters, namespace)\n\tparameters = append(parameters, clusterName)\n\tparameters = append(parameters, bucketName)\n\tparameters = append(parameters, versioning)\n\tparameters = append(parameters, accessControl)\n\tparameters = append(parameters, loggingenabled)\n\tparameters = append(parameters, loggingprefix)\n\tparameters = append(parameters, websiteenabled)\n\tparameters = append(parameters, websiteindexPage)\n\tparameters = append(parameters, websiteerrorPage)\n\n\tstackInputs.SetParameters(parameters)\n\n\tresourceNameTag := helpers.CreateTag(\"ResourceName\", s.S3Bucket.Name)\n\tresourceVersionTag := helpers.CreateTag(\"ResourceVersion\", s.S3Bucket.ResourceVersion)\n\tnamespaceTag := helpers.CreateTag(\"Namespace\", s.S3Bucket.Namespace)\n\tclusterNameTag := helpers.CreateTag(\"ClusterName\", s.config.ClusterName)\n\n\ttags := []*cloudformation.Tag{}\n\ttags = append(tags, resourceNameTag)\n\ttags = append(tags, resourceVersionTag)\n\ttags = append(tags, namespaceTag)\n\ttags = append(tags, clusterNameTag)\n\n\tstackInputs.SetTags(tags)\n\n\toutput, err = svc.UpdateStack(&stackInputs)\n\treturn\n}", "func (a *StacksApiService) CreateStack(ctx _context.Context) apiCreateStackRequest {\n\treturn apiCreateStackRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t}\n}", "func UpdateStack(ctx context.Context, svc *cf.CloudFormation, opts *RequestOptions) (*cf.UpdateStackOutput, error) {\n\tinput := &cf.UpdateStackInput{\n\t\tStackName: aws.String(opts.StackName),\n\t\tCapabilities: []*string{\n\t\t\taws.String(\"CAPABILITY_IAM\"),\n\t\t},\n\t\tParameters: toParameters(opts.Params),\n\t\tTemplateURL: aws.String(opts.TemplateURL),\n\t}\n\n\treturn svc.UpdateStackWithContext(ctx, input)\n}", "func NewCfnStack(scope awscdk.Construct, id *string, props *CfnStackProps) CfnStack {\n\t_init_.Initialize()\n\n\tj := jsiiProxy_CfnStack{}\n\n\t_jsii_.Create(\n\t\t\"monocdk.aws_opsworks.CfnStack\",\n\t\t[]interface{}{scope, id, props},\n\t\t&j,\n\t)\n\n\treturn &j\n}", "func LoadStack(api cloudformationiface.CloudFormationAPI, config *StackConfig) (*Stack, error) {\n\tstack := &Stack{\n\t\tapi: api,\n\t\tconfig: config,\n\t\twaitAttempts: maxWaitAttempts,\n\t\twaiter: waiterFunc(sleepWaiter),\n\t\teventLoader: &stackEvents{\n\t\t\tapi: api,\n\t\t\tstackName: aws.String(config.Name),\n\t\t},\n\n\t\ttemplateReader: fileReaderFunc(ioutil.ReadFile),\n\t}\n\n\terr := stack.load()\n\tif err == nil {\n\t\terr = stack.storeLastEvent()\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn stack, nil\n}", "func (c *StackCollection) DeleteTasksForDeprecatedStacks() (*tasks.TaskTree, error) {\n\tstacks, err := c.ListStacksMatching(fmtDeprecatedStacksRegexForCluster(c.spec.Metadata.Name))\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"describing deprecated CloudFormation stacks for %q\", c.spec.Metadata.Name)\n\t}\n\tif len(stacks) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tdeleteControlPlaneTask := &tasks.TaskWithoutParams{\n\t\tInfo: fmt.Sprintf(\"delete control plane %q\", c.spec.Metadata.Name),\n\t\tCall: func(errs chan error) error {\n\t\t\t_, err := c.eksAPI.DescribeCluster(&eks.DescribeClusterInput{\n\t\t\t\tName: &c.spec.Metadata.Name,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t_, err = c.eksAPI.DeleteCluster(&eks.DeleteClusterInput{\n\t\t\t\tName: &c.spec.Metadata.Name,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tnewRequest := func() *request.Request {\n\t\t\t\tinput := &eks.DescribeClusterInput{\n\t\t\t\t\tName: &c.spec.Metadata.Name,\n\t\t\t\t}\n\t\t\t\treq, _ := c.eksAPI.DescribeClusterRequest(input)\n\t\t\t\treturn req\n\t\t\t}\n\n\t\t\tmsg := fmt.Sprintf(\"waiting for control plane %q to be deleted\", c.spec.Metadata.Name)\n\n\t\t\tacceptors := waiters.MakeAcceptors(\n\t\t\t\t\"Cluster.Status\",\n\t\t\t\teks.ClusterStatusDeleting,\n\t\t\t\t[]string{\n\t\t\t\t\teks.ClusterStatusFailed,\n\t\t\t\t},\n\t\t\t)\n\n\t\t\treturn waiters.Wait(c.spec.Metadata.Name, msg, acceptors, newRequest, c.waitTimeout, nil)\n\t\t},\n\t}\n\n\tcpStackFound := false\n\tfor _, s := range stacks {\n\t\tif strings.HasSuffix(*s.StackName, \"-ControlPlane\") {\n\t\t\tcpStackFound = true\n\t\t}\n\t}\n\ttaskTree := &tasks.TaskTree{}\n\n\tfor _, suffix := range deprecatedStackSuffices() {\n\t\tfor _, s := range stacks {\n\t\t\tif strings.HasSuffix(*s.StackName, \"-\"+suffix) {\n\t\t\t\tif suffix == \"-ControlPlane\" && !cpStackFound {\n\t\t\t\t\ttaskTree.Append(deleteControlPlaneTask)\n\t\t\t\t} else {\n\t\t\t\t\ttaskTree.Append(&taskWithStackSpec{\n\t\t\t\t\t\tstack: s,\n\t\t\t\t\t\tcall: c.DeleteStackBySpecSync,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn taskTree, nil\n}", "func deleteHyperShiftVPC(workingDir string) error {\n\tctx := context.Background()\n\n\ttf, err := terraform.New(workingDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\t_ = tf.Uninstall(ctx)\n\t}()\n\n\terr = tf.Init(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Println(\"Deleting ROSA HyperShift aws vpc\")\n\n\terr = callAndSetAWSSession(func() error {\n\t\treturn tf.Destroy(\n\t\t\tctx,\n\t\t\ttfexec.Var(fmt.Sprintf(\"aws_region=%s\", viper.GetString(config.AWSRegion))),\n\t\t\ttfexec.Var(fmt.Sprintf(\"cluster_name=%s\", viper.GetString(config.Cluster.Name))),\n\t\t)\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Println(\"ROSA HyperShift aws vpc deleted!\")\n\n\treturn nil\n}", "func (client *LocalRulestacksClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, localRulestackName string, options *LocalRulestacksClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/PaloAltoNetworks.Cloudngfw/localRulestacks/{localRulestackName}\"\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\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 localRulestackName == \"\" {\n\t\treturn nil, errors.New(\"parameter localRulestackName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{localRulestackName}\", url.PathEscape(localRulestackName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, 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-29\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (c *quarksStatefulSets) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"quarksstatefulsets\").\n\t\tName(name).\n\t\tBody(&opts).\n\t\tDo(ctx).\n\t\tError()\n}", "func (client *Client) CreateStack(request *CreateStackRequest) (response *CreateStackResponse, err error) {\n\tresponse = CreateCreateStackResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func popFromStack(stack *Stack) *Node {\n\treturn stack.Pop()\n}", "func NewDeleteStackActivity(awsSessionFactory AWSFactory) *DeleteStackActivity {\n\treturn &DeleteStackActivity{\n\t\tawsSessionFactory: awsSessionFactory,\n\t}\n}", "func lookupStack(clustername string) (string, string, error) {\n\tcfg, err := external.LoadDefaultAWSConfig()\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tsvc := cloudformation.New(cfg)\n\tvar activeStacks = []cloudformation.StackStatus{\"CREATE_COMPLETE\"}\n\tlsreq := svc.ListStacksRequest(&cloudformation.ListStacksInput{StackStatusFilter: activeStacks})\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tlsresp, err := lsreq.Send(context.TODO())\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\t// iterate over active stacks to find the two eksctl created, by label\n\tcpstack, dpstack := \"\", \"\"\n\tfor _, stack := range lsresp.StackSummaries {\n\t\tdsreq := svc.DescribeStacksRequest(&cloudformation.DescribeStacksInput{StackName: stack.StackName})\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", err\n\t\t}\n\t\tdsresp, err := dsreq.Send(context.TODO())\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", err\n\t\t}\n\t\t// fmt.Printf(\"DEBUG:: checking stack %v if it has label with cluster name %v\\n\", *dsresp.Stacks[0].StackName, clustername)\n\t\tcnofstack := tagValueOf(dsresp.Stacks[0], \"eksctl.cluster.k8s.io/v1alpha1/cluster-name\")\n\t\tif cnofstack != \"\" && cnofstack == clustername {\n\t\t\tswitch {\n\t\t\tcase tagValueOf(dsresp.Stacks[0], \"alpha.eksctl.io/nodegroup-name\") != \"\":\n\t\t\t\tdpstack = *dsresp.Stacks[0].StackName\n\t\t\tdefault:\n\t\t\t\tcpstack = *dsresp.Stacks[0].StackName\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Printf(\"DEBUG:: found control plane stack [%v] and data plane stack [%v] for cluster %v\\n\", cpstack, dpstack, clustername)\n\treturn cpstack, dpstack, nil\n}", "func terraformDestroy(path string) {\n\toldPwd := sh.Pwd()\n\tsh.Cd(path)\n\tlog.Info(\"Destroying terraformed resources...\")\n\tif !sh.FileExists(\"terraform.tfstate\") {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"pwd\": sh.Pwd(),\n\t\t}).Warn(\"No terraform.tfstate file to use in destruction!\")\n\t}\n\tcmd := exec.Command(\"terraform\", \"destroy\", \"-force\")\n\toutStr, err := ExecuteWithOutput(cmd)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"output\": outStr,\n\t\t\t\"command\": cmd.Args,\n\t\t}).Warn(\"Terraform destroy may have failed\")\n\t}\n\tsh.Cd(oldPwd)\n\tlog.Debug(\"Done destroying terraformed resources.\")\n}", "func (c *StackCollection) DescribeStack(ctx context.Context, i *Stack) (*Stack, error) {\n\tinput := &cloudformation.DescribeStacksInput{\n\t\tStackName: i.StackName,\n\t}\n\tif api.IsSetAndNonEmptyString(i.StackId) {\n\t\tinput.StackName = i.StackId\n\t}\n\tresp, err := c.cloudformationAPI.DescribeStacks(ctx, input)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"describing CloudFormation stack %q\", *i.StackName)\n\t}\n\tif len(resp.Stacks) == 0 {\n\t\treturn nil, fmt.Errorf(\"no CloudFormation stack found for %s\", *i.StackName)\n\t}\n\treturn &resp.Stacks[0], nil\n}", "func (c *StackCollection) UpdateStack(ctx context.Context, options UpdateStackOptions) error {\n\tlogger.Info(options.Description)\n\tif options.Stack == nil {\n\t\ti := &Stack{StackName: &options.StackName}\n\t\t// Read existing tags\n\t\ts, err := c.DescribeStack(ctx, i)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\toptions.Stack = s\n\t} else {\n\t\toptions.StackName = *options.Stack.StackName\n\t}\n\tif err := c.doCreateChangeSetRequest(ctx,\n\t\toptions.StackName,\n\t\toptions.ChangeSetName,\n\t\toptions.Description,\n\t\toptions.TemplateData,\n\t\toptions.Parameters,\n\t\toptions.Stack.Capabilities,\n\t\toptions.Stack.Tags,\n\t); err != nil {\n\t\treturn err\n\t}\n\tif err := c.doWaitUntilChangeSetIsCreated(ctx, options.Stack, options.ChangeSetName); err != nil {\n\t\tif _, ok := err.(*noChangeError); ok {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\tchangeSet, err := c.DescribeStackChangeSet(ctx, options.Stack, options.ChangeSetName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlogger.Debug(\"changes = %#v\", changeSet.Changes)\n\tif err := c.doExecuteChangeSet(ctx, options.StackName, options.ChangeSetName); err != nil {\n\t\tlogger.Warning(\"error executing Cloudformation changeSet %s in stack %s. Check the Cloudformation console for further details\", options.ChangeSetName, options.StackName)\n\t\treturn err\n\t}\n\tif options.Wait {\n\t\treturn c.doWaitUntilStackIsUpdated(ctx, options.Stack)\n\t}\n\treturn nil\n}", "func Remove(name string) error", "func (s *TattooStorage) DeleteTag(tagName string) {\n\treturn\n}", "func CleanUp(ctx context.Context, cfg *config.Config, pipeline *pipelines.Pipeline, name names.Name) error {\n\tkubectlPath, err := cfg.Tools[config.Kubectl].Resolve()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmd := proc.GracefulCommandContext(ctx, kubectlPath, \"delete\",\n\t\t\"all\",\n\t\t\"-l\", k8s.StackLabel+\"=\"+name.DNSName(),\n\t)\n\tif err := cmd.Run(); err != nil {\n\t\treturn fmt.Errorf(\"could not delete k8s resources: %v\", err)\n\t}\n\treturn nil\n}", "func (db *mongoDatabase) Destroy(opts *DestroyOptions) error {\n\tif err := opts.Valid(); err != nil {\n\t\treturn err\n\t}\n\n\terr := new(multierror.Error)\n\n\tfor _, id := range opts.Stack.Machines {\n\t\tif e := modelhelper.DeleteMachine(id); e != nil {\n\t\t\terr = multierror.Append(err, e)\n\t\t}\n\t}\n\n\tif e := modelhelper.DeleteComputeStack(opts.Stack.Id.Hex()); e != nil {\n\t\terr = multierror.Append(err, e)\n\t}\n\n\treturn err.ErrorOrNil()\n}", "func (y *YogClient) DescribeStack(request DescribeStackRequest) (DescribeStackResponse, YogError) {\n\treturn DescribeStackResponse{}, YogError{}\n}", "func (handler *Handler) stackCreate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {\n\tstackType, err := request.RetrieveNumericQueryParameter(r, \"type\", false)\n\tif err != nil {\n\t\treturn &httperror.HandlerError{http.StatusBadRequest, \"Invalid query parameter: type\", err}\n\t}\n\n\tmethod, err := request.RetrieveQueryParameter(r, \"method\", false)\n\tif err != nil {\n\t\treturn &httperror.HandlerError{http.StatusBadRequest, \"Invalid query parameter: method\", err}\n\t}\n\n\tendpointID, err := request.RetrieveNumericQueryParameter(r, \"endpointId\", false)\n\tif err != nil {\n\t\treturn &httperror.HandlerError{http.StatusBadRequest, \"Invalid query parameter: endpointId\", err}\n\t}\n\n\tendpoint, err := handler.EndpointService.Endpoint(portainer.EndpointID(endpointID))\n\tif err == portainer.ErrObjectNotFound {\n\t\treturn &httperror.HandlerError{http.StatusNotFound, \"Unable to find an endpoint with the specified identifier inside the database\", err}\n\t} else if err != nil {\n\t\treturn &httperror.HandlerError{http.StatusInternalServerError, \"Unable to find an endpoint with the specified identifier inside the database\", err}\n\t}\n\n\terr = handler.requestBouncer.EndpointAccess(r, endpoint)\n\tif err != nil {\n\t\treturn &httperror.HandlerError{http.StatusForbidden, \"Permission denied to access endpoint\", portainer.ErrEndpointAccessDenied}\n\t}\n\n\tswitch portainer.StackType(stackType) {\n\tcase portainer.DockerSwarmStack:\n\t\treturn handler.createSwarmStack(w, r, method, endpoint)\n\tcase portainer.DockerComposeStack:\n\t\treturn handler.createComposeStack(w, r, method, endpoint)\n\t}\n\n\treturn &httperror.HandlerError{http.StatusBadRequest, \"Invalid value for query parameter: type. Value must be one of: 1 (Swarm stack) or 2 (Compose stack)\", errors.New(request.ErrInvalidQueryParameter)}\n}", "func NewDeleteInstanceStackV4OK() *DeleteInstanceStackV4OK {\n\treturn &DeleteInstanceStackV4OK{}\n}", "func getStackName(input *commands.BucketInput) string {\n\treturn strings.Replace(input.FullDomainName, \".\", \"-\", -1) + \"-cdn\"\n}" ]
[ "0.8518868", "0.7966902", "0.77053547", "0.7586303", "0.7506792", "0.7419008", "0.695851", "0.6467567", "0.64151096", "0.6259764", "0.60829246", "0.60809505", "0.60699147", "0.6050879", "0.6039881", "0.6039098", "0.5982669", "0.5944772", "0.5906172", "0.58737314", "0.58247685", "0.5732748", "0.5727147", "0.5705568", "0.5698645", "0.5474361", "0.5468989", "0.5456977", "0.5454083", "0.5435543", "0.53369886", "0.5336363", "0.53327334", "0.5287761", "0.52837515", "0.5278425", "0.526099", "0.5225741", "0.52094084", "0.5184402", "0.51468116", "0.5145703", "0.51018536", "0.50903106", "0.5015817", "0.49904892", "0.49719417", "0.4930596", "0.49004257", "0.4889982", "0.4885382", "0.4880798", "0.4879151", "0.48684874", "0.48634028", "0.4859513", "0.4843681", "0.48322302", "0.4826033", "0.48161456", "0.48066193", "0.48006082", "0.47852722", "0.47660428", "0.4760792", "0.47572148", "0.47452554", "0.47423473", "0.47218594", "0.47189596", "0.4714636", "0.47077405", "0.47007385", "0.4691432", "0.46910208", "0.46909836", "0.46894678", "0.46877855", "0.46854246", "0.4680198", "0.46727085", "0.46631935", "0.46466437", "0.46225876", "0.46184057", "0.461763", "0.46171844", "0.4616803", "0.46061277", "0.45940417", "0.45921025", "0.45904276", "0.45831773", "0.4583003", "0.4579704", "0.457402", "0.45706543", "0.45668", "0.4566484", "0.4554113" ]
0.71696025
6
NewFinder constructs an Finder
func NewFinder(getter storage.Getter, feed *feeds.Feed) feeds.Lookup { return &finder{feeds.NewGetter(getter, feed)} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewFinder(conf Config) *Finder {\n\treturn &Finder{config: conf }\n}", "func NewFinder() Finder {\n\treturn &finder{fsWalk: filepath.Walk}\n}", "func NewFinder() *Finder {\n\tfinder := &Finder{\n\t\tFinder: core.NewFinder(),\n\t\tControlPoint: upnp.NewControlPoint(),\n\t}\n\n\tfinder.ControlPoint.Listener = finder\n\n\treturn finder\n}", "func NewFinder(ctx context.Context, zctx *zson.Context, uri iosrc.URI) (*Finder, error) {\n\treader, err := NewReaderFromURI(ctx, zctx, uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Finder{\n\t\tReader: reader,\n\t\tzctx: zctx,\n\t\turi: uri,\n\t}, nil\n}", "func NewFinder(ctx context.Context, zctx *zson.Context, engine storage.Engine, uri *storage.URI) (*Finder, error) {\n\treader, err := NewReaderFromURI(ctx, zctx, engine, uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Finder{\n\t\tReader: reader,\n\t\tzctx: zctx,\n\t\turi: uri,\n\t}, nil\n}", "func New(paths ...string) Finder {\n\tif len(paths) == 0 {\n\t\tpaths = []string{\"./\"}\n\t}\n\treturn Finder{paths}\n}", "func NewFinder(cfg *pb.GlobalConfig) Finder {\n\tf := &finder{\n\t\tlogs: make(map[string]*dpb.LogEntryDescriptor),\n\t\tmetrics: make(map[string]*dpb.MetricDescriptor),\n\t\tmonitoredResources: make(map[string]*dpb.MonitoredResourceDescriptor),\n\t\tprincipals: make(map[string]*dpb.PrincipalDescriptor),\n\t\tquotas: make(map[string]*dpb.QuotaDescriptor),\n\t\tattributes: make(map[string]*pb.AttributeManifest_AttributeInfo),\n\t}\n\n\tif cfg == nil {\n\t\treturn f\n\t}\n\n\tfor _, desc := range cfg.Logs {\n\t\tf.logs[desc.Name] = desc\n\t}\n\n\tfor _, desc := range cfg.Metrics {\n\t\tf.metrics[desc.Name] = desc\n\t}\n\n\tfor _, desc := range cfg.MonitoredResources {\n\t\tf.monitoredResources[desc.Name] = desc\n\t}\n\n\tfor _, desc := range cfg.Principals {\n\t\tf.principals[desc.Name] = desc\n\t}\n\n\tfor _, desc := range cfg.Quotas {\n\t\tf.quotas[desc.Name] = desc\n\t}\n\n\tfor _, manifest := range cfg.Manifests {\n\t\tfor name, info := range manifest.Attributes {\n\t\t\tf.attributes[name] = info\n\t\t}\n\t}\n\n\treturn f\n}", "func NewFinder(opt AgonesOption) *ServerFinder {\n\tfmt.Println(\"Agones Host:\", opt.Host)\n\tfmt.Println(\"Agones Port:\", opt.Port)\n\treturn &ServerFinder{\n\t\tagonesPort: opt.Port,\n\t\tagonesHost: opt.Host,\n\t\tfleetName: opt.FleetName,\n\t\tservers: make(map[uint32]*allocation.GameServerAllocation),\n\t}\n}", "func New(b []byte) (*Finding, error) {\n\tvar f Finding\n\tif err := json.Unmarshal(b, &f.Containerscanner); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &f, nil\n}", "func (c *DeviceConfig) newDeviceFinder() (*device.DeviceFinder, error) {\n\tif c.deviceFinderPath == \"\" {\n\t\treturn nil, fmt.Errorf(\"--device-finder-path not specified\")\n\t}\n\n\treturn device.NewDeviceFinder(c.deviceFinderPath), nil\n}", "func NewMockFinder(result [][]byte) *MockFinder {\n\treturn &MockFinder{\n\t\tresult: result,\n\t}\n}", "func NewFinding() *Finding {\n\treturn &Finding{}\n}", "func NewMockFinder(result [][]byte) *MockFinder {\n\treturn &MockFinder{\n\t\tfnd: NewCachedIndex(bytes.Join(result, []byte{'\\n'})),\n\t}\n}", "func NewTemplateFinder(templateProvider templates.TemplateProvider, osFinder os.OSFinder) *TemplateFinder {\n\treturn &TemplateFinder{\n\t\ttemplateProvider: templateProvider,\n\t\tosFinder: osFinder,\n\t}\n}", "func New(b []byte) (*Finding, error) {\n\tvar f Finding\n\tif err := json.Unmarshal(b, &f.FirewallScanner); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &f, nil\n}", "func NewTemplateFinder(templateProvider templates.TemplateProvider, osMapProvider templates.OSMapProvider) *TemplateFinder {\n\treturn &TemplateFinder{\n\t\ttemplateProvider: templateProvider,\n\t\tosMapProvider: osMapProvider,\n\t}\n}", "func NewMockFinder(ctrl *gomock.Controller) *MockFinder {\n\tmock := &MockFinder{ctrl: ctrl}\n\tmock.recorder = &MockFinderMockRecorder{mock}\n\treturn mock\n}", "func NewFind(filter bsoncore.Document) *Find {\n\treturn &Find{\n\t\tfilter: filter,\n\t}\n}", "func NewAsyncFinder(getter storage.Getter, feed *feeds.Feed) feeds.Lookup {\n\treturn &asyncFinder{feeds.NewGetter(getter, feed)}\n}", "func NewAsyncFinder(getter storage.Getter, feed *feeds.Feed) feeds.Lookup {\n\treturn &asyncFinder{feeds.NewGetter(getter, feed)}\n}", "func NewTaskFinder(sess *session.Session, cluster string) *TaskFinder {\n\treturn &TaskFinder{\n\t\tcluster: cluster,\n\t\tecs: ecs.New(sess),\n\t\tec2: ec2.New(sess),\n\t}\n}", "func NewPathFinder(container Container) *PathFinder {\n\treturn &PathFinder{\n\t\troot: container,\n\t}\n}", "func NewRepoFinder(root string) *RepoFinder {\n\treturn &RepoFinder{\n\t\troot: root,\n\t}\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 NewRepoFinder(root string) *RepoFinder {\n\treturn &RepoFinder{\n\t\troot: root,\n\t\tmaxWorkers: maxWorkers,\n\t}\n}", "func (sc *Scavenger) Finder() *MessageFinder {\n\treturn (*MessageFinder)(sc)\n}", "func newSearcher() *defaultSearcher {\n\treturn &defaultSearcher{\n\t\tpathStringer: new(defaultPathStringer),\n\t}\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 NewPeerFinder(t testing.TB) *PeerFinder {\n\tmock := &PeerFinder{}\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewDedupingFinder(sortedRecords []*common.Record, ra io.ReaderAt, combiner common.ObjectCombiner) common.Finder {\n\treturn &dedupingFinder{\n\t\tra: ra,\n\t\tsortedRecords: sortedRecords,\n\t\tcombiner: combiner,\n\t}\n}", "func NewFindOptions(flavor Flavor) *FindOptions {\n\treturn &FindOptions{\n\t\tFields: []string{\"*\"},\n\t\tFlavor: flavor,\n\t\tFilters: make(map[string]interface{}),\n\t}\n}", "func NewSourceFinder(ctx Context, config Config) (f *finder.Finder) {\n\tctx.BeginTrace(metrics.RunSetupTool, \"find modules\")\n\tdefer ctx.EndTrace()\n\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\tctx.Fatalf(\"No working directory for module-finder: %v\", err.Error())\n\t}\n\tfilesystem := fs.OsFs\n\n\t// if the root dir is ignored, then the subsequent error messages are very confusing,\n\t// so check for that upfront\n\tpruneFiles := []string{\".out-dir\", \".find-ignore\"}\n\tfor _, name := range pruneFiles {\n\t\tprunePath := filepath.Join(dir, name)\n\t\t_, statErr := filesystem.Lstat(prunePath)\n\t\tif statErr == nil {\n\t\t\tctx.Fatalf(\"%v must not exist\", prunePath)\n\t\t}\n\t}\n\n\tcacheParams := finder.CacheParams{\n\t\tWorkingDirectory: dir,\n\t\tRootDirs: []string{\".\"},\n\t\tExcludeDirs: []string{\".git\", \".repo\"},\n\t\tPruneFiles: pruneFiles,\n\t\tIncludeFiles: []string{\n\t\t\t\"Android.mk\",\n\t\t\t\"AndroidProducts.mk\",\n\t\t\t\"Android.bp\",\n\t\t\t\"Blueprints\",\n\t\t\t\"CleanSpec.mk\",\n\t\t\t\"OWNERS\",\n\t\t\t\"TEST_MAPPING\",\n\t\t},\n\t}\n\tdumpDir := config.FileListDir()\n\tf, err = finder.New(cacheParams, filesystem, logger.New(ioutil.Discard),\n\t\tfilepath.Join(dumpDir, \"files.db\"))\n\tif err != nil {\n\t\tctx.Fatalf(\"Could not create module-finder: %v\", err)\n\t}\n\treturn f\n}", "func NewPathfinder(start, end entity.Location) *Pathfinder {\n\tstartNode := &tileNode{loc: start, open: true}\n\tp := &Pathfinder{start: start, end: end, tileQueue: tileQueue{startNode}, activeTiles: map[int]*tileNode{start.Hash(): startNode, end.Hash(): {loc: end}}}\n\theap.Init(&p.tileQueue)\n\treturn p\n}", "func NewBarrageFinder() *BarrageFinder {\n\tf := new(BarrageFinder)\n\tf.where = bson.M{}\n\tf.barrages = []*Barrage{}\n\treturn f\n}", "func New(ctx context.Context, client *http.Client, projectName string) (*tree.FS, error) {\n\tp, err := newGithubProject(ctx, client, projectName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstart := time.Now()\n\tt, err := p.getTree(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"Loaded project with %d files in %.1fs\", len(t), time.Now().Sub(start).Seconds())\n\treturn tree.NewFS(t), nil\n}", "func NewSearchEngine(opts ...Option) *sqliteFilesSearchEngine {\n\tusr, _ := user.Current()\n\n\tsearchOptions := sqliteSearchOption{\n\t\tdbPath: filepath.Join(usr.HomeDir, \".fleek-space\"),\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(&searchOptions)\n\t}\n\n\treturn &sqliteFilesSearchEngine{\n\t\tdb: nil,\n\t\topts: searchOptions,\n\t}\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 newIntFinder(rids []int) intFinder {\n\tf := intFinder{}\n\tf.m = make(map[int]int)\n\tfor i, rid := range rids { f.m[rid] = i }\n\treturn f\n}", "func NewSearcher(cfg *Config, repos KeyValueStorer) searcher {\n\treturn searcher{\n\t\tcfg: cfg,\n\t\trepos: repos,\n\t}\n}", "func NewSimpleFakeResourceFinder(infos ...*resource.Info) ResourceFinder {\n\treturn &fakeResourceFinder{\n\t\tInfos: infos,\n\t}\n}", "func New(slice *[]int) (*Search, error) {\n\tvar s = Search{slice: slice}\n\treturn &s, nil\n}", "func (d *Disk) Find(name string) (File, error) {\n\n\td.moot.RLock()\n\tif f, ok := d.files[name]; ok {\n\t\tif seek, ok := f.(io.Seeker); ok {\n\t\t\t_, err := seek.Seek(0, 0)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\td.moot.RUnlock()\n\t\treturn f, nil\n\t}\n\td.moot.RUnlock()\n\n\tgf := NewFile(name, bytes.NewReader([]byte(\"\")))\n\n\tosname := name\n\tif runtime.GOOS == \"windows\" {\n\t\tosname = strings.Replace(osname, \"/\", \"\\\\\", -1)\n\t}\n\tf, err := os.Open(osname)\n\tif err != nil {\n\t\treturn gf, err\n\t}\n\tdefer f.Close()\n\n\tbb := &bytes.Buffer{}\n\n\tif _, err := io.Copy(bb, f); err != nil {\n\t\treturn gf, err\n\t}\n\tgf = NewFile(name, bb)\n\td.Add(gf)\n\treturn gf, nil\n}", "func NewDiscovery(conf *SDConfig, logger log.Logger) *Discovery {\n\tif logger == nil {\n\t\tlogger = log.NewNopLogger()\n\t}\n\n\tdisc := &Discovery{\n\t\tpaths: conf.Files,\n\t\tinterval: time.Duration(conf.RefreshInterval),\n\t\ttimestamps: make(map[string]float64),\n\t\tlogger: logger,\n\t}\n\tfileSDTimeStamp.addDiscoverer(disc)\n\treturn disc\n}", "func NewJiraFinder(c *config.Configuration) (error, *JiraFinder) {\n\tif c.JiraURL == \"\" {\n\t\treturn errors.New(\"no config file found. Set the config first before searching using SetConfig() func\"), nil\n\t}\n\n\treturn nil, &JiraFinder{\n\t\tConfig: *c,\n\t\tapi: httprequest.NewClient(c.JiraURL, c.AuthToken),\n\n\t\tfiltersCh: make(chan keyPairValue),\n\t\tfieldsCh: make(chan fieldParam),\n\n\t\tfieldKeys: make([]string, len(c.FieldsToRetrieve)),\n\t\tmu: sync.RWMutex{},\n\t}\n}", "func New(decoder fsio.ReadSeekerAt) (*FS, error) {\n\t// parser volume header\n\tvh := volumeHeader{}\n\terr := binary.Read(decoder, binary.LittleEndian, &vh)\n\tif err != nil && err != io.EOF {\n\t\treturn nil, err\n\t}\n\tdecoder.Seek(0, 0) // nolint: errcheck\n\n\tfs := &FS{vh: vh, decoder: decoder}\n\n\treturn fs, err\n}", "func NewInMemoryFinder(graph *orderbook.OrderBookGraph, includePools bool) InMemoryFinder {\n\treturn InMemoryFinder{\n\t\tgraph: graph,\n\t\tincludePools: includePools,\n\t}\n}", "func New(o *Options) (Matcher, error) {\n\t// creates data clients\n\tdataClients, err := createDataClients(o.RoutesFile)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trouting := createRouting(dataClients, o)\n\n\treturn &matcher{\n\t\trouting,\n\t}, nil\n}", "func NewBlobRangeFinder(getObjects *[]helperModels.GetObject) BlobRangeFinder {\n rangeMap := toRangeMap(getObjects)\n return &BlobRangeFinderImpl{\n rangeMap: *rangeMap,\n collapser: RangeCollapserImpl{},\n }\n}", "func NewMatcher(readonly bool, fsType string) Matcher {\n\treturn mount{readonly, fsType}\n}", "func New(data []byte) (*FS, error) {\n\tgzdata, err := gzip.NewReader(bytes.NewReader(data))\n\tif err != nil {\n\t\treturn nil, errs.Wrap(err)\n\t}\n\n\tfs := &FS{\n\t\troot: newFile(),\n\t}\n\tfs.root.setFileInfo(rootFileInfo{})\n\n\ttardata := tar.NewReader(gzdata)\n\tfor {\n\t\th, err := tardata.Next()\n\t\tif err == io.EOF {\n\t\t\treturn fs, nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, errs.Wrap(err)\n\t\t}\n\n\t\tfile := fs.getFile(h.Name, true)\n\t\tfile.setFileInfo(h.FileInfo())\n\n\t\tdata, err := ioutil.ReadAll(tardata)\n\t\tif err != nil {\n\t\t\treturn nil, errs.Wrap(err)\n\t\t}\n\t\tfile.setData(data)\n\n\t\tswitch h.Name {\n\t\tcase \"index.html\", \"./index.html\":\n\t\t\tfs.def = file\n\t\t}\n\t}\n}", "func NewClosestDiffFinder(exp expectations.ReadOnly, dCounter digest_counter.DigestCounter, diffStore diff.DiffStore) *Impl {\n\treturn &Impl{\n\t\texpectations: exp,\n\t\tdCounter: dCounter,\n\t\tdiffStore: diffStore,\n\t}\n}", "func New(root *file.File, server *fs.Server, opts *Options) *FS {\n\tfs := &FS{root: root, server: server}\n\tfs.rnode = &Node{fs: fs, file: fs.root}\n\treturn fs\n}", "func Constructor() MedianFinder {\n\treturn MedianFinder{}\n}", "func Constructor() MedianFinder {\n\treturn MedianFinder{}\n}", "func New() http.FileSystem {\n\treturn &fileSystem{\n\t\tfiles: files,\n\t}\n}", "func (sp SourceSpec) NewFilesystem(base string) *Filesystem {\n\treturn &Filesystem{SourceSpec: sp, Base: base}\n}", "func WithMethod(method Method) func(*Finder) {\n\treturn func(n *Finder) {\n\t\tn.method = method\n\t}\n}", "func New(drv Driver) FileSystem {\n\treturn FileSystem{drv}\n}", "func NewFindResult(args ...interface{}) *FindResult {\n\tt, ok := args[0].(string)\n\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\"expected string for type, got %T\", args[0]))\n\t}\n\n\ti, ok := args[1].(string)\n\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\"expected string for id, got %T\", args[1]))\n\t}\n\n\tr, ok := args[2].(map[string]interface{})\n\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\"expected map[string]interface{} for result, got %T\", args[2]))\n\t}\n\n\tm, ok := args[3].(map[string]interface{})\n\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\"expected map[string]interface{} for metadata, got %T\", args[3]))\n\t}\n\n\treturn &FindResult{\n\t\tType: t,\n\t\tId: i,\n\t\tMetadata: m,\n\t\tRecord: r,\n\t}\n}", "func NewExplorer(search vectorClassSearch,\n\tdistancer distancer, logger logrus.FieldLogger,\n\tmodulesProvider ModulesProvider) *Explorer {\n\treturn &Explorer{search, distancer, logger, modulesProvider}\n}", "func NewExplorer(search vectorClassSearch, vectorizer CorpiVectorizer,\n\tdistancer distancer, logger logrus.FieldLogger, nnExtender nnExtender,\n\tprojector projector, pathBuilder pathBuilder) *Explorer {\n\treturn &Explorer{search, vectorizer, distancer, logger, nnExtender, projector, pathBuilder}\n}", "func New(opts ...option) FS {\n\tf := fs{\n\t\tsys: sys{},\n\t}\n\tf.applyOptions(opts...)\n\treturn f\n}", "func newExplorer(period, offset int) *explorer {\n\te := explorer{period: period}\n\te.advance(offset)\n\treturn &e\n}", "func New() *FS {\n\treturn &FS{}\n}", "func Find(ctx context.Context, tconn *chrome.TestConn) (*FilePicker, error) {\n\tfilesApp, err := filesapp.App(ctx, tconn, vars.FilePickerPseudoAppID)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to find file picker\")\n\t}\n\treturn &FilePicker{filesApp: filesApp}, nil\n}", "func New(cmd *cobra.Command, args []string) {\n\t// Create object for current working directory\n\tpwd, err := teflon.NewTeflonObject(\".\")\n\tif err != nil {\n\t\tlog.Fatalln(\"Couldn't create object for '.' :\", err)\n\t}\n\n\t// Create a show.\n\tif showFlag {\n\t\tnshws, err := pwd.CreateShow(args[0], newShowProtoFlag)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"ABORT: Couldnt create show:\", err)\n\t\t}\n\t\tfor _, shw := range nshws {\n\t\t\tfmt.Println(shw.Path)\n\t\t}\n\t\treturn\n\t}\n\n\t// If nothing else commands otherwise new will create an ordinary file-system\n\t// object.\n\tnobjs, err := pwd.CreateObject(args[0], newFileFlag)\n\tif err != nil {\n\t\tlog.Fatalln(\"ABORT: Couldn't create objects:\", err)\n\t}\n\tclose(teflon.Events)\n\tfor _, obj := range nobjs {\n\t\tfmt.Println(obj.Path)\n\t}\n}", "func Constructor() MedianFinder {\n return MedianFinder{}\n}", "func New(base fsio.ReadSeekerAt) (*FS, error) {\n\tsize, err := fsio.GetSize(base)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tzr, err := zip.NewReader(base, size)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &FS{zr}, nil\n}", "func New(options Options) *Diskv {\n\tif options.BasePath == \"\" {\n\t\toptions.BasePath = defaultBasePath\n\t}\n\tif options.Transform == nil {\n\t\toptions.Transform = defaultTransform\n\t}\n\tif options.PathPerm == 0 {\n\t\toptions.PathPerm = defaultPathPerm\n\t}\n\tif options.FilePerm == 0 {\n\t\toptions.FilePerm = defaultFilePerm\n\t}\n\n\td := &Diskv{\n\t\tOptions: options,\n\t\tcache: map[string][]byte{},\n\t\tcacheSize: 0,\n\t}\n\n\tif d.Index != nil && d.IndexLess != nil {\n\t\td.Index.Initialize(d.IndexLess, d.Keys())\n\t}\n\n\treturn d\n}", "func New(baseDir string, opts ...Option) billy.Filesystem {\n\to := &options{}\n\tfor _, opt := range opts {\n\t\topt(o)\n\t}\n\n\tif o.Type == BoundOSFS {\n\t\treturn newBoundOS(baseDir)\n\t}\n\n\treturn newChrootOS(baseDir)\n}", "func NewMeshFinder(\n\tctx context.Context,\n\tclusterName string,\n\tmeshScanners []MeshScanner,\n\tlocalMeshClient smh_discovery.MeshClient,\n\tclusterClient client.Client,\n\tclusterScopedDeploymentClient k8s_apps.DeploymentClient,\n) MeshFinder {\n\treturn &meshFinder{\n\t\tclusterName: clusterName,\n\t\tmeshScanners: meshScanners,\n\t\tlocalMeshClient: localMeshClient,\n\t\tctx: ctx,\n\t\tclusterClient: clusterClient,\n\t\tclusterScopedDeploymentClient: clusterScopedDeploymentClient,\n\t}\n}", "func New(options ...Option) *Scanner {\n\ts := &Scanner{\n\t\tignoreCheckErrors: true,\n\t}\n\tfor _, option := range options {\n\t\toption(s)\n\t}\n\treturn s\n}", "func ConstructorMedianFinder() MedianFinder {\n\tm := MedianFinder{}\n\tm.Small = (*smallInt)(new([]int))\n\tm.Large = (*largeInt)(new([]int))\n\treturn m\n}", "func NewRepoFinder(client *github.Client) *RepoFinder {\n\treturn &RepoFinder{Client: client}\n}", "func New(ctx context.Context, path string) (Interface, error) {\n\tscheme := getScheme(path)\n\tmkfs, ok := registry[scheme]\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"file system scheme %v not registered for %v\", scheme, path)\n\t}\n\treturn mkfs(ctx), nil\n}", "func NewLister(tableName string, selectedColumns []string) Lister {\n\treturn &universalLister{\n\t\ttableName: tableName,\n\t\tselectedColumns: strings.Join(selectedColumns, \", \"),\n\t\torderByParams: NoOrderBy,\n\t}\n}", "func New(root string, config *converter.Config) (runtime.Source, error) {\n\treturn newFsSource(root, config, kube_meta.Types.All())\n}", "func NewUnionFind(sz int) *UnionFind {\n\tPanicIf(sz < 0, \"bad argument: %d\", sz)\n\tid := make([]int, sz)\n\tsize := make([]int, sz)\n\tfor i, _ := range id {\n\t\tid[i] = i\n\t\tsize[i] = 1\n\t}\n\treturn &UnionFind{id: id, size: size, volume: sz}\n}", "func NewSearcher(token string) (Searcher, error) {\n\tif token == \"\" {\n\t\treturn nil, fmt.Errorf(\"[err] NewSearcher %w\", ErrInvalidParam)\n\t}\n\n\tcfgPath, err := ConfigPath()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"[err] NewSearcher %w\", err)\n\t}\n\tdbPath := filepath.Join(cfgPath, dbFileName)\n\n\t// make git client\n\tgit, err := git.NewGit(token)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"[err] NewSearcher %w\", err)\n\t}\n\n\t// make bolt db\n\tdb, err := bolt.Open(dbPath, os.ModePerm, &bolt.Options{Timeout: 5 * time.Second})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"[err] NewSearcher fail db %w.(maybe already running findgs)\", err)\n\t}\n\n\t// make index\n\tindex, err := bleve.NewMemOnly(bleve.NewIndexMapping())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"[err] NewSearcher fail db %w\", err)\n\t}\n\n\treturn &searcher{git: git, db: db, index: index, gitToken: token, dbPath: dbPath}, nil\n}", "func NewSearcher(lat_tiles, lng_tiles int) Searcher {\n\tsearcher := Searcher{}\n\tsearcher.lat_tiles = lat_tiles\n\tsearcher.lng_tiles = lng_tiles\n\tsearcher.locatable_map = newLocatableMap(lat_tiles, lng_tiles)\n\treturn searcher\n}", "func NewFs() *Fs { return &Fs{make(map[string]*file)} }", "func NewScanner(r io.Reader, filename string) *Scanner {\n s := scanner.Scanner{}\n s.Init(r)\n s.Position.Filename = filename\n\n tok := s.Scan()\n toktext := s.TokenText()\n\n return &Scanner{s, tok, toktext}\n}", "func New(resolver keyResolver, suites ...SignatureSuite) (*DocumentVerifier, error) {\n\treturn verifier.New(resolver, suites...)\n}", "func New(root, id string) (Pather, error) {\n\tswitch id {\n\tcase DockerTag:\n\t\treturn DockerTagPather{root}, nil\n\tcase ShardedDockerBlob:\n\t\treturn ShardedDockerBlobPather{root}, nil\n\tcase Identity:\n\t\treturn IdentityPather{root}, nil\n\tcase \"\":\n\t\treturn nil, fmt.Errorf(\"invalid pather identifier: empty\")\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown pather identifier: %s\", id)\n\t}\n}", "func New(r *io.RuneReader) *Scanner {\n\treturn &Scanner{\n\t\tr: *r,\n\t}\n}", "func (f FileLocation) construct() FileLocationClass { return &f }", "func New(root string, options ...func(*LinuxFactory) error) (Factory, error) {\n\tif root != \"\" {\n\t\tif err := os.MkdirAll(root, 0700); err != nil {\n\t\t\treturn nil, newGenericError(err, SystemError)\n\t\t}\n\t}\n\tl := &LinuxFactory{\n\t\tRoot: root,\n\t\tValidator: validate.New(),\n\t\tCriuPath: \"criu\",\n\t}\n\tInitArgs(os.Args[0], \"init\")(l)\n\tCgroupfs(l)\n\tfor _, opt := range options {\n\t\tif err := opt(l); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn l, nil\n}", "func NewFileManager(log backend.LogFunc) *FileManager {\n\treturn &FileManager{\n\t\tpatch: make(map[string][]*plugin.Generated),\n\t\tindex: make(map[string]int),\n\t\tcount: make(map[string]int),\n\t\tlog: log,\n\t}\n}", "func NewFactory(options ...Option) Factory {\n\n\treturn Factory(func(from ...interface{}) (result Paginator) {\n\n\t\tresult = defaultPaginator(options...)\n\n\t\t// apply options\n\t\trunOptions(result, true, options...)\n\n\t\tif len(from) > 0 {\n\t\t\tresult.From(from...)\n\t\t}\n\n\t\treturn\n\t})\n}", "func newSearch(inst *Instagram) *Search {\n\tsearch := &Search{\n\t\tinst: inst,\n\t}\n\treturn search\n}", "func New(root string, expire time.Duration, interval time.Duration, batchNum int64) *FCleaner {\n\treturn &FCleaner{\n\t\troot: root,\n\t\texpire: expire,\n\t\tinterval: interval,\n\t\tbatchNum: batchNum,\n\t\tfilter: func(path string, info os.FileInfo) (willClean bool) {\n\t\t\treturn true\n\t\t},\n\t}\n}", "func New(store database.DAL) *Resolver {\n\treturn &Resolver{store}\n}", "func (f *RepoFinder) Find() error {\n\tif _, err := Exists(f.root); err != nil {\n\t\treturn err\n\t}\n\n\twalkOpts := &godirwalk.Options{\n\t\tErrorCallback: f.errorCb,\n\t\tCallback: f.walkCb,\n\t\t// Use Unsorted to improve speed because repos will be processed by goroutines in a random order anyway.\n\t\tUnsorted: true,\n\t}\n\n\terr := godirwalk.Walk(f.root, walkOpts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(f.repos) == 0 {\n\t\treturn fmt.Errorf(\"no git repos found in root path %s\", f.root)\n\t}\n\n\treturn nil\n}", "func New() *differ {\n\treturn &differ{}\n}", "func NewOwnerLister(tableName string, selectedColumns []string, ownerCheck bool) Lister {\n\treturn &universalLister{\n\t\ttableName: tableName,\n\t\tselectedColumns: strings.Join(selectedColumns, \", \"),\n\t\townerCheck: ownerCheck,\n\t\torderByParams: NoOrderBy,\n\t}\n}", "func NewSearcher(\n\tpeerSigner client.Signer,\n\torgSigner client.Signer,\n\trec comm.QueryRecorder,\n\tdoc comm.Doctor,\n\tc client.FinderCreator,\n\trp ResponseProcessor,\n) Searcher {\n\treturn &searcher{\n\t\tpeerSigner: peerSigner,\n\t\torgSigner: orgSigner,\n\t\tfinderCreator: c,\n\t\tdoc: doc,\n\t\trp: rp,\n\t\trec: rec,\n\t}\n}", "func New(fsys fs.FS, path string) (source.Driver, error) {\n\tvar i driver\n\tif err := i.Init(fsys, path); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to init driver with path %s: %w\", path, err)\n\t}\n\treturn &i, nil\n}", "func DummyFinder(productsQuery *ProductsQuery) ([]*Product, error) {\n\treturn []*Product{}, nil\n}", "func NewScanner(dir string, offset uint64) (*Scanner, error) {\n\tdir = JournalDirPath(dir)\n\tr := Scanner{Timeout: time.Second}\n\tjournalDir, err := openWatchedJournalDir(dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tjournalFile, err := journalDir.Find(offset)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif journalDir.IsLast(journalFile) {\n\t\tr.file, err = openWatchedFile(journalFile.FileName)\n\t} else {\n\t\tr.file, err = openDummyWatchedFile(journalFile.FileName)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr.offset = journalFile.FirstOffset\n\tr.journalFile = journalFile\n\tr.journalDir = journalDir\n\tfor r.offset < offset && r.Scan() {\n\t}\n\t// ignore r.Err(), which will be detected by the caller later anyway\n\t// ignore the difference between r.offset and offset, in case the journal has been truncated\n\t// TODO: add a testcase\n\treturn &r, nil\n}" ]
[ "0.8122834", "0.79264635", "0.78552455", "0.7817888", "0.777309", "0.76406205", "0.73853225", "0.68734574", "0.6478233", "0.63309747", "0.62455803", "0.6234578", "0.62128097", "0.6159686", "0.6150639", "0.5968015", "0.5944875", "0.593422", "0.5801198", "0.5801198", "0.57359344", "0.57356614", "0.56527674", "0.55556273", "0.55500686", "0.5538613", "0.55152625", "0.54672486", "0.53760505", "0.5372601", "0.53529066", "0.53180134", "0.52955043", "0.52643484", "0.5237906", "0.5233001", "0.5228676", "0.5197293", "0.5157549", "0.51520324", "0.51469827", "0.51452124", "0.50910616", "0.50572175", "0.50524586", "0.5034241", "0.5022889", "0.50084114", "0.5004426", "0.4987028", "0.49744904", "0.49475184", "0.49432188", "0.49432188", "0.4938771", "0.49303612", "0.49277604", "0.49172014", "0.49133885", "0.49093756", "0.49004802", "0.4883333", "0.48832467", "0.4881795", "0.48815465", "0.48636153", "0.48508754", "0.48497504", "0.48453635", "0.48432034", "0.48431587", "0.4836351", "0.4819067", "0.479727", "0.47601104", "0.4740767", "0.47400615", "0.4731763", "0.4727282", "0.47231692", "0.4691004", "0.46622634", "0.46615806", "0.4660211", "0.4654407", "0.4650991", "0.4647624", "0.46424803", "0.46423945", "0.46368572", "0.46297872", "0.46261537", "0.4625345", "0.46172196", "0.46141517", "0.460788", "0.46057585", "0.45982453", "0.45965436" ]
0.77743185
4
At looks up the version valid at time `at` after is a unix time hint of the latest known update
func (f *finder) At(ctx context.Context, at, after int64) (ch swarm.Chunk, current, next feeds.Index, err error) { for i := uint64(0); ; i++ { u, err := f.getter.Get(ctx, &index{i}) if err != nil { if !errors.Is(err, storage.ErrNotFound) { return nil, nil, nil, err } return ch, &index{i - 1}, &index{i}, nil } ts, err := feeds.UpdatedAt(u) if err != nil { return nil, nil, nil, err } if ts > uint64(at) { return ch, &index{i}, nil, nil } ch = u } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r ApiGetHyperflexServerFirmwareVersionListRequest) At(at string) ApiGetHyperflexServerFirmwareVersionListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetHyperflexServerFirmwareVersionEntryListRequest) At(at string) ApiGetHyperflexServerFirmwareVersionEntryListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetHyperflexHxdpVersionListRequest) At(at string) ApiGetHyperflexHxdpVersionListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetHyperflexSoftwareDistributionVersionListRequest) At(at string) ApiGetHyperflexSoftwareDistributionVersionListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAt() error {\n\tu, err := fetchUpdatedAt(federalRevenueURL)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting updated at: %w\", err)\n\t}\n\tfmt.Println(u)\n\treturn nil\n}", "func (b *FollowUpBuilder) UpdatedAt(value time.Time) *FollowUpBuilder {\n\tb.updatedAt = value\n\tb.bitmap_ |= 8192\n\treturn b\n}", "func (b *BalanceAs) repriceAt(at time.Time) error {\n\t// find latest price for trading pair\n\tpriceAs, err := DefaultArchive.GetPriceAs(SymbolType(b.Symbol), b.As, at)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get latest price for: %s as %s - %s\", b.Symbol, b.As, err)\n\t}\n\treturn b.repriceUsing(priceAs)\n}", "func UpdatedAt(v time.Time) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetHyperflexSoftwareVersionPolicyListRequest) At(at string) ApiGetHyperflexSoftwareVersionPolicyListRequest {\n\tr.at = &at\n\treturn r\n}", "func archiveAt(timestamp int64, svc *Checkin) archiveFunc {\n\treturn func(nano int64, event []byte) error {\n\t\treturn svc.archive(timestamp, event)\n\t}\n}", "func (w *watcher) updatedAtTime() time.Time {\n\treturn time.Unix(0, atomic.LoadInt64(&w.updatedAt))\n}", "func (r BuildInfoResolver) BuiltAt() *graphql.Time {\n\tif t := r.bi.BuiltAt; t != nil {\n\t\treturn &graphql.Time{Time: *t}\n\t}\n\treturn nil\n}", "func UpdatedAt(v time.Time) predicate.MetaSchema {\n\treturn predicate.MetaSchema(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t},\n\t)\n}", "func UpdatedAt(v time.Time) predicate.GameServer {\n\treturn predicate.GameServer(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (f *finder) At(ctx context.Context, at int64, _ uint64) (ch swarm.Chunk, current, next feeds.Index, err error) {\n\tfor i := uint64(0); ; i++ {\n\t\tu, err := f.getter.Get(ctx, &index{i})\n\t\tif err != nil {\n\t\t\tif !errors.Is(err, storage.ErrNotFound) {\n\t\t\t\treturn nil, nil, nil, err\n\t\t\t}\n\t\t\tif i > 0 {\n\t\t\t\tcurrent = &index{i - 1}\n\t\t\t}\n\t\t\treturn ch, current, &index{i}, nil\n\t\t}\n\t\tts, err := feeds.UpdatedAt(u)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t\t// if index is later than the `at` target index, then return previous chunk and index\n\t\tif ts > uint64(at) {\n\t\t\treturn ch, &index{i - 1}, &index{i}, nil\n\t\t}\n\t\tch = u\n\t}\n}", "func UpdatedAt(v time.Time) predicate.Step {\n\treturn predicate.Step(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func UpdatedAt(v time.Time) predicate.Ethnicity {\n\treturn predicate.Ethnicity(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r *ChainResolver) UpdatedAt() graphql.Time {\n\treturn graphql.Time{Time: r.chain.UpdatedAt}\n}", "func (r ApiGetHyperflexVmSnapshotInfoListRequest) At(at string) ApiGetHyperflexVmSnapshotInfoListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetHyperflexVmBackupInfoListRequest) At(at string) ApiGetHyperflexVmBackupInfoListRequest {\n\tr.at = &at\n\treturn r\n}", "func (mnuo *MedicalNoteUpdateOne) SetAt(t time.Time) *MedicalNoteUpdateOne {\n\tmnuo.at = &t\n\treturn mnuo\n}", "func At(dt time.Time, job *Job, buildWrapper BuildWrapperFunc) cron.EntryID {\n\tif dt.Before(Now()) {\n\t\treturn InvalidEntryID\n\t}\n\n\tjob.entryID = mainCron.Schedule(schedules.Absolute(dt), buildWrapper(job))\n\tjob.typ = JobTypeOnce\n\treturn addJob(job)\n}", "func UpdatedAtLTE(v time.Time) predicate.MetaSchema {\n\treturn predicate.MetaSchema(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldUpdatedAt), v))\n\t},\n\t)\n}", "func (o FaqOutput) UpdatedAt() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Faq) pulumi.StringOutput { return v.UpdatedAt }).(pulumi.StringOutput)\n}", "func (su *SystemUser) ValidAt(when time.Time) bool {\n\tvalid := when.After(su.since) || when.Equal(su.since)\n\tif valid {\n\t\tvalid = when.Before(su.until)\n\t}\n\treturn valid\n}", "func AtVersion(version string) GetOption {\n\treturn func(o *getOptions) {\n\t\to.version = version\n\t}\n}", "func UpdatedAt(v time.Time) predicate.Job {\n\treturn predicate.Job(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetHyperflexHealthCheckPackageChecksumListRequest) At(at string) ApiGetHyperflexHealthCheckPackageChecksumListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAt(v time.Time) predicate.OrderItem {\n\treturn predicate.OrderItem(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetHyperflexClusterBackupPolicyDeploymentListRequest) At(at string) ApiGetHyperflexClusterBackupPolicyDeploymentListRequest {\n\tr.at = &at\n\treturn r\n}", "func (mnu *MedicalNoteUpdate) SetAt(t time.Time) *MedicalNoteUpdate {\n\tmnu.at = &t\n\treturn mnu\n}", "func (o *Handoff) UpdatedAt() time.Time {\n\tif o != nil && o.bitmap_&256 != 0 {\n\t\treturn o.updatedAt\n\t}\n\treturn time.Time{}\n}", "func UpdatedAtLTE(v time.Time) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (a *versionedValue) AtVersion(v int) (r *versionedValue) {\n\tfor ; a != nil; a = a.versionedValue {\n\t\tif a.version <= v {\n\t\t\treturn a\n\t\t}\n\t}\n\treturn\n}", "func (r ApiGetHyperflexHealthCheckExecutionSnapshotListRequest) At(at string) ApiGetHyperflexHealthCheckExecutionSnapshotListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetHyperflexSoftwareDistributionEntryListRequest) At(at string) ApiGetHyperflexSoftwareDistributionEntryListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAt(v time.Time) predicate.Delivery {\n\treturn predicate.Delivery(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetHyperflexDevicePackageDownloadStateListRequest) At(at string) ApiGetHyperflexDevicePackageDownloadStateListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAt(v time.Time) predicate.Permission {\n\treturn predicate.Permission(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (ref FileView) At(seqNum commit.SeqNum) (r fileversion.Reference, err error) {\n\tfile, ok := ref.repo.files[ref.file]\n\tif !ok {\n\t\treturn nil, fileview.NotFound{File: ref.file, Drive: ref.drive, Commit: seqNum}\n\t}\n\tview, ok := file.Views[ref.drive]\n\tif !ok {\n\t\treturn nil, fileview.NotFound{File: ref.file, Drive: ref.drive, Commit: seqNum}\n\t}\n\tvar (\n\t\tmaxCommit commit.SeqNum\n\t\tmaxVersion resource.Version\n\t\tfound bool\n\t)\n\tfor seqNum, version := range view {\n\t\tif !found || seqNum > maxCommit {\n\t\t\tfound = true\n\t\t\tmaxCommit = seqNum\n\t\t\tmaxVersion = version\n\t\t}\n\t}\n\tif !found {\n\t\treturn nil, fileview.NotFound{File: ref.file, Drive: ref.drive, Commit: seqNum}\n\t}\n\t// FIXME: What about deleted files?\n\t// TODO: Include deletions in the view with a -1 version number so we\n\t// don't pick up the pre-deleted states?\n\treturn FileVersion{\n\t\trepo: ref.repo,\n\t\tfile: ref.file,\n\t\tversion: maxVersion,\n\t}, nil\n}", "func (o InfraAlertConditionOutput) UpdatedAt() pulumi.IntOutput {\n\treturn o.ApplyT(func(v *InfraAlertCondition) pulumi.IntOutput { return v.UpdatedAt }).(pulumi.IntOutput)\n}", "func UpdatedAtLTE(v time.Time) predicate.Ethnicity {\n\treturn predicate.Ethnicity(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetHyperflexAppCatalogListRequest) At(at string) ApiGetHyperflexAppCatalogListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAt(v time.Time) predicate.Order {\n\treturn predicate.Order(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetIqnpoolUniverseListRequest) At(at string) ApiGetIqnpoolUniverseListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAtLTE(v time.Time) predicate.GameServer {\n\treturn predicate.GameServer(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetHyperflexDatastoreStatisticListRequest) At(at string) ApiGetHyperflexDatastoreStatisticListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAtLTE(v time.Time) predicate.Permission {\n\treturn predicate.Permission(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetHyperflexSoftwareDistributionComponentListRequest) At(at string) ApiGetHyperflexSoftwareDistributionComponentListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetHyperflexVolumeListRequest) At(at string) ApiGetHyperflexVolumeListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAtLTE(v time.Time) predicate.Job {\n\treturn predicate.Job(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetHyperflexBackupClusterListRequest) At(at string) ApiGetHyperflexBackupClusterListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAtLTE(v time.Time) predicate.Delivery {\n\treturn predicate.Delivery(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetHyperflexClusterHealthCheckExecutionSnapshotListRequest) At(at string) ApiGetHyperflexClusterHealthCheckExecutionSnapshotListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAtLTE(v time.Time) predicate.Step {\n\treturn predicate.Step(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func UpdatedAtLTE(v time.Time) predicate.OrderItem {\n\treturn predicate.OrderItem(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (qs SysDBQuerySet) UpdatedAtLte(updatedAt time.Time) SysDBQuerySet {\n\treturn qs.w(qs.db.Where(\"updated_at <= ?\", updatedAt))\n}", "func (r ApiGetHyperflexConfigResultEntryListRequest) At(at string) ApiGetHyperflexConfigResultEntryListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAtGTE(v time.Time) predicate.MetaSchema {\n\treturn predicate.MetaSchema(func(s *sql.Selector) {\n\t\ts.Where(sql.GTE(s.C(FieldUpdatedAt), v))\n\t},\n\t)\n}", "func (r ApiGetHyperflexLicenseListRequest) At(at string) ApiGetHyperflexLicenseListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAtLTE(v time.Time) predicate.Order {\n\treturn predicate.Order(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetIqnpoolReservationListRequest) At(at string) ApiGetIqnpoolReservationListRequest {\n\tr.at = &at\n\treturn r\n}", "func (qs ConstraintQuerySet) UpdatedAtLte(updatedAt time.Time) ConstraintQuerySet {\n\treturn qs.w(qs.db.Where(\"updated_at <= ?\", updatedAt))\n}", "func (r ApiGetHyperflexAutoSupportPolicyListRequest) At(at string) ApiGetHyperflexAutoSupportPolicyListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetHyperflexServerModelListRequest) At(at string) ApiGetHyperflexServerModelListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetResourcepoolUniverseListRequest) At(at string) ApiGetResourcepoolUniverseListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAtLTE(v time.Time) predicate.K8sEvent {\n\treturn predicate.K8sEvent(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func PublishedAt(v time.Time) predicate.GithubRelease {\n\treturn predicate.GithubRelease(sql.FieldEQ(FieldPublishedAt, v))\n}", "func (r ApiGetIqnpoolLeaseListRequest) At(at string) ApiGetIqnpoolLeaseListRequest {\n\tr.at = &at\n\treturn r\n}", "func (m *AddressMutation) UpdatedAt() (r time.Time, exists bool) {\n\tv := m.updated_at\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (r ApiGetHyperflexAlarmListRequest) At(at string) ApiGetHyperflexAlarmListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetHyperflexClusterBackupPolicyListRequest) At(at string) ApiGetHyperflexClusterBackupPolicyListRequest {\n\tr.at = &at\n\treturn r\n}", "func (o Comment) UpdatedAt() *graphql.Time {\n\tif o.model.UpdatedAt.Valid {\n\t\treturn &graphql.Time{Time: o.model.UpdatedAt.Time}\n\t}\n\treturn nil // null.Time\n}", "func (t *TOTP) At(timestamp int64) string {\n\treturn t.generateOTP(t.timecode(timestamp))\n}", "func UpdatedAtLT(v time.Time) predicate.MetaSchema {\n\treturn predicate.MetaSchema(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldUpdatedAt), v))\n\t},\n\t)\n}", "func UpdatedAt(v time.Time) predicate.K8sEvent {\n\treturn predicate.K8sEvent(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetEtherHostPortListRequest) At(at string) ApiGetEtherHostPortListRequest {\n\tr.at = &at\n\treturn r\n}", "func At(at int64) OffsetOpt {\n\tif at < 0 {\n\t\tat = -2\n\t}\n\treturn offsetOpt{func(o *Offset) { o.request = at }}\n}", "func UpdatedAtGTE(v time.Time) predicate.Ethnicity {\n\treturn predicate.Ethnicity(func(s *sql.Selector) {\n\t\ts.Where(sql.GTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func UpdatedAtLT(v time.Time) predicate.Ethnicity {\n\treturn predicate.Ethnicity(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (o LookupExperienceResultOutput) UpdatedAt() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupExperienceResult) string { return v.UpdatedAt }).(pulumi.StringOutput)\n}", "func UpdatedAt(v time.Time) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (m *FeedMutation) UpdatedAt() (r time.Time, exists bool) {\n\tv := m.updated_at\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func UpdatedAtGTE(v time.Time) predicate.GameServer {\n\treturn predicate.GameServer(func(s *sql.Selector) {\n\t\ts.Where(sql.GTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetHyperflexSysConfigPolicyListRequest) At(at string) ApiGetHyperflexSysConfigPolicyListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetHyperflexConfigResultListRequest) At(at string) ApiGetHyperflexConfigResultListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAtGTE(v time.Time) predicate.Permission {\n\treturn predicate.Permission(func(s *sql.Selector) {\n\t\ts.Where(sql.GTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func UpdatedAtGTE(v time.Time) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.GTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func UpdatedAt(v time.Time) predicate.OrderLineItem {\n\treturn predicate.OrderLineItem(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func UpdatedAtLT(v time.Time) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldUpdatedAt), v))\n\t})\n}", "func tryVersionDateSha(ver string) (ref string, ok bool) {\n\tcomponents := strings.Split(ver, \"-\")\n\n\tif len(components) != 3 {\n\t\treturn\n\t}\n\n\tok = true\n\tref = components[2]\n\n\treturn\n}", "func UpdatedAtLT(v time.Time) predicate.Permission {\n\treturn predicate.Permission(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetHyperflexHealthCheckExecutionListRequest) At(at string) ApiGetHyperflexHealthCheckExecutionListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAtGT(v time.Time) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.GT(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetHyperflexHealthCheckDefinitionListRequest) At(at string) ApiGetHyperflexHealthCheckDefinitionListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetHyperflexLunListRequest) At(at string) ApiGetHyperflexLunListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetHyperflexClusterReplicationNetworkPolicyDeploymentListRequest) At(at string) ApiGetHyperflexClusterReplicationNetworkPolicyDeploymentListRequest {\n\tr.at = &at\n\treturn r\n}", "func (m *TenantMutation) UpdatedAt() (r time.Time, exists bool) {\n\tv := m.updated_at\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (r ApiGetResourcepoolLeaseListRequest) At(at string) ApiGetResourcepoolLeaseListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAtGT(v time.Time) predicate.GameServer {\n\treturn predicate.GameServer(func(s *sql.Selector) {\n\t\ts.Where(sql.GT(s.C(FieldUpdatedAt), v))\n\t})\n}" ]
[ "0.6024724", "0.5971322", "0.5965791", "0.5946821", "0.59386605", "0.5537376", "0.5519222", "0.55184233", "0.55153024", "0.5472949", "0.5458037", "0.5456405", "0.5440827", "0.5440527", "0.5412469", "0.54073024", "0.53969324", "0.53810334", "0.5380731", "0.53776205", "0.53692293", "0.5363863", "0.53506327", "0.5337451", "0.5330512", "0.5329137", "0.5325801", "0.5319804", "0.53166187", "0.52989835", "0.5298118", "0.52974546", "0.52933586", "0.52892643", "0.5288289", "0.52868664", "0.5266634", "0.52626854", "0.52574027", "0.52464217", "0.5236985", "0.52326584", "0.522025", "0.52074915", "0.5206961", "0.5194253", "0.5181767", "0.5179767", "0.51789117", "0.517887", "0.5167243", "0.5163413", "0.5158708", "0.5156214", "0.5152438", "0.51495826", "0.51328474", "0.5121042", "0.51135933", "0.5110475", "0.51095265", "0.51058364", "0.5088766", "0.508846", "0.5087006", "0.5085739", "0.50754946", "0.5068723", "0.5064057", "0.5052563", "0.505057", "0.5041375", "0.5037448", "0.5033719", "0.5023904", "0.5009298", "0.5008743", "0.50023824", "0.49920708", "0.49896476", "0.49870494", "0.49812147", "0.49794388", "0.4967407", "0.49646324", "0.49605098", "0.49591762", "0.4958843", "0.4954482", "0.49515584", "0.4948385", "0.4946354", "0.4945401", "0.49451676", "0.49428532", "0.49419636", "0.4935941", "0.49343592", "0.49280253", "0.49211994" ]
0.57098186
5
NewAsyncFinder constructs an AsyncFinder
func NewAsyncFinder(getter storage.Getter, feed *feeds.Feed) feeds.Lookup { return &asyncFinder{feeds.NewGetter(getter, feed)} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func findAsync(findStruct *Find, callback chan *Callback) {\n\trecords, err := find(findStruct)\n\tcb := new(Callback)\n\tcb.Data = records\n\tcb.Error = err\n\tcallback <- cb\n}", "func NewFinder(conf Config) *Finder {\n\treturn &Finder{config: conf }\n}", "func NewFinder(ctx context.Context, zctx *zson.Context, engine storage.Engine, uri *storage.URI) (*Finder, error) {\n\treader, err := NewReaderFromURI(ctx, zctx, engine, uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Finder{\n\t\tReader: reader,\n\t\tzctx: zctx,\n\t\turi: uri,\n\t}, nil\n}", "func NewFinder() *Finder {\n\tfinder := &Finder{\n\t\tFinder: core.NewFinder(),\n\t\tControlPoint: upnp.NewControlPoint(),\n\t}\n\n\tfinder.ControlPoint.Listener = finder\n\n\treturn finder\n}", "func newAsync() *async {\n\treturn &async{state: pending, completions: []func(){}, done: make(chan struct{})}\n}", "func NewFinder(ctx context.Context, zctx *zson.Context, uri iosrc.URI) (*Finder, error) {\n\treader, err := NewReaderFromURI(ctx, zctx, uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Finder{\n\t\tReader: reader,\n\t\tzctx: zctx,\n\t\turi: uri,\n\t}, nil\n}", "func New(ReqSize int, BufSzie int) *Async {\n\tas := Async{\n\t\tquit: make(chan bool),\n\t\ttaskChan: make(chan *task, ReqSize),\n\t\tbufSize: BufSzie,\n\t\twait: &sync.WaitGroup{},\n\t\tdone: make(chan bool),\n\t}\n\n\tgo as.watcher()\n\treturn &as\n}", "func NewFinder() Finder {\n\treturn &finder{fsWalk: filepath.Walk}\n}", "func NewFinder(getter storage.Getter, feed *feeds.Feed) feeds.Lookup {\n\treturn &finder{feeds.NewGetter(getter, feed)}\n}", "func NewFinder(getter storage.Getter, feed *feeds.Feed) feeds.Lookup {\n\treturn &finder{feeds.NewGetter(getter, feed)}\n}", "func NewFinder(cfg *pb.GlobalConfig) Finder {\n\tf := &finder{\n\t\tlogs: make(map[string]*dpb.LogEntryDescriptor),\n\t\tmetrics: make(map[string]*dpb.MetricDescriptor),\n\t\tmonitoredResources: make(map[string]*dpb.MonitoredResourceDescriptor),\n\t\tprincipals: make(map[string]*dpb.PrincipalDescriptor),\n\t\tquotas: make(map[string]*dpb.QuotaDescriptor),\n\t\tattributes: make(map[string]*pb.AttributeManifest_AttributeInfo),\n\t}\n\n\tif cfg == nil {\n\t\treturn f\n\t}\n\n\tfor _, desc := range cfg.Logs {\n\t\tf.logs[desc.Name] = desc\n\t}\n\n\tfor _, desc := range cfg.Metrics {\n\t\tf.metrics[desc.Name] = desc\n\t}\n\n\tfor _, desc := range cfg.MonitoredResources {\n\t\tf.monitoredResources[desc.Name] = desc\n\t}\n\n\tfor _, desc := range cfg.Principals {\n\t\tf.principals[desc.Name] = desc\n\t}\n\n\tfor _, desc := range cfg.Quotas {\n\t\tf.quotas[desc.Name] = desc\n\t}\n\n\tfor _, manifest := range cfg.Manifests {\n\t\tfor name, info := range manifest.Attributes {\n\t\t\tf.attributes[name] = info\n\t\t}\n\t}\n\n\treturn f\n}", "func findAllAsync(findAllStruct *FindAll, callback chan *Callback) {\n\trecords, err := findAll(findAllStruct)\n\tcb := new(Callback)\n\tcb.Data = records\n\tcb.Error = err\n\tcallback <- cb\n}", "func findByIDAsync(findByIDStruct *FindByID, callback chan *Callback) {\n\trecords, err := findByID(findByIDStruct)\n\tcb := new(Callback)\n\tcb.Data = records\n\tcb.Error = err\n\tcallback <- cb\n}", "func NewTaskFinder(sess *session.Session, cluster string) *TaskFinder {\n\treturn &TaskFinder{\n\t\tcluster: cluster,\n\t\tecs: ecs.New(sess),\n\t\tec2: ec2.New(sess),\n\t}\n}", "func NewFinder(opt AgonesOption) *ServerFinder {\n\tfmt.Println(\"Agones Host:\", opt.Host)\n\tfmt.Println(\"Agones Port:\", opt.Port)\n\treturn &ServerFinder{\n\t\tagonesPort: opt.Port,\n\t\tagonesHost: opt.Host,\n\t\tfleetName: opt.FleetName,\n\t\tservers: make(map[uint32]*allocation.GameServerAllocation),\n\t}\n}", "func New(paths ...string) Finder {\n\tif len(paths) == 0 {\n\t\tpaths = []string{\"./\"}\n\t}\n\treturn Finder{paths}\n}", "func NewAsync(APIaddr string, requiredUserAgent string, requiredPassword string, nodeParams node.NodeParams, loadStartTime time.Time) (*Server, <-chan error) {\n\tc := make(chan error, 1)\n\tdefer close(c)\n\n\tvar errChan <-chan error\n\tvar n *node.Node\n\ts, err := func() (*Server, error) {\n\t\t// Create the server listener.\n\t\tlistener, err := net.Listen(\"tcp\", APIaddr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Load the config file.\n\t\tcfg, err := modules.NewConfig(filepath.Join(nodeParams.Dir, modules.ConfigName))\n\t\tif err != nil {\n\t\t\treturn nil, errors.AddContext(err, \"failed to load siad config\")\n\t\t}\n\n\t\t// Create the api for the server.\n\t\tapi := api.New(cfg, requiredUserAgent, requiredPassword, nil, nil, nil, nil, nil, nil, nil, nil, nil)\n\t\tsrv := &Server{\n\t\t\tapi: api,\n\t\t\tapiServer: &http.Server{\n\t\t\t\tHandler: api,\n\n\t\t\t\t// set reasonable timeout windows for requests, to prevent the Sia API\n\t\t\t\t// server from leaking file descriptors due to slow, disappearing, or\n\t\t\t\t// unreliable API clients.\n\n\t\t\t\t// ReadTimeout defines the maximum amount of time allowed to fully read\n\t\t\t\t// the request body. This timeout is applied to every handler in the\n\t\t\t\t// server.\n\t\t\t\tReadTimeout: time.Minute * 360,\n\n\t\t\t\t// ReadHeaderTimeout defines the amount of time allowed to fully read the\n\t\t\t\t// request headers.\n\t\t\t\tReadHeaderTimeout: time.Minute * 2,\n\n\t\t\t\t// IdleTimeout defines the maximum duration a HTTP Keep-Alive connection\n\t\t\t\t// the API is kept open with no activity before closing.\n\t\t\t\tIdleTimeout: time.Minute * 5,\n\t\t\t},\n\t\t\tcloseChan: make(chan struct{}),\n\t\t\tserveChan: make(chan struct{}),\n\t\t\tlistener: listener,\n\t\t\trequiredUserAgent: requiredUserAgent,\n\t\t\tDir: nodeParams.Dir,\n\t\t}\n\n\t\t// Set the shutdown method to allow the api to shutdown the server.\n\t\tapi.Shutdown = srv.Close\n\n\t\t// Spin up a goroutine that serves the API and closes srv.done when\n\t\t// finished.\n\t\tgo func() {\n\t\t\tsrv.serveErr = srv.serve()\n\t\t\tclose(srv.serveChan)\n\t\t}()\n\n\t\t// Create the Sia node for the server after the server was started.\n\t\tn, errChan = node.New(nodeParams, loadStartTime)\n\t\tif err := modules.PeekErr(errChan); err != nil {\n\t\t\tif isAddrInUseErr(err) {\n\t\t\t\treturn nil, fmt.Errorf(\"%v; are you running another instance of siad?\", err.Error())\n\t\t\t}\n\t\t\treturn nil, errors.AddContext(err, \"server is unable to create the Sia node\")\n\t\t}\n\n\t\t// Make sure that the server wasn't shut down while loading the modules.\n\t\tsrv.closeMu.Lock()\n\t\tdefer srv.closeMu.Unlock()\n\t\tselect {\n\t\tcase <-srv.serveChan:\n\t\t\t// Server was shut down. Close node and exit.\n\t\t\treturn srv, n.Close()\n\t\tdefault:\n\t\t}\n\n\t\t// Server wasn't shut down. Add node and replace modules.\n\t\tsrv.node = n\n\t\tapi.SetModules(n.ConsensusSet, n.Explorer, n.FeeManager, n.Gateway, n.Host, n.Miner, n.Renter, n.TransactionPool, n.Wallet)\n\t\treturn srv, nil\n\t}()\n\tif err != nil {\n\t\tif n != nil {\n\t\t\terr = errors.Compose(err, n.Close())\n\t\t}\n\t\tc <- err\n\t\treturn nil, c\n\t}\n\treturn s, errChan\n}", "func New() Awaiter {\n\ta := new(awaiter)\n\ta.cancel = make(chan interface{})\n\ta.wg = new(sync.WaitGroup)\n\ta.locker = new(sync.Mutex)\n\treturn a\n}", "func NewMockFinder(result [][]byte) *MockFinder {\n\treturn &MockFinder{\n\t\tfnd: NewCachedIndex(bytes.Join(result, []byte{'\\n'})),\n\t}\n}", "func New(b []byte) (*Finding, error) {\n\tvar f Finding\n\tif err := json.Unmarshal(b, &f.Containerscanner); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &f, nil\n}", "func Async() Fitting {\n\treturn &asyncFitting{}\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 (mdhth *MockDHTHandler) FindProvidersAsync(id string, count int) (<-chan peer2.AddrInfo, error) {\n\tif len(id) != 46 {\n\t\treturn nil, fmt.Errorf(\"FindProvidersAsync: wrong id %s\", id)\n\t}\n\n\tch := make(chan peer2.AddrInfo)\n\taddr, err := AddrToPeerInfo(\"/ip4/104.236.76.40/tcp/4001/ipfs/QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzawe34\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"FindProvidersAsync: AddrToPeerInfo wrong\")\n\t}\n\tgo func() {\n\t\tch <- *addr\n\t}()\n\n\ttime.Sleep(time.Second)\n\n\treturn ch, nil\n}", "func newAsyncResult() *asyncResult {\n\treturn &asyncResult{state: pending, completions: []func(result interface{}){}, done: make(chan struct{}), async: newAsync()}\n}", "func NewMockFinder(result [][]byte) *MockFinder {\n\treturn &MockFinder{\n\t\tresult: result,\n\t}\n}", "func NewPeerFinder(t testing.TB) *PeerFinder {\n\tmock := &PeerFinder{}\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func New() (interfaces.AsyncWork, error) {\n\treturn NewWithContext(context.Background())\n}", "func (box *ReadingBox) Async() *ReadingAsyncBox {\n\treturn &ReadingAsyncBox{AsyncBox: box.Box.Async()}\n}", "func New() *asyncPipeRdr {\n\tvar instance asyncPipeRdr\n\tinstance.channel = make(chan string)\n\tinstance.rtnStop = routinestop.New()\n\treturn &instance\n}", "func NewAsyncTower() *AsyncTower {\n\treturn &AsyncTower{\n\t\treqStop: make(chan bool),\n\t}\n}", "func NewAsyncController(ctx context.Context, options *Options, resourceBaseURL string, objectType types.ObjectType, isAsyncDefault bool, objectBlueprint func() types.Object, supportsCascadeDelete bool) *BaseController {\n\tcontroller := NewController(ctx, options, resourceBaseURL, objectType, objectBlueprint, supportsCascadeDelete)\n\tcontroller.supportsAsync = true\n\tcontroller.isAsyncDefault = isAsyncDefault\n\n\treturn controller\n}", "func (box *EventBox) Async() *EventAsyncBox {\n\treturn &EventAsyncBox{AsyncBox: box.Box.Async()}\n}", "func New(concurrency int) Async {\n\ta := &async{}\n\ta.funcs = make(chan func() error, concurrency)\n\ta.wg.Add(concurrency)\n\tfor i := 0; i < concurrency; i++ {\n\t\tgo func() {\n\t\t\tdefer a.wg.Done()\n\t\t\tfor f := range a.funcs {\n\t\t\t\tif err := f(); err != nil {\n\t\t\t\t\ta.mu.Lock()\n\t\t\t\t\ta.err = err\n\t\t\t\t\ta.mu.Unlock()\n\t\t\t\t\treturn // stopping processing if we get an error\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\treturn a\n}", "func FullFinder(url, server string, timeout time.Duration, verbose bool) (*FullOutput, error) {\n\traw, err := discoverResources(url, timeout, verbose)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif verbose {\n\t\tlog.Println(raw)\n\t}\n\treturn parseraw(raw, server, verbose), nil\n}", "func (c *DeviceConfig) newDeviceFinder() (*device.DeviceFinder, error) {\n\tif c.deviceFinderPath == \"\" {\n\t\treturn nil, fmt.Errorf(\"--device-finder-path not specified\")\n\t}\n\n\treturn device.NewDeviceFinder(c.deviceFinderPath), nil\n}", "func (bsnet *impl) FindProvidersAsync(ctx context.Context, k cid.Cid, max int) <-chan peer.ID {\n\tout := make(chan peer.ID, max)\n\tgo func() {\n\t\tdefer close(out)\n\t\tproviders := bsnet.routing.FindProvidersAsync(ctx, k, max)\n\t\tfor info := range providers {\n\t\t\tif info.ID == bsnet.host.ID() {\n\t\t\t\tcontinue // ignore self as provider\n\t\t\t}\n\t\t\tbsnet.host.Peerstore().AddAddrs(info.ID, info.Addrs, peerstore.TempAddrTTL)\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase out <- info.ID:\n\t\t\t}\n\t\t}\n\t}()\n\treturn out\n}", "func New(b []byte) (*Finding, error) {\n\tvar f Finding\n\tif err := json.Unmarshal(b, &f.FirewallScanner); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &f, nil\n}", "func NewTemplateFinder(templateProvider templates.TemplateProvider, osFinder os.OSFinder) *TemplateFinder {\n\treturn &TemplateFinder{\n\t\ttemplateProvider: templateProvider,\n\t\tosFinder: osFinder,\n\t}\n}", "func NewCallbackAsync(fnc func(v []Value)) Func {\n\treturn AsyncCallbackOf(fnc)\n}", "func (s *Sun) StartAsync() {\n\ts.start(true)\n}", "func NewTemplateFinder(templateProvider templates.TemplateProvider, osMapProvider templates.OSMapProvider) *TemplateFinder {\n\treturn &TemplateFinder{\n\t\ttemplateProvider: templateProvider,\n\t\tosMapProvider: osMapProvider,\n\t}\n}", "func (dht *FullRT) FindProvidersAsync(ctx context.Context, key cid.Cid, count int) <-chan peer.AddrInfo {\n\tif !dht.enableProviders || !key.Defined() {\n\t\tpeerOut := make(chan peer.AddrInfo)\n\t\tclose(peerOut)\n\t\treturn peerOut\n\t}\n\n\tchSize := count\n\tif count == 0 {\n\t\tchSize = 1\n\t}\n\tpeerOut := make(chan peer.AddrInfo, chSize)\n\n\tkeyMH := key.Hash()\n\n\tlogger.Debugw(\"finding providers\", \"cid\", key, \"mh\", internal.LoggableProviderRecordBytes(keyMH))\n\tgo dht.findProvidersAsyncRoutine(ctx, keyMH, count, peerOut)\n\treturn peerOut\n}", "func newManager(shape []int, k int) (m *manager) {\n\tm = &manager{\n\t\trand: newRandom(),\n\t\tmonitor: stats.New(),\n\t\tshape: shape,\n\t}\n\n\tm.watch = newWatcher(m.onPing, 500*time.Millisecond)\n\tm.work = async.Repeat(context.Background(), 5*time.Second, func(ctx context.Context) (interface{}, error) {\n\t\tm.update(k)\n\t\treturn nil, nil\n\t})\n\treturn\n}", "func (f *Find) AwaitData(awaitData bool) *Find {\n\tif f == nil {\n\t\tf = new(Find)\n\t}\n\n\tf.awaitData = &awaitData\n\treturn f\n}", "func New(cb Done, transport http.RoundTripper) *Manager {\n\treturn &Manager{\n\t\tkeys: sets.NewString(),\n\t\tcb: cb,\n\t\ttransport: transport,\n\t}\n}", "func NewAsyncBR(t mockConstructorTestingTNewAsyncBR) *AsyncBR {\n\tmock := &AsyncBR{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func AsyncGenerator(a MatrixFixture) *MatrixFixture {\n\texpr := &Async{a.expr}\n\tif expr.Err() != nil {\n\t\treturn nil\n\t}\n\n\tm := &MatrixFixture{\n\t\tname: \"Async(\" + a.name + \")\",\n\t\tr: a.r,\n\t\tc: a.c,\n\t\texpr: expr,\n\t\twant: a.want,\n\t}\n\treturn m\n}", "func (_m *specificationSvc) AsyncAPI(baseURL string, name string) (*spec.AsyncAPISpec, error) {\n\tvar r0 *spec.AsyncAPISpec\n\tvar r1 error\n\tr1 = _m.err\n\n\treturn r0, r1\n}", "func New(cfg *config.Config, rootPath string) (*Manager, error) {\n\tself := peer.NewSelf(cfg, rootPath)\n\tm := &Manager{\n\t\tself: self,\n\t}\n\tp := self.ToPeer()\n\trecent, err := p.ReadRecent()\n\tif log.If(err) {\n\t\tlog.Println(err)\n\t}\n\tm.recent, err = thread.NewList(self, recent)\n\tm.peers, err = p.ReadPeers()\n\tlog.If(err)\n\tif len(m.peers) == 0 {\n\t\tm.peers = self.LoadInitPeers()\n\t}\n\tm.tags, err = p.ReadTags()\n\tlog.If(err)\n\tm.spams, err = p.ReadSpams()\n\tlog.If(err)\n\tm.readThreads = self.ReadThreads()\n\tif err := self.StartListen(m.accept); log.If(err) {\n\t\treturn nil, err\n\t}\n\tgo func() {\n\t\tfor {\n\t\t\tm.cron()\n\t\t\ttime.Sleep(time.Hour)\n\t\t}\n\t}()\n\treturn m, nil\n}", "func NewRepoFinder(root string) *RepoFinder {\n\treturn &RepoFinder{\n\t\troot: root,\n\t\tmaxWorkers: maxWorkers,\n\t}\n}", "func (a *asyncProvidersFinder) Find(ctx context.Context, router ReadContentRouting, key []byte, onProvider onProviderFunc) error {\n\ta.pendingMut.Lock()\n\tdefer a.pendingMut.Unlock()\n\tks := string(key)\n\tpending := a.pending[ks]\n\tif pending {\n\t\treturn nil\n\t}\n\tif a.negativeCache.Has(ks) {\n\t\trecordPrefetches(ctx, \"failed-cached\")\n\t\treturn nil\n\t}\n\tselect {\n\tcase a.workQueue <- findRequest{ctx: ctx, router: router, key: key, onProvider: onProvider}:\n\t\ta.pending[ks] = true\n\t\treturn nil\n\tdefault:\n\t\trecordPrefetches(ctx, \"discarded\")\n\t\treturn nil\n\t}\n}", "func NewInvokeSync(ctx context.Context, cb func(data []byte) error) *InvokeSync {\n\twait, fire := task.NewSignal()\n\ts := &InvokeSync{wait: wait}\n\ts.Handler = func(data []byte, more bool, err error) {\n\t\tif err != nil {\n\t\t\ts.err = err\n\t\t} else {\n\t\t\ts.err = cb(data)\n\t\t}\n\n\t\tif !more || s.err != nil {\n\t\t\tfire(ctx)\n\t\t}\n\t}\n\treturn s\n}", "func NewFinding() *Finding {\n\treturn &Finding{}\n}", "func New(o *Options) (Matcher, error) {\n\t// creates data clients\n\tdataClients, err := createDataClients(o.RoutesFile)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trouting := createRouting(dataClients, o)\n\n\treturn &matcher{\n\t\trouting,\n\t}, nil\n}", "func invokeFind(e Task, c *Context) (Task, error) {\n\trv, err := utils.InvokeMethod(e, \"Find\", c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar task Task\n\tif !rv[0].IsNil() {\n\t\ttask = rv[0].Interface().(Task)\n\t}\n\tif !rv[1].IsNil() {\n\t\terr = rv[1].Interface().(error)\n\t}\n\treturn task, err\n}", "func NewBlobRangeFinder(getObjects *[]helperModels.GetObject) BlobRangeFinder {\n rangeMap := toRangeMap(getObjects)\n return &BlobRangeFinderImpl{\n rangeMap: *rangeMap,\n collapser: RangeCollapserImpl{},\n }\n}", "func Find(ctx context.Context, tconn *chrome.TestConn) (*FilePicker, error) {\n\tfilesApp, err := filesapp.App(ctx, tconn, vars.FilePickerPseudoAppID)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to find file picker\")\n\t}\n\treturn &FilePicker{filesApp: filesApp}, nil\n}", "func WithAsyncFunc(f func(r Result)) InvocationOption {\n\treturn func(op InvocationOp) InvocationOp { op.Func = f; op.Async = true; return op }\n}", "func (aReq *ArchiveRequest) Await(ctx context.Context) (*repo_model.RepoArchiver, error) {\n\tarchiver, err := repo_model.GetRepoArchiver(ctx, aReq.RepoID, aReq.Type, aReq.CommitID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"models.GetRepoArchiver: %w\", err)\n\t}\n\n\tif archiver != nil && archiver.Status == repo_model.ArchiverReady {\n\t\t// Archive already generated, we're done.\n\t\treturn archiver, nil\n\t}\n\n\tif err := StartArchive(aReq); err != nil {\n\t\treturn nil, fmt.Errorf(\"archiver.StartArchive: %w\", err)\n\t}\n\n\tpoll := time.NewTicker(time.Second * 1)\n\tdefer poll.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-graceful.GetManager().HammerContext().Done():\n\t\t\t// System stopped.\n\t\t\treturn nil, graceful.GetManager().HammerContext().Err()\n\t\tcase <-ctx.Done():\n\t\t\treturn nil, ctx.Err()\n\t\tcase <-poll.C:\n\t\t\tarchiver, err = repo_model.GetRepoArchiver(ctx, aReq.RepoID, aReq.Type, aReq.CommitID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"repo_model.GetRepoArchiver: %w\", err)\n\t\t\t}\n\t\t\tif archiver != nil && archiver.Status == repo_model.ArchiverReady {\n\t\t\t\treturn archiver, nil\n\t\t\t}\n\t\t}\n\t}\n}", "func Async(a bool) CollectorOption {\n\treturn func(collector *Collector) {\n\t\tcollector.async = a\n\t}\n}", "func (s StatsGraphAsync) construct() StatsGraphClass { return &s }", "func (rb *RequestBuilder) AsyncOptions(url string, f func(*Response)) {\n\tgo func() {\n\t\tf(rb.Options(url))\n\t}()\n}", "func (sc *Scavenger) Finder() *MessageFinder {\n\treturn (*MessageFinder)(sc)\n}", "func NewAsyncStats(s Stats) Stats {\n\treturn &async{s}\n}", "func (defintion *IndexDefinition) SetAsync(value bool) (outDef *IndexDefinition) {\n\toutDef = defintion\n\toutDef.Async = value\n\treturn\n}", "func NewRepoFinder(root string) *RepoFinder {\n\treturn &RepoFinder{\n\t\troot: root,\n\t}\n}", "func NewAsyncProducer(loggerID string) IAsyncProducer {\n\tap := AsyncProducer{\n\t\tloggerID: loggerID,\n\t\tconf: conf(),\n\t}\n\tvar err error\n\tif ap.brokers, err = getBrokersFromEnv(); err != nil {\n\t\tpanic(err.Error())\n\t}\n\tif err := GetSaramaProducer(&ap); err != nil {\n\t\tpanic(err.Error())\n\t}\n\tap.init()\n\treturn &ap\n}", "func NewAsyncLogger(writer io.WriteCloser, showInGlobalLogger bool) *AsyncLogger {\n\tlogger := &AsyncLogger{writer: writer, logCh: make(chan interface{}, 20000), showInGlobalLogger: showInGlobalLogger}\n\n\tsafego.RunWithRestart(func() {\n\t\tfor {\n\t\t\tif logger.closed.Load() {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tevent := <-logger.logCh\n\t\t\tbts, err := json.Marshal(event)\n\t\t\tif err != nil {\n\t\t\t\tErrorf(\"Error marshaling event to json: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif logger.showInGlobalLogger {\n\t\t\t\tprettyJSONBytes, _ := json.MarshalIndent(&event, \" \", \" \")\n\t\t\t\tInfo(string(prettyJSONBytes))\n\t\t\t}\n\n\t\t\tbuf := bytes.NewBuffer(bts)\n\t\t\tbuf.Write([]byte(\"\\n\"))\n\n\t\t\tif _, err := logger.writer.Write(buf.Bytes()); err != nil {\n\t\t\t\tErrorf(\"Error writing event to log file: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t})\n\n\treturn logger\n}", "func NewFind(filter bsoncore.Document) *Find {\n\treturn &Find{\n\t\tfilter: filter,\n\t}\n}", "func DoAsync(repos []string, fwrap Wrapper) {\n\tviper.Set(config.UseSync, false)\n\tDo(repos, fwrap)\n}", "func New(\n\tnotifier discovery.Notifier,\n\tdiscoverer discovery.Discoverer,\n\tlogger *zap.Logger,\n\tdiscoveryMinPeers int,\n) *Resolver {\n\tseed := time.Now().UnixNano()\n\trandom := rand.New(rand.NewSource(seed))\n\tr := &Resolver{\n\t\tnotifier: notifier,\n\t\tdiscoverer: discoverer,\n\t\tdiscoCh: make(chan []string, 100),\n\t\tlogger: logger,\n\t\tdiscoveryMinPeers: discoveryMinPeers,\n\t\tsalt: []byte(strconv.FormatInt(random.Int63(), 10)), // random salt for rendezvousHash\n\t\tscheme: strconv.FormatInt(seed, 36), // make random scheme which will be used when registering\n\t}\n\n\t// Register the resolver with grpc so it's available for grpc.Dial\n\tresolver.Register(r)\n\n\t// Register the discoCh channel with notifier so it continues to fetch a list of host/port\n\tnotifier.Register(r.discoCh)\n\treturn r\n}", "func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {\n\topt := new(Options)\n\terr := configstruct.Set(m, opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\troot = parsePath(root)\n\tclient := fshttp.NewClient(ctx)\n\tf := &Fs{\n\t\tname: name,\n\t\troot: root,\n\t\topt: *opt,\n\t\tsrv: rest.NewClient(client).SetRoot(rootURL),\n\t\tpacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),\n\t\tm: m,\n\t\tauthExpiry: parseExpiry(opt.AuthorizationExpiry),\n\t}\n\tf.features = (&fs.Features{\n\t\tCaseInsensitive: true,\n\t\tCanHaveEmptyDirectories: true,\n\t}).Fill(ctx, f)\n\tf.srv.SetSigner(f.getAuth) // use signing hook to get the auth\n\tf.srv.SetErrorHandler(errorHandler)\n\n\t// Get rootID\n\tif f.opt.RootID == \"\" {\n\t\tuser, err := f.getUser(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tf.opt.RootID = user.SyncFolders\n\t\tif strings.HasSuffix(f.opt.RootID, \"/contents\") {\n\t\t\tf.opt.RootID = f.opt.RootID[:len(f.opt.RootID)-9]\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"unexpected rootID %q\", f.opt.RootID)\n\t\t}\n\t\t// Cache the results\n\t\tf.m.Set(\"root_id\", f.opt.RootID)\n\t\tf.opt.DeletedID = user.Deleted\n\t\tf.m.Set(\"deleted_id\", f.opt.DeletedID)\n\t}\n\tf.dirCache = dircache.New(root, f.opt.RootID, f)\n\n\t// Find the current root\n\terr = f.dirCache.FindRoot(ctx, false)\n\tif err != nil {\n\t\t// Assume it is a file\n\t\tnewRoot, remote := dircache.SplitPath(root)\n\t\toldDirCache := f.dirCache\n\t\tf.dirCache = dircache.New(newRoot, f.opt.RootID, f)\n\t\tf.root = newRoot\n\t\tresetF := func() {\n\t\t\tf.dirCache = oldDirCache\n\t\t\tf.root = root\n\t\t}\n\t\t// Make new Fs which is the parent\n\t\terr = f.dirCache.FindRoot(ctx, false)\n\t\tif err != nil {\n\t\t\t// No root so return old f\n\t\t\tresetF()\n\t\t\treturn f, nil\n\t\t}\n\t\t_, err := f.newObjectWithInfo(ctx, remote, nil)\n\t\tif err != nil {\n\t\t\tif err == fs.ErrorObjectNotFound {\n\t\t\t\t// File doesn't exist so return old f\n\t\t\t\tresetF()\n\t\t\t\treturn f, nil\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\t// return an error with an fs which points to the parent\n\t\treturn f, fs.ErrorIsFile\n\t}\n\treturn f, nil\n}", "func NewDiscovery(conf *SDConfig, logger log.Logger) *Discovery {\n\tif logger == nil {\n\t\tlogger = log.NewNopLogger()\n\t}\n\n\tdisc := &Discovery{\n\t\tpaths: conf.Files,\n\t\tinterval: time.Duration(conf.RefreshInterval),\n\t\ttimestamps: make(map[string]float64),\n\t\tlogger: logger,\n\t}\n\tfileSDTimeStamp.addDiscoverer(disc)\n\treturn disc\n}", "func NewResolver(cln *client.Client, mw *progress.MultiWriter) (Resolver, error) {\n\troot, exist, err := modulesPathExist()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !exist {\n\t\treturn &remoteResolver{cln, mw, root}, nil\n\t}\n\n\treturn &vendorResolver{root}, nil\n}", "func NewUnionFind(sz int) *UnionFind {\n\tPanicIf(sz < 0, \"bad argument: %d\", sz)\n\tid := make([]int, sz)\n\tsize := make([]int, sz)\n\tfor i, _ := range id {\n\t\tid[i] = i\n\t\tsize[i] = 1\n\t}\n\treturn &UnionFind{id: id, size: size, volume: sz}\n}", "func NewFindOptions(flavor Flavor) *FindOptions {\n\treturn &FindOptions{\n\t\tFields: []string{\"*\"},\n\t\tFlavor: flavor,\n\t\tFilters: make(map[string]interface{}),\n\t}\n}", "func (f *Find) Timeout(timeout *time.Duration) *Find {\n\tif f == nil {\n\t\tf = new(Find)\n\t}\n\n\tf.timeout = timeout\n\treturn f\n}", "func NewDedupingFinder(sortedRecords []*common.Record, ra io.ReaderAt, combiner common.ObjectCombiner) common.Finder {\n\treturn &dedupingFinder{\n\t\tra: ra,\n\t\tsortedRecords: sortedRecords,\n\t\tcombiner: combiner,\n\t}\n}", "func (f *asyncFinder) at(ctx context.Context, at int64, min int, i *interval, c chan<- *result, quit <-chan struct{}) {\n\tvar wg sync.WaitGroup\n\n\tfor l := i.level; l > min; l-- {\n\t\tselect {\n\t\tcase <-quit: // if the parent process quit\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\twg.Add(1)\n\t\tgo func(l int) {\n\t\t\t// TODO: remove hardcoded timeout and define it as constant or inject in the getter.\n\t\t\treqCtx, cancel := context.WithTimeout(ctx, 1*time.Second)\n\t\t\tdefer func() {\n\t\t\t\tcancel()\n\t\t\t\twg.Done()\n\t\t\t}()\n\t\t\tindex := i.base + (1 << l) - 1\n\t\t\tchunk := f.asyncGet(reqCtx, at, index)\n\n\t\t\tselect {\n\t\t\tcase ch := <-chunk:\n\t\t\t\tselect {\n\t\t\t\tcase c <- &result{ch, i, l, index}:\n\t\t\t\tcase <-quit:\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tcase <-reqCtx.Done():\n\t\t\t\tselect {\n\t\t\t\tcase c <- &result{nil, i, l, index}:\n\t\t\t\tcase <-quit:\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tcase <-quit:\n\t\t\t}\n\t\t}(l)\n\t}\n\n\twg.Wait()\n}", "func NewPathFinder(container Container) *PathFinder {\n\treturn &PathFinder{\n\t\troot: container,\n\t}\n}", "func FindFile(ah *gcs.CAsyncHandler) *CStreamingFile {\n\tcsFile.Lock()\n\tdefer csFile.Unlock()\n\tif val, ok := gMapFile[ah]; ok {\n\t\treturn val\n\t}\n\treturn nil\n}", "func NewMockFinder(ctrl *gomock.Controller) *MockFinder {\n\tmock := &MockFinder{ctrl: ctrl}\n\tmock.recorder = &MockFinderMockRecorder{mock}\n\treturn mock\n}", "func NewResolver(root string, backgroundTaskManager *task.BackgroundTaskManager, cfg config.Config, resolveHandlers map[string]remote.Handler, metadataStore metadata.Store, overlayOpaqueType OverlayOpaqueType, additionalDecompressors func(context.Context, source.RegistryHosts, reference.Spec, ocispec.Descriptor) []metadata.Decompressor) (*Resolver, error) {\n\tresolveResultEntryTTL := time.Duration(cfg.ResolveResultEntryTTLSec) * time.Second\n\tif resolveResultEntryTTL == 0 {\n\t\tresolveResultEntryTTL = defaultResolveResultEntryTTLSec * time.Second\n\t}\n\tprefetchTimeout := time.Duration(cfg.PrefetchTimeoutSec) * time.Second\n\tif prefetchTimeout == 0 {\n\t\tprefetchTimeout = defaultPrefetchTimeoutSec * time.Second\n\t}\n\n\t// layerCache caches resolved layers for future use. This is useful in a use-case where\n\t// the filesystem resolves and caches all layers in an image (not only queried one) in parallel,\n\t// before they are actually queried.\n\tlayerCache := cacheutil.NewTTLCache(resolveResultEntryTTL)\n\tlayerCache.OnEvicted = func(key string, value interface{}) {\n\t\tif err := value.(*layer).close(); err != nil {\n\t\t\tlogrus.WithField(\"key\", key).WithError(err).Warnf(\"failed to clean up layer\")\n\t\t\treturn\n\t\t}\n\t\tlogrus.WithField(\"key\", key).Debugf(\"cleaned up layer\")\n\t}\n\n\t// blobCache caches resolved blobs for futural use. This is especially useful when a layer\n\t// isn't eStargz/stargz (the *layer object won't be created/cached in this case).\n\tblobCache := cacheutil.NewTTLCache(resolveResultEntryTTL)\n\tblobCache.OnEvicted = func(key string, value interface{}) {\n\t\tif err := value.(remote.Blob).Close(); err != nil {\n\t\t\tlogrus.WithField(\"key\", key).WithError(err).Warnf(\"failed to clean up blob\")\n\t\t\treturn\n\t\t}\n\t\tlogrus.WithField(\"key\", key).Debugf(\"cleaned up blob\")\n\t}\n\n\tif err := os.MkdirAll(root, 0700); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Resolver{\n\t\trootDir: root,\n\t\tresolver: remote.NewResolver(cfg.BlobConfig, resolveHandlers),\n\t\tlayerCache: layerCache,\n\t\tblobCache: blobCache,\n\t\tprefetchTimeout: prefetchTimeout,\n\t\tbackgroundTaskManager: backgroundTaskManager,\n\t\tconfig: cfg,\n\t\tresolveLock: new(namedmutex.NamedMutex),\n\t\tmetadataStore: metadataStore,\n\t\toverlayOpaqueType: overlayOpaqueType,\n\t\tadditionalDecompressors: additionalDecompressors,\n\t}, nil\n}", "func New(cfg *rest.Config, o ...Option) (*Manager, error) {\n\tvar useExisting bool\n\tif cfg != nil {\n\t\tuseExisting = true\n\t}\n\n\tc := defaultConfig()\n\tfor _, op := range o {\n\t\top(c)\n\t}\n\n\tdir, err := os.MkdirTemp(\"\", \"\")\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, errCreateTmpDir)\n\t}\n\n\tcrdPaths := []string{}\n\tfor _, path := range c.CRDPaths {\n\t\tdst, err := downloadPath(path, dir)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, errGetCRDs)\n\t\t}\n\t\tcrdPaths = append(crdPaths, dst)\n\t}\n\n\te := &envtest.Environment{\n\t\tCRDDirectoryPaths: crdPaths,\n\t\tConfig: cfg,\n\t\tUseExistingCluster: &useExisting,\n\t}\n\n\tcfg, err = e.Start()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient, err := client.New(cfg, client.Options{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := c.Builder(client); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmgr, err := manager.New(cfg, c.ManagerOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstop := make(chan struct{})\n\treturn &Manager{mgr, stop, e, client, c, dir}, nil\n}", "func New(tp elastictransport.Interface) *Search {\n\tr := &Search{\n\t\ttransport: tp,\n\t\tvalues: make(url.Values),\n\t\theaders: make(http.Header),\n\t\tbuf: gobytes.NewBuffer(nil),\n\n\t\treq: NewRequest(),\n\t}\n\n\treturn r\n}", "func New(ctx context.Context) *Resolver {\n\treturn &Resolver{\n\t\tctx: ctx,\n\t\tresultSetPool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn &resultSet{\n\t\t\t\t\tbuffers: make(map[int]*BufPair, 8),\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\tbyteSlicesPool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\tslice := make([][]byte, 0, 24)\n\t\t\t\treturn &slice\n\t\t\t},\n\t\t},\n\t\twaitGroupPool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn &sync.WaitGroup{}\n\t\t\t},\n\t\t},\n\t\tbufPairPool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\tpair := BufPair{\n\t\t\t\t\tData: fastbuffer.New(),\n\t\t\t\t\tErrors: fastbuffer.New(),\n\t\t\t\t}\n\t\t\t\treturn &pair\n\t\t\t},\n\t\t},\n\t\tbufPairSlicePool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\tslice := make([]*BufPair, 0, 24)\n\t\t\t\treturn &slice\n\t\t\t},\n\t\t},\n\t\terrChanPool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn make(chan error, 1)\n\t\t\t},\n\t\t},\n\t\thash64Pool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn xxhash.New()\n\t\t\t},\n\t\t},\n\t\tinflightFetchPool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn &inflightFetch{\n\t\t\t\t\tbufPair: BufPair{\n\t\t\t\t\t\tData: fastbuffer.New(),\n\t\t\t\t\t\tErrors: fastbuffer.New(),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\tinflightFetches: map[uint64]*inflightFetch{},\n\t}\n}", "func NewSync(mountID mount.ID, m mount.Mount, opts SyncOpts) (*Sync, error) {\n\tif err := opts.Valid(); err != nil {\n\t\treturn nil, err\n\t}\n\n\ts := &Sync{\n\t\topts: opts,\n\t\tmountID: mountID,\n\t\tm: m,\n\t}\n\n\tif opts.Log != nil {\n\t\ts.log = opts.Log.New(\"sync\")\n\t} else {\n\t\ts.log = machine.DefaultLogger.New(\"sync\")\n\t}\n\n\t// Create directory structure if it doesn't exist.\n\tif err := os.MkdirAll(filepath.Join(s.opts.WorkDir, \"data\"), 0755); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Fetch or load remote index.\n\tvar err error\n\tif s.ridx, err = s.loadIdx(RemoteIndexName, s.fetchRemoteIdx); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create or load local index.\n\tif s.lidx, err = s.loadIdx(LocalIndexName, s.fetchLocalIdx); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Update local index if needed.\n\tif err := s.updateLocal(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create FS event consumer queue.\n\ts.a = NewAnteroom()\n\n\t// Create file system notification object.\n\ts.n, err = opts.NotifyBuilder.Build(&notify.BuildOpts{\n\t\tMountID: mountID,\n\t\tMount: m,\n\t\tCache: s.a,\n\t\tCacheDir: filepath.Join(s.opts.WorkDir, \"data\"),\n\t\tRemoteIdx: s.ridx,\n\t\tLocalIdx: s.lidx,\n\t})\n\tif err != nil {\n\t\ts.a.Close()\n\t\treturn nil, err\n\t}\n\n\t// Create file synchronization object.\n\ts.s, err = opts.SyncBuilder.Build(&BuildOpts{\n\t\tRemoteIdx: s.ridx,\n\t\tLocalIdx: s.lidx,\n\t})\n\tif err != nil {\n\t\ts.n.Close()\n\t\ts.a.Close()\n\t\treturn nil, err\n\t}\n\n\treturn s, nil\n}", "func New(o *Options) (Interface, error) {\n\tvar (\n\t\tregistration = o.registration()\n\t\tpath = o.path()\n\t\tserviceName = o.serviceName()\n\t\tregistrar sd.Registrar\n\t\tlogger = logging.DefaultCaller(o.logger(), \"serviceName\", o.serviceName(), \"path\", path, \"registration\", registration)\n\n\t\t// use the internal singleton factory function, which is set to zk.NewClient normally\n\t\tclient, err = zkClientFactory(\n\t\t\to.servers(),\n\t\t\tlogger,\n\t\t\tzk.ConnectTimeout(o.connectTimeout()),\n\t\t\tzk.SessionTimeout(o.sessionTimeout()),\n\t\t)\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(registration) > 0 {\n\t\tregistrar = zk.NewRegistrar(\n\t\t\tclient,\n\t\t\tzk.Service{\n\t\t\t\tPath: path,\n\t\t\t\tName: serviceName,\n\t\t\t\tData: []byte(registration),\n\t\t\t},\n\t\t\tlogger,\n\t\t)\n\t}\n\n\tlogger.Log(level.Key(), level.InfoValue(), logging.MessageKey(), \"service discovery initialized\")\n\n\treturn &zkFacade{\n\t\tlogger: logger,\n\t\tclient: client,\n\t\tpath: path,\n\t\tregistrar: registrar,\n\t}, nil\n}", "func NewBarrageFinder() *BarrageFinder {\n\tf := new(BarrageFinder)\n\tf.where = bson.M{}\n\tf.barrages = []*Barrage{}\n\treturn f\n}", "func AsyncBoxForReading(ob *objectbox.ObjectBox, timeoutMs uint64) *ReadingAsyncBox {\n\tvar async, err = objectbox.NewAsyncBox(ob, 2, timeoutMs)\n\tif err != nil {\n\t\tpanic(\"Could not create async box for entity ID 2: %s\" + err.Error())\n\t}\n\treturn &ReadingAsyncBox{AsyncBox: async}\n}", "func NewFindingRevealedWaiter(client GetSensitiveDataOccurrencesAPIClient, optFns ...func(*FindingRevealedWaiterOptions)) *FindingRevealedWaiter {\n\toptions := FindingRevealedWaiterOptions{}\n\toptions.MinDelay = 2 * time.Second\n\toptions.MaxDelay = 120 * time.Second\n\toptions.Retryable = findingRevealedStateRetryable\n\n\tfor _, fn := range optFns {\n\t\tfn(&options)\n\t}\n\treturn &FindingRevealedWaiter{\n\t\tclient: client,\n\t\toptions: options,\n\t}\n}", "func WithAsync() EventConfigurator {\n\treturn func(handler EventHandler) {\n\t\th := handler.(*eventHandler)\n\t\th.async = true\n\t}\n}", "func StartAsync(ctx context.Context) {\n\tgo func() {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\terr := manager().processOnce()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t}()\n}", "func New(APIaddr string, requiredUserAgent string, requiredPassword string, nodeParams node.NodeParams, loadStartTime time.Time) (*Server, error) {\n\t// Wait for the node to be done loading.\n\tsrv, errChan := NewAsync(APIaddr, requiredUserAgent, requiredPassword, nodeParams, loadStartTime)\n\tif err := <-errChan; err != nil {\n\t\t// Error occurred during async load. Close all modules.\n\t\tif build.Release == \"standard\" {\n\t\t\tfmt.Println(\"ERROR:\", err)\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn srv, nil\n}", "func New(u string, opts ...extfs.ClientOption) (extfs.Filesystem, error) {\n\tcfg := &extfs.Config{}\n\tfor _, option := range opts {\n\t\terr := option(cfg)\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"Failed to read opts\")\n\t\t}\n\t}\n\treturn NewFilesystem(u, cfg)\n}", "func NewFetcher(ASlist []string) *Fetcher {\n\treturn &Fetcher{\n\t\tASNs: ASlist,\n\t}\n\n}", "func NewManager(task *tasks.Task, rootDirectory string) (*GoManager, error) {\n\tvar selectedVersion *version.Version\n\tvar installedVersions version.Collection\n\n\tfileInfos, err := ioutil.ReadDir(rootDirectory)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, fileInfo := range fileInfos {\n\t\tif fileInfo.IsDir() || fileInfo.Mode()&os.ModeSymlink != 0 {\n\t\t\tdetectedVersion, err := detectGoVersion(filepath.Join(rootDirectory, fileInfo.Name()))\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif fileInfo.Name() == selectedDirectoryName {\n\t\t\t\tselectedVersion = detectedVersion\n\t\t\t} else {\n\t\t\t\tinstalledVersions = append(installedVersions, detectedVersion)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &GoManager{\n\t\tRootDirectory: rootDirectory,\n\t\tInstalledVersions: installedVersions,\n\t\tSelectedVersion: selectedVersion,\n\t\ttask: task,\n\t}, nil\n}", "func NewResolver() *Resolver {\n\tclient := http.Client{\n\t\tTimeout: time.Second * 3,\n\t}\n\n\treturn &Resolver{\n\t\tClient: client,\n\t}\n}", "func newFuture() *future {\n\treturn &future{\n\t\twaitCh: make(chan struct{}),\n\t\tid: uuid.Generate(),\n\t}\n}" ]
[ "0.6278817", "0.60753214", "0.6067157", "0.6022303", "0.60068786", "0.59324783", "0.5866529", "0.56715345", "0.56193966", "0.56193966", "0.5493856", "0.547196", "0.5442003", "0.5435475", "0.53768", "0.5223182", "0.52034193", "0.51921666", "0.5136617", "0.5093945", "0.5092701", "0.5057361", "0.499759", "0.49382752", "0.49351472", "0.4919162", "0.48708963", "0.48522067", "0.4813057", "0.48090783", "0.4767482", "0.47649163", "0.4746253", "0.47387108", "0.47297972", "0.46999517", "0.46970707", "0.46781668", "0.46244577", "0.46161985", "0.46106562", "0.46006867", "0.459651", "0.45840383", "0.45491654", "0.45450532", "0.45443758", "0.45271274", "0.45102364", "0.4507468", "0.44916084", "0.44854945", "0.44748837", "0.44268662", "0.44263625", "0.44021633", "0.43864068", "0.43655363", "0.43230808", "0.43143684", "0.43054286", "0.42955485", "0.4293288", "0.42902976", "0.42861107", "0.428441", "0.4273667", "0.4263661", "0.4258738", "0.4251232", "0.42438886", "0.42415252", "0.42358878", "0.4233152", "0.42281762", "0.4224342", "0.4218939", "0.4209732", "0.42063215", "0.42042097", "0.41997346", "0.41833988", "0.4159323", "0.4158695", "0.4154214", "0.41539976", "0.41446966", "0.4142971", "0.41382957", "0.41312107", "0.41252446", "0.41229168", "0.41130632", "0.4098811", "0.40980235", "0.40867153", "0.40862295", "0.40840253", "0.40789917" ]
0.80872023
1
At looks up the version valid at time `at` after is a unix time hint of the latest known update
func (f *asyncFinder) At(ctx context.Context, at, after int64) (ch swarm.Chunk, cur, next feeds.Index, err error) { ch, diff, err := f.get(ctx, at, 0) if err != nil { return nil, nil, nil, err } if ch == nil { return nil, nil, nil, nil } if diff == 0 { return ch, &index{0}, &index{1}, nil } c := make(chan result) p := newPath(0) p.latest.chunk = ch for p.level = 1; diff>>p.level > 0; p.level++ { } quit := make(chan struct{}) defer close(quit) go f.at(ctx, at, p, c, quit) for r := range c { p = r.path if r.chunk == nil { if r.level == 0 { return p.latest.chunk, &index{p.latest.seq}, &index{p.latest.seq + 1}, nil } if p.level < r.level { continue } p.level = r.level - 1 } else { if r.diff == 0 { return r.chunk, &index{r.seq}, &index{r.seq + 1}, nil } if p.latest.level > r.level { continue } p.close() p.latest = r } // below applies even if p.latest==maxLevel if p.latest.level == p.level { if p.level == 0 { return p.latest.chunk, &index{p.latest.seq}, &index{p.latest.seq + 1}, nil } p.close() np := newPath(p.latest.seq) np.level = p.level np.latest.chunk = p.latest.chunk go f.at(ctx, at, np, c, quit) } } return nil, nil, nil, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r ApiGetHyperflexServerFirmwareVersionListRequest) At(at string) ApiGetHyperflexServerFirmwareVersionListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetHyperflexServerFirmwareVersionEntryListRequest) At(at string) ApiGetHyperflexServerFirmwareVersionEntryListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetHyperflexHxdpVersionListRequest) At(at string) ApiGetHyperflexHxdpVersionListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetHyperflexSoftwareDistributionVersionListRequest) At(at string) ApiGetHyperflexSoftwareDistributionVersionListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAt() error {\n\tu, err := fetchUpdatedAt(federalRevenueURL)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting updated at: %w\", err)\n\t}\n\tfmt.Println(u)\n\treturn nil\n}", "func (f *finder) At(ctx context.Context, at, after int64) (ch swarm.Chunk, current, next feeds.Index, err error) {\n\tfor i := uint64(0); ; i++ {\n\t\tu, err := f.getter.Get(ctx, &index{i})\n\t\tif err != nil {\n\t\t\tif !errors.Is(err, storage.ErrNotFound) {\n\t\t\t\treturn nil, nil, nil, err\n\t\t\t}\n\t\t\treturn ch, &index{i - 1}, &index{i}, nil\n\t\t}\n\t\tts, err := feeds.UpdatedAt(u)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t\tif ts > uint64(at) {\n\t\t\treturn ch, &index{i}, nil, nil\n\t\t}\n\t\tch = u\n\t}\n}", "func (b *FollowUpBuilder) UpdatedAt(value time.Time) *FollowUpBuilder {\n\tb.updatedAt = value\n\tb.bitmap_ |= 8192\n\treturn b\n}", "func UpdatedAt(v time.Time) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (b *BalanceAs) repriceAt(at time.Time) error {\n\t// find latest price for trading pair\n\tpriceAs, err := DefaultArchive.GetPriceAs(SymbolType(b.Symbol), b.As, at)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get latest price for: %s as %s - %s\", b.Symbol, b.As, err)\n\t}\n\treturn b.repriceUsing(priceAs)\n}", "func (r ApiGetHyperflexSoftwareVersionPolicyListRequest) At(at string) ApiGetHyperflexSoftwareVersionPolicyListRequest {\n\tr.at = &at\n\treturn r\n}", "func archiveAt(timestamp int64, svc *Checkin) archiveFunc {\n\treturn func(nano int64, event []byte) error {\n\t\treturn svc.archive(timestamp, event)\n\t}\n}", "func (w *watcher) updatedAtTime() time.Time {\n\treturn time.Unix(0, atomic.LoadInt64(&w.updatedAt))\n}", "func (r BuildInfoResolver) BuiltAt() *graphql.Time {\n\tif t := r.bi.BuiltAt; t != nil {\n\t\treturn &graphql.Time{Time: *t}\n\t}\n\treturn nil\n}", "func UpdatedAt(v time.Time) predicate.GameServer {\n\treturn predicate.GameServer(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func UpdatedAt(v time.Time) predicate.MetaSchema {\n\treturn predicate.MetaSchema(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t},\n\t)\n}", "func (f *finder) At(ctx context.Context, at int64, _ uint64) (ch swarm.Chunk, current, next feeds.Index, err error) {\n\tfor i := uint64(0); ; i++ {\n\t\tu, err := f.getter.Get(ctx, &index{i})\n\t\tif err != nil {\n\t\t\tif !errors.Is(err, storage.ErrNotFound) {\n\t\t\t\treturn nil, nil, nil, err\n\t\t\t}\n\t\t\tif i > 0 {\n\t\t\t\tcurrent = &index{i - 1}\n\t\t\t}\n\t\t\treturn ch, current, &index{i}, nil\n\t\t}\n\t\tts, err := feeds.UpdatedAt(u)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t\t// if index is later than the `at` target index, then return previous chunk and index\n\t\tif ts > uint64(at) {\n\t\t\treturn ch, &index{i - 1}, &index{i}, nil\n\t\t}\n\t\tch = u\n\t}\n}", "func UpdatedAt(v time.Time) predicate.Step {\n\treturn predicate.Step(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func UpdatedAt(v time.Time) predicate.Ethnicity {\n\treturn predicate.Ethnicity(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r *ChainResolver) UpdatedAt() graphql.Time {\n\treturn graphql.Time{Time: r.chain.UpdatedAt}\n}", "func (r ApiGetHyperflexVmSnapshotInfoListRequest) At(at string) ApiGetHyperflexVmSnapshotInfoListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetHyperflexVmBackupInfoListRequest) At(at string) ApiGetHyperflexVmBackupInfoListRequest {\n\tr.at = &at\n\treturn r\n}", "func (mnuo *MedicalNoteUpdateOne) SetAt(t time.Time) *MedicalNoteUpdateOne {\n\tmnuo.at = &t\n\treturn mnuo\n}", "func At(dt time.Time, job *Job, buildWrapper BuildWrapperFunc) cron.EntryID {\n\tif dt.Before(Now()) {\n\t\treturn InvalidEntryID\n\t}\n\n\tjob.entryID = mainCron.Schedule(schedules.Absolute(dt), buildWrapper(job))\n\tjob.typ = JobTypeOnce\n\treturn addJob(job)\n}", "func UpdatedAtLTE(v time.Time) predicate.MetaSchema {\n\treturn predicate.MetaSchema(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldUpdatedAt), v))\n\t},\n\t)\n}", "func (o FaqOutput) UpdatedAt() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Faq) pulumi.StringOutput { return v.UpdatedAt }).(pulumi.StringOutput)\n}", "func (su *SystemUser) ValidAt(when time.Time) bool {\n\tvalid := when.After(su.since) || when.Equal(su.since)\n\tif valid {\n\t\tvalid = when.Before(su.until)\n\t}\n\treturn valid\n}", "func AtVersion(version string) GetOption {\n\treturn func(o *getOptions) {\n\t\to.version = version\n\t}\n}", "func UpdatedAt(v time.Time) predicate.Job {\n\treturn predicate.Job(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetHyperflexHealthCheckPackageChecksumListRequest) At(at string) ApiGetHyperflexHealthCheckPackageChecksumListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAt(v time.Time) predicate.OrderItem {\n\treturn predicate.OrderItem(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetHyperflexClusterBackupPolicyDeploymentListRequest) At(at string) ApiGetHyperflexClusterBackupPolicyDeploymentListRequest {\n\tr.at = &at\n\treturn r\n}", "func (mnu *MedicalNoteUpdate) SetAt(t time.Time) *MedicalNoteUpdate {\n\tmnu.at = &t\n\treturn mnu\n}", "func (o *Handoff) UpdatedAt() time.Time {\n\tif o != nil && o.bitmap_&256 != 0 {\n\t\treturn o.updatedAt\n\t}\n\treturn time.Time{}\n}", "func UpdatedAtLTE(v time.Time) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (a *versionedValue) AtVersion(v int) (r *versionedValue) {\n\tfor ; a != nil; a = a.versionedValue {\n\t\tif a.version <= v {\n\t\t\treturn a\n\t\t}\n\t}\n\treturn\n}", "func (r ApiGetHyperflexHealthCheckExecutionSnapshotListRequest) At(at string) ApiGetHyperflexHealthCheckExecutionSnapshotListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetHyperflexSoftwareDistributionEntryListRequest) At(at string) ApiGetHyperflexSoftwareDistributionEntryListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAt(v time.Time) predicate.Delivery {\n\treturn predicate.Delivery(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetHyperflexDevicePackageDownloadStateListRequest) At(at string) ApiGetHyperflexDevicePackageDownloadStateListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAt(v time.Time) predicate.Permission {\n\treturn predicate.Permission(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (ref FileView) At(seqNum commit.SeqNum) (r fileversion.Reference, err error) {\n\tfile, ok := ref.repo.files[ref.file]\n\tif !ok {\n\t\treturn nil, fileview.NotFound{File: ref.file, Drive: ref.drive, Commit: seqNum}\n\t}\n\tview, ok := file.Views[ref.drive]\n\tif !ok {\n\t\treturn nil, fileview.NotFound{File: ref.file, Drive: ref.drive, Commit: seqNum}\n\t}\n\tvar (\n\t\tmaxCommit commit.SeqNum\n\t\tmaxVersion resource.Version\n\t\tfound bool\n\t)\n\tfor seqNum, version := range view {\n\t\tif !found || seqNum > maxCommit {\n\t\t\tfound = true\n\t\t\tmaxCommit = seqNum\n\t\t\tmaxVersion = version\n\t\t}\n\t}\n\tif !found {\n\t\treturn nil, fileview.NotFound{File: ref.file, Drive: ref.drive, Commit: seqNum}\n\t}\n\t// FIXME: What about deleted files?\n\t// TODO: Include deletions in the view with a -1 version number so we\n\t// don't pick up the pre-deleted states?\n\treturn FileVersion{\n\t\trepo: ref.repo,\n\t\tfile: ref.file,\n\t\tversion: maxVersion,\n\t}, nil\n}", "func (o InfraAlertConditionOutput) UpdatedAt() pulumi.IntOutput {\n\treturn o.ApplyT(func(v *InfraAlertCondition) pulumi.IntOutput { return v.UpdatedAt }).(pulumi.IntOutput)\n}", "func UpdatedAtLTE(v time.Time) predicate.Ethnicity {\n\treturn predicate.Ethnicity(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetHyperflexAppCatalogListRequest) At(at string) ApiGetHyperflexAppCatalogListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAt(v time.Time) predicate.Order {\n\treturn predicate.Order(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetIqnpoolUniverseListRequest) At(at string) ApiGetIqnpoolUniverseListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAtLTE(v time.Time) predicate.GameServer {\n\treturn predicate.GameServer(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func UpdatedAtLTE(v time.Time) predicate.Permission {\n\treturn predicate.Permission(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetHyperflexDatastoreStatisticListRequest) At(at string) ApiGetHyperflexDatastoreStatisticListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetHyperflexVolumeListRequest) At(at string) ApiGetHyperflexVolumeListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetHyperflexSoftwareDistributionComponentListRequest) At(at string) ApiGetHyperflexSoftwareDistributionComponentListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAtLTE(v time.Time) predicate.Job {\n\treturn predicate.Job(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetHyperflexBackupClusterListRequest) At(at string) ApiGetHyperflexBackupClusterListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAtLTE(v time.Time) predicate.Delivery {\n\treturn predicate.Delivery(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetHyperflexClusterHealthCheckExecutionSnapshotListRequest) At(at string) ApiGetHyperflexClusterHealthCheckExecutionSnapshotListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAtLTE(v time.Time) predicate.Step {\n\treturn predicate.Step(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func UpdatedAtLTE(v time.Time) predicate.OrderItem {\n\treturn predicate.OrderItem(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (qs SysDBQuerySet) UpdatedAtLte(updatedAt time.Time) SysDBQuerySet {\n\treturn qs.w(qs.db.Where(\"updated_at <= ?\", updatedAt))\n}", "func (r ApiGetHyperflexConfigResultEntryListRequest) At(at string) ApiGetHyperflexConfigResultEntryListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAtGTE(v time.Time) predicate.MetaSchema {\n\treturn predicate.MetaSchema(func(s *sql.Selector) {\n\t\ts.Where(sql.GTE(s.C(FieldUpdatedAt), v))\n\t},\n\t)\n}", "func UpdatedAtLTE(v time.Time) predicate.Order {\n\treturn predicate.Order(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetHyperflexLicenseListRequest) At(at string) ApiGetHyperflexLicenseListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetIqnpoolReservationListRequest) At(at string) ApiGetIqnpoolReservationListRequest {\n\tr.at = &at\n\treturn r\n}", "func (qs ConstraintQuerySet) UpdatedAtLte(updatedAt time.Time) ConstraintQuerySet {\n\treturn qs.w(qs.db.Where(\"updated_at <= ?\", updatedAt))\n}", "func (r ApiGetHyperflexAutoSupportPolicyListRequest) At(at string) ApiGetHyperflexAutoSupportPolicyListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetHyperflexServerModelListRequest) At(at string) ApiGetHyperflexServerModelListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetResourcepoolUniverseListRequest) At(at string) ApiGetResourcepoolUniverseListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAtLTE(v time.Time) predicate.K8sEvent {\n\treturn predicate.K8sEvent(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func PublishedAt(v time.Time) predicate.GithubRelease {\n\treturn predicate.GithubRelease(sql.FieldEQ(FieldPublishedAt, v))\n}", "func (r ApiGetIqnpoolLeaseListRequest) At(at string) ApiGetIqnpoolLeaseListRequest {\n\tr.at = &at\n\treturn r\n}", "func (m *AddressMutation) UpdatedAt() (r time.Time, exists bool) {\n\tv := m.updated_at\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (r ApiGetHyperflexAlarmListRequest) At(at string) ApiGetHyperflexAlarmListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetHyperflexClusterBackupPolicyListRequest) At(at string) ApiGetHyperflexClusterBackupPolicyListRequest {\n\tr.at = &at\n\treturn r\n}", "func (o Comment) UpdatedAt() *graphql.Time {\n\tif o.model.UpdatedAt.Valid {\n\t\treturn &graphql.Time{Time: o.model.UpdatedAt.Time}\n\t}\n\treturn nil // null.Time\n}", "func (t *TOTP) At(timestamp int64) string {\n\treturn t.generateOTP(t.timecode(timestamp))\n}", "func UpdatedAtLT(v time.Time) predicate.MetaSchema {\n\treturn predicate.MetaSchema(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldUpdatedAt), v))\n\t},\n\t)\n}", "func UpdatedAt(v time.Time) predicate.K8sEvent {\n\treturn predicate.K8sEvent(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetEtherHostPortListRequest) At(at string) ApiGetEtherHostPortListRequest {\n\tr.at = &at\n\treturn r\n}", "func At(at int64) OffsetOpt {\n\tif at < 0 {\n\t\tat = -2\n\t}\n\treturn offsetOpt{func(o *Offset) { o.request = at }}\n}", "func UpdatedAtGTE(v time.Time) predicate.Ethnicity {\n\treturn predicate.Ethnicity(func(s *sql.Selector) {\n\t\ts.Where(sql.GTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func UpdatedAtLT(v time.Time) predicate.Ethnicity {\n\treturn predicate.Ethnicity(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (o LookupExperienceResultOutput) UpdatedAt() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupExperienceResult) string { return v.UpdatedAt }).(pulumi.StringOutput)\n}", "func UpdatedAt(v time.Time) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (m *FeedMutation) UpdatedAt() (r time.Time, exists bool) {\n\tv := m.updated_at\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func UpdatedAtGTE(v time.Time) predicate.GameServer {\n\treturn predicate.GameServer(func(s *sql.Selector) {\n\t\ts.Where(sql.GTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetHyperflexSysConfigPolicyListRequest) At(at string) ApiGetHyperflexSysConfigPolicyListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAtGTE(v time.Time) predicate.Permission {\n\treturn predicate.Permission(func(s *sql.Selector) {\n\t\ts.Where(sql.GTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetHyperflexConfigResultListRequest) At(at string) ApiGetHyperflexConfigResultListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAtGTE(v time.Time) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.GTE(s.C(FieldUpdatedAt), v))\n\t})\n}", "func UpdatedAt(v time.Time) predicate.OrderLineItem {\n\treturn predicate.OrderLineItem(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldUpdatedAt), v))\n\t})\n}", "func UpdatedAtLT(v time.Time) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldUpdatedAt), v))\n\t})\n}", "func tryVersionDateSha(ver string) (ref string, ok bool) {\n\tcomponents := strings.Split(ver, \"-\")\n\n\tif len(components) != 3 {\n\t\treturn\n\t}\n\n\tok = true\n\tref = components[2]\n\n\treturn\n}", "func UpdatedAtLT(v time.Time) predicate.Permission {\n\treturn predicate.Permission(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldUpdatedAt), v))\n\t})\n}", "func UpdatedAtGT(v time.Time) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.GT(s.C(FieldUpdatedAt), v))\n\t})\n}", "func (r ApiGetHyperflexHealthCheckExecutionListRequest) At(at string) ApiGetHyperflexHealthCheckExecutionListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetHyperflexHealthCheckDefinitionListRequest) At(at string) ApiGetHyperflexHealthCheckDefinitionListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetHyperflexLunListRequest) At(at string) ApiGetHyperflexLunListRequest {\n\tr.at = &at\n\treturn r\n}", "func (r ApiGetHyperflexClusterReplicationNetworkPolicyDeploymentListRequest) At(at string) ApiGetHyperflexClusterReplicationNetworkPolicyDeploymentListRequest {\n\tr.at = &at\n\treturn r\n}", "func (m *TenantMutation) UpdatedAt() (r time.Time, exists bool) {\n\tv := m.updated_at\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (r ApiGetResourcepoolLeaseListRequest) At(at string) ApiGetResourcepoolLeaseListRequest {\n\tr.at = &at\n\treturn r\n}", "func UpdatedAtGT(v time.Time) predicate.GameServer {\n\treturn predicate.GameServer(func(s *sql.Selector) {\n\t\ts.Where(sql.GT(s.C(FieldUpdatedAt), v))\n\t})\n}" ]
[ "0.60237", "0.597019", "0.59644204", "0.59450865", "0.59381974", "0.57100904", "0.5538346", "0.5518835", "0.55184263", "0.5513792", "0.547175", "0.5458565", "0.5456444", "0.5441323", "0.5441174", "0.54125583", "0.54082346", "0.53972095", "0.5381042", "0.53801376", "0.5376697", "0.5369259", "0.5363501", "0.53518486", "0.5338412", "0.5330474", "0.5328381", "0.5326634", "0.53190106", "0.5317179", "0.52980596", "0.5298003", "0.52975243", "0.5294699", "0.5289299", "0.5287564", "0.5284977", "0.5267301", "0.5261333", "0.52580154", "0.52476966", "0.52377015", "0.5233931", "0.52191097", "0.5208125", "0.52054346", "0.5195915", "0.5181251", "0.51805335", "0.5177625", "0.5177094", "0.5168988", "0.51622474", "0.5160251", "0.51555485", "0.5154189", "0.5150976", "0.51338077", "0.51198703", "0.5113891", "0.5110938", "0.5108425", "0.51048386", "0.50898534", "0.50873494", "0.50864136", "0.5084433", "0.5077126", "0.50688875", "0.5062949", "0.5052695", "0.5049174", "0.50404465", "0.50384194", "0.5033101", "0.5024648", "0.5010063", "0.50073284", "0.50023973", "0.4992219", "0.4990247", "0.4987303", "0.49819276", "0.4979653", "0.49680138", "0.4963741", "0.4959656", "0.49594763", "0.4959228", "0.4955238", "0.49523476", "0.49478826", "0.49472713", "0.49458554", "0.49442336", "0.49416247", "0.49405083", "0.49351007", "0.4934364", "0.4927082", "0.4922205" ]
0.0
-1
NewUpdater constructs a feed updater
func NewUpdater(putter storage.Putter, signer crypto.Signer, topic []byte) (feeds.Updater, error) { p, err := feeds.NewPutter(putter, signer, topic) if err != nil { return nil, err } return &updater{Putter: p}, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func New() *Updater {\n\treturn &Updater{}\n}", "func NewUpdater(cfg *Config, rdb *redis.Client) *Updater {\n\treturn &Updater{\n\t\tConfig: cfg,\n\t\trdb: rdb,\n\t\tdone: make(chan struct{}),\n\t\tabort: make(chan error),\n\t\twork: make(chan WorkTuple),\n\t\tprocessed: make(chan ProcessedTuple),\n\t}\n}", "func NewUpdater(sv *Values) Updater {\n\treturn updater{\n\t\tm: make(map[string]struct{}, len(Registry)),\n\t\tsv: sv,\n\t}\n}", "func New(connector connectors.AutoUpdateDataConnector, collectionPeriod int,\n postgresUrl string, apiConfig utils.APIDependencyConfig) *AutoUpdater {\n return &AutoUpdater{\n PostgresURL: postgresUrl,\n DataConnector: connector,\n CollectionPeriodMinutes: collectionPeriod,\n TRFApiConfig: apiConfig,\n }\n}", "func New(removeUnusedDeclarations bool, updateComments bool, bazelAnalyze BazelAnalyzer, updateFile UpdateFile) *Updater {\n\treturn &Updater{removeUnusedDeclarations, updateComments, bazelAnalyze, updateFile}\n}", "func NewUpdater(o Options) *Updater {\n\tu := &Updater{}\n\tu.v.Store(o)\n\treturn u\n}", "func NewUpdater(root string) (*Updater, error) {\n\tif len(root) == 0 {\n\t\treturn nil, errors.New(\"no root directory specified\")\n\t}\n\n\treturn &Updater{\n\t\troot: root,\n\t}, nil\n}", "func New(qw QueueWriter) *Updater {\n\treturn &Updater{qw, sync.Map{}}\n}", "func NewUpdater(dryRun bool, isPatched bool) *Updater {\n\tupdater := Updater{\n\t\tupdaters: make([]UpdateComponents, 0),\n\t\tdryRun: dryRun,\n\t\tisPatched: isPatched,\n\t}\n\treturn &updater\n}", "func NewUpdater(v Release, opt ...Option) (*Updater, error) {\n\tu := &Updater{\n\t\tname: fmt.Sprintf(\"rhel-%d-updater\", v),\n\t\trelease: v,\n\t}\n\tvar err error\n\tu.Fetcher.URL, err = url.Parse(fmt.Sprintf(dbURL, v))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, f := range opt {\n\t\tif err := f(u); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif u.Fetcher.Client == nil {\n\t\tu.Fetcher.Client = http.DefaultClient // TODO(hank) Remove DefaultClient\n\t}\n\treturn u, nil\n}", "func New(config Config) (*Updater, error) {\n\t// Everything we need it set?\n\tif config.InstallsDir == \"\" {\n\t\treturn nil, errors.New(\"InstallsDir must be set\")\n\t}\n\tif config.WorkingDir == \"\" {\n\t\treturn nil, errors.New(\"WorkingDir must be set\")\n\t}\n\tif config.UpdateURL == \"\" {\n\t\treturn nil, errors.New(\"UpdateURL must be set\")\n\t}\n\tif config.ClientID == \"\" {\n\t\treturn nil, errors.New(\"ClientID must be set\")\n\t}\n\t// Paths exist?\n\tfileInfo, err := os.Stat(config.InstallsDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !fileInfo.IsDir() {\n\t\treturn nil, errors.New(\"InstallDir must be a directory\")\n\t}\n\tfileInfo, err = os.Stat(config.WorkingDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !fileInfo.IsDir() {\n\t\treturn nil, errors.New(\"InstallDir must be a directory\")\n\t}\n\t// All ok\n\tupdater := Updater{\n\t\tconfig: config,\n\t}\n\terr = updater.updateVersionMap()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to update version map: %s\", err.Error())\n\t}\n\treturn &updater, nil\n}", "func NewUpdater(\n\tdbStore DBStore,\n\tlocker Locker,\n\tgitserverClient GitserverClient,\n\tmaxAgeForNonStaleBranches time.Duration,\n\tmaxAgeForNonStaleTags time.Duration,\n\tinterval time.Duration,\n\tobservationContext *observation.Context,\n) goroutine.BackgroundRoutine {\n\treturn goroutine.NewPeriodicGoroutine(context.Background(), interval, &Updater{\n\t\tdbStore: dbStore,\n\t\tlocker: locker,\n\t\tgitserverClient: gitserverClient,\n\t\tmaxAgeForNonStaleBranches: maxAgeForNonStaleBranches,\n\t\tmaxAgeForNonStaleTags: maxAgeForNonStaleTags,\n\t\toperations: newOperations(dbStore, observationContext),\n\t})\n}", "func (b *bookie) newFeed(u *BookUpdate) *bookFeed {\n\tb.timerMtx.Lock()\n\tif b.closeTimer != nil {\n\t\t// If Stop returns true, the timer did not fire. If false, the timer\n\t\t// already fired and the close func was called. The caller of feed()\n\t\t// must be OK with that, or the close func must be able to detect when\n\t\t// new feeds exist and abort. To solve the race, the caller of feed()\n\t\t// must synchronize with the close func. e.g. Sync locks bookMtx before\n\t\t// creating new feeds, and StopBook locks bookMtx to check for feeds\n\t\t// before unsubscribing.\n\t\tb.closeTimer.Stop()\n\t\tb.closeTimer = nil\n\t}\n\tb.timerMtx.Unlock()\n\tfeed := &bookFeed{\n\t\tc: make(chan *BookUpdate, 256),\n\t\tbookie: b,\n\t\tid: atomic.AddUint32(&feederID, 1),\n\t}\n\tfeed.c <- u\n\tb.feedsMtx.Lock()\n\tb.feeds[feed.id] = feed\n\tb.feedsMtx.Unlock()\n\treturn feed\n}", "func NewUpdater(currentVersion, githubOwner, githubRepo, filePrefix string) *Updater {\n\treturn &Updater{\n\t\tCurrentVersion: currentVersion,\n\t\tGithubOwner: githubOwner,\n\t\tGithubRepo: githubRepo,\n\t\tFilePrefix: filePrefix,\n\t}\n}", "func (u Updates) construct() UpdatesClass { return &u }", "func newFirmwareUpdater(store storage.DataStore, coapServer *apn.RxTxReceiver, config Parameters) *fwUpdater {\n\tret := &fwUpdater{\n\t\tcheckChan: make(chan checkData),\n\t\tconfig: config,\n\t\tstore: store,\n\t\tmutex: &sync.Mutex{},\n\t\tcoapServer: coapServer,\n\t\tinProgress: make(map[int64]bool),\n\t}\n\tgo ret.checkLoop()\n\treturn ret\n}", "func (feed *NewsLetterFeed) Update(entries []FeedEntry) error {\n\tfeed.Entries = entries\n\n\tfeed.Updated = time.Now().Format(time.RFC1123Z)\n\n\tfeedFilePath := \"./data/feeds/\" + feed.ID + \".xml\"\n\n\tfeedFile, err := os.OpenFile(feedFilePath, os.O_WRONLY|os.O_CREATE, 0755)\n\tdefer feedFile.Close()\n\tif err != nil {\n\t\tlog.Printf(\"failed to open feed file to write: %v\", err)\n\t\treturn err\n\t}\n\n\terr = feedTmpl.Execute(feedFile, feed)\n\tif err != nil {\n\t\tlog.Printf(\"failed to execute feed template: %v\", err)\n\t\treturn err\n\t}\n\n\tlog.Printf(\"updated feed with %d entries\", len(entries))\n\treturn nil\n}", "func (f *Feed) Update() error {\n\n\t// Check that we don't update too often.\n\tif f.Refresh.After(time.Now()) {\n\t\treturn nil\n\t}\n\n\tif f.UpdateURL == \"\" {\n\t\treturn errors.New(\"Error: feed has no URL.\")\n\t}\n\n\tupdate, err := Fetch(f.UpdateURL, f.Seen)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf.Refresh = update.Refresh\n\tf.Title = update.Title\n\tf.Description = update.Description\n\n\treturn nil\n}", "func NewUpdateChecker(policeDataCollector DataCollector, lastUpdated DataCollector) (checker Checker) {\n\tchecker = &UpdateChecker{\n\t\tpoliceDateCollector: policeDataCollector,\n\t\tlastUpdatedDateCollector: lastUpdated,\n\t}\n\treturn\n}", "func NewUpdater(output interface{}) (*Updater, error) {\n\tif output == nil {\n\t\treturn nil, ErrNilPtr\n\t}\n\n\tif reflect.TypeOf(output).Kind() != reflect.Ptr {\n\t\treturn nil, ErrNonStructPtr\n\t}\n\n\tptr := reflect.ValueOf(output).Elem()\n\tif ptr.Type().Kind() != reflect.Struct {\n\t\treturn nil, ErrNonStructPtr\n\t}\n\n\treturn &Updater{\n\t\toutput: output,\n\t\tFindFieldByName: findFieldByInsensitiveName,\n\t\tShouldSkipField: shouldSkipFieldImpl,\n\t}, nil\n}", "func New(opts Options) (*Updater, error) {\n\terr := opts.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tver, err := version.NewVersion(opts.Version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tu := &Updater{\n\t\topts: opts,\n\t\tpkg: &updater.Updater{\n\t\t\tProvider: &provider.Github{\n\t\t\t\tRepositoryURL: opts.GithubURL,\n\t\t\t},\n\t\t\tVersion: opts.Version,\n\t\t},\n\t\tversion: ver,\n\t}\n\n\treturn u, nil\n}", "func newWatcher(loader *Loader, uri string, interval time.Duration, onStop func()) *watcher {\n\treturn &watcher{\n\t\tstate: isCreated,\n\t\tupdatedAt: 0,\n\t\tloader: loader,\n\t\turi: uri,\n\t\tupdates: make(chan Update, 1),\n\t\tinterval: interval,\n\t\tonStop: onStop,\n\t}\n}", "func NewUpdaterFor(target string) (Updater, error) {\n\tupdateInfoString, err := util.ReadUpdateInfo(target)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewUpdateForUpdateString(updateInfoString, target)\n}", "func New(store *storage.Store, interval int) {\n\tlog.Info().Int(\"interval\", interval).Msg(\"Starting the scheduler\")\n\n\tgo func() {\n\t\tticker := time.NewTicker(time.Minute * time.Duration(interval))\n\n\t\tfor range ticker.C {\n\t\t\tgo func() {\n\t\t\t\tnotRefreshedSince := time.Now().Add(-1 * time.Hour)\n\n\t\t\t\tfeeds, totalCount := store.FeedList(context.TODO(), &storage.FeedListOptions{\n\t\t\t\t\tNotRefreshedSince: notRefreshedSince,\n\t\t\t\t\tLimit: 100,\n\t\t\t\t})\n\n\t\t\t\tlog.Info().Int(\"feeds\", totalCount).Time(\"not_refreshed_since\", notRefreshedSince).Msg(\"Unfresh feeds found\")\n\n\t\t\t\tfor _, feed := range *feeds {\n\t\t\t\t\tif err := store.FeedRefresh(context.TODO(), feed); err != nil {\n\t\t\t\t\t\tlog.Warn().Err(err).Str(\"feed_title\", feed.Title).Msg(\"Error refreshing feed\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t}()\n}", "func (b Bot) NewUpdateChan() Updates {\n\tu := botAPI.NewUpdate(0)\n\tu.Timeout = 60\n\tch, err := b.bot.GetUpdatesChan(u)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn Updates{ch: ch, bot: b}\n}", "func NewRealUpdater(k8sGardenClient kubernetes.Interface, projectLister gardencorelisters.ProjectLister) UpdaterInterface {\n\treturn &realUpdater{k8sGardenClient, projectLister}\n}", "func build_feeds(ps []Post, conf Configuration, name string) {\n\tnow := time.Now()\n\tfeed := &feeds.Feed{\n\t\tTitle: conf.Title,\n\t\tLink: &feeds.Link{Href: conf.URL},\n\t\tDescription: conf.Description,\n\t\tAuthor: &feeds.Author{conf.Author, conf.Email},\n\t\tCreated: now.UTC(),\n\t}\n\titems := make([]*feeds.Item, 0)\n\tvar item *feeds.Item\n\tfor i := range ps {\n\t\tpost := ps[i]\n\t\tif post.Changed {\n\t\t\titem = &feeds.Item{\n\t\t\t\tTitle: post.Title,\n\t\t\t\tDescription: string(post.Body),\n\t\t\t\tCreated: post.Date.UTC(),\n\t\t\t\tUpdated: now.UTC(),\n\t\t\t\tAuthor: &feeds.Author{post.Author, conf.Email},\n\t\t\t\tLink: &feeds.Link{Href: post.Url},\n\t\t\t}\n\n\t\t} else { // Post not changed, so keeping same old date.\n\t\t\titem = &feeds.Item{\n\t\t\t\tTitle: post.Title,\n\t\t\t\tDescription: string(post.Body),\n\t\t\t\tCreated: post.Date.UTC(),\n\t\t\t\tUpdated: post.Date.UTC(),\n\t\t\t\tAuthor: &feeds.Author{post.Author, conf.Email},\n\t\t\t\tLink: &feeds.Link{Href: post.Url},\n\t\t\t}\n\t\t}\n\t\titems = append(items, item)\n\t}\n\n\tfeed.Items = items\n\trss, err := feed.ToRss()\n\tatom, err := feed.ToAtom()\n\tif err != nil {\n\t\tfmt.Println(\"Error building feeds: \", err)\n\t} else {\n\t\tif name == \"cmain\" {\n\t\t\tf, _ := os.Create(\"./output/rss.xml\")\n\t\t\tdefer f.Close()\n\t\t\tio.WriteString(f, rss)\n\t\t\tf2, _ := os.Create(\"./output/atom.xml\")\n\t\t\tdefer f2.Close()\n\t\t\tio.WriteString(f2, atom)\n\t\t} else {\n\t\t\tf, _ := os.Create(\"./output/categories/\" + name + \".xml\")\n\t\t\tdefer f.Close()\n\t\t\tio.WriteString(f, rss)\n\t\t}\n\t}\n\n}", "func (u *Updater) updateFeed(ctx context.Context, feedConfig *config.Feed) error {\n\tinfo, err := builder.ParseURL(feedConfig.URL)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to parse URL: %s\", feedConfig.URL)\n\t}\n\n\tkeyProvider, ok := u.keys[info.Provider]\n\tif !ok {\n\t\treturn errors.Errorf(\"key provider %q not loaded\", info.Provider)\n\t}\n\n\t// Create an updater for this feed type\n\tprovider, err := builder.New(ctx, info.Provider, keyProvider.Get())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Query API to get episodes\n\tlog.Debug(\"building feed\")\n\tresult, err := provider.Build(ctx, feedConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Debugf(\"received %d episode(s) for %q\", len(result.Episodes), result.Title)\n\n\tepisodeSet := make(map[string]struct{})\n\tif err := u.db.WalkEpisodes(ctx, feedConfig.ID, func(episode *model.Episode) error {\n\t\tif episode.Status != model.EpisodeDownloaded && episode.Status != model.EpisodeCleaned {\n\t\t\tepisodeSet[episode.ID] = struct{}{}\n\t\t}\n\t\treturn nil\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tif err := u.db.AddFeed(ctx, feedConfig.ID, result); err != nil {\n\t\treturn err\n\t}\n\n\tfor _, episode := range result.Episodes {\n\t\tdelete(episodeSet, episode.ID)\n\t}\n\n\t// removing episodes that are no longer available in the feed and not downloaded or cleaned\n\tfor id := range episodeSet {\n\t\tlog.Infof(\"removing episode %q\", id)\n\t\terr := u.db.DeleteEpisode(feedConfig.ID, id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tlog.Debug(\"successfully saved updates to storage\")\n\treturn nil\n}", "func (u UpdateShortMessage) construct() UpdatesClass { return &u }", "func updater(ticker *time.Ticker) {\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tprintln(\"Updating feeds\")\n\t\t\tlock.Lock()\n\t\t\tfor _, folder := range folders {\n\t\t\t\tfor _, source := range folder {\n\t\t\t\t\tnow := time.Now()\n\t\t\t\t\tfmt.Printf(\"Updating feed %s at %s\\n\", source.Title, source.Url)\n\t\t\t\t\tresp, err := http.Get(source.Url)\n\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Printf(\"Error: %s\\n\", err.Error())\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tdefer resp.Body.Close()\n\t\t\t\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Printf(\"Error: %s\\n\", err.Error())\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tnewSource, err := readAtom(now, source.Url, body)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tnewSource, err = readRss(now, source.Url, body)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Printf(\"Could not parse as atom or RSS... skipping\\n\")\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tupdateSource(source, newSource)\n\t\t\t\t}\n\t\t\t}\n\t\t\tdirty = true\n\t\t\tlock.Unlock()\n\t\t}\n\t}\n}", "func newWriteModeUpdate(rev string) *writeModeUpdate {\n\treturn &writeModeUpdate{\n\t\tTag: \"update\",\n\t\tRev: rev,\n\t}\n}", "func newDataUpdateTracker() *dataUpdateTracker {\n\td := &dataUpdateTracker{\n\t\tCurrent: dataUpdateFilter{\n\t\t\tidx: 1,\n\t\t},\n\t\tdebug: serverDebugLog,\n\t\tinput: make(chan string, dataUpdateTrackerQueueSize),\n\t\tsave: make(chan struct{}, 1),\n\t\tsaveExited: make(chan struct{}),\n\t}\n\td.Current.bf = d.newBloomFilter()\n\td.dirty = true\n\treturn d\n}", "func NewUpdateFeedContext(ctx context.Context, r *http.Request, service *goa.Service) (*UpdateFeedContext, error) {\n\tvar err error\n\tresp := goa.ContextResponse(ctx)\n\tresp.Service = service\n\treq := goa.ContextRequest(ctx)\n\treq.Request = r\n\trctx := UpdateFeedContext{Context: ctx, ResponseData: resp, RequestData: req}\n\tparamID := req.Params[\"id\"]\n\tif len(paramID) > 0 {\n\t\trawID := paramID[0]\n\t\trctx.ID = rawID\n\t}\n\tparamTags := req.Params[\"tags\"]\n\tif len(paramTags) > 0 {\n\t\trawTags := paramTags[0]\n\t\trctx.Tags = &rawTags\n\t}\n\tparamTitle := req.Params[\"title\"]\n\tif len(paramTitle) > 0 {\n\t\trawTitle := paramTitle[0]\n\t\trctx.Title = &rawTitle\n\t}\n\treturn &rctx, err\n}", "func (c *cookRun) newBuildUpdater() (*buildUpdater, error) {\n\thttpClient, err := c.systemAuth.Authenticator().Client()\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to create a system-auth HTTP client for updating build state on the server\").Err()\n\t}\n\treturn &buildUpdater{\n\t\tannAddr: &c.AnnotationURL,\n\t\tbuildID: c.BuildbucketBuildID,\n\t\tbuildToken: c.buildSecrets.BuildToken,\n\t\tclient: buildbucketpb.NewBuildsPRPCClient(&prpc.Client{\n\t\t\tHost: c.BuildbucketHostname,\n\t\t\tC: httpClient,\n\t\t}),\n\t\tannotations: make(chan []byte),\n\t}, nil\n}", "func (u UpdatesCombined) construct() UpdatesClass { return &u }", "func (s *Service) update(entry ytfeed.Entry, file string, fi FeedInfo) ytfeed.Entry {\n\tentry.File = file\n\n\t// only reset time if published not too long ago\n\t// this is done to avoid initial set of entries added with a new channel to the top of the feed\n\tif time.Since(entry.Published) < time.Hour*24 {\n\t\tlog.Printf(\"[DEBUG] reset published time for %s, from %s to %s (%v), %s\",\n\t\t\tentry.VideoID, entry.Published.Format(time.RFC3339), time.Now().Format(time.RFC3339),\n\t\t\ttime.Since(entry.Published), entry.String())\n\t\tentry.Published = time.Now() // reset published ts to prevent possible out-of-order entries\n\t} else {\n\t\tlog.Printf(\"[DEBUG] keep published time for %s, %s\", entry.VideoID, entry.Published.Format(time.RFC3339))\n\t}\n\n\tif !strings.Contains(entry.Title, fi.Name) { // if title doesn't contains channel name add it\n\t\tentry.Title = fi.Name + \": \" + entry.Title\n\t}\n\n\tentry.Duration = s.DurationService.File(file)\n\tlog.Printf(\"[DEBUG] updated entry: %s\", entry.String())\n\treturn entry\n}", "func Listener() {\n\tfor {\n\t\tfor p, _ := range Config.Feeds {\n\t\t\t//fmt.Print(\"Updating feed: \", Config.Feeds[p].Feed.Title, \"\\n\")\n\t\t\t// maybe only do at init step?\n\t\t\tstr := Config.Feeds[p].Feed.UpdateURL\n\t\t\tfeed, err := rss.Fetch(str)\n\t\t\tif feed != nil {\n\t\t\t\tConfig.Feeds[p].Feed = *feed\n\t\t\t} else {\n\t\t\t\t//fmt.Println(\"Got a nil pointer for feed in commits for \", str, \" as \", err)\n\t\t\t}\n\t\t\t//err := Config.Feeds[p].Feed.Update()\n\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Error in updating RSS feed, see: x/mux/commits.go\")\n\t\t\t\tfmt.Printf(\"%s\\n\\n\", err)\n\t\t\t} else {\n\t\t\t\tadditem := true\n\t\t\t\tfor j, _ := range Config.Feeds[p].Recent {\n\t\t\t\t\tif Config.Feeds[p].Recent[j] == Config.Feeds[p].Feed.Items[0].Title {\n\t\t\t\t\t\t//fmt.Println(\"Checking Recent \", j, \" against \", Config.Feeds[p].Feed.Items[0].Title)\n\t\t\t\t\t\tadditem = false\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif additem {\n\t\t\t\t\t// x y z → x y z 0 → y z 0\n\t\t\t\t\tfmt.Println(\"Updating: \", Config.Feeds[p].Feed.Title)\n\t\t\t\t\tConfig.Feeds[p].Recent = append(Config.Feeds[p].Recent, Config.Feeds[p].Feed.Items[0].Title)\n\t\t\t\t\tConfig.Feeds[p].Recent = Config.Feeds[p].Recent[1:]\n\t\t\t\t\tNotify(p)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\ttime.Sleep(2 * time.Minute)\n\t\t}\n\t\ttime.Sleep(10 * time.Minute)\n\t\t// Dump config to file regularly\n\t\t//fmt.Println(\"\", dump())\n\t}\n}", "func NewUpdateAction(log *zap.Logger, client *local.Client, cfg UpdateConfig) Action {\n\treturn &Update{\n\t\tlog: log,\n\t\tclient: client,\n\t\tcfg: cfg,\n\t}\n}", "func (f Feeds) New(url string) error {\n\tfeed, err := gofeed.NewParser().ParseURL(url)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"gofeed parse %v\", err)\n\t}\n\tf[url] = NewFeed(feed.Title)\n\treturn nil\n}", "func NewDefaultUpdateChecker() (checker Checker) {\n\tpoliceDataCollector := NewHttpDataCollector(dateCheckEndpoint)\n\tlastUpdated := NewDefaultS3DataCollector()\n\tchecker = &UpdateChecker{\n\t\tpoliceDateCollector: policeDataCollector,\n\t\tlastUpdatedDateCollector: lastUpdated,\n\t}\n\treturn\n}", "func New(cachetimeout time.Duration, ih ItemHandler, database Database) *Feed {\n\tv := new(Feed)\n\tv.cacheTimeout = cachetimeout\n\tv.format = \"none\"\n\tv.known = database\n\tv.itemhandler = ih\n\treturn v\n}", "func New(hostedZoneID string, lbAdapter adapter.FrontendAdapter, retries int) controller.Updater {\n\tinitMetrics()\n\n\treturn &updater{\n\t\tr53: r53.New(hostedZoneID, retries),\n\t\tlbAdapter: lbAdapter,\n\t\tschemeToFrontendMap: make(map[string]adapter.DNSDetails),\n\t}\n}", "func (u UpdateShort) construct() UpdatesClass { return &u }", "func NewUpdateReader(in io.Reader) *updateReader {\n\treturn &updateReader{Reader: in, buffer: bufio.NewReader(in)}\n}", "func NewFeed(title string, subtitle string, id string,\n\trights string, website string, feedurl string) *Feed {\n\tf := Feed{\n\t\tTitle: title,\n\t\tSubtitle: subtitle,\n\t\tUpdated: time.Now(),\n\t\tID: id,\n\t\tLinks: []Link{{\n\t\t\tRel: \"alternate\",\n\t\t\tType: \"text/html\",\n\t\t\tHref: website,\n\t\t}, {\n\t\t\tRel: \"self\",\n\t\t\tType: \"application/atom+xml\",\n\t\t\tHref: feedurl,\n\t\t}},\n\t\tRights: rights,\n\t}\n\n\tf.Generator = g\n\tf.XMLNS = xmlns\n\n\treturn &f\n}", "func New(datastore Datastore, restricter RestrictMiddleware, closed <-chan struct{}) *Autoupdate {\n\ta := &Autoupdate{\n\t\tdatastore: datastore,\n\t\ttopic: topic.New(topic.WithClosed(closed)),\n\t\trestricter: restricter,\n\t}\n\n\t// Update the topic when an data update is received.\n\ta.datastore.RegisterChangeListener(func(data map[string][]byte) error {\n\t\tkeys := make([]string, 0, len(data))\n\t\tfor k := range data {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\n\t\ta.topic.Publish(keys...)\n\t\treturn nil\n\t})\n\n\treturn a\n}", "func New() feed.Feeder {\n\treturn &FileFeed{}\n}", "func NewBugUpdater(project string, mgrs map[string]BugManager, ac AnalysisClient, projectCfg *compiledcfg.ProjectConfig) *BugUpdater {\n\treturn &BugUpdater{\n\t\tproject: project,\n\t\tmanagers: mgrs,\n\t\tanalysisClient: ac,\n\t\tprojectCfg: projectCfg,\n\t\tMaxBugsFiledPerRun: 1, // Default value.\n\t}\n}", "func (p *Projector) NewFeed(topic string, request *protobuf.MutationStreamRequest) (*Feed, error) {\n\trespch := make(chan []interface{}, 1)\n\tcmd := []interface{}{pCmdNewFeed, topic, request, respch}\n\tresp, err := c.FailsafeOp(p.reqch, respch, cmd, p.finch)\n\tif err = c.OpError(err, resp, 1); err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp[0].(*Feed), nil\n}", "func New(url string) (data.Feed, error) {\n\tlog.Info().Str(\"url\", url).Msg(\"using rss feed\")\n\n\thttpClient, err := httpclient.New(httpclient.RSSPolicy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &feed{\n\t\tURL: url,\n\t\tHTTPClient: httpClient,\n\t}, nil\n}", "func NewProviderUpdater(name string, version string) (Updater, error) {\n\tif len(name) == 0 {\n\t\treturn nil, errors.Errorf(\"failed to new provider updater. name is required.\")\n\t}\n\n\tif len(version) == 0 {\n\t\treturn nil, errors.Errorf(\"failed to new provider updater. version is required.\")\n\t}\n\n\treturn &ProviderUpdater{\n\t\tname: name,\n\t\tversion: version,\n\t}, nil\n}", "func newFeedMutation(c config, op Op, opts ...feedOption) *FeedMutation {\n\tm := &FeedMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeFeed,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}", "func NewFeed(id int64, fileData file.Data) (*Feed, error) {\n\tvar db *sql.DB\n\tvar err error\n\tif id != -1 {\n\t\t//Initialize database\n\t\tdb, err = Init(TestDB, false)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\t//Parse the feed\n\tfp := gofeed.NewParser()\n\tdata, err := fp.ParseURL(fileData.URL)\n\tif err != nil {\n\t\treturn &Feed{ID: id, URL: fileData.URL, Tags: fileData.Tags, Data: data}, fmt.Errorf(\"Error occured while trying to parse feed\")\n\t}\n\n\t//Initalize a feed\n\tfeed := &Feed{ID: id, URL: fileData.URL, Tags: fileData.Tags, Data: data}\n\n\tif id != -1 {\n\n\t\t//get raw data for feed\n\t\trawData, err := GetFeedDataFromSite(feed.URL)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\t//Add the feed data to the database\n\t\terr = UpdateFeedRawData(db, feed.ID, rawData)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\terr = UpdateFeedTitle(db, feed.ID, feed.Title)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\treturn feed, nil\n}", "func (c *InstallerConfig) Updater(repo *packages.Repository, updatePackageURL string) (updater.Updater, error) {\n\tswitch c.installerMode {\n\tcase Omaha:\n\t\tavbTool, err := c.AVBTool()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tzbiTool, err := c.ZBITool()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn updater.NewOmahaUpdater(repo, updatePackageURL, c.omahaServer, avbTool, zbiTool)\n\n\tcase SystemUpdateChecker:\n\t\t// TODO: The e2e tests only support using the system-update-checker\n\t\t// with the standard update package URL. Otherwise we need to\n\t\t// fall back to manually triggering the system-updater.\n\t\tif updatePackageURL == defaultUpdatePackageURL {\n\t\t\treturn updater.NewSystemUpdateChecker(repo), nil\n\t\t}\n\n\t\treturn updater.NewSystemUpdater(repo, updatePackageURL), nil\n\n\tdefault:\n\t\treturn nil, errors.New(\"Invalid installer mode\")\n\t}\n}", "func (u UpdateShortSentMessage) construct() UpdatesClass { return &u }", "func NewUpdateCommand(parent cmd.Registerer, globals *config.Data, data manifest.Data) *UpdateCommand {\n\tvar c UpdateCommand\n\tc.Globals = globals\n\tc.manifest = data\n\tc.CmdClause = parent.Command(\"update\", \"Update or insert an item on a Fastly edge dictionary\")\n\tc.RegisterServiceIDFlag(&c.manifest.Flag.ServiceID)\n\tc.CmdClause.Flag(\"dictionary-id\", \"Dictionary ID\").Required().StringVar(&c.Input.DictionaryID)\n\tc.CmdClause.Flag(\"key\", \"Dictionary item key\").Required().StringVar(&c.Input.ItemKey)\n\tc.CmdClause.Flag(\"value\", \"Dictionary item value\").Required().StringVar(&c.Input.ItemValue)\n\treturn &c\n}", "func newDispatcherUpdateTest(name string, options ...controllertesting.DeploymentOption) TableRow {\n\ttest := newDispatcherBasicTest(\"Existing Dispatcher Deployment, \" + name + \", Update Needed\")\n\ttest.Objects = append(test.Objects,\n\t\tcontrollertesting.NewKafkaChannelDispatcherService(),\n\t\tcontrollertesting.NewKafkaChannelDispatcherDeployment(options...))\n\ttest.WantUpdates = append(test.WantUpdates,\n\t\tcontrollertesting.NewDeploymentUpdateActionImpl(controllertesting.NewKafkaChannelDispatcherDeployment()))\n\ttest.WantEvents = append([]string{controllertesting.NewKafkaChannelDispatcherDeploymentUpdatedEvent()},\n\t\ttest.WantEvents...)\n\treturn test\n}", "func NewUpdateBuilder() *UpdateBuilder {\n\treturn DefaultFlavor.NewUpdateBuilder()\n}", "func NewUpdate(zone string, class uint16) *Msg {\n\tu := new(Msg)\n\tu.MsgHdr.Response = false\n\tu.MsgHdr.Opcode = OpcodeUpdate\n\tu.Compress = false // Seems BIND9 at least cannot handle compressed update pkgs\n\tu.Question = make([]Question, 1)\n\tu.Question[0] = Question{zone, TypeSOA, class}\n\treturn u\n}", "func NewUpdateCommand(parent cmd.Registerer, g *global.Data, m manifest.Data) *UpdateCommand {\n\tc := UpdateCommand{\n\t\tBase: cmd.Base{\n\t\t\tGlobals: g,\n\t\t},\n\t\tmanifest: m,\n\t}\n\tc.CmdClause = parent.Command(\"update\", \"Update a Fastly service version\")\n\tc.RegisterFlag(cmd.StringFlagOpts{\n\t\tName: cmd.FlagServiceIDName,\n\t\tDescription: cmd.FlagServiceIDDesc,\n\t\tDst: &c.manifest.Flag.ServiceID,\n\t\tShort: 's',\n\t})\n\tc.RegisterFlag(cmd.StringFlagOpts{\n\t\tAction: c.serviceName.Set,\n\t\tName: cmd.FlagServiceName,\n\t\tDescription: cmd.FlagServiceDesc,\n\t\tDst: &c.serviceName.Value,\n\t})\n\tc.RegisterFlag(cmd.StringFlagOpts{\n\t\tName: cmd.FlagVersionName,\n\t\tDescription: cmd.FlagVersionDesc,\n\t\tDst: &c.serviceVersion.Value,\n\t\tRequired: true,\n\t})\n\tc.RegisterAutoCloneFlag(cmd.AutoCloneFlagOpts{\n\t\tAction: c.autoClone.Set,\n\t\tDst: &c.autoClone.Value,\n\t})\n\n\t// TODO(integralist):\n\t// Make 'comment' field mandatory once we roll out a new release of Go-Fastly\n\t// which will hopefully have better/more correct consistency as far as which\n\t// fields are supposed to be optional and which should be 'required'.\n\t//\n\tc.CmdClause.Flag(\"comment\", \"Human-readable comment\").Action(c.comment.Set).StringVar(&c.comment.Value)\n\treturn &c\n}", "func NewUpdateHandler(providers *Providers) *UpdateHandler {\n\tlogger.Info(\"Creating new cache update updateHandler\")\n\n\th := &UpdateHandler{\n\t\tProviders: providers,\n\t}\n\n\th.cacheUpdaters = gcache.New(0).LoaderFunc(func(channelID interface{}) (interface{}, error) {\n\t\treturn h.createCacheUpdater(channelID.(string)), nil\n\t}).Build()\n\n\tif roles.IsCommitter() {\n\t\tlogger.Info(\"Registering cache updates request handler\")\n\n\t\tif err := h.HandlerRegistry.Register(cacheUpdatesDataType, h.handleCacheUpdatesRequest); err != nil {\n\t\t\t// Should never happen\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tupdateHandler = h\n\n\treturn h\n}", "func (u UpdatesTooLong) construct() UpdatesClass { return &u }", "func initializeUpdater(w http.ResponseWriter, r *http.Request) {\n\tvar component string\n\terr := json.NewDecoder(r.Body).Decode(&component)\n\tif err != nil {\n\t\tsendResponse(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\tlog.Printf(\"Initializing updater with component: %s\\n\", component)\n\tswitch component {\n\tcase \"redis\":\n\t\tupdater = &RedisUpdater{}\n\t\terr := updater.Init()\n\t\tif err != nil {\n\t\t\tsendResponse(w, http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\tdefault:\n\t\tsendResponse(w, http.StatusBadRequest, \"Invalid component:\"+component+\".Allowed values are 'redis'\")\n\t\treturn\n\t}\n\tsendResponse(w, http.StatusOK, \"OK\")\n}", "func (s *FeedService) updateFeedFromURL(f *db.FeedSource) (int, error) {\n\tfp := gofeed.NewParser()\n\tfp.Client = s.httpClient\n\tgf, err := fp.ParseURL(f.UrlSource)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tlastUpdated := f.LastChecked\n\tvar updatedItemCount int\n\tfor _, i := range gf.Items {\n\t\tif i.PublishedParsed != nil {\n\t\t\tif i.PublishedParsed.Before(lastUpdated) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else if i.UpdatedParsed != nil {\n\t\t\tif i.UpdatedParsed.Before(lastUpdated) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else {\n\t\t\tfound, err := s.findFeedItemByGUID(f.Id, i.GUID)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"skipping because cannot find feed by guid to check for duplicate: %v \", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif found {\n\t\t\t\t// assume items are sorted reverse chronological order. When we find one item, we have should have the rest of the items.\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ti.Published = time.Now().Format(time.RFC3339)\n\t\t\ti.Updated = i.Published\n\t\t}\n\t\tfixFeedItem(i)\n\t\terr := s.dbClient.AddNews(f.Id, db.ToFeedItem(f.Id, i))\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tupdatedItemCount++\n\t}\n\tfmt.Printf(\"Updated feed ID %d - %d items added.\\n\", f.Id, updatedItemCount)\n\tf.LastChecked = time.Now()\n\ts.dbClient.UpdateFeedSource(f)\n\treturn updatedItemCount, err\n}", "func RefreshRSSCron(c *cron.Cron, db *storm.DB, tclient *torrent.Client, torrentLocalStorage Storage.TorrentLocal, dataDir string) {\n\tc.AddFunc(\"@hourly\", func() {\n\t\ttorrentHashHistory := Storage.FetchHashHistory(db)\n\t\tRSSFeedStore := Storage.FetchRSSFeeds(db)\n\t\tsingleRSSTorrent := Storage.SingleRSSTorrent{}\n\t\tnewFeedStore := Storage.RSSFeedStore{ID: RSSFeedStore.ID} //creating a new feed store just using old one to parse for new torrents\n\t\tfp := gofeed.NewParser()\n\t\tfor _, singleFeed := range RSSFeedStore.RSSFeeds {\n\t\t\tfeed, err := fp.ParseURL(singleFeed.URL)\n\t\t\tif err != nil {\n\t\t\t\tLogger.WithFields(logrus.Fields{\"err\": err, \"url\": singleFeed.URL}).Error(\"Failed to parse RSS URL\")\n\t\t\t}\n\t\t\tfor _, RSSTorrent := range feed.Items {\n\t\t\t\tLogger.WithFields(logrus.Fields{\"Torrent\": RSSTorrent.Title}).Info(\"Found new torrent\")\n\t\t\t\tsingleRSSTorrent.Link = RSSTorrent.Link\n\t\t\t\tsingleRSSTorrent.Title = RSSTorrent.Title\n\t\t\t\tsingleRSSTorrent.PubDate = RSSTorrent.Published\n\t\t\t\tfor _, hash := range torrentHashHistory.HashList {\n\t\t\t\t\tlinkHash := singleRSSTorrent.Link[20:60] //cutting the infohash out of the link\n\t\t\t\t\tif linkHash == hash {\n\t\t\t\t\t\tLogger.WithFields(logrus.Fields{\"Torrent\": RSSTorrent.Title}).Warn(\"Torrent already added for this RSS item, skipping torrent\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tclientTorrent, err := tclient.AddMagnet(RSSTorrent.Link)\n\t\t\t\tif err != nil {\n\t\t\t\t\tLogger.WithFields(logrus.Fields{\"err\": err, \"Torrent\": RSSTorrent.Title}).Warn(\"Unable to add torrent to torrent client!\")\n\t\t\t\t\tbreak //break out of the loop entirely for this message since we hit an error\n\t\t\t\t}\n\t\t\t\tStartTorrent(clientTorrent, torrentLocalStorage, db, dataDir, \"magnet\", \"\", dataDir) //TODO let user specify torrent default storage location and let change on fly\n\t\t\t\tsingleFeed.Torrents = append(singleFeed.Torrents, singleRSSTorrent)\n\n\t\t\t}\n\t\t\tnewFeedStore.RSSFeeds = append(newFeedStore.RSSFeeds, singleFeed)\n\t\t}\n\t\tStorage.UpdateRSSFeeds(db, newFeedStore) //Calling this to fully update storage will all rss feeds\n\t})\n\n}", "func NewVersionUpdater(g *gsloader.GSLoader, syncer *syncer.FuzzSyncer) *VersionUpdater {\n\treturn &VersionUpdater{\n\t\tgsLoader: g,\n\t\tsyncer: syncer,\n\t}\n}", "func newUpdateConsumer(t *testing.T) (*Consumer, chan Event) {\n\tc := make(chan Event, 2048)\n\tac := NewConsumer(t.Name(), c, ConsumerUpdate)\n\trequire.NoError(t, acctProbe.RegisterConsumer(ac))\n\n\treturn ac, c\n}", "func newApplyManager(rf *Raft) *applyManager {\n\treturn &applyManager{rf: rf, indexChange: make(chan struct{}, 1)}\n}", "func updateRiver(name string, newUpdate *UpdatedFeed) func(*bolt.Tx) error {\n\treturn func(tx *bolt.Tx) error {\n\t\tvar updates []*UpdatedFeed\n\n\t\t// Get the JSON out of boltdb\n\t\tb := tx.Bucket([]byte(name))\n\t\tobj := b.Get([]byte(\"river\"))\n\n\t\t// Decode the byte slice into a slice of *UpdateFeed and\n\t\t// prepend the new update\n\t\tif obj != nil {\n\t\t\tjson.Unmarshal(obj, &updates)\n\t\t\tupdates = append([]*UpdatedFeed{newUpdate}, updates...)\n\t\t} else {\n\t\t\tupdates = []*UpdatedFeed{newUpdate}\n\t\t}\n\n\t\t// Trim the update slice down to size\n\t\tif len(updates) > maxFeedUpdates {\n\t\t\tupdates = updates[:maxFeedUpdates]\n\t\t}\n\n\t\t// Encode the new river object and update bolt with it\n\t\tupdatedRiver, err := json.Marshal(updates)\n\t\terr = b.Put([]byte(\"river\"), updatedRiver)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n}", "func NewUpdateCommand(parent cmd.Registerer, g *global.Data, m manifest.Data) *UpdateCommand {\n\tc := UpdateCommand{\n\t\tBase: cmd.Base{\n\t\t\tGlobals: g,\n\t\t},\n\t\tmanifest: m,\n\t}\n\tc.CmdClause = parent.Command(\"update\", \"Update name of dictionary on a Fastly service version\").Alias(\"get\")\n\n\t// Required.\n\tc.CmdClause.Flag(\"name\", \"Old name of Dictionary\").Short('n').Required().StringVar(&c.input.Name)\n\tc.RegisterFlag(cmd.StringFlagOpts{\n\t\tName: cmd.FlagVersionName,\n\t\tDescription: cmd.FlagVersionDesc,\n\t\tDst: &c.serviceVersion.Value,\n\t\tRequired: true,\n\t})\n\n\t// Optional.\n\tc.RegisterAutoCloneFlag(cmd.AutoCloneFlagOpts{\n\t\tAction: c.autoClone.Set,\n\t\tDst: &c.autoClone.Value,\n\t})\n\tc.CmdClause.Flag(\"new-name\", \"New name of Dictionary\").Action(c.newname.Set).StringVar(&c.newname.Value)\n\tc.RegisterFlag(cmd.StringFlagOpts{\n\t\tName: cmd.FlagServiceIDName,\n\t\tDescription: cmd.FlagServiceIDDesc,\n\t\tDst: &c.manifest.Flag.ServiceID,\n\t\tShort: 's',\n\t})\n\tc.RegisterFlag(cmd.StringFlagOpts{\n\t\tAction: c.serviceName.Set,\n\t\tName: cmd.FlagServiceName,\n\t\tDescription: cmd.FlagServiceDesc,\n\t\tDst: &c.serviceName.Value,\n\t})\n\tc.CmdClause.Flag(\"write-only\", \"Whether to mark this dictionary as write-only. Can be true or false (defaults to false)\").Action(c.writeOnly.Set).StringVar(&c.writeOnly.Value)\n\treturn &c\n}", "func newDelayedRouteUpdater(az *Cloud, interval time.Duration) *delayedRouteUpdater {\n\treturn &delayedRouteUpdater{\n\t\taz: az,\n\t\tinterval: interval,\n\t\troutesToUpdate: make([]*delayedRouteOperation, 0),\n\t}\n}", "func NewUpdateHandler(auth x.Authenticator, control Controller, checkAddr AuthCheckAddress) UpdateHandler {\n\treturn UpdateHandler{\n\t\tauth: auth,\n\t\tcontrol: control,\n\t\tauthCheckAddress: checkAddr,\n\t}\n}", "func (c *ServiceCreate) update() error {\n\tcmd := exec.Command(\"go\", \"get\", \"-u\", \"github.com/RobyFerro/go-web-framework\")\n\tcmd.Dir = c.Args\n\n\treturn cmd.Run()\n}", "func (u UpdateShortChatMessage) construct() UpdatesClass { return &u }", "func EditFetcher(id uint, url string, interval uint) {\n\tapp.Logger(nil).Info(\"URL: \", url)\n\t//fmt.Println(url)\n\tfor _, fetcher := range FetchersWork {\n\t\tif (fetcher.Id == id) {\n\t\t\tfetcher.Url = url\n\t\t\tfetcher.Interval = interval\n\t\t}\n\t}\n}", "func (d *DB) itemUpdater(catogoryID uint16) {\n\tarticles, err := FeedzillaArticles(catogoryID, NumberToGet)\n\tif err != nil {\n\t\tglog.Error(err)\n\t\treturn\n\t}\n\n\tfor _, art := range articles.List {\n\t\tart.CategoryID = catogoryID\n\t\t_, err := d.Items.Upsert(bson.M{\"url\": art.URL}, art)\n\t\tif err != nil {\n\t\t\tglog.Error(err)\n\t\t\tcontinue\n\t\t}\n\t\tglog.Infof(\"%+v\", art)\n\t}\n}", "func NewUpdateEngine(c FSMConfig) (*fsmUpdateEngine, error) {\n\tlogger := logrus.WithFields(logrus.Fields{\n\t\ttrace.Component: \"engine:update\",\n\t})\n\tengine := &fsmUpdateEngine{\n\t\tFSMConfig: c,\n\t\tFieldLogger: logger,\n\t\tuseEtcd: true,\n\t}\n\n\treturn engine, nil\n}", "func NewUpdateStats(\n\trootDir string,\n\tfilesToImport *[]string,\n\timportFilesCount int,\n\tupdatedFilesCount int,\n\tfailedFiles *[]string,\n) *UpdateStats {\n\n\ttotalCountOfFiles := len(*filesToImport)\n\tcountOfFailedFiles := len(*failedFiles)\n\n\treturn &UpdateStats{\n\t\tImportStats: ImportStats{\n\t\t\tRootDirectory: rootDir,\n\t\t\tScannedFilesCount: totalCountOfFiles,\n\t\t\tImportedFilesCount: importFilesCount,\n\t\t\tFailedFilesCount: countOfFailedFiles,\n\t\t\tFailedFiles: *failedFiles,\n\t\t},\n\t\tUpdatedFilesCount: updatedFilesCount,\n\t}\n}", "func (c *Crawler) newFetcher(height uint64) {\n\t\n\t// Stop previous fetcher\n\tif c.fetcherStop != nil {\n\t\tc.fetcherStop <- true\n\t}\n\t\n\t// Both channels to be closed by fetcher task\n\tc.fetcherStop = make(chan bool)\n\tc.fetcherBlocks = make(chan blockRecord, FetcherBlockBufferSize)\n\n\t//\n\tgo fetcher(c.rpcConfig, height, c.fetcherBlocks, c.fetcherStop)\n}", "func PollUpdater(fetch func() (Points, error), interval time.Duration) Updater {\n\treturn func(result chan Points, stop chan bool) (retErr error) {\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tif err, ok := r.(error); ok {\n\t\t\t\t\tretErr = err\n\t\t\t\t} else {\n\t\t\t\t\tretErr = errors.New(\"panic in poll updater\")\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-time.After(interval):\n\t\t\t\tpoints, err := fetch()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tresult <- points\n\t\t\tcase <-stop:\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t}\n\t}\n}", "func (p *Projector) doUpdateFeed(request *protobuf.UpdateMutationStreamRequest) ap.MessageMarshaller {\n\tvar err error\n\n\tc.Debugf(\"%v doUpdateFeed()\\n\", p.logPrefix)\n\tresponse := protobuf.NewMutationStreamResponse(request)\n\n\ttopic := request.GetTopic()\n\tbucketns := request.GetBuckets()\n\n\tfeed, err := p.GetFeed(topic) // only existing feed\n\tif err != nil {\n\t\tc.Errorf(\"%v %v\\n\", p.logPrefix, err)\n\t\tresponse.UpdateErr(err)\n\t\treturn response\n\t}\n\n\tif err = feed.UpdateFeed(request); err == nil {\n\t\t// gather latest set of timestamps for each bucket, provided request\n\t\t// is not for deleting the bucket.\n\t\tif !request.IsDelBuckets() {\n\t\t\t// we expect failoverTimestamps and kvTimestamps to be re-populated.\n\t\t\tfailTss := make([]*protobuf.TsVbuuid, 0, len(bucketns))\n\t\t\tkvTss := make([]*protobuf.TsVbuuid, 0, len(bucketns))\n\t\t\tfor _, bucketn := range bucketns {\n\t\t\t\tfailTss = append(failTss, feed.failoverTimestamps[bucketn])\n\t\t\t\tkvTss = append(kvTss, feed.kvTimestamps[bucketn])\n\t\t\t}\n\t\t\tresponse.UpdateTimestamps(failTss, kvTss)\n\t\t}\n\t} else {\n\t\tresponse.UpdateErr(err)\n\t}\n\treturn response\n}", "func NewUpdateEndpoint(s Service) goa.Endpoint {\n\treturn func(ctx context.Context, req interface{}) (interface{}, error) {\n\t\tp := req.(*UpdatePayload)\n\t\treturn nil, s.Update(ctx, p)\n\t}\n}", "func New(path string, maxAge time.Duration, updater Updater) *Cache {\n\tcache := &Cache{\n\t\tPath: path,\n\t\tMaxAge: maxAge,\n\t\tUpdateFunc: updater,\n\t}\n\treturn cache\n}", "func NewFake(calls []ViewUpdate) *FakeViewUpdater {\n\tctx, cancel := context.WithCancel(context.Background())\n\treturn &FakeViewUpdater{behavior: calls, unwanted: []ViewUpdateRequest{}, ctx: ctx, cancel: cancel}\n}", "func (f *FeedModificationRequest) Patch(feed *Feed) {\n\tif f.FeedURL != nil && *f.FeedURL != \"\" {\n\t\tfeed.FeedURL = *f.FeedURL\n\t}\n\n\tif f.SiteURL != nil && *f.SiteURL != \"\" {\n\t\tfeed.SiteURL = *f.SiteURL\n\t}\n\n\tif f.Title != nil && *f.Title != \"\" {\n\t\tfeed.Title = *f.Title\n\t}\n\n\tif f.ScraperRules != nil {\n\t\tfeed.ScraperRules = *f.ScraperRules\n\t}\n\n\tif f.RewriteRules != nil {\n\t\tfeed.RewriteRules = *f.RewriteRules\n\t}\n\n\tif f.KeeplistRules != nil {\n\t\tfeed.KeeplistRules = *f.KeeplistRules\n\t}\n\n\tif f.UrlRewriteRules != nil {\n\t\tfeed.UrlRewriteRules = *f.UrlRewriteRules\n\t}\n\n\tif f.BlocklistRules != nil {\n\t\tfeed.BlocklistRules = *f.BlocklistRules\n\t}\n\n\tif f.Crawler != nil {\n\t\tfeed.Crawler = *f.Crawler\n\t}\n\n\tif f.UserAgent != nil {\n\t\tfeed.UserAgent = *f.UserAgent\n\t}\n\n\tif f.Cookie != nil {\n\t\tfeed.Cookie = *f.Cookie\n\t}\n\n\tif f.Username != nil {\n\t\tfeed.Username = *f.Username\n\t}\n\n\tif f.Password != nil {\n\t\tfeed.Password = *f.Password\n\t}\n\n\tif f.CategoryID != nil && *f.CategoryID > 0 {\n\t\tfeed.Category.ID = *f.CategoryID\n\t}\n\n\tif f.Disabled != nil {\n\t\tfeed.Disabled = *f.Disabled\n\t}\n\n\tif f.NoMediaPlayer != nil {\n\t\tfeed.NoMediaPlayer = *f.NoMediaPlayer\n\t}\n\n\tif f.IgnoreHTTPCache != nil {\n\t\tfeed.IgnoreHTTPCache = *f.IgnoreHTTPCache\n\t}\n\n\tif f.AllowSelfSignedCertificates != nil {\n\t\tfeed.AllowSelfSignedCertificates = *f.AllowSelfSignedCertificates\n\t}\n\n\tif f.FetchViaProxy != nil {\n\t\tfeed.FetchViaProxy = *f.FetchViaProxy\n\t}\n\n\tif f.HideGlobally != nil {\n\t\tfeed.HideGlobally = *f.HideGlobally\n\t}\n}", "func NewWatcher(\n\tlister ListerService,\n\tinterval time.Duration,\n\topts ...func(*WatcherConfig),\n) *Watcher {\n\tcfg := WatcherConfig{\n\t\tLogger: zero.Logger(),\n\t}\n\tfor _, opt := range opts {\n\t\topt(&cfg)\n\t}\n\tw := &Watcher{\n\t\tlister: lister,\n\t\tstreamer: stream.NewPoller(\n\t\t\tfunc() (zero.Interface, error) {\n\t\t\t\treturn lister.ListGoRepos()\n\t\t\t},\n\t\t\tinterval,\n\t\t),\n\t\tlog: cfg.Logger,\n\t}\n\tgo w.run()\n\treturn w\n}", "func New(dir string, conn *websocket.Conn) *Watcher {\n\treturn &Watcher{\n\t\tConn: conn,\n\t\tDir: dir,\n\t}\n}", "func NewVersionUpdater(s *storage.Client, agg *aggregator.Aggregator, g []*generator.Generator) *VersionUpdater {\n\treturn &VersionUpdater{\n\t\tstorageClient: s,\n\t\taggregator: agg,\n\t\tgenerators: g,\n\t}\n}", "func NewFeed(title, mail string) *NewsLetterFeed {\n\tfeed := &NewsLetterFeed{}\n\n\tfeed.Title = title\n\tfeed.ID = slug.New(title, func(id string) bool {\n\t\tfor _, f := range AllFeeds {\n\t\t\tif f.ID == id {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t})\n\n\tfeed.URL = fmt.Sprintf(\"/feeds/%s.xml\", feed.ID)\n\tfeed.Email = mail\n\n\treturn feed\n}", "func NewInstaller(us *session.UpdateSession, uc *updatecollection.Collection) (*Installer, error) {\n\tudi, err := us.CreateInterface(session.Installer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif _, err = oleutil.PutProperty(udi, \"Updates\", uc.IUpdateCollection); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to register updates for install: \\n %v\", err)\n\t}\n\n\treturn &Installer{IUpdateInstaller: udi}, nil\n}", "func New(app *grun.App, newW func() gtk.Widgetter) *Maker {\n\tbaseID := app.ID\n\tif baseID == \"\" {\n\t\tbaseID = \"com.github.gotk4.gtkest.default\"\n\t}\n\treturn &Maker{app: app, newW: newW, baseID: baseID}\n}", "func NewUpdateHandler(processor Processor, pc protocol.Client, metrics metricsProvider) *UpdateHandler {\n\treturn &UpdateHandler{\n\t\tprocessor: processor,\n\t\tprotocol: pc,\n\t\tmetrics: metrics,\n\t}\n}", "func newManager(id int, wg *sync.WaitGroup, pr int64, cr float64, ps float64) *Manager {\n\tvar weather Weather\n\tweather.initializeWeather()\n\tweather.generateWeather()\n\tforecast, multiplier := weather.getWeather()\n\tfmt.Printf(\"\\nCURRENT FORECAST: %s\\n\", forecast)\n\n\tproductsRate = pr\n\tcustomerRate = cr * multiplier\n\tprocessSpeed = ps\n\n\tcustomerStatusChan = make(chan int, 256)\n\tcheckoutChangeStatusChan = make(chan int, 256)\n\n\t// Default to 1 Checkout when the store opens\n\tnumberOfCheckoutsOpen = 1\n\n\treturn &Manager{id: id, wg: wg}\n}", "func NewMTOServiceItemUpdater(t interface {\n\tmock.TestingT\n\tCleanup(func())\n}) *MTOServiceItemUpdater {\n\tmock := &MTOServiceItemUpdater{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewNodeUpdate(bootState BootStateType, interfaces []InterfaceType, hostname string, nodeId int32, siteId int32, administrativeState AdministrativeStateType, dnsServers []string) *NodeUpdate {\n\tthis := NodeUpdate{}\n\tthis.BootState = bootState\n\tthis.Interfaces = interfaces\n\tthis.Hostname = hostname\n\tthis.NodeId = nodeId\n\tthis.SiteId = siteId\n\tthis.AdministrativeState = administrativeState\n\tthis.DnsServers = dnsServers\n\treturn &this\n}", "func New(cfg *cfg.File, backend string, productionFlag bool) (p *FeedService, err error) {\n\tp = &FeedService{\n\t\tproductionFlag: productionFlag,\n\t\tmux: new(sync.Mutex),\n\t\tcfg: cfg,\n\t}\n\n\tp.errs = NewPE(\n\t\tp.mux,\n\t\tp.productionFlag,\n\t)\n\n\tp.backend, err = checkBackend(backend)\n\tif err != nil {\n\t\treturn p, err\n\t}\n\n\treturn p, nil\n}", "func NewUpdateCommand(parent common.Registerer, globals *config.Data) *UpdateCommand {\n\tvar c UpdateCommand\n\tc.Globals = globals\n\tc.CmdClause = parent.Command(\"update\", \"Update a backend on a Fastly service version\")\n\n\tc.CmdClause.Flag(\"service-id\", \"Service ID\").Short('s').Required().StringVar(&c.Input.Service)\n\tc.CmdClause.Flag(\"version\", \"Number of service version\").Required().IntVar(&c.Input.Version)\n\tc.CmdClause.Flag(\"name\", \"backend name\").Short('n').Required().StringVar(&c.Input.Name)\n\n\tc.CmdClause.Flag(\"new-name\", \"New backend name\").Action(c.NewName.Set).StringVar(&c.NewName.Value)\n\tc.CmdClause.Flag(\"comment\", \"A descriptive note\").Action(c.Comment.Set).StringVar(&c.Comment.Value)\n\tc.CmdClause.Flag(\"address\", \"A hostname, IPv4, or IPv6 address for the backend\").Action(c.Address.Set).StringVar(&c.Address.Value)\n\tc.CmdClause.Flag(\"port\", \"Port number of the address\").Action(c.Port.Set).UintVar(&c.Port.Value)\n\tc.CmdClause.Flag(\"override-host\", \"The hostname to override the Host header\").Action(c.OverrideHost.Set).StringVar(&c.OverrideHost.Value)\n\tc.CmdClause.Flag(\"connect-timeout\", \"How long to wait for a timeout in milliseconds\").Action(c.ConnectTimeout.Set).UintVar(&c.ConnectTimeout.Value)\n\tc.CmdClause.Flag(\"max-conn\", \"Maximum number of connections\").Action(c.MaxConn.Set).UintVar(&c.MaxConn.Value)\n\tc.CmdClause.Flag(\"first-byte-timeout\", \"How long to wait for the first bytes in milliseconds\").Action(c.FirstByteTimeout.Set).UintVar(&c.MaxConn.Value)\n\tc.CmdClause.Flag(\"between-bytes-timeout\", \"How long to wait between bytes in milliseconds\").Action(c.BetweenBytesTimeout.Set).UintVar(&c.BetweenBytesTimeout.Value)\n\tc.CmdClause.Flag(\"auto-loadbalance\", \"Whether or not this backend should be automatically load balanced\").Action(c.AutoLoadbalance.Set).BoolVar(&c.AutoLoadbalance.Value)\n\tc.CmdClause.Flag(\"weight\", \"Weight used to load balance this backend against others\").Action(c.Weight.Set).UintVar(&c.Weight.Value)\n\tc.CmdClause.Flag(\"request-condition\", \"condition, which if met, will select this backend during a request\").Action(c.RequestCondition.Set).StringVar(&c.RequestCondition.Value)\n\tc.CmdClause.Flag(\"healthcheck\", \"The name of the healthcheck to use with this backend\").Action(c.HealthCheck.Set).StringVar(&c.HealthCheck.Value)\n\tc.CmdClause.Flag(\"shield\", \"The shield POP designated to reduce inbound load on this origin by serving the cached data to the rest of the network\").Action(c.Shield.Set).StringVar(&c.Shield.Value)\n\tc.CmdClause.Flag(\"use-ssl\", \"Whether or not to use SSL to reach the backend\").Action(c.UseSSL.Set).BoolVar(&c.UseSSL.Value)\n\tc.CmdClause.Flag(\"ssl-check-cert\", \"Be strict on checking SSL certs\").Action(c.SSLCheckCert.Set).BoolVar(&c.SSLCheckCert.Value)\n\tc.CmdClause.Flag(\"ssl-ca-cert\", \"CA certificate attached to origin\").Action(c.SSLCACert.Set).StringVar(&c.SSLCACert.Value)\n\tc.CmdClause.Flag(\"ssl-client-cert\", \"Client certificate attached to origin\").Action(c.SSLClientCert.Set).StringVar(&c.SSLClientCert.Value)\n\tc.CmdClause.Flag(\"ssl-client-key\", \"Client key attached to origin\").Action(c.SSLClientKey.Set).StringVar(&c.SSLClientKey.Value)\n\tc.CmdClause.Flag(\"ssl-cert-hostname\", \"Overrides ssl_hostname, but only for cert verification. Does not affect SNI at all.\").Action(c.SSLCertHostname.Set).StringVar(&c.SSLCertHostname.Value)\n\tc.CmdClause.Flag(\"ssl-sni-hostname\", \"Overrides ssl_hostname, but only for SNI in the handshake. Does not affect cert validation at all.\").Action(c.SSLSNIHostname.Set).StringVar(&c.SSLSNIHostname.Value)\n\tc.CmdClause.Flag(\"min-tls-version\", \"Minimum allowed TLS version on SSL connections to this backend\").Action(c.MinTLSVersion.Set).StringVar(&c.MinTLSVersion.Value)\n\tc.CmdClause.Flag(\"max-tls-version\", \"Maximum allowed TLS version on SSL connections to this backend\").Action(c.MaxTLSVersion.Set).StringVar(&c.MaxTLSVersion.Value)\n\tc.CmdClause.Flag(\"ssl-ciphers\", \"List of OpenSSL ciphers (see https://www.openssl.org/docs/man1.0.2/man1/ciphers for details)\").Action(c.SSLCiphers.Set).StringsVar(&c.SSLCiphers.Value)\n\n\treturn &c\n}", "func (service *RssService) UpdateFeed(url string, userId uint) {\n\t//defer wg.Done()\n\trssBody, err := service.getFeedBody(url)\n\n\tif err != nil {\n\t\tlog.Println(\"get rss error: \", err.Error())\n\t\treturn\n\t}\n\n\t// get feed from DB by url, if not - add\n\tdefer rssBody.Close()\n\tvar rss models.Feeds\n\t//service.dbp().Preload(\"Articles\").Where(&models.Feeds{Url: url, UserId: userId}).Find(&rss)\n\tservice.dbp().Where(&models.Feeds{Url: url, UserId: userId}).First(&rss)\n\n\tif rss.Url == \"\" {\n\t\tservice.AddFeed(url, userId)\n\t\treturn\n\t}\n\n\t// unmarshal xml\n\tvar xmlModel models.XMLFeed\n\tdecoder := xml.NewDecoder(rssBody)\n\tdecoder.CharsetReader = charset.NewReaderLabel\n\terr = decoder.Decode(&xmlModel)\n\n\tif err != nil {\n\t\tlog.Println(\"unmarshal error: \" + err.Error())\n\t\treturn\n\t}\n\n\t// update DB\n\tservice.updateArticles(rss, xmlModel)\n}", "func newTracker(maxAge, evaluationInterval time.Duration, minimumPortScanned int) (t *Tracker) {\n\tt = &Tracker{\n\t\tportScanners: make(chan *TrackerEntry),\n\t\tminimumPortScanned: minimumPortScanned,\n\t\tmaxAge: maxAge,\n\t\tm: make(map[string]*TrackerEntry),\n\t}\n\tgo func() {\n\t\tfor now := range time.Tick(evaluationInterval) {\n\t\t\tt.l.Lock()\n\t\t\tfor k, v := range t.m {\n\t\t\t\tif now.After(v.expiry) {\n\t\t\t\t\tlog.Infof(\"removing %q because entry is expired\", k)\n\t\t\t\t\tdelete(t.m, k)\n\t\t\t\t}\n\t\t\t}\n\t\t\tt.l.Unlock()\n\t\t}\n\t}()\n\treturn\n}" ]
[ "0.69606626", "0.67406523", "0.6593128", "0.65879697", "0.6474466", "0.6468645", "0.62675405", "0.6217244", "0.6181586", "0.6118874", "0.60844964", "0.60467017", "0.6034148", "0.6026278", "0.5980703", "0.59795487", "0.59422725", "0.5822659", "0.5807095", "0.5796147", "0.57917684", "0.57314", "0.5691694", "0.5637653", "0.5602059", "0.557771", "0.54935145", "0.5492089", "0.54307204", "0.54283005", "0.53869337", "0.537936", "0.5375755", "0.5369029", "0.5361332", "0.5358793", "0.5336542", "0.53329927", "0.5319988", "0.5319773", "0.5286477", "0.5270954", "0.5266281", "0.52639717", "0.52618617", "0.52567947", "0.5240854", "0.52241755", "0.5219817", "0.5208416", "0.5203981", "0.51910037", "0.518279", "0.51731277", "0.5169959", "0.5161393", "0.51445484", "0.5113923", "0.5088556", "0.5087168", "0.5073393", "0.5064546", "0.5030083", "0.5026149", "0.50025296", "0.5001628", "0.49919796", "0.4987393", "0.49871665", "0.49522024", "0.49345663", "0.49197388", "0.49192366", "0.49154797", "0.4909165", "0.49047166", "0.48951885", "0.48935226", "0.4892704", "0.48777723", "0.4841329", "0.48230785", "0.48115855", "0.47996104", "0.47930968", "0.4783822", "0.47829828", "0.47781032", "0.47694314", "0.47666547", "0.4766279", "0.47477177", "0.47467047", "0.47444564", "0.47435644", "0.47220963", "0.4718086", "0.4716591", "0.47143102" ]
0.7205077
1
Update pushes an update to the feed through the chunk stores
func (u *updater) Update(ctx context.Context, at int64, payload []byte) error { err := u.Put(ctx, &index{u.next}, at, payload) if err != nil { return err } u.next++ return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *MhistConnector) Update() {\n\tfor {\n\t\tmessage := <-c.brokerChannel\n\t\tmeasurement := proto.MeasurementFromModel(&models.Raw{\n\t\t\tValue: message.Measurement,\n\t\t})\n\t\terr := c.writeStream.Send(&proto.MeasurementMessage{\n\t\t\tName: message.Channel,\n\t\t\tMeasurement: measurement,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Writing to MHIST StoreStream failed: %v\", err)\n\t\t}\n\t\tlog.Printf(\"Message added to MHIST:\\nName: %s,\\nMeasurement: %s,\\nTimestamp: %d\", message.Channel, string(message.Measurement), message.Timestamp)\n\t}\n}", "func (w *HotCache) Update(item *HotPeerStat) {\n\tswitch item.Kind {\n\tcase WriteFlow:\n\t\tw.writeFlow.Update(item)\n\tcase ReadFlow:\n\t\tw.readFlow.Update(item)\n\t}\n\n\tif item.IsNeedDelete() {\n\t\tw.incMetrics(\"remove_item\", item.StoreID, item.Kind)\n\t} else if item.IsNew() {\n\t\tw.incMetrics(\"add_item\", item.StoreID, item.Kind)\n\t} else {\n\t\tw.incMetrics(\"update_item\", item.StoreID, item.Kind)\n\t}\n}", "func (s *Stream) Update(ctx context.Context, c Collector) (err error) {\n\tupdate := newTaskLogger(s.stdout).Task(fmt.Sprintf(\"DRIVE %s\", s.drive)).Task(\"UPDATE\")\n\n\tupdate.Log(\"Started %s\\n\", time.Now().Format(time.RFC3339))\n\tdefer func(e *error) {\n\t\tif *e != nil {\n\t\t\tupdate.Log(\"ERROR: %v\\n\", *e)\n\t\t\tupdate.Log(\"Aborted %s | %s\\n\", time.Now().Format(time.RFC3339), update.Duration())\n\t\t} else {\n\t\t\tupdate.Log(\"Finished %s | %s\\n\", time.Now().Format(time.RFC3339), update.Duration())\n\t\t}\n\t}(&err)\n\n\tif err = s.collect(ctx, c, update); err != nil {\n\t\treturn err\n\t}\n\n\treturn s.buildCommits(ctx, update)\n}", "func (s *Store) Update(c *gin.Context) {\n\n}", "func (f *Fills) Update(data ...Data) error {\n\tif len(data) == 0 {\n\t\t// nothing to do\n\t\treturn nil\n\t}\n\n\tif !f.fillsFeedEnabled {\n\t\treturn ErrFeedDisabled\n\t}\n\n\tf.dataHandler <- data\n\n\treturn nil\n}", "func (feed *NewsLetterFeed) Update(entries []FeedEntry) error {\n\tfeed.Entries = entries\n\n\tfeed.Updated = time.Now().Format(time.RFC1123Z)\n\n\tfeedFilePath := \"./data/feeds/\" + feed.ID + \".xml\"\n\n\tfeedFile, err := os.OpenFile(feedFilePath, os.O_WRONLY|os.O_CREATE, 0755)\n\tdefer feedFile.Close()\n\tif err != nil {\n\t\tlog.Printf(\"failed to open feed file to write: %v\", err)\n\t\treturn err\n\t}\n\n\terr = feedTmpl.Execute(feedFile, feed)\n\tif err != nil {\n\t\tlog.Printf(\"failed to execute feed template: %v\", err)\n\t\treturn err\n\t}\n\n\tlog.Printf(\"updated feed with %d entries\", len(entries))\n\treturn nil\n}", "func (b *Backend) Update() (c context.Context, err error) {\n\tvar m Mutation\n\tfor {\n\t\terr = b.cursor.Next(c, &m)\n\t\tif err == scroll.Done {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn\n\t\t}\n\t\tm.Update(b)\n\t}\n\treturn\n}", "func (store *payloadStore) Update(p *Payload) error {\n\tstore.Lock()\n\tdefer store.Unlock()\n\tstore.m[p.Id] = p\n\treturn nil\n}", "func (b *Block) Update(data *models.Block) (wasPublished bool) {\n\tb.mutex.Lock()\n\tdefer b.mutex.Unlock()\n\n\tif !b.missing {\n\t\treturn\n\t}\n\n\tb.ImportStorable(&data.Storable)\n\tb.missing = false\n\n\treturn true\n}", "func (s *Service) Update(b *Base) error {\n\tname := strings.ToLower(b.Exchange)\n\ts.mu.Lock()\n\tm1, ok := s.books[name]\n\tif !ok {\n\t\tid, err := s.Mux.GetID()\n\t\tif err != nil {\n\t\t\ts.mu.Unlock()\n\t\t\treturn err\n\t\t}\n\t\tm1 = Exchange{\n\t\t\tm: make(map[asset.Item]map[*currency.Item]map[*currency.Item]*Depth),\n\t\t\tID: id,\n\t\t}\n\t\ts.books[name] = m1\n\t}\n\n\tm2, ok := m1.m[b.Asset]\n\tif !ok {\n\t\tm2 = make(map[*currency.Item]map[*currency.Item]*Depth)\n\t\tm1.m[b.Asset] = m2\n\t}\n\n\tm3, ok := m2[b.Pair.Base.Item]\n\tif !ok {\n\t\tm3 = make(map[*currency.Item]*Depth)\n\t\tm2[b.Pair.Base.Item] = m3\n\t}\n\n\tbook, ok := m3[b.Pair.Quote.Item]\n\tif !ok {\n\t\tbook = NewDepth(m1.ID)\n\t\tbook.AssignOptions(b)\n\t\tm3[b.Pair.Quote.Item] = book\n\t}\n\tbook.LoadSnapshot(b.Bids, b.Asks, b.LastUpdateID, b.LastUpdated, true)\n\ts.mu.Unlock()\n\treturn s.Mux.Publish(book, m1.ID)\n}", "func (s *State) Update(status mesos.TaskStatus) {\n\ts.updates <- status\n}", "func (p *MemProvider) update(sid string) error {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\n\tif e, ok := p.data[sid]; ok {\n\t\te.Value.(*MemStore).lastAccess = time.Now()\n\t\tp.list.MoveToFront(e)\n\t\treturn nil\n\t}\n\treturn nil\n}", "func publishUpdate(msg string) {\n\thub.broadcast <- []byte(msg)\n}", "func (s *Service) update(entry ytfeed.Entry, file string, fi FeedInfo) ytfeed.Entry {\n\tentry.File = file\n\n\t// only reset time if published not too long ago\n\t// this is done to avoid initial set of entries added with a new channel to the top of the feed\n\tif time.Since(entry.Published) < time.Hour*24 {\n\t\tlog.Printf(\"[DEBUG] reset published time for %s, from %s to %s (%v), %s\",\n\t\t\tentry.VideoID, entry.Published.Format(time.RFC3339), time.Now().Format(time.RFC3339),\n\t\t\ttime.Since(entry.Published), entry.String())\n\t\tentry.Published = time.Now() // reset published ts to prevent possible out-of-order entries\n\t} else {\n\t\tlog.Printf(\"[DEBUG] keep published time for %s, %s\", entry.VideoID, entry.Published.Format(time.RFC3339))\n\t}\n\n\tif !strings.Contains(entry.Title, fi.Name) { // if title doesn't contains channel name add it\n\t\tentry.Title = fi.Name + \": \" + entry.Title\n\t}\n\n\tentry.Duration = s.DurationService.File(file)\n\tlog.Printf(\"[DEBUG] updated entry: %s\", entry.String())\n\treturn entry\n}", "func (f *Feed) Update() error {\n\n\t// Check that we don't update too often.\n\tif f.Refresh.After(time.Now()) {\n\t\treturn nil\n\t}\n\n\tif f.UpdateURL == \"\" {\n\t\treturn errors.New(\"Error: feed has no URL.\")\n\t}\n\n\tupdate, err := Fetch(f.UpdateURL, f.Seen)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf.Refresh = update.Refresh\n\tf.Title = update.Title\n\tf.Description = update.Description\n\n\treturn nil\n}", "func (honest *Honest) flushUpdates() {\n\n\thonest.blockUpdates = honest.blockUpdates[:0]\n}", "func upd() {\n\tsavePageMemory()\n\tfor range time.Tick(time.Minute) {\n\t\tsavePageMemory()\n\t}\n}", "func (f *BasicFeature) Update(TimeCurrent uint64, data []*dfedata.InputData, connectionChannel ...chan ConnectionChannelData) {\n}", "func (q *Queue) Update(id int, data []byte) error {\n\tif _, ok := q.data[id]; !ok {\n\t\treturn fmt.Errorf(\"could not find any job with id : %d\", id)\n\t}\n\tq.lock.Lock()\n\tq.data[id] = data\n\tq.lock.Unlock()\n\treturn nil\n}", "func updater(ticker *time.Ticker) {\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tprintln(\"Updating feeds\")\n\t\t\tlock.Lock()\n\t\t\tfor _, folder := range folders {\n\t\t\t\tfor _, source := range folder {\n\t\t\t\t\tnow := time.Now()\n\t\t\t\t\tfmt.Printf(\"Updating feed %s at %s\\n\", source.Title, source.Url)\n\t\t\t\t\tresp, err := http.Get(source.Url)\n\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Printf(\"Error: %s\\n\", err.Error())\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tdefer resp.Body.Close()\n\t\t\t\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Printf(\"Error: %s\\n\", err.Error())\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tnewSource, err := readAtom(now, source.Url, body)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tnewSource, err = readRss(now, source.Url, body)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Printf(\"Could not parse as atom or RSS... skipping\\n\")\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tupdateSource(source, newSource)\n\t\t\t\t}\n\t\t\t}\n\t\t\tdirty = true\n\t\t\tlock.Unlock()\n\t\t}\n\t}\n}", "func (a *apiEndpoint) Update() error {\n\ta.e.mutex.RLock()\n\ta.SetEntry(\"server\", api.String(a.e.poolEntry.Desc))\n\ta.SetEntry(\"status\", api.String(a.e.status.String()))\n\tif a.e.lastErr != nil {\n\t\ta.SetEntry(\"last_error\", api.String(a.e.lastErr.Error()))\n\t\ta.SetEntry(\"last_error_time\", api.String(a.e.lastErrTime.Format(time.RFC3339)))\n\t} else {\n\t\ta.SetEntry(\"last_error\", api.Null)\n\t\ta.SetEntry(\"last_error_time\", api.Null)\n\t}\n\ta.SetEntry(\"pendingPayloads\", api.Number(a.e.NumPending()))\n\ta.SetEntry(\"publishedLines\", api.Number(a.e.LineCount()))\n\ta.SetEntry(\"averageLatency\", api.Float(a.e.AverageLatency()/time.Millisecond))\n\ta.e.mutex.RUnlock()\n\n\treturn nil\n}", "func (s BoltStore) BatchUpdate(ids []interface{}, data []interface{}, store string, opts ObjectStoreOptions) (err error) {\n\treturn ErrNotImplemented\n}", "func (reporter *ProgressReporter) sendUpdates() {\n\tb := reporter.serialize()\n\tfmt.Println(string(b))\n\tgo reporter.postProgressToURL(b)\n}", "func (hubPtr *Hub) updater() {\n\tfor {\n\t\t// TODO: Wait for a USB hotplug event (not supported yet) or a refresh timeout\n\t\t// <-hubPtr.changes\n\t\ttime.Sleep(refreshCycle)\n\n\t\t// Run the wallet refresher\n\t\thubPtr.refreshWallets()\n\n\t\t// If all our subscribers left, stop the updater\n\t\thubPtr.stateLock.Lock()\n\t\tif hubPtr.updateScope.Count() == 0 {\n\t\t\thubPtr.updating = false\n\t\t\thubPtr.stateLock.Unlock()\n\t\t\treturn\n\t\t}\n\t\thubPtr.stateLock.Unlock()\n\t}\n}", "func (c *Cache) recordUpdate(p *partition, bytesAdded, bytesGuessed, entriesAdded int32) {\n\t// This method is always called while p.mu is held.\n\t// The below code takes care to ensure that all bytes in c due to p are\n\t// updated appropriately.\n\n\t// NB: The loop and atomics are used because p.size can be modified\n\t// concurrently to calls to recordUpdate. In all cases where p.size is updated\n\t// outside of this function occur while c.mu is held inside of c.Add. These\n\t// occur when either:\n\t//\n\t// 1) a new write adds its guessed write size to p\n\t// 2) p is evicted to make room for a write\n\t//\n\t// Thus p.size is either increasing or becomes evicted while we attempt to\n\t// record the update to p. Once p is evicted it stays evicted forever.\n\t// These facts combine to ensure that p.size never becomes negative from the\n\t// below call to add.\n\n\tdelta := bytesAdded - bytesGuessed\n\tfor {\n\t\tcurSize := p.loadSize()\n\t\tif curSize == evicted {\n\t\t\treturn\n\t\t}\n\t\tnewSize := curSize.add(delta, entriesAdded)\n\t\tif updated := p.setSize(curSize, newSize); updated {\n\t\t\tc.updateGauges(c.addBytes(delta), c.addEntries(entriesAdded))\n\t\t\treturn\n\t\t}\n\t}\n}", "func updateRiver(name string, newUpdate *UpdatedFeed) func(*bolt.Tx) error {\n\treturn func(tx *bolt.Tx) error {\n\t\tvar updates []*UpdatedFeed\n\n\t\t// Get the JSON out of boltdb\n\t\tb := tx.Bucket([]byte(name))\n\t\tobj := b.Get([]byte(\"river\"))\n\n\t\t// Decode the byte slice into a slice of *UpdateFeed and\n\t\t// prepend the new update\n\t\tif obj != nil {\n\t\t\tjson.Unmarshal(obj, &updates)\n\t\t\tupdates = append([]*UpdatedFeed{newUpdate}, updates...)\n\t\t} else {\n\t\t\tupdates = []*UpdatedFeed{newUpdate}\n\t\t}\n\n\t\t// Trim the update slice down to size\n\t\tif len(updates) > maxFeedUpdates {\n\t\t\tupdates = updates[:maxFeedUpdates]\n\t\t}\n\n\t\t// Encode the new river object and update bolt with it\n\t\tupdatedRiver, err := json.Marshal(updates)\n\t\terr = b.Put([]byte(\"river\"), updatedRiver)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n}", "func (svr *Server) recvUpdate(key string, val string, id int, counter int, vecI []int, senderId int) {\n\tentry := WitnessEntry{id: id, counter: counter}\n\tif _,isIn := svr.witness[entry]; isIn {\n\t\tif _,hasReceived := svr.witness[entry][senderId]; !hasReceived {\n\t\t\tsvr.witness[entry][senderId] = true\n\n\t\t\t// Publish UPDATE\n\t\t\tsvr.hasSentLock.Lock()\n\t\t\tif _,isIn := svr.hasSent[entry]; !isIn {\n\t\t\t\tmsg := Message{Kind: UPDATE, Key: key, Val: val, Id: id, Counter: counter, Vec: vecI, Sender: nodeId}\n\t\t\t\tsvr.publish(&msg)\n\t\t\t\tsvr.hasSent[entry] = true\n\t\t\t\t// fmt.Printf(\"Server %d published msg UPDATE in response to UPDATE from server %d\\n\", nodeId, senderId)\n\t\t\t}\n\t\t\tsvr.hasSentLock.Unlock()\n\n\t\t\tif len(svr.witness[entry]) == F+1 {\n\t\t\t\tqueueEntry := QueueEntry{Key: key, Val: val, Id: id, Vec: vecI}\n\t\t\t\tsvr.queue.Enqueue(queueEntry)\n\t\t\t\tgo svr.update()\n\t\t\t\t// fmt.Println(\"server enqueues entry: \", queueEntry)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tsvr.witness[entry] = make(map[int]bool)\n\t\tsvr.witness[entry][senderId] = true\n\n\t\t// Publish UPDATE\n\t\tsvr.hasSentLock.Lock()\n\t\tif _,isIn := svr.hasSent[entry]; !isIn {\n\t\t\tmsg := Message{Kind: UPDATE, Key: key, Val: val, Id: id, Counter: counter, Vec: vecI, Sender: nodeId}\n\t\t\tsvr.publish(&msg)\n\t\t\tsvr.hasSent[entry] = true\n\t\t\t// fmt.Printf(\"Server %d published msg UPDATE in response to UPDATE from server %d\\n\", nodeId, senderId)\n\t\t}\n\t\tsvr.hasSentLock.Unlock()\n\n\t\tif len(svr.witness[entry]) == F+1 {\n\t\t\tqueueEntry := QueueEntry{Key: key, Val: val, Id: id, Vec: vecI}\n\t\t\tsvr.queue.Enqueue(queueEntry)\n\t\t\tgo svr.update()\n\t\t\t// fmt.Println(\"server enqueues entry: \", queueEntry)\n\t\t}\n\t}\n}", "func (s *OnDiskStateMachine) Update(entries []sm.Entry) ([]sm.Entry, error) {\n\tif !s.opened {\n\t\tpanic(\"Update called before Open\")\n\t}\n\treturn s.sm.Update(entries)\n}", "func (db *queueDatabase) update(m *persistence.QueueMessage) {\n\texisting := db.messages[m.ID()]\n\n\t// Apply the changes to the database, ensuring that the envelope is never\n\t// changed.\n\tenv := existing.Envelope\n\t*existing = *m\n\texisting.Envelope = env\n\texisting.Revision++\n\n\t// Queue messages are typically updated after an error, when their\n\t// next-attempt time is updated as per the backoff strategy, so in practice\n\t// we always need to sort.\n\tsort.Slice(\n\t\tdb.order,\n\t\tfunc(i, j int) bool {\n\t\t\treturn db.order[i].NextAttemptAt.Before(\n\t\t\t\tdb.order[j].NextAttemptAt,\n\t\t\t)\n\t\t},\n\t)\n}", "func (sm *ShardMaster) Update() {\n\tfor true {\n\t\tlog := <- sm.applyCh\n\t\ttp := log.Command.(Op)\n\t\tvar cid int64\n\t\tvar rid int\n\t\tvar result OpReply\n\t\tswitch tp.OpType{\n\t\tcase Join:\n\t\t\targs := tp.Args.(JoinArgs)\n\t\t\tcid = args.ClientId\n\t\t\trid = args.RequestId\n\t\t\tresult.args = args\n\t\tcase Leave:\n\t\t\targs := tp.Args.(LeaveArgs)\n\t\t\tcid = args.ClientId\n\t\t\trid = args.RequestId\n\t\t\tresult.args = args\n\t\tcase Move:\n\t\t\targs := tp.Args.(MoveArgs)\n\t\t\tcid = args.ClientId\n\t\t\trid = args.RequestId\n\t\t\tresult.args = args\n\t\tcase Query:\n\t\t\targs := tp.Args.(QueryArgs)\n\t\t\tcid = args.ClientId\n\t\t\trid = args.RequestId\n\t\t\tresult.args = args\n\t\t}\n\t\tresult.OpType = tp.OpType\n\t\tdup := sm.duplication(cid, rid)\n\t\tresult.reply = sm.getApply(tp, dup)\n\t\tsm.sendResult(log.Index, result)\n\t\tsm.Validation()\n\t}\n}", "func (s *HelloSystem) Update(ctx core.UpdateCtx) {}", "func (s *Server) Update(ctx context.Context, message *steppb.UpdateRequest) (*steppb.UpdateResponse, error) {\n\tctx = context.WithValue(ctx, goa.MethodKey, \"update\")\n\tctx = context.WithValue(ctx, goa.ServiceKey, \"step\")\n\tresp, err := s.UpdateH.Handle(ctx, message)\n\tif err != nil {\n\t\treturn nil, goagrpc.EncodeError(err)\n\t}\n\treturn resp.(*steppb.UpdateResponse), nil\n}", "func (s *ConcurrentStateMachine) Update(entries []sm.Entry) ([]sm.Entry, error) {\n\treturn s.sm.Update(entries)\n}", "func (m *store) Update(w ukjent.Word) error {\n\tdefer m.withWrite()()\n\tm.data[w.Word] = entry{w.Translation, w.Note}\n\treturn nil\n}", "func (j *journal) update(us updateSet) error {\n\tif err := json.NewEncoder(j.f).Encode(us); err != nil {\n\t\treturn err\n\t}\n\treturn j.f.Sync()\n}", "func (q *reapQueue) Update(ch *ManagedChannel, t time.Time) {\n\tmReapqUpdate.WithLabelValues(q.label).Inc()\n\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\n\tidx := -1\n\tfor i, v := range *q.items {\n\t\tif v.ch.ChannelID == ch.ChannelID {\n\t\t\tidx = i\n\t\t\t(*q.items)[i].ch = ch\n\t\t\tbreak\n\t\t}\n\t}\n\tif idx == -1 {\n\t\theap.Push(q.items, &pqItem{\n\t\t\tch: ch,\n\t\t\tnextReap: t,\n\t\t})\n\t} else {\n\t\t(*q.items)[idx].nextReap = t\n\t\theap.Fix(q.items, idx)\n\t}\n\tq.cond.Signal()\n}", "func update(ctx context.Context, w io.Writer, client *spanner.Client) error {\n\tcols := []string{\"SingerId\", \"AlbumId\", \"MarketingBudget\"}\n\t_, err := client.Apply(ctx, []*spanner.Mutation{\n\t\tspanner.Update(\"Albums\", cols, []interface{}{1, 1, 100000}),\n\t\tspanner.Update(\"Albums\", cols, []interface{}{2, 2, 500000}),\n\t})\n\treturn err\n}", "func (d *DB) itemUpdater(catogoryID uint16) {\n\tarticles, err := FeedzillaArticles(catogoryID, NumberToGet)\n\tif err != nil {\n\t\tglog.Error(err)\n\t\treturn\n\t}\n\n\tfor _, art := range articles.List {\n\t\tart.CategoryID = catogoryID\n\t\t_, err := d.Items.Upsert(bson.M{\"url\": art.URL}, art)\n\t\tif err != nil {\n\t\t\tglog.Error(err)\n\t\t\tcontinue\n\t\t}\n\t\tglog.Infof(\"%+v\", art)\n\t}\n}", "func (p *AutoCommitter) Update(pair []interface{}) (e error) {\n\tif p.started {\n\t\tp.docsUpdate <- pair\n\t} else {\n\t\te = errors.New(fmt.Sprintf(\"AutoCommitter-%s(%s)_is_closed\", p.name, p.coll))\n\t}\n\treturn\n}", "func (w* Workermeta) Update(state WorkerState) Workermeta {\n\tw.State = state\n\tw.LastUpdateTime = time.Now().Unix()\n\tnw := *w\n\treturn nw\n}", "func (s *storage) Update(*entity.Deck) error {\n\treturn nil\n}", "func UpdateFeedDB(url string, key string, finflag chan string) {\n\tclient := &http.Client{\n\t\tTimeout: time.Second * 30,\n\t}\n\treq, _ := http.NewRequest(\"GET\", url, nil)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tdefer resp.Body.Close()\n\tdataBody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tfilePath := \"pkg/feeds/db/\" + key\n\top, err := os.Create(filePath)\n\tdefer op.Close()\n\tif err != nil {\n\t\tlog.Println(\"Error while updating feed\", err)\n\t}\n\top.Write(dataBody)\n\tfinflag <- \"done\"\n}", "func (msink *MetricsSink) UpdatePersisted(addr string, totalWritten int,\n\tserverDropped int) {\n\tmsink.lock.Lock()\n\tdefer msink.lock.Unlock()\n\tmsink.WrittenSpans += uint64(totalWritten)\n\tmsink.ServerDropped += uint64(serverDropped)\n\tmsink.updateSpanMetrics(addr, totalWritten, serverDropped)\n}", "func UpdateLoop() {\n\tfor {\n\t\tup, ok := <-ostent.Updates.Get()\n\t\tif ok {\n\t\t\tconnections.update(up)\n\t\t\tlastCopy.set(up)\n\t\t}\n\t}\n}", "func (m *DBMem) Update(idToUpdate int, data Person) {\n m.Lock()\n defer m.Unlock()\n\n\tif len(m.data) <= idToUpdate {\n\t\tfmt.Println(\"ID is out of range\")\n\t\treturn\n\t}\n m.data[idToUpdate] = data\n m.history.Append(\"UPDATE\", idToUpdate, data)\n}", "func (r *Roster) update() {\n\tiq := &Iq{Header: Header{Type: \"get\", Id: NextId(),\n\t\tNested: []interface{}{RosterQuery{}}}}\n\tr.toServer <- iq\n}", "func (e *ExpireQueue) Update(value IEntry) {\n\theap.Fix(e.q, value.ExIndex())\n}", "func (p *Projector) doUpdateFeed(request *protobuf.UpdateMutationStreamRequest) ap.MessageMarshaller {\n\tvar err error\n\n\tc.Debugf(\"%v doUpdateFeed()\\n\", p.logPrefix)\n\tresponse := protobuf.NewMutationStreamResponse(request)\n\n\ttopic := request.GetTopic()\n\tbucketns := request.GetBuckets()\n\n\tfeed, err := p.GetFeed(topic) // only existing feed\n\tif err != nil {\n\t\tc.Errorf(\"%v %v\\n\", p.logPrefix, err)\n\t\tresponse.UpdateErr(err)\n\t\treturn response\n\t}\n\n\tif err = feed.UpdateFeed(request); err == nil {\n\t\t// gather latest set of timestamps for each bucket, provided request\n\t\t// is not for deleting the bucket.\n\t\tif !request.IsDelBuckets() {\n\t\t\t// we expect failoverTimestamps and kvTimestamps to be re-populated.\n\t\t\tfailTss := make([]*protobuf.TsVbuuid, 0, len(bucketns))\n\t\t\tkvTss := make([]*protobuf.TsVbuuid, 0, len(bucketns))\n\t\t\tfor _, bucketn := range bucketns {\n\t\t\t\tfailTss = append(failTss, feed.failoverTimestamps[bucketn])\n\t\t\t\tkvTss = append(kvTss, feed.kvTimestamps[bucketn])\n\t\t\t}\n\t\t\tresponse.UpdateTimestamps(failTss, kvTss)\n\t\t}\n\t} else {\n\t\tresponse.UpdateErr(err)\n\t}\n\treturn response\n}", "func (ob *Observer) Update() {\n\tchainID := ob.deps.Recorder.ChainID()\n\tstartHeight := ob.conf.StartHeight\n\tfor {\n\t\tcurBlockLog, err := ob.GetCurrentBlockLog()\n\t\tif err != nil {\n\t\t\tutil.Logger.Errorf(\"[Observer.Update]: get current block log from db error: %s\", err.Error())\n\t\t\ttime.Sleep(ob.conf.FetchInterval)\n\t\t\tcontinue\n\t\t}\n\n\t\tnextHeight := curBlockLog.Height + 1\n\t\tif curBlockLog.Height == 0 && startHeight != 0 {\n\t\t\tnextHeight = startHeight\n\t\t}\n\n\t\tutil.Logger.Debugf(\"[Observer.Update]: fetch from chain id %s, height=%d\", chainID, nextHeight)\n\t\terr = ob.updateBlock(curBlockLog.Height, nextHeight, curBlockLog.BlockHash)\n\t\tif err != nil {\n\t\t\tif errors.Cause(err) != common.ErrBlockNotFound {\n\t\t\t\tutil.Logger.Errorf(\"[Observer.Update]: fetch from chain id %s error, err=%s\", chainID, err.Error())\n\t\t\t}\n\n\t\t\tutil.Logger.Debugf(\"[Observer.Update]: failed to fetch from chain id %s error, err=%s\", chainID, err.Error())\n\n\t\t\ttime.Sleep(ob.conf.FetchInterval)\n\t\t}\n\t}\n}", "func (c *meminfoCollector) Update(ch chan<- prometheus.Metric) error {\n\tvar metricType prometheus.ValueType\n\tmemInfo, err := c.getMemInfo()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't get meminfo: %w\", err)\n\t}\n\tlevel.Debug(c.logger).Log(\"msg\", \"Set node_mem\", \"memInfo\", memInfo)\n\tfor k, v := range memInfo {\n\t\tif strings.HasSuffix(k, \"_total\") {\n\t\t\tmetricType = prometheus.CounterValue\n\t\t} else {\n\t\t\tmetricType = prometheus.GaugeValue\n\t\t}\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tprometheus.NewDesc(\n\t\t\t\tprometheus.BuildFQName(namespace, memInfoSubsystem, k),\n\t\t\t\tfmt.Sprintf(\"Memory information field %s.\", k),\n\t\t\t\tnil, nil,\n\t\t\t),\n\t\t\tmetricType, v,\n\t\t)\n\t}\n\treturn nil\n}", "func (m *Message) Update(objectstorage.StorableObject) {\n\tpanic(\"messages should never be overwritten and only stored once to optimize IO\")\n}", "func (sm *ConcurrentStateMachine) Update(entries []sm.Entry) []sm.Entry {\n\treturn sm.sm.Update(entries)\n}", "func (d *Deployment) update() error {\n\tselect {\n\tcase event, ok := <-d.events:\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"service stream closed unexpectedly: %s\", d.stream.Err())\n\t\t}\n\t\tif event.Kind == discoverd.EventKindServiceMeta {\n\t\t\td.meta = event.ServiceMeta\n\t\t}\n\tdefault:\n\t}\n\treturn nil\n}", "func (job *AnalyzeJob) Update(rowCount int64) {\n\tnow := time.Now()\n\tjob.Mutex.Lock()\n\tjob.RowCount += rowCount\n\tjob.updateTime = now\n\tjob.Mutex.Unlock()\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 (u *Updater) updateFeed(ctx context.Context, feedConfig *config.Feed) error {\n\tinfo, err := builder.ParseURL(feedConfig.URL)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to parse URL: %s\", feedConfig.URL)\n\t}\n\n\tkeyProvider, ok := u.keys[info.Provider]\n\tif !ok {\n\t\treturn errors.Errorf(\"key provider %q not loaded\", info.Provider)\n\t}\n\n\t// Create an updater for this feed type\n\tprovider, err := builder.New(ctx, info.Provider, keyProvider.Get())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Query API to get episodes\n\tlog.Debug(\"building feed\")\n\tresult, err := provider.Build(ctx, feedConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Debugf(\"received %d episode(s) for %q\", len(result.Episodes), result.Title)\n\n\tepisodeSet := make(map[string]struct{})\n\tif err := u.db.WalkEpisodes(ctx, feedConfig.ID, func(episode *model.Episode) error {\n\t\tif episode.Status != model.EpisodeDownloaded && episode.Status != model.EpisodeCleaned {\n\t\t\tepisodeSet[episode.ID] = struct{}{}\n\t\t}\n\t\treturn nil\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tif err := u.db.AddFeed(ctx, feedConfig.ID, result); err != nil {\n\t\treturn err\n\t}\n\n\tfor _, episode := range result.Episodes {\n\t\tdelete(episodeSet, episode.ID)\n\t}\n\n\t// removing episodes that are no longer available in the feed and not downloaded or cleaned\n\tfor id := range episodeSet {\n\t\tlog.Infof(\"removing episode %q\", id)\n\t\terr := u.db.DeleteEpisode(feedConfig.ID, id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tlog.Debug(\"successfully saved updates to storage\")\n\treturn nil\n}", "func (x *x509Handler) update(u *workload.X509SVIDResponse) {\n\tx.mtx.Lock()\n\tdefer x.mtx.Unlock()\n\n\tif reflect.DeepEqual(u, x.latest) {\n\t\treturn\n\t}\n\n\tx.latest = u\n\n\t// Don't block if the channel is full\n\tselect {\n\tcase x.changes <- struct{}{}:\n\t\tbreak\n\tdefault:\n\t\tbreak\n\t}\n}", "func (ch *ClickHouse) Update(object map[string]interface{}) error {\n\treturn ch.SyncStore(nil, []map[string]interface{}{object}, \"\", true)\n}", "func (_m *Repository) Update(p *entity.Person, commitChan <-chan bool, doneChan chan<- bool) {\n\t_m.Called(p, commitChan, doneChan)\n}", "func (ds *RegularStateMachineWrapper) Update(e sm.Entry) (sm.Result, error) {\n\tds.ensureNotDestroyed()\n\tvar dp *C.uchar\n\tif len(e.Cmd) > 0 {\n\t\tdp = (*C.uchar)(unsafe.Pointer(&e.Cmd[0]))\n\t}\n\tv := C.UpdateDBRegularStateMachine(\n\t\tds.dataStore, C.uint64_t(e.Index), dp, C.size_t(len(e.Cmd)))\n\treturn sm.Result{Value: uint64(v)}, nil\n}", "func (service *RssService) UpdateFeed(url string, userId uint) {\n\t//defer wg.Done()\n\trssBody, err := service.getFeedBody(url)\n\n\tif err != nil {\n\t\tlog.Println(\"get rss error: \", err.Error())\n\t\treturn\n\t}\n\n\t// get feed from DB by url, if not - add\n\tdefer rssBody.Close()\n\tvar rss models.Feeds\n\t//service.dbp().Preload(\"Articles\").Where(&models.Feeds{Url: url, UserId: userId}).Find(&rss)\n\tservice.dbp().Where(&models.Feeds{Url: url, UserId: userId}).First(&rss)\n\n\tif rss.Url == \"\" {\n\t\tservice.AddFeed(url, userId)\n\t\treturn\n\t}\n\n\t// unmarshal xml\n\tvar xmlModel models.XMLFeed\n\tdecoder := xml.NewDecoder(rssBody)\n\tdecoder.CharsetReader = charset.NewReaderLabel\n\terr = decoder.Decode(&xmlModel)\n\n\tif err != nil {\n\t\tlog.Println(\"unmarshal error: \" + err.Error())\n\t\treturn\n\t}\n\n\t// update DB\n\tservice.updateArticles(rss, xmlModel)\n}", "func (self *dpaChunkStore) Put(entry *Chunk) {\n\tchunk, err := self.localStore.Get(entry.Key)\n\tif err != nil {\n\t\tlog.Trace(fmt.Sprintf(\"DPA.Put: %v new chunk. call netStore.Put\", entry.Key.Log()))\n\t\tchunk = entry\n\t} else if chunk.SData == nil {\n\t\tlog.Trace(fmt.Sprintf(\"DPA.Put: %v request entry found\", entry.Key.Log()))\n\t\tchunk.SData = entry.SData\n\t\tchunk.Size = entry.Size\n\t} else {\n\t\tlog.Trace(fmt.Sprintf(\"DPA.Put: %v chunk already known\", entry.Key.Log()))\n\t\treturn\n\t}\n\t// from this point on the storage logic is the same with network storage requests\n\tlog.Trace(fmt.Sprintf(\"DPA.Put %v: %v\", self.n, chunk.Key.Log()))\n\tself.n++\n\tself.netStore.Put(chunk)\n}", "func (r *renderer) Update(_ tea.Msg, _ *list.Model) tea.Cmd { return nil }", "func (s *EntityStorage) update() {\n\ts.outdated = false\n\ts.occupied = s.occupied[:0]\n\tl := len(s.vec)\n\tfor i := 0; i < l; i++ {\n\t\tif s.vec[i].occupied {\n\t\t\ts.occupied = append(s.occupied, i)\n\t\t}\n\t}\n}", "func (s *Store) Update(key []byte, value []byte) error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\tr := s.recByKey(key, maxTX)\n\tif r == nil {\n\t\treturn fmt.Errorf(\"key not found\")\n\t}\n\n\tts := time.Now().Unix()\n\n\ts.delRec(r, ts)\n\ts.addRec(key, value)\n\n\ts.txCount++\n\ts.rCount++\n\n\treturn s.updateHeader()\n}", "func (s *RegularStateMachine) Update(entries []sm.Entry) ([]sm.Entry, error) {\n\tif len(entries) != 1 {\n\t\tpanic(\"len(entries) != 1\")\n\t}\n\tvar err error\n\tentries[0].Result, err = s.sm.Update(entries[0].Cmd)\n\treturn entries, err\n}", "func (pq *PriorityQueue) update(iServer *Server, url string, priority int64) {\n\tiServer.url = url\n\tiServer.priority = priority\n\theap.Fix(pq, iServer.index)\n}", "func (s *Statistics) Update(location int, split Split) {\n\ts.Splits[location] = split\n}", "func (svr *Server) recvUpdate(key int, val string, id int, counter int, vec_i []int) {\n\tentry := WitnessEntry{id: id, counter: counter}\n\tsvr.witness_lock.Lock()\n\tif _, isIn := svr.witness[entry]; isIn {\n\t\tsvr.witness[entry] += 1\n\t} else {\n\t\tsvr.witness[entry] = 1\n\t}\n\twitness_num := svr.witness[entry]\n\tsvr.witness_lock.Unlock()\n\n\tif witness_num == 1 {\n\t\tmsg := Message{Kind: UPDATE, Key: key, Val: val, Id: id, Counter: counter, Vec: vec_i}\n\t\tbroadcast(&msg)\n\t}\n\tif witness_num == F+1 {\n\t\tqueue_entry := QueueEntry{Key: key, Val: val, Id: id, Vec: vec_i}\n\t\tsvr.queue.Enqueue(queue_entry)\n\t\tsvr.update_needed <- true\n\t\t// fmt.Println(\"server enqueues entry: \", queue_entry)\n\t}\n\t\n}", "func (sm *RegularStateMachine) Update(entries []sm.Entry) []sm.Entry {\n\tif len(entries) != 1 {\n\t\tpanic(\"len(entries) != 1\")\n\t}\n\tentries[0].Result = sm.sm.Update(entries[0].Cmd)\n\treturn entries\n}", "func (counter *Counter) Update(request map[string]string) {\n\th := sha256.New()\n\tfor _, f := range []string{\"remote\", \"path\", \"agent\", \"http_x_forwarded_for\"} {\n\t\th.Write([]byte(request[f]))\n\t}\n\tvar k [sha256.Size]byte\n\tcopy(k[:], h.Sum(nil))\n\n\tcounter.mutex.Lock()\n\tdefer counter.mutex.Unlock()\n\n\tcounter.entries[k] = time.Now()\n\tcounter.callback(float64(len(counter.entries)))\n}", "func (p *progress) update(nodeIndex NodeIndex, index LogEntryIndex) {\n\tp.NextIndex[nodeIndex] = index + 1\n\tp.MatchIndex[nodeIndex] = index\n}", "func (pe *WzPingEvent) Update(msg *wzlib_transport.WzGenericMessage) {\n\tuid := msg.Payload[wzlib_transport.PAYLOAD_SYSTEM_ID].(string)\n\tif pe.uid != uid {\n\t\treturn\n\t}\n\n\tpingId, ok := msg.Payload[wzlib_transport.PAYLOAD_PING_ID]\n\tif !ok {\n\t\tpe.GetLogger().Errorln(\"Ping message contains no 'ping.id' section!\")\n\t} else {\n\t\tpingStatItf, ok := pe.pings.Get(pingId.(string))\n\t\tpingStat := pingStatItf.(*WzPingStat)\n\t\tif !ok {\n\t\t\tpe.GetLogger().Errorln(\"Unable to find ping ID for\", pingId)\n\t\t} else {\n\t\t\tpingStat.Ticks = time.Now().Unix() - pingStat.Ticks\n\t\t\tpingStat.Responded = true\n\t\t}\n\t}\n}", "func (c *Aggregator) Update(_ context.Context, number number.Number, desc *sdkapi.Descriptor) error {\n\tnow := time.Now()\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tc.samples = append(c.samples, Point{\n\t\tNumber: number,\n\t\tTime: now,\n\t})\n\n\treturn nil\n}", "func UpdateCount(w http.ResponseWriter, r *http.Request) {\n\n\tvar message Message\n\t_ = json.NewDecoder(r.Body).Decode(&message)\n\tid := message.ID\n\t\n\twrite(id, read(id) + message.Count) \n\n\t//broadcast in background routine\n\tgo func(msg Message) {\n broadcast(msg)\n\t}(message)\n\t\n\tfmt.Println(\"Broadcast done\")\n\tjson.NewEncoder(w).Encode(Message{ID : id, Count : read(id)})\n}", "func (s *IndexablePartitionClockStorage) update(clock PartitionClock) {\n\ts.VbNos = s.VbNos[:0]\n\ts.Seqs = s.Seqs[:0]\n\tfor vb, seq := range clock {\n\t\ts.VbNos = append(s.VbNos, vb)\n\t\ts.Seqs = append(s.Seqs, seq)\n\t}\n}", "func handleUpdate(w http.ResponseWriter, r *http.Request) {\n\tfmt.Printf(\"Received request: %v %v %v\\n\", r.Method, r.URL, r.Proto)\n\tbf.RepopulateBloomFilter()\n}", "func (s *stepsrvc) Update(ctx context.Context, p *step.StoredListOfSteps) (err error) {\n\ts.logger.Print(\"step.update\")\n\n\terr = s.db.UpdateOneStep(*p)\n\n\treturn err\n}", "func (w *Watcher) Update() {\n\tw.Action = true\n\tfits := w.SessionKey[:2]\n\tfmt.Println(\"[!] Attempting to update watcher: %s\", fits)\n\twriten, err := w.Connection.Write([]byte(\"Y\"))\n\tif writen != len([]byte(\"Y\")) {\n\t\tfmt.Println(\"[!]Error writting: unable to write\")\n\t}\n\tif err != nil {\n\t\tfmt.Printf(\"%s\", err)\n\t}\n\n}", "func (o *sampleUpdateHandler) Update(rw http.ResponseWriter, req *http.Request) {\n\to.UpdateHandler.Update(rw, req)\n}", "func (s *baseStore[T, E, TPtr, EPtr]) Update(ctx context.Context, object T) error {\n\teventPtr := s.newObjectEvent(ctx, UpdateEvent)\n\teventPtr.SetObject(object)\n\treturn s.createObjectEvent(ctx, eventPtr)\n}", "func (p *Peer) Update(ctx context.Context, info content.Info, fieldpaths ...string) (content.Info, error) {\n\treturn content.Info{}, errors.Wrapf(errdefs.ErrFailedPrecondition, \"update not supported on immutable content store\")\n}", "func (hg *Hg) Update() error {\n\treturn nil\n}", "func (ob *OrderBook) BatchUpdate() {\n\n}", "func (p *Polling) Update(data Polling) {\n\tdb.Model(p).Updates(data)\n}", "func (h *Handler) UpdateCount() {\n\th.Client.Do(\"INCR\", \"visitors\")\n}", "func (s *RPC) Update(c context.Context, id string, state rpc.State) error {\n\tworkflowID, err := strconv.ParseInt(id, 10, 64)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tworkflow, err := s.store.WorkflowLoad(workflowID)\n\tif err != nil {\n\t\tlog.Error().Msgf(\"error: rpc.update: cannot find workflow with id %d: %s\", workflowID, err)\n\t\treturn err\n\t}\n\n\tcurrentPipeline, err := s.store.GetPipeline(workflow.PipelineID)\n\tif err != nil {\n\t\tlog.Error().Msgf(\"error: cannot find pipeline with id %d: %s\", workflow.PipelineID, err)\n\t\treturn err\n\t}\n\n\tstep, err := s.store.StepChild(currentPipeline, workflow.PID, state.Step)\n\tif err != nil {\n\t\tlog.Error().Msgf(\"error: cannot find step with name %s: %s\", state.Step, err)\n\t\treturn err\n\t}\n\n\trepo, err := s.store.GetRepo(currentPipeline.RepoID)\n\tif err != nil {\n\t\tlog.Error().Msgf(\"error: cannot find repo with id %d: %s\", currentPipeline.RepoID, err)\n\t\treturn err\n\t}\n\n\tif err := pipeline.UpdateStepStatus(s.store, step, state, currentPipeline.Started); err != nil {\n\t\tlog.Error().Err(err).Msg(\"rpc.update: cannot update step\")\n\t}\n\n\tif currentPipeline.Workflows, err = s.store.WorkflowGetTree(currentPipeline); err != nil {\n\t\tlog.Error().Err(err).Msg(\"can not build tree from step list\")\n\t\treturn err\n\t}\n\tmessage := pubsub.Message{\n\t\tLabels: map[string]string{\n\t\t\t\"repo\": repo.FullName,\n\t\t\t\"private\": strconv.FormatBool(repo.IsSCMPrivate),\n\t\t},\n\t}\n\tmessage.Data, _ = json.Marshal(model.Event{\n\t\tRepo: *repo,\n\t\tPipeline: *currentPipeline,\n\t})\n\tif err := s.pubsub.Publish(c, \"topic/events\", message); err != nil {\n\t\tlog.Error().Err(err).Msg(\"can not publish step list to\")\n\t}\n\n\treturn nil\n}", "func (cl *RestClient) Update() {\n}", "func (m *MemberlistEvents) NotifyUpdate(node *memberlist.Node) {\n\tif node.Meta != nil {\n\t\tmember := &MemberlistNode{node}\n\t\tm.toystore.AddMember(member)\n\t}\n}", "func (blt Bolt) Update(execute dbtx.Execute) error {\n\treturn blt.db.Update(func(tx *b.Tx) error {\n\t\treturn execute(tx.Bucket(blt.Bucket))\n\t})\n}", "func (pq *priorityQueue) update(item *item) {\n\theap.Fix(pq, item.index)\n}", "func (s *Service) Update(p *Price) error {\n\tname := strings.ToLower(p.ExchangeName)\n\ts.Lock()\n\n\tticker, ok := s.Tickers[name][p.Pair.Base.Item][p.Pair.Quote.Item][p.AssetType]\n\tif ok {\n\t\tticker.Last = p.Last\n\t\tticker.High = p.High\n\t\tticker.Low = p.Low\n\t\tticker.Bid = p.Bid\n\t\tticker.Ask = p.Ask\n\t\tticker.Volume = p.Volume\n\t\tticker.QuoteVolume = p.QuoteVolume\n\t\tticker.PriceATH = p.PriceATH\n\t\tticker.Open = p.Open\n\t\tticker.Close = p.Close\n\t\tticker.LastUpdated = p.LastUpdated\n\t\tids := append(ticker.Assoc, ticker.Main)\n\t\ts.Unlock()\n\t\treturn s.mux.Publish(ids, p)\n\t}\n\n\tswitch {\n\tcase s.Tickers[name] == nil:\n\t\ts.Tickers[name] = make(map[*currency.Item]map[*currency.Item]map[asset.Item]*Ticker)\n\t\tfallthrough\n\tcase s.Tickers[name][p.Pair.Base.Item] == nil:\n\t\ts.Tickers[name][p.Pair.Base.Item] = make(map[*currency.Item]map[asset.Item]*Ticker)\n\t\tfallthrough\n\tcase s.Tickers[name][p.Pair.Base.Item][p.Pair.Quote.Item] == nil:\n\t\ts.Tickers[name][p.Pair.Base.Item][p.Pair.Quote.Item] = make(map[asset.Item]*Ticker)\n\t}\n\n\terr := s.SetItemID(p, name)\n\tif err != nil {\n\t\ts.Unlock()\n\t\treturn err\n\t}\n\n\ts.Unlock()\n\treturn nil\n}", "func (summary *StorageSummary) Update(s3Object *s3Service.Object) {\n\tsummary.lock.Lock()\n\tdefer summary.lock.Unlock()\n\n\tsummary.Count++\n\tsummary.Size += *s3Object.Size\n}", "func (m *MemoryRewardStorage) Update(reward rewards.Reward) {\n\tfor index, r := range m.rewards {\n\t\tif r.ID == reward.ID {\n\t\t\tm.rewards[index] = reward\n\t\t}\n\t}\n}", "func (w *WeightsBatch) Update(id identity.ID, diff int64) {\n\tif w.diffs[id] += diff; w.diffs[id] == 0 {\n\t\tdelete(w.diffs, id)\n\t}\n\n\tw.totalDiff += diff\n}", "func (ds *RegularStateMachineWrapper) BatchedUpdate(entries []sm.Entry) ([]sm.Entry, error) {\n\tpanic(\"BatchedUpdate not supported in C++ regular state machine\")\n}", "func (svr *Server) update(){\n\tmsg := svr.queue.Dequeue()\n\tif msg != nil {\n\t\t// fmt.Println(\"server receives msg with vecClocks: \", msg.Vec)\n\t\t// fmt.Println(\"server has vecClocks: \", svr.vecClocks)\n\t\tsvr.vecClockCond.L.Lock()\n\t\tfor svr.vecClocks[msg.Id] != msg.Vec[msg.Id]-1 || !smallerEqualExceptI(msg.Vec, svr.vecClocks, msg.Id) {\n\t\t\tif svr.vecClocks[msg.Id] > msg.Vec[msg.Id]-1 {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tsvr.vecClockCond.Wait()\n\t\t}\n\t\t// update timestamp and write to local memory\n\t\tsvr.vecClocks[msg.Id] = msg.Vec[msg.Id]\n\t\t// fmt.Println(\"server increments vecClocks: \", svr.vecClocks)\n\t\tsvr.vecClockCond.Broadcast()\n\t\tsvr.vecClockCond.L.Unlock()\n\t\tif err := d.WriteString(msg.Key,msg.Val); err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n}", "func (s *ImagesByRepositoryRegistryStorage) Update(obj interface{}) (<-chan interface{}, error) {\n\treturn s.Create(obj)\n}", "func (m *DutyManager) Update(id []byte, freq float32, size uint32, datr string, codr string) error {\n\tm.InUpdate.ID = id\n\tm.InUpdate.Freq = freq\n\tm.InUpdate.Size = size\n\tm.InUpdate.Datr = datr\n\tm.InUpdate.Codr = codr\n\treturn m.Failures[\"Update\"]\n}" ]
[ "0.7061625", "0.66837144", "0.62871474", "0.6194512", "0.60975534", "0.6057079", "0.6047295", "0.5998641", "0.59809476", "0.59769446", "0.5959136", "0.5950485", "0.59360564", "0.5931388", "0.59304947", "0.5909306", "0.58996606", "0.58698773", "0.5844536", "0.582643", "0.57744294", "0.576627", "0.5764854", "0.5763409", "0.5751547", "0.5741046", "0.5715154", "0.5711809", "0.56965286", "0.5692599", "0.56925344", "0.56919825", "0.5691266", "0.5689351", "0.5685736", "0.5673346", "0.5652618", "0.5650574", "0.56505257", "0.5638403", "0.56357634", "0.5629177", "0.56217515", "0.5618214", "0.56171244", "0.561288", "0.5606886", "0.56067276", "0.5605679", "0.5602966", "0.5599198", "0.558979", "0.55858886", "0.5581626", "0.55711", "0.55707467", "0.556969", "0.5556084", "0.55545264", "0.55493176", "0.55478275", "0.553826", "0.55359733", "0.5535774", "0.5532951", "0.55299836", "0.5529957", "0.5524993", "0.5517901", "0.55127054", "0.55113345", "0.55035263", "0.54994434", "0.5498943", "0.5498581", "0.5488947", "0.5486635", "0.54854614", "0.54851735", "0.5476983", "0.54762423", "0.54733", "0.54709595", "0.54661316", "0.5460155", "0.54597616", "0.5439177", "0.54368466", "0.5436145", "0.54184306", "0.54159117", "0.54115", "0.5404204", "0.5402927", "0.53987646", "0.53985506", "0.53887045", "0.5386594", "0.5386203" ]
0.6672352
2
CredentialAssertionToProto converts a CredentialAssertion to its proto counterpart.
func CredentialAssertionToProto(assertion *CredentialAssertion) *wantypes.CredentialAssertion { if assertion == nil { return nil } return &wantypes.CredentialAssertion{ PublicKey: &wantypes.PublicKeyCredentialRequestOptions{ Challenge: assertion.Response.Challenge, TimeoutMs: int64(assertion.Response.Timeout), RpId: assertion.Response.RelyingPartyID, AllowCredentials: credentialDescriptorsToProto(assertion.Response.AllowedCredentials), Extensions: inputExtensionsToProto(assertion.Response.Extensions), UserVerification: string(assertion.Response.UserVerification), }, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CredentialAssertionResponseToProto(car *CredentialAssertionResponse) *wantypes.CredentialAssertionResponse {\n\tif car == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialAssertionResponse{\n\t\tType: car.Type,\n\t\tRawId: car.RawID,\n\t\tResponse: &wantypes.AuthenticatorAssertionResponse{\n\t\t\tClientDataJson: car.AssertionResponse.ClientDataJSON,\n\t\t\tAuthenticatorData: car.AssertionResponse.AuthenticatorData,\n\t\t\tSignature: car.AssertionResponse.Signature,\n\t\t\tUserHandle: car.AssertionResponse.UserHandle,\n\t\t},\n\t\tExtensions: outputExtensionsToProto(car.Extensions),\n\t}\n}", "func CredentialAssertionFromProto(assertion *wantypes.CredentialAssertion) *CredentialAssertion {\n\tif assertion == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialAssertion{\n\t\tResponse: publicKeyCredentialRequestOptionsFromProto(assertion.PublicKey),\n\t}\n}", "func CredentialCreationToProto(cc *CredentialCreation) *wantypes.CredentialCreation {\n\tif cc == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialCreation{\n\t\tPublicKey: &wantypes.PublicKeyCredentialCreationOptions{\n\t\t\tChallenge: cc.Response.Challenge,\n\t\t\tRp: rpEntityToProto(cc.Response.RelyingParty),\n\t\t\tUser: userEntityToProto(cc.Response.User),\n\t\t\tCredentialParameters: credentialParametersToProto(cc.Response.Parameters),\n\t\t\tTimeoutMs: int64(cc.Response.Timeout),\n\t\t\tExcludeCredentials: credentialDescriptorsToProto(cc.Response.CredentialExcludeList),\n\t\t\tAttestation: string(cc.Response.Attestation),\n\t\t\tExtensions: inputExtensionsToProto(cc.Response.Extensions),\n\t\t\tAuthenticatorSelection: authenticatorSelectionToProto(cc.Response.AuthenticatorSelection),\n\t\t},\n\t}\n}", "func CredentialCreationResponseToProto(ccr *CredentialCreationResponse) *wantypes.CredentialCreationResponse {\n\tif ccr == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialCreationResponse{\n\t\tType: ccr.Type,\n\t\tRawId: ccr.RawID,\n\t\tResponse: &wantypes.AuthenticatorAttestationResponse{\n\t\t\tClientDataJson: ccr.AttestationResponse.ClientDataJSON,\n\t\t\tAttestationObject: ccr.AttestationResponse.AttestationObject,\n\t\t},\n\t\tExtensions: outputExtensionsToProto(ccr.Extensions),\n\t}\n}", "func ServiceAccountToProto(resource *iam.ServiceAccount) *iampb.IamServiceAccount {\n\tp := &iampb.IamServiceAccount{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetUniqueId(dcl.ValueOrEmptyString(resource.UniqueId))\n\tp.SetEmail(dcl.ValueOrEmptyString(resource.Email))\n\tp.SetDisplayName(dcl.ValueOrEmptyString(resource.DisplayName))\n\tp.SetDescription(dcl.ValueOrEmptyString(resource.Description))\n\tp.SetOauth2ClientId(dcl.ValueOrEmptyString(resource.OAuth2ClientId))\n\tp.SetActasResources(IamServiceAccountActasResourcesToProto(resource.ActasResources))\n\tp.SetDisabled(dcl.ValueOrEmptyBool(resource.Disabled))\n\n\treturn p\n}", "func CredentialAssertionResponseFromProto(car *wantypes.CredentialAssertionResponse) *CredentialAssertionResponse {\n\tif car == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialAssertionResponse{\n\t\tPublicKeyCredential: PublicKeyCredential{\n\t\t\tCredential: Credential{\n\t\t\t\tID: base64.RawURLEncoding.EncodeToString(car.RawId),\n\t\t\t\tType: car.Type,\n\t\t\t},\n\t\t\tRawID: car.RawId,\n\t\t\tExtensions: outputExtensionsFromProto(car.Extensions),\n\t\t},\n\t\tAssertionResponse: authenticatorAssertionResponseFromProto(car.Response),\n\t}\n}", "func CredentialAssertionFromProtocol(a *protocol.CredentialAssertion) *CredentialAssertion {\n\tif a == nil {\n\t\treturn nil\n\t}\n\n\treturn &CredentialAssertion{\n\t\tResponse: PublicKeyCredentialRequestOptions{\n\t\t\tChallenge: Challenge(a.Response.Challenge),\n\t\t\tTimeout: a.Response.Timeout,\n\t\t\tRelyingPartyID: a.Response.RelyingPartyID,\n\t\t\tAllowedCredentials: credentialDescriptorsFromProtocol(a.Response.AllowedCredentials),\n\t\t\tUserVerification: a.Response.UserVerification,\n\t\t\tExtensions: a.Response.Extensions,\n\t\t},\n\t}\n}", "func CertificateTemplateToProto(resource *beta.CertificateTemplate) *betapb.PrivatecaBetaCertificateTemplate {\n\tp := &betapb.PrivatecaBetaCertificateTemplate{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetPredefinedValues(PrivatecaBetaCertificateTemplatePredefinedValuesToProto(resource.PredefinedValues))\n\tp.SetIdentityConstraints(PrivatecaBetaCertificateTemplateIdentityConstraintsToProto(resource.IdentityConstraints))\n\tp.SetPassthroughExtensions(PrivatecaBetaCertificateTemplatePassthroughExtensionsToProto(resource.PassthroughExtensions))\n\tp.SetDescription(dcl.ValueOrEmptyString(resource.Description))\n\tp.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime))\n\tp.SetUpdateTime(dcl.ValueOrEmptyString(resource.UpdateTime))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetLocation(dcl.ValueOrEmptyString(resource.Location))\n\tmLabels := make(map[string]string, len(resource.Labels))\n\tfor k, r := range resource.Labels {\n\t\tmLabels[k] = r\n\t}\n\tp.SetLabels(mLabels)\n\n\treturn p\n}", "func ComputeBetaInstanceTemplatePropertiesServiceAccountsToProto(o *beta.InstanceTemplatePropertiesServiceAccounts) *betapb.ComputeBetaInstanceTemplatePropertiesServiceAccounts {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.ComputeBetaInstanceTemplatePropertiesServiceAccounts{\n\t\tEmail: dcl.ValueOrEmptyString(o.Email),\n\t}\n\tfor _, r := range o.Scopes {\n\t\tp.Scopes = append(p.Scopes, r)\n\t}\n\treturn p\n}", "func PrivatecaBetaCertificateTemplateIdentityConstraintsToProto(o *beta.CertificateTemplateIdentityConstraints) *betapb.PrivatecaBetaCertificateTemplateIdentityConstraints {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.PrivatecaBetaCertificateTemplateIdentityConstraints{}\n\tp.SetCelExpression(PrivatecaBetaCertificateTemplateIdentityConstraintsCelExpressionToProto(o.CelExpression))\n\tp.SetAllowSubjectPassthrough(dcl.ValueOrEmptyBool(o.AllowSubjectPassthrough))\n\tp.SetAllowSubjectAltNamesPassthrough(dcl.ValueOrEmptyBool(o.AllowSubjectAltNamesPassthrough))\n\treturn p\n}", "func CryptoKeyToProto(resource *beta.CryptoKey) *betapb.CloudkmsBetaCryptoKey {\n\tp := &betapb.CloudkmsBetaCryptoKey{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetPrimary(CloudkmsBetaCryptoKeyPrimaryToProto(resource.Primary))\n\tp.SetPurpose(CloudkmsBetaCryptoKeyPurposeEnumToProto(resource.Purpose))\n\tp.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime))\n\tp.SetNextRotationTime(dcl.ValueOrEmptyString(resource.NextRotationTime))\n\tp.SetRotationPeriod(dcl.ValueOrEmptyString(resource.RotationPeriod))\n\tp.SetVersionTemplate(CloudkmsBetaCryptoKeyVersionTemplateToProto(resource.VersionTemplate))\n\tp.SetImportOnly(dcl.ValueOrEmptyBool(resource.ImportOnly))\n\tp.SetDestroyScheduledDuration(dcl.ValueOrEmptyString(resource.DestroyScheduledDuration))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetLocation(dcl.ValueOrEmptyString(resource.Location))\n\tp.SetKeyRing(dcl.ValueOrEmptyString(resource.KeyRing))\n\tmLabels := make(map[string]string, len(resource.Labels))\n\tfor k, r := range resource.Labels {\n\t\tmLabels[k] = r\n\t}\n\tp.SetLabels(mLabels)\n\n\treturn p\n}", "func ProtoToServiceAccount(p *iampb.IamServiceAccount) *iam.ServiceAccount {\n\tobj := &iam.ServiceAccount{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tProject: dcl.StringOrNil(p.GetProject()),\n\t\tUniqueId: dcl.StringOrNil(p.GetUniqueId()),\n\t\tEmail: dcl.StringOrNil(p.GetEmail()),\n\t\tDisplayName: dcl.StringOrNil(p.GetDisplayName()),\n\t\tDescription: dcl.StringOrNil(p.GetDescription()),\n\t\tOAuth2ClientId: dcl.StringOrNil(p.GetOauth2ClientId()),\n\t\tActasResources: ProtoToIamServiceAccountActasResources(p.GetActasResources()),\n\t\tDisabled: dcl.Bool(p.GetDisabled()),\n\t}\n\treturn obj\n}", "func CloudkmsBetaCryptoKeyVersionTemplateToProto(o *beta.CryptoKeyVersionTemplate) *betapb.CloudkmsBetaCryptoKeyVersionTemplate {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.CloudkmsBetaCryptoKeyVersionTemplate{}\n\tp.SetProtectionLevel(CloudkmsBetaCryptoKeyVersionTemplateProtectionLevelEnumToProto(o.ProtectionLevel))\n\tp.SetAlgorithm(CloudkmsBetaCryptoKeyVersionTemplateAlgorithmEnumToProto(o.Algorithm))\n\treturn p\n}", "func ContainerClusterAuthenticatorGroupsConfigToProto(o *container.ClusterAuthenticatorGroupsConfig) *containerpb.ContainerClusterAuthenticatorGroupsConfig {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &containerpb.ContainerClusterAuthenticatorGroupsConfig{\n\t\tEnabled: dcl.ValueOrEmptyBool(o.Enabled),\n\t\tSecurityGroup: dcl.ValueOrEmptyString(o.SecurityGroup),\n\t}\n\treturn p\n}", "func ProtoToCertificateTemplate(p *betapb.PrivatecaBetaCertificateTemplate) *beta.CertificateTemplate {\n\tobj := &beta.CertificateTemplate{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tPredefinedValues: ProtoToPrivatecaBetaCertificateTemplatePredefinedValues(p.GetPredefinedValues()),\n\t\tIdentityConstraints: ProtoToPrivatecaBetaCertificateTemplateIdentityConstraints(p.GetIdentityConstraints()),\n\t\tPassthroughExtensions: ProtoToPrivatecaBetaCertificateTemplatePassthroughExtensions(p.GetPassthroughExtensions()),\n\t\tDescription: dcl.StringOrNil(p.GetDescription()),\n\t\tCreateTime: dcl.StringOrNil(p.GetCreateTime()),\n\t\tUpdateTime: dcl.StringOrNil(p.GetUpdateTime()),\n\t\tProject: dcl.StringOrNil(p.GetProject()),\n\t\tLocation: dcl.StringOrNil(p.GetLocation()),\n\t}\n\treturn obj\n}", "func PrivatecaBetaCertificateTemplateIdentityConstraintsCelExpressionToProto(o *beta.CertificateTemplateIdentityConstraintsCelExpression) *betapb.PrivatecaBetaCertificateTemplateIdentityConstraintsCelExpression {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.PrivatecaBetaCertificateTemplateIdentityConstraintsCelExpression{}\n\tp.SetExpression(dcl.ValueOrEmptyString(o.Expression))\n\tp.SetTitle(dcl.ValueOrEmptyString(o.Title))\n\tp.SetDescription(dcl.ValueOrEmptyString(o.Description))\n\tp.SetLocation(dcl.ValueOrEmptyString(o.Location))\n\treturn p\n}", "func VertexaiEndpointEncryptionSpecToProto(o *vertexai.EndpointEncryptionSpec) *vertexaipb.VertexaiEndpointEncryptionSpec {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &vertexaipb.VertexaiEndpointEncryptionSpec{}\n\tp.SetKmsKeyName(dcl.ValueOrEmptyString(o.KmsKeyName))\n\treturn p\n}", "func SubscriptionToProto(resource *pubsublite.Subscription) *pubsublitepb.PubsubliteSubscription {\n\tp := &pubsublitepb.PubsubliteSubscription{\n\t\tName: dcl.ValueOrEmptyString(resource.Name),\n\t\tTopic: dcl.ValueOrEmptyString(resource.Topic),\n\t\tDeliveryConfig: PubsubliteSubscriptionDeliveryConfigToProto(resource.DeliveryConfig),\n\t\tProject: dcl.ValueOrEmptyString(resource.Project),\n\t\tLocation: dcl.ValueOrEmptyString(resource.Location),\n\t}\n\n\treturn p\n}", "func PrivatecaBetaCertificateTemplatePassthroughExtensionsToProto(o *beta.CertificateTemplatePassthroughExtensions) *betapb.PrivatecaBetaCertificateTemplatePassthroughExtensions {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.PrivatecaBetaCertificateTemplatePassthroughExtensions{}\n\tsKnownExtensions := make([]betapb.PrivatecaBetaCertificateTemplatePassthroughExtensionsKnownExtensionsEnum, len(o.KnownExtensions))\n\tfor i, r := range o.KnownExtensions {\n\t\tsKnownExtensions[i] = betapb.PrivatecaBetaCertificateTemplatePassthroughExtensionsKnownExtensionsEnum(betapb.PrivatecaBetaCertificateTemplatePassthroughExtensionsKnownExtensionsEnum_value[string(r)])\n\t}\n\tp.SetKnownExtensions(sKnownExtensions)\n\tsAdditionalExtensions := make([]*betapb.PrivatecaBetaCertificateTemplatePassthroughExtensionsAdditionalExtensions, len(o.AdditionalExtensions))\n\tfor i, r := range o.AdditionalExtensions {\n\t\tsAdditionalExtensions[i] = PrivatecaBetaCertificateTemplatePassthroughExtensionsAdditionalExtensionsToProto(&r)\n\t}\n\tp.SetAdditionalExtensions(sAdditionalExtensions)\n\treturn p\n}", "func (st *Account) ToProto() *accountpb.Account {\n\tacPb := &accountpb.Account{}\n\tacPb.Nonce = st.nonce\n\tif _, ok := accountpb.AccountType_name[st.accountType]; !ok {\n\t\tpanic(\"unknown account type\")\n\t}\n\tacPb.Type = accountpb.AccountType(st.accountType)\n\tif st.Balance != nil {\n\t\tacPb.Balance = st.Balance.String()\n\t}\n\tacPb.Root = make([]byte, len(st.Root))\n\tcopy(acPb.Root, st.Root[:])\n\tacPb.CodeHash = make([]byte, len(st.CodeHash))\n\tcopy(acPb.CodeHash, st.CodeHash)\n\tacPb.IsCandidate = st.isCandidate\n\tif st.votingWeight != nil {\n\t\tacPb.VotingWeight = st.votingWeight.Bytes()\n\t}\n\treturn acPb\n}", "func PrivatecaAlphaCaPoolIssuancePolicyIdentityConstraintsToProto(o *alpha.CaPoolIssuancePolicyIdentityConstraints) *alphapb.PrivatecaAlphaCaPoolIssuancePolicyIdentityConstraints {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &alphapb.PrivatecaAlphaCaPoolIssuancePolicyIdentityConstraints{}\n\tp.SetCelExpression(PrivatecaAlphaCaPoolIssuancePolicyIdentityConstraintsCelExpressionToProto(o.CelExpression))\n\tp.SetAllowSubjectPassthrough(dcl.ValueOrEmptyBool(o.AllowSubjectPassthrough))\n\tp.SetAllowSubjectAltNamesPassthrough(dcl.ValueOrEmptyBool(o.AllowSubjectAltNamesPassthrough))\n\treturn p\n}", "func ProtoToCryptoKey(p *betapb.CloudkmsBetaCryptoKey) *beta.CryptoKey {\n\tobj := &beta.CryptoKey{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tPrimary: ProtoToCloudkmsBetaCryptoKeyPrimary(p.GetPrimary()),\n\t\tPurpose: ProtoToCloudkmsBetaCryptoKeyPurposeEnum(p.GetPurpose()),\n\t\tCreateTime: dcl.StringOrNil(p.GetCreateTime()),\n\t\tNextRotationTime: dcl.StringOrNil(p.GetNextRotationTime()),\n\t\tRotationPeriod: dcl.StringOrNil(p.GetRotationPeriod()),\n\t\tVersionTemplate: ProtoToCloudkmsBetaCryptoKeyVersionTemplate(p.GetVersionTemplate()),\n\t\tImportOnly: dcl.Bool(p.GetImportOnly()),\n\t\tDestroyScheduledDuration: dcl.StringOrNil(p.GetDestroyScheduledDuration()),\n\t\tProject: dcl.StringOrNil(p.GetProject()),\n\t\tLocation: dcl.StringOrNil(p.GetLocation()),\n\t\tKeyRing: dcl.StringOrNil(p.GetKeyRing()),\n\t}\n\treturn obj\n}", "func (tn *ListNamespaceDescriptors) ToProto() proto.Message {\n\treturn &pb.ListNamespaceDescriptorsRequest{\n\t}\n}", "func (m *Mutate) ToProto() proto.Message {\n\tp, _, _ := m.toProto(false, nil)\n\treturn p\n}", "func CredentialCreationResponseFromProto(ccr *wantypes.CredentialCreationResponse) *CredentialCreationResponse {\n\tif ccr == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialCreationResponse{\n\t\tPublicKeyCredential: PublicKeyCredential{\n\t\t\tCredential: Credential{\n\t\t\t\tID: base64.RawURLEncoding.EncodeToString(ccr.RawId),\n\t\t\t\tType: ccr.Type,\n\t\t\t},\n\t\t\tRawID: ccr.RawId,\n\t\t\tExtensions: outputExtensionsFromProto(ccr.Extensions),\n\t\t},\n\t\tAttestationResponse: authenticatorAttestationResponseFromProto(ccr.Response),\n\t}\n}", "func BigqueryRoutineArgumentsDataTypeToProto(o *bigquery.RoutineArgumentsDataType) *bigquerypb.BigqueryRoutineArgumentsDataType {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &bigquerypb.BigqueryRoutineArgumentsDataType{}\n\tp.SetTypeKind(BigqueryRoutineArgumentsDataTypeTypeKindEnumToProto(o.TypeKind))\n\tp.SetArrayElementType(BigqueryRoutineArgumentsDataTypeToProto(o.ArrayElementType))\n\tp.SetStructType(BigqueryRoutineArgumentsDataTypeStructTypeToProto(o.StructType))\n\treturn p\n}", "func ManagedSslCertificateToProto(resource *beta.ManagedSslCertificate) *betapb.ComputeBetaManagedSslCertificate {\n\tp := &betapb.ComputeBetaManagedSslCertificate{\n\t\tName: dcl.ValueOrEmptyString(resource.Name),\n\t\tId: dcl.ValueOrEmptyInt64(resource.Id),\n\t\tCreationTimestamp: dcl.ValueOrEmptyString(resource.CreationTimestamp),\n\t\tDescription: dcl.ValueOrEmptyString(resource.Description),\n\t\tSelfLink: dcl.ValueOrEmptyString(resource.SelfLink),\n\t\tManaged: ComputeBetaManagedSslCertificateManagedToProto(resource.Managed),\n\t\tType: ComputeBetaManagedSslCertificateTypeEnumToProto(resource.Type),\n\t\tExpireTime: dcl.ValueOrEmptyString(resource.ExpireTime),\n\t\tProject: dcl.ValueOrEmptyString(resource.Project),\n\t}\n\tfor _, r := range resource.SubjectAlternativeNames {\n\t\tp.SubjectAlternativeNames = append(p.SubjectAlternativeNames, r)\n\t}\n\n\treturn p\n}", "func BigqueryRoutineArgumentsDataTypeStructTypeToProto(o *bigquery.RoutineArgumentsDataTypeStructType) *bigquerypb.BigqueryRoutineArgumentsDataTypeStructType {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &bigquerypb.BigqueryRoutineArgumentsDataTypeStructType{}\n\tsFields := make([]*bigquerypb.BigqueryRoutineArgumentsDataTypeStructTypeFields, len(o.Fields))\n\tfor i, r := range o.Fields {\n\t\tsFields[i] = BigqueryRoutineArgumentsDataTypeStructTypeFieldsToProto(&r)\n\t}\n\tp.SetFields(sFields)\n\treturn p\n}", "func (st *Account) ToProto() *iproto.AccountPb {\n\tacPb := &iproto.AccountPb{}\n\tacPb.Nonce = st.Nonce\n\tif st.Balance != nil {\n\t\tacPb.Balance = st.Balance.Bytes()\n\t}\n\tacPb.Root = make([]byte, hash.HashSize)\n\tcopy(acPb.Root, st.Root[:])\n\tacPb.CodeHash = make([]byte, len(st.CodeHash))\n\tcopy(acPb.CodeHash, st.CodeHash)\n\tacPb.IsCandidate = st.IsCandidate\n\tif st.VotingWeight != nil {\n\t\tacPb.VotingWeight = st.VotingWeight.Bytes()\n\t}\n\tacPb.Votee = st.Votee\n\treturn acPb\n}", "func ContainerClusterMasterAuthToProto(o *container.ClusterMasterAuth) *containerpb.ContainerClusterMasterAuth {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &containerpb.ContainerClusterMasterAuth{\n\t\tUsername: dcl.ValueOrEmptyString(o.Username),\n\t\tPassword: dcl.ValueOrEmptyString(o.Password),\n\t\tClientCertificateConfig: ContainerClusterMasterAuthClientCertificateConfigToProto(o.ClientCertificateConfig),\n\t\tClusterCaCertificate: dcl.ValueOrEmptyString(o.ClusterCaCertificate),\n\t\tClientCertificate: dcl.ValueOrEmptyString(o.ClientCertificate),\n\t\tClientKey: dcl.ValueOrEmptyString(o.ClientKey),\n\t}\n\treturn p\n}", "func CloudkmsBetaCryptoKeyPrimaryAttestationToProto(o *beta.CryptoKeyPrimaryAttestation) *betapb.CloudkmsBetaCryptoKeyPrimaryAttestation {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.CloudkmsBetaCryptoKeyPrimaryAttestation{}\n\tp.SetFormat(CloudkmsBetaCryptoKeyPrimaryAttestationFormatEnumToProto(o.Format))\n\tp.SetContent(dcl.ValueOrEmptyString(o.Content))\n\tp.SetCertChains(CloudkmsBetaCryptoKeyPrimaryAttestationCertChainsToProto(o.CertChains))\n\treturn p\n}", "func RecaptchaenterpriseKeyTestingOptionsToProto(o *recaptchaenterprise.KeyTestingOptions) *recaptchaenterprisepb.RecaptchaenterpriseKeyTestingOptions {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &recaptchaenterprisepb.RecaptchaenterpriseKeyTestingOptions{}\n\tp.SetTestingScore(dcl.ValueOrEmptyDouble(o.TestingScore))\n\tp.SetTestingChallenge(RecaptchaenterpriseKeyTestingOptionsTestingChallengeEnumToProto(o.TestingChallenge))\n\treturn p\n}", "func IamServiceAccountActasResourcesToProto(o *iam.ServiceAccountActasResources) *iampb.IamServiceAccountActasResources {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &iampb.IamServiceAccountActasResources{}\n\tsResources := make([]*iampb.IamServiceAccountActasResourcesResources, len(o.Resources))\n\tfor i, r := range o.Resources {\n\t\tsResources[i] = IamServiceAccountActasResourcesResourcesToProto(&r)\n\t}\n\tp.SetResources(sResources)\n\treturn p\n}", "func (t *Trade) ToProto() *pb.Trade {\n\ttrade := &pb.Trade{}\n\ttrade.Id = t.ID\n\ttrade.Time = t.Time.Unix()\n\ttrade.Char1Id = t.Char1id\n\ttrade.Char1Pp = t.Char1pp\n\ttrade.Char1Gp = t.Char1gp\n\ttrade.Char1Sp = t.Char1sp\n\ttrade.Char1Cp = t.Char1cp\n\ttrade.Char1Items = t.Char1items\n\ttrade.Char2Id = t.Char2id\n\ttrade.Char2Pp = t.Char2pp\n\ttrade.Char2Gp = t.Char2gp\n\ttrade.Char2Sp = t.Char2sp\n\ttrade.Char2Cp = t.Char2cp\n\ttrade.Char2Items = t.Char2items\n\treturn trade\n}", "func ComputeBetaInterconnectAttachmentPartnerMetadataToProto(o *beta.InterconnectAttachmentPartnerMetadata) *betapb.ComputeBetaInterconnectAttachmentPartnerMetadata {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.ComputeBetaInterconnectAttachmentPartnerMetadata{}\n\tp.SetPartnerName(dcl.ValueOrEmptyString(o.PartnerName))\n\tp.SetInterconnectName(dcl.ValueOrEmptyString(o.InterconnectName))\n\tp.SetPortalUrl(dcl.ValueOrEmptyString(o.PortalUrl))\n\treturn p\n}", "func PrivatecaBetaCertificateTemplatePredefinedValuesAdditionalExtensionsToProto(o *beta.CertificateTemplatePredefinedValuesAdditionalExtensions) *betapb.PrivatecaBetaCertificateTemplatePredefinedValuesAdditionalExtensions {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.PrivatecaBetaCertificateTemplatePredefinedValuesAdditionalExtensions{}\n\tp.SetObjectId(PrivatecaBetaCertificateTemplatePredefinedValuesAdditionalExtensionsObjectIdToProto(o.ObjectId))\n\tp.SetCritical(dcl.ValueOrEmptyBool(o.Critical))\n\tp.SetValue(dcl.ValueOrEmptyString(o.Value))\n\treturn p\n}", "func InspectTemplateToProto(resource *dlp.InspectTemplate) *dlppb.DlpInspectTemplate {\n\tp := &dlppb.DlpInspectTemplate{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetDisplayName(dcl.ValueOrEmptyString(resource.DisplayName))\n\tp.SetDescription(dcl.ValueOrEmptyString(resource.Description))\n\tp.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime))\n\tp.SetUpdateTime(dcl.ValueOrEmptyString(resource.UpdateTime))\n\tp.SetInspectConfig(DlpInspectTemplateInspectConfigToProto(resource.InspectConfig))\n\tp.SetLocationId(dcl.ValueOrEmptyString(resource.LocationId))\n\tp.SetParent(dcl.ValueOrEmptyString(resource.Parent))\n\tp.SetLocation(dcl.ValueOrEmptyString(resource.Location))\n\n\treturn p\n}", "func CaPoolToProto(resource *alpha.CaPool) *alphapb.PrivatecaAlphaCaPool {\n\tp := &alphapb.PrivatecaAlphaCaPool{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetTier(PrivatecaAlphaCaPoolTierEnumToProto(resource.Tier))\n\tp.SetIssuancePolicy(PrivatecaAlphaCaPoolIssuancePolicyToProto(resource.IssuancePolicy))\n\tp.SetPublishingOptions(PrivatecaAlphaCaPoolPublishingOptionsToProto(resource.PublishingOptions))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetLocation(dcl.ValueOrEmptyString(resource.Location))\n\tmLabels := make(map[string]string, len(resource.Labels))\n\tfor k, r := range resource.Labels {\n\t\tmLabels[k] = r\n\t}\n\tp.SetLabels(mLabels)\n\n\treturn p\n}", "func CredentialCreationFromProto(cc *wantypes.CredentialCreation) *CredentialCreation {\n\tif cc == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialCreation{\n\t\tResponse: publicKeyCredentialCreationOptionsFromProto(cc.PublicKey),\n\t}\n}", "func CloudkmsBetaCryptoKeyPurposeEnumToProto(e *beta.CryptoKeyPurposeEnum) betapb.CloudkmsBetaCryptoKeyPurposeEnum {\n\tif e == nil {\n\t\treturn betapb.CloudkmsBetaCryptoKeyPurposeEnum(0)\n\t}\n\tif v, ok := betapb.CloudkmsBetaCryptoKeyPurposeEnum_value[\"CryptoKeyPurposeEnum\"+string(*e)]; ok {\n\t\treturn betapb.CloudkmsBetaCryptoKeyPurposeEnum(v)\n\t}\n\treturn betapb.CloudkmsBetaCryptoKeyPurposeEnum(0)\n}", "func ContainerClusterDatabaseEncryptionToProto(o *container.ClusterDatabaseEncryption) *containerpb.ContainerClusterDatabaseEncryption {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &containerpb.ContainerClusterDatabaseEncryption{\n\t\tState: ContainerClusterDatabaseEncryptionStateEnumToProto(o.State),\n\t\tKeyName: dcl.ValueOrEmptyString(o.KeyName),\n\t}\n\treturn p\n}", "func BigqueryRoutineArgumentsToProto(o *bigquery.RoutineArguments) *bigquerypb.BigqueryRoutineArguments {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &bigquerypb.BigqueryRoutineArguments{}\n\tp.SetName(dcl.ValueOrEmptyString(o.Name))\n\tp.SetArgumentKind(BigqueryRoutineArgumentsArgumentKindEnumToProto(o.ArgumentKind))\n\tp.SetMode(BigqueryRoutineArgumentsModeEnumToProto(o.Mode))\n\tp.SetDataType(BigqueryRoutineArgumentsDataTypeToProto(o.DataType))\n\treturn p\n}", "func ContainerClusterBinaryAuthorizationToProto(o *container.ClusterBinaryAuthorization) *containerpb.ContainerClusterBinaryAuthorization {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &containerpb.ContainerClusterBinaryAuthorization{\n\t\tEnabled: dcl.ValueOrEmptyBool(o.Enabled),\n\t}\n\treturn p\n}", "func (ci CertIdentity) ToBytes() ([]byte, error) {\n\treturn proto.Marshal(ci.ToSerialized())\n}", "func AttestorToProto(resource *binaryauthorization.Attestor) *binaryauthorizationpb.BinaryauthorizationAttestor {\n\tp := &binaryauthorizationpb.BinaryauthorizationAttestor{\n\t\tName: dcl.ValueOrEmptyString(resource.Name),\n\t\tDescription: dcl.ValueOrEmptyString(resource.Description),\n\t\tUserOwnedGrafeasNote: BinaryauthorizationAttestorUserOwnedGrafeasNoteToProto(resource.UserOwnedGrafeasNote),\n\t\tUpdateTime: dcl.ValueOrEmptyString(resource.UpdateTime),\n\t\tProject: dcl.ValueOrEmptyString(resource.Project),\n\t}\n\n\treturn p\n}", "func DomainMappingToProto(resource *appengine.DomainMapping) *appenginepb.AppengineDomainMapping {\n\tp := &appenginepb.AppengineDomainMapping{\n\t\tSelfLink: dcl.ValueOrEmptyString(resource.SelfLink),\n\t\tName: dcl.ValueOrEmptyString(resource.Name),\n\t\tSslSettings: AppengineDomainMappingSslSettingsToProto(resource.SslSettings),\n\t\tApp: dcl.ValueOrEmptyString(resource.App),\n\t}\n\tfor _, r := range resource.ResourceRecords {\n\t\tp.ResourceRecords = append(p.ResourceRecords, AppengineDomainMappingResourceRecordsToProto(&r))\n\t}\n\n\treturn p\n}", "func SignatureToProto(sig interfaces.Signature) *Signature {\n\tif sig == nil {\n\t\treturn nil\n\t}\n\tpb := NewEmptySignature()\n\tpb.Raw = sig.Serialize()\n\treturn pb\n}", "func PrivatecaAlphaCaPoolIssuancePolicyIdentityConstraintsCelExpressionToProto(o *alpha.CaPoolIssuancePolicyIdentityConstraintsCelExpression) *alphapb.PrivatecaAlphaCaPoolIssuancePolicyIdentityConstraintsCelExpression {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &alphapb.PrivatecaAlphaCaPoolIssuancePolicyIdentityConstraintsCelExpression{}\n\tp.SetExpression(dcl.ValueOrEmptyString(o.Expression))\n\tp.SetTitle(dcl.ValueOrEmptyString(o.Title))\n\tp.SetDescription(dcl.ValueOrEmptyString(o.Description))\n\tp.SetLocation(dcl.ValueOrEmptyString(o.Location))\n\treturn p\n}", "func DeidentifyTemplateToProto(resource *beta.DeidentifyTemplate) *betapb.DlpBetaDeidentifyTemplate {\n\tp := &betapb.DlpBetaDeidentifyTemplate{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetDisplayName(dcl.ValueOrEmptyString(resource.DisplayName))\n\tp.SetDescription(dcl.ValueOrEmptyString(resource.Description))\n\tp.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime))\n\tp.SetUpdateTime(dcl.ValueOrEmptyString(resource.UpdateTime))\n\tp.SetDeidentifyConfig(DlpBetaDeidentifyTemplateDeidentifyConfigToProto(resource.DeidentifyConfig))\n\tp.SetLocationId(dcl.ValueOrEmptyString(resource.LocationId))\n\tp.SetParent(dcl.ValueOrEmptyString(resource.Parent))\n\tp.SetLocation(dcl.ValueOrEmptyString(resource.Location))\n\n\treturn p\n}", "func ComputeBetaManagedSslCertificateTypeEnumToProto(e *beta.ManagedSslCertificateTypeEnum) betapb.ComputeBetaManagedSslCertificateTypeEnum {\n\tif e == nil {\n\t\treturn betapb.ComputeBetaManagedSslCertificateTypeEnum(0)\n\t}\n\tif v, ok := betapb.ComputeBetaManagedSslCertificateTypeEnum_value[\"ManagedSslCertificateTypeEnum\"+string(*e)]; ok {\n\t\treturn betapb.ComputeBetaManagedSslCertificateTypeEnum(v)\n\t}\n\treturn betapb.ComputeBetaManagedSslCertificateTypeEnum(0)\n}", "func ComputeBetaInstanceTemplatePropertiesDisksDiskEncryptionKeyToProto(o *beta.InstanceTemplatePropertiesDisksDiskEncryptionKey) *betapb.ComputeBetaInstanceTemplatePropertiesDisksDiskEncryptionKey {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.ComputeBetaInstanceTemplatePropertiesDisksDiskEncryptionKey{\n\t\tRawKey: dcl.ValueOrEmptyString(o.RawKey),\n\t\tRsaEncryptedKey: dcl.ValueOrEmptyString(o.RsaEncryptedKey),\n\t\tSha256: dcl.ValueOrEmptyString(o.Sha256),\n\t}\n\treturn p\n}", "func KeyToProto(resource *recaptchaenterprise.Key) *recaptchaenterprisepb.RecaptchaenterpriseKey {\n\tp := &recaptchaenterprisepb.RecaptchaenterpriseKey{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetDisplayName(dcl.ValueOrEmptyString(resource.DisplayName))\n\tp.SetWebSettings(RecaptchaenterpriseKeyWebSettingsToProto(resource.WebSettings))\n\tp.SetAndroidSettings(RecaptchaenterpriseKeyAndroidSettingsToProto(resource.AndroidSettings))\n\tp.SetIosSettings(RecaptchaenterpriseKeyIosSettingsToProto(resource.IosSettings))\n\tp.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime))\n\tp.SetTestingOptions(RecaptchaenterpriseKeyTestingOptionsToProto(resource.TestingOptions))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tmLabels := make(map[string]string, len(resource.Labels))\n\tfor k, r := range resource.Labels {\n\t\tmLabels[k] = r\n\t}\n\tp.SetLabels(mLabels)\n\n\treturn p\n}", "func ComputeBetaInterconnectAttachmentTypeEnumToProto(e *beta.InterconnectAttachmentTypeEnum) betapb.ComputeBetaInterconnectAttachmentTypeEnum {\n\tif e == nil {\n\t\treturn betapb.ComputeBetaInterconnectAttachmentTypeEnum(0)\n\t}\n\tif v, ok := betapb.ComputeBetaInterconnectAttachmentTypeEnum_value[\"InterconnectAttachmentTypeEnum\"+string(*e)]; ok {\n\t\treturn betapb.ComputeBetaInterconnectAttachmentTypeEnum(v)\n\t}\n\treturn betapb.ComputeBetaInterconnectAttachmentTypeEnum(0)\n}", "func ContainerClusterConditionsToProto(o *container.ClusterConditions) *containerpb.ContainerClusterConditions {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &containerpb.ContainerClusterConditions{\n\t\tCode: dcl.ValueOrEmptyString(o.Code),\n\t\tMessage: dcl.ValueOrEmptyString(o.Message),\n\t}\n\treturn p\n}", "func sessionToProto(session *domain.Session) *protosession.Session {\n\treturn &protosession.Session{\n\t\tCreatedTimestamp: timeToProto(session.Token.Created),\n\t\tMech: proto.String(session.Token.AuthMechanism),\n\t\tDeviceType: proto.String(session.Token.DeviceType),\n\t}\n}", "func PrivatecaBetaCertificateTemplatePredefinedValuesKeyUsageToProto(o *beta.CertificateTemplatePredefinedValuesKeyUsage) *betapb.PrivatecaBetaCertificateTemplatePredefinedValuesKeyUsage {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.PrivatecaBetaCertificateTemplatePredefinedValuesKeyUsage{}\n\tp.SetBaseKeyUsage(PrivatecaBetaCertificateTemplatePredefinedValuesKeyUsageBaseKeyUsageToProto(o.BaseKeyUsage))\n\tp.SetExtendedKeyUsage(PrivatecaBetaCertificateTemplatePredefinedValuesKeyUsageExtendedKeyUsageToProto(o.ExtendedKeyUsage))\n\tsUnknownExtendedKeyUsages := make([]*betapb.PrivatecaBetaCertificateTemplatePredefinedValuesKeyUsageUnknownExtendedKeyUsages, len(o.UnknownExtendedKeyUsages))\n\tfor i, r := range o.UnknownExtendedKeyUsages {\n\t\tsUnknownExtendedKeyUsages[i] = PrivatecaBetaCertificateTemplatePredefinedValuesKeyUsageUnknownExtendedKeyUsagesToProto(&r)\n\t}\n\tp.SetUnknownExtendedKeyUsages(sUnknownExtendedKeyUsages)\n\treturn p\n}", "func ContainerClusterAddonsConfigHttpLoadBalancingToProto(o *container.ClusterAddonsConfigHttpLoadBalancing) *containerpb.ContainerClusterAddonsConfigHttpLoadBalancing {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &containerpb.ContainerClusterAddonsConfigHttpLoadBalancing{\n\t\tDisabled: dcl.ValueOrEmptyBool(o.Disabled),\n\t}\n\treturn p\n}", "func ProtoToKey(p *recaptchaenterprisepb.RecaptchaenterpriseKey) *recaptchaenterprise.Key {\n\tobj := &recaptchaenterprise.Key{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tDisplayName: dcl.StringOrNil(p.GetDisplayName()),\n\t\tWebSettings: ProtoToRecaptchaenterpriseKeyWebSettings(p.GetWebSettings()),\n\t\tAndroidSettings: ProtoToRecaptchaenterpriseKeyAndroidSettings(p.GetAndroidSettings()),\n\t\tIosSettings: ProtoToRecaptchaenterpriseKeyIosSettings(p.GetIosSettings()),\n\t\tCreateTime: dcl.StringOrNil(p.GetCreateTime()),\n\t\tTestingOptions: ProtoToRecaptchaenterpriseKeyTestingOptions(p.GetTestingOptions()),\n\t\tProject: dcl.StringOrNil(p.GetProject()),\n\t}\n\treturn obj\n}", "func PrivatecaAlphaCaPoolIssuancePolicyPassthroughExtensionsToProto(o *alpha.CaPoolIssuancePolicyPassthroughExtensions) *alphapb.PrivatecaAlphaCaPoolIssuancePolicyPassthroughExtensions {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &alphapb.PrivatecaAlphaCaPoolIssuancePolicyPassthroughExtensions{}\n\tsKnownExtensions := make([]alphapb.PrivatecaAlphaCaPoolIssuancePolicyPassthroughExtensionsKnownExtensionsEnum, len(o.KnownExtensions))\n\tfor i, r := range o.KnownExtensions {\n\t\tsKnownExtensions[i] = alphapb.PrivatecaAlphaCaPoolIssuancePolicyPassthroughExtensionsKnownExtensionsEnum(alphapb.PrivatecaAlphaCaPoolIssuancePolicyPassthroughExtensionsKnownExtensionsEnum_value[string(r)])\n\t}\n\tp.SetKnownExtensions(sKnownExtensions)\n\tsAdditionalExtensions := make([]*alphapb.PrivatecaAlphaCaPoolIssuancePolicyPassthroughExtensionsAdditionalExtensions, len(o.AdditionalExtensions))\n\tfor i, r := range o.AdditionalExtensions {\n\t\tsAdditionalExtensions[i] = PrivatecaAlphaCaPoolIssuancePolicyPassthroughExtensionsAdditionalExtensionsToProto(&r)\n\t}\n\tp.SetAdditionalExtensions(sAdditionalExtensions)\n\treturn p\n}", "func WorkloadIdentityPoolToProto(resource *beta.WorkloadIdentityPool) *betapb.IamBetaWorkloadIdentityPool {\n\tp := &betapb.IamBetaWorkloadIdentityPool{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetDisplayName(dcl.ValueOrEmptyString(resource.DisplayName))\n\tp.SetDescription(dcl.ValueOrEmptyString(resource.Description))\n\tp.SetState(IamBetaWorkloadIdentityPoolStateEnumToProto(resource.State))\n\tp.SetDisabled(dcl.ValueOrEmptyBool(resource.Disabled))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetLocation(dcl.ValueOrEmptyString(resource.Location))\n\n\treturn p\n}", "func PrivatecaBetaCertificateTemplatePassthroughExtensionsAdditionalExtensionsToProto(o *beta.CertificateTemplatePassthroughExtensionsAdditionalExtensions) *betapb.PrivatecaBetaCertificateTemplatePassthroughExtensionsAdditionalExtensions {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.PrivatecaBetaCertificateTemplatePassthroughExtensionsAdditionalExtensions{}\n\tsObjectIdPath := make([]int64, len(o.ObjectIdPath))\n\tfor i, r := range o.ObjectIdPath {\n\t\tsObjectIdPath[i] = r\n\t}\n\tp.SetObjectIdPath(sObjectIdPath)\n\treturn p\n}", "func ComputeBetaInterconnectAttachmentEncryptionEnumToProto(e *beta.InterconnectAttachmentEncryptionEnum) betapb.ComputeBetaInterconnectAttachmentEncryptionEnum {\n\tif e == nil {\n\t\treturn betapb.ComputeBetaInterconnectAttachmentEncryptionEnum(0)\n\t}\n\tif v, ok := betapb.ComputeBetaInterconnectAttachmentEncryptionEnum_value[\"InterconnectAttachmentEncryptionEnum\"+string(*e)]; ok {\n\t\treturn betapb.ComputeBetaInterconnectAttachmentEncryptionEnum(v)\n\t}\n\treturn betapb.ComputeBetaInterconnectAttachmentEncryptionEnum(0)\n}", "func ComputeBetaInstanceTemplatePropertiesDisksInitializeParamsToProto(o *beta.InstanceTemplatePropertiesDisksInitializeParams) *betapb.ComputeBetaInstanceTemplatePropertiesDisksInitializeParams {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.ComputeBetaInstanceTemplatePropertiesDisksInitializeParams{\n\t\tDiskName: dcl.ValueOrEmptyString(o.DiskName),\n\t\tDiskSizeGb: dcl.ValueOrEmptyInt64(o.DiskSizeGb),\n\t\tDiskType: dcl.ValueOrEmptyString(o.DiskType),\n\t\tSourceImage: dcl.ValueOrEmptyString(o.SourceImage),\n\t\tSourceSnapshot: dcl.ValueOrEmptyString(o.SourceSnapshot),\n\t\tSourceSnapshotEncryptionKey: ComputeBetaInstanceTemplatePropertiesDisksInitializeParamsSourceSnapshotEncryptionKeyToProto(o.SourceSnapshotEncryptionKey),\n\t\tDescription: dcl.ValueOrEmptyString(o.Description),\n\t\tOnUpdateAction: dcl.ValueOrEmptyString(o.OnUpdateAction),\n\t\tSourceImageEncryptionKey: ComputeBetaInstanceTemplatePropertiesDisksInitializeParamsSourceImageEncryptionKeyToProto(o.SourceImageEncryptionKey),\n\t}\n\tp.Labels = make(map[string]string)\n\tfor k, r := range o.Labels {\n\t\tp.Labels[k] = r\n\t}\n\tfor _, r := range o.ResourcePolicies {\n\t\tp.ResourcePolicies = append(p.ResourcePolicies, r)\n\t}\n\treturn p\n}", "func DlpInspectTemplateInspectConfigLimitsToProto(o *dlp.InspectTemplateInspectConfigLimits) *dlppb.DlpInspectTemplateInspectConfigLimits {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &dlppb.DlpInspectTemplateInspectConfigLimits{}\n\tp.SetMaxFindingsPerItem(dcl.ValueOrEmptyInt64(o.MaxFindingsPerItem))\n\tp.SetMaxFindingsPerRequest(dcl.ValueOrEmptyInt64(o.MaxFindingsPerRequest))\n\tsMaxFindingsPerInfoType := make([]*dlppb.DlpInspectTemplateInspectConfigLimitsMaxFindingsPerInfoType, len(o.MaxFindingsPerInfoType))\n\tfor i, r := range o.MaxFindingsPerInfoType {\n\t\tsMaxFindingsPerInfoType[i] = DlpInspectTemplateInspectConfigLimitsMaxFindingsPerInfoTypeToProto(&r)\n\t}\n\tp.SetMaxFindingsPerInfoType(sMaxFindingsPerInfoType)\n\treturn p\n}", "func VertexaiModelEncryptionSpecToProto(o *vertexai.ModelEncryptionSpec) *vertexaipb.VertexaiModelEncryptionSpec {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &vertexaipb.VertexaiModelEncryptionSpec{}\n\tp.SetKmsKeyName(dcl.ValueOrEmptyString(o.KmsKeyName))\n\treturn p\n}", "func ContainerClusterNetworkPolicyToProto(o *container.ClusterNetworkPolicy) *containerpb.ContainerClusterNetworkPolicy {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &containerpb.ContainerClusterNetworkPolicy{\n\t\tProvider: ContainerClusterNetworkPolicyProviderEnumToProto(o.Provider),\n\t\tEnabled: dcl.ValueOrEmptyBool(o.Enabled),\n\t}\n\treturn p\n}", "func IamServiceAccountActasResourcesResourcesToProto(o *iam.ServiceAccountActasResourcesResources) *iampb.IamServiceAccountActasResourcesResources {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &iampb.IamServiceAccountActasResourcesResources{}\n\tp.SetFullResourceName(dcl.ValueOrEmptyString(o.FullResourceName))\n\treturn p\n}", "func (e *Email) ToProto() *emailService.Email {\n\treturn &emailService.Email{\n\t\tEmailID: e.EmailID.String(),\n\t\tFrom: e.From,\n\t\tTo: e.To,\n\t\tSubject: e.Subject,\n\t\tMessage: e.Subject,\n\t\tCreatedAt: timestamppb.New(e.CreatedAt),\n\t}\n}", "func BigqueryRoutineArgumentsDataTypeStructTypeFieldsToProto(o *bigquery.RoutineArgumentsDataTypeStructTypeFields) *bigquerypb.BigqueryRoutineArgumentsDataTypeStructTypeFields {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &bigquerypb.BigqueryRoutineArgumentsDataTypeStructTypeFields{}\n\tp.SetName(dcl.ValueOrEmptyString(o.Name))\n\tp.SetType(BigqueryRoutineArgumentsDataTypeToProto(o.Type))\n\treturn p\n}", "func (t *trade) ToProto() *datastreams_pb.Trade {\n\treturn &datastreams_pb.Trade{\n\t\tTradePrice: t.tradePrice,\n\t\tTradeQuantity: t.tradeQuantity,\n\t\tTradeTime: t.tradeTime,\n\t}\n}", "func InstanceTemplateToProto(resource *beta.InstanceTemplate) *betapb.ComputeBetaInstanceTemplate {\n\tp := &betapb.ComputeBetaInstanceTemplate{\n\t\tCreationTimestamp: dcl.ValueOrEmptyString(resource.CreationTimestamp),\n\t\tDescription: dcl.ValueOrEmptyString(resource.Description),\n\t\tId: dcl.ValueOrEmptyInt64(resource.Id),\n\t\tSelfLink: dcl.ValueOrEmptyString(resource.SelfLink),\n\t\tName: dcl.ValueOrEmptyString(resource.Name),\n\t\tProperties: ComputeBetaInstanceTemplatePropertiesToProto(resource.Properties),\n\t\tProject: dcl.ValueOrEmptyString(resource.Project),\n\t}\n\n\treturn p\n}", "func AppengineDomainMappingSslSettingsToProto(o *appengine.DomainMappingSslSettings) *appenginepb.AppengineDomainMappingSslSettings {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &appenginepb.AppengineDomainMappingSslSettings{\n\t\tCertificateId: dcl.ValueOrEmptyString(o.CertificateId),\n\t\tSslManagementType: AppengineDomainMappingSslSettingsSslManagementTypeEnumToProto(o.SslManagementType),\n\t\tPendingManagedCertificateId: dcl.ValueOrEmptyString(o.PendingManagedCertificateId),\n\t}\n\treturn p\n}", "func ContainerClusterAutoscalingResourceLimitsToProto(o *container.ClusterAutoscalingResourceLimits) *containerpb.ContainerClusterAutoscalingResourceLimits {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &containerpb.ContainerClusterAutoscalingResourceLimits{\n\t\tResourceType: dcl.ValueOrEmptyString(o.ResourceType),\n\t\tMinimum: dcl.ValueOrEmptyInt64(o.Minimum),\n\t\tMaximum: dcl.ValueOrEmptyInt64(o.Maximum),\n\t}\n\treturn p\n}", "func ContainerawsAlphaAwsClusterAuthorizationToProto(o *alpha.AwsClusterAuthorization) *alphapb.ContainerawsAlphaAwsClusterAuthorization {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &alphapb.ContainerawsAlphaAwsClusterAuthorization{}\n\tfor _, r := range o.AdminUsers {\n\t\tp.AdminUsers = append(p.AdminUsers, ContainerawsAlphaAwsClusterAuthorizationAdminUsersToProto(&r))\n\t}\n\treturn p\n}", "func RoutineToProto(resource *bigquery.Routine) *bigquerypb.BigqueryRoutine {\n\tp := &bigquerypb.BigqueryRoutine{}\n\tp.SetEtag(dcl.ValueOrEmptyString(resource.Etag))\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetDataset(dcl.ValueOrEmptyString(resource.Dataset))\n\tp.SetRoutineType(BigqueryRoutineRoutineTypeEnumToProto(resource.RoutineType))\n\tp.SetCreationTime(dcl.ValueOrEmptyInt64(resource.CreationTime))\n\tp.SetLastModifiedTime(dcl.ValueOrEmptyInt64(resource.LastModifiedTime))\n\tp.SetLanguage(BigqueryRoutineLanguageEnumToProto(resource.Language))\n\tp.SetReturnType(BigqueryRoutineArgumentsDataTypeToProto(resource.ReturnType))\n\tp.SetDefinitionBody(dcl.ValueOrEmptyString(resource.DefinitionBody))\n\tp.SetDescription(dcl.ValueOrEmptyString(resource.Description))\n\tp.SetDeterminismLevel(BigqueryRoutineDeterminismLevelEnumToProto(resource.DeterminismLevel))\n\tp.SetStrictMode(dcl.ValueOrEmptyBool(resource.StrictMode))\n\tsArguments := make([]*bigquerypb.BigqueryRoutineArguments, len(resource.Arguments))\n\tfor i, r := range resource.Arguments {\n\t\tsArguments[i] = BigqueryRoutineArgumentsToProto(&r)\n\t}\n\tp.SetArguments(sArguments)\n\tsImportedLibraries := make([]string, len(resource.ImportedLibraries))\n\tfor i, r := range resource.ImportedLibraries {\n\t\tsImportedLibraries[i] = r\n\t}\n\tp.SetImportedLibraries(sImportedLibraries)\n\n\treturn p\n}", "func ToProto(sandbox *Sandbox) *types.Sandbox {\n\textensions := make(map[string]*gogo_types.Any)\n\tfor k, v := range sandbox.Extensions {\n\t\textensions[k] = protobuf.FromAny(v)\n\t}\n\treturn &types.Sandbox{\n\t\tSandboxID: sandbox.ID,\n\t\tRuntime: &types.Sandbox_Runtime{\n\t\t\tName: sandbox.Runtime.Name,\n\t\t\tOptions: protobuf.FromAny(sandbox.Runtime.Options),\n\t\t},\n\t\tLabels: sandbox.Labels,\n\t\tCreatedAt: protobuf.ToTimestamp(sandbox.CreatedAt),\n\t\tUpdatedAt: protobuf.ToTimestamp(sandbox.UpdatedAt),\n\t\tExtensions: extensions,\n\t\tSpec: protobuf.FromAny(sandbox.Spec),\n\t}\n}", "func CloudkmsBetaCryptoKeyVersionTemplateProtectionLevelEnumToProto(e *beta.CryptoKeyVersionTemplateProtectionLevelEnum) betapb.CloudkmsBetaCryptoKeyVersionTemplateProtectionLevelEnum {\n\tif e == nil {\n\t\treturn betapb.CloudkmsBetaCryptoKeyVersionTemplateProtectionLevelEnum(0)\n\t}\n\tif v, ok := betapb.CloudkmsBetaCryptoKeyVersionTemplateProtectionLevelEnum_value[\"CryptoKeyVersionTemplateProtectionLevelEnum\"+string(*e)]; ok {\n\t\treturn betapb.CloudkmsBetaCryptoKeyVersionTemplateProtectionLevelEnum(v)\n\t}\n\treturn betapb.CloudkmsBetaCryptoKeyVersionTemplateProtectionLevelEnum(0)\n}", "func RecaptchaenterpriseKeyTestingOptionsTestingChallengeEnumToProto(e *recaptchaenterprise.KeyTestingOptionsTestingChallengeEnum) recaptchaenterprisepb.RecaptchaenterpriseKeyTestingOptionsTestingChallengeEnum {\n\tif e == nil {\n\t\treturn recaptchaenterprisepb.RecaptchaenterpriseKeyTestingOptionsTestingChallengeEnum(0)\n\t}\n\tif v, ok := recaptchaenterprisepb.RecaptchaenterpriseKeyTestingOptionsTestingChallengeEnum_value[\"KeyTestingOptionsTestingChallengeEnum\"+string(*e)]; ok {\n\t\treturn recaptchaenterprisepb.RecaptchaenterpriseKeyTestingOptionsTestingChallengeEnum(v)\n\t}\n\treturn recaptchaenterprisepb.RecaptchaenterpriseKeyTestingOptionsTestingChallengeEnum(0)\n}", "func ResourceRecordSetToProto(resource *dns.ResourceRecordSet) *dnspb.DnsResourceRecordSet {\n\tp := &dnspb.DnsResourceRecordSet{\n\t\tDnsName: dcl.ValueOrEmptyString(resource.DnsName),\n\t\tDnsType: dcl.ValueOrEmptyString(resource.DnsType),\n\t\tTtl: dcl.ValueOrEmptyInt64(resource.Ttl),\n\t\tManagedZone: dcl.ValueOrEmptyString(resource.ManagedZone),\n\t\tProject: dcl.ValueOrEmptyString(resource.Project),\n\t}\n\tfor _, r := range resource.Target {\n\t\tp.Target = append(p.Target, r)\n\t}\n\n\treturn p\n}", "func BigqueryRoutineArgumentsArgumentKindEnumToProto(e *bigquery.RoutineArgumentsArgumentKindEnum) bigquerypb.BigqueryRoutineArgumentsArgumentKindEnum {\n\tif e == nil {\n\t\treturn bigquerypb.BigqueryRoutineArgumentsArgumentKindEnum(0)\n\t}\n\tif v, ok := bigquerypb.BigqueryRoutineArgumentsArgumentKindEnum_value[\"RoutineArgumentsArgumentKindEnum\"+string(*e)]; ok {\n\t\treturn bigquerypb.BigqueryRoutineArgumentsArgumentKindEnum(v)\n\t}\n\treturn bigquerypb.BigqueryRoutineArgumentsArgumentKindEnum(0)\n}", "func RunServiceTerminalConditionToProto(o *run.ServiceTerminalCondition) *runpb.RunServiceTerminalCondition {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &runpb.RunServiceTerminalCondition{}\n\tp.SetType(dcl.ValueOrEmptyString(o.Type))\n\tp.SetState(RunServiceTerminalConditionStateEnumToProto(o.State))\n\tp.SetMessage(dcl.ValueOrEmptyString(o.Message))\n\tp.SetLastTransitionTime(dcl.ValueOrEmptyString(o.LastTransitionTime))\n\tp.SetSeverity(RunServiceTerminalConditionSeverityEnumToProto(o.Severity))\n\tp.SetReason(RunServiceTerminalConditionReasonEnumToProto(o.Reason))\n\tp.SetInternalReason(RunServiceTerminalConditionInternalReasonEnumToProto(o.InternalReason))\n\tp.SetDomainMappingReason(RunServiceTerminalConditionDomainMappingReasonEnumToProto(o.DomainMappingReason))\n\tp.SetRevisionReason(RunServiceTerminalConditionRevisionReasonEnumToProto(o.RevisionReason))\n\tp.SetJobReason(RunServiceTerminalConditionJobReasonEnumToProto(o.JobReason))\n\treturn p\n}", "func ProtoToManagedSslCertificate(p *betapb.ComputeBetaManagedSslCertificate) *beta.ManagedSslCertificate {\n\tobj := &beta.ManagedSslCertificate{\n\t\tName: dcl.StringOrNil(p.Name),\n\t\tId: dcl.Int64OrNil(p.Id),\n\t\tCreationTimestamp: dcl.StringOrNil(p.CreationTimestamp),\n\t\tDescription: dcl.StringOrNil(p.Description),\n\t\tSelfLink: dcl.StringOrNil(p.SelfLink),\n\t\tManaged: ProtoToComputeBetaManagedSslCertificateManaged(p.GetManaged()),\n\t\tType: ProtoToComputeBetaManagedSslCertificateTypeEnum(p.GetType()),\n\t\tExpireTime: dcl.StringOrNil(p.ExpireTime),\n\t\tProject: dcl.StringOrNil(p.Project),\n\t}\n\tfor _, r := range p.GetSubjectAlternativeNames() {\n\t\tobj.SubjectAlternativeNames = append(obj.SubjectAlternativeNames, r)\n\t}\n\treturn obj\n}", "func ProtoToInterconnectAttachment(p *betapb.ComputeBetaInterconnectAttachment) *beta.InterconnectAttachment {\n\tobj := &beta.InterconnectAttachment{\n\t\tDescription: dcl.StringOrNil(p.GetDescription()),\n\t\tSelfLink: dcl.StringOrNil(p.GetSelfLink()),\n\t\tId: dcl.Int64OrNil(p.GetId()),\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tInterconnect: dcl.StringOrNil(p.GetInterconnect()),\n\t\tRouter: dcl.StringOrNil(p.GetRouter()),\n\t\tRegion: dcl.StringOrNil(p.GetRegion()),\n\t\tMtu: dcl.Int64OrNil(p.GetMtu()),\n\t\tPrivateInterconnectInfo: ProtoToComputeBetaInterconnectAttachmentPrivateInterconnectInfo(p.GetPrivateInterconnectInfo()),\n\t\tOperationalStatus: ProtoToComputeBetaInterconnectAttachmentOperationalStatusEnum(p.GetOperationalStatus()),\n\t\tCloudRouterIPAddress: dcl.StringOrNil(p.GetCloudRouterIpAddress()),\n\t\tCustomerRouterIPAddress: dcl.StringOrNil(p.GetCustomerRouterIpAddress()),\n\t\tType: ProtoToComputeBetaInterconnectAttachmentTypeEnum(p.GetType()),\n\t\tPairingKey: dcl.StringOrNil(p.GetPairingKey()),\n\t\tAdminEnabled: dcl.Bool(p.GetAdminEnabled()),\n\t\tVlanTag8021q: dcl.Int64OrNil(p.GetVlanTag8021Q()),\n\t\tEdgeAvailabilityDomain: ProtoToComputeBetaInterconnectAttachmentEdgeAvailabilityDomainEnum(p.GetEdgeAvailabilityDomain()),\n\t\tBandwidth: ProtoToComputeBetaInterconnectAttachmentBandwidthEnum(p.GetBandwidth()),\n\t\tPartnerMetadata: ProtoToComputeBetaInterconnectAttachmentPartnerMetadata(p.GetPartnerMetadata()),\n\t\tState: ProtoToComputeBetaInterconnectAttachmentStateEnum(p.GetState()),\n\t\tPartnerAsn: dcl.Int64OrNil(p.GetPartnerAsn()),\n\t\tEncryption: ProtoToComputeBetaInterconnectAttachmentEncryptionEnum(p.GetEncryption()),\n\t\tDataplaneVersion: dcl.Int64OrNil(p.GetDataplaneVersion()),\n\t\tSatisfiesPzs: dcl.Bool(p.GetSatisfiesPzs()),\n\t\tLabelFingerprint: dcl.StringOrNil(p.GetLabelFingerprint()),\n\t\tProject: dcl.StringOrNil(p.GetProject()),\n\t}\n\tfor _, r := range p.GetCandidateSubnets() {\n\t\tobj.CandidateSubnets = append(obj.CandidateSubnets, r)\n\t}\n\tfor _, r := range p.GetIpsecInternalAddresses() {\n\t\tobj.IpsecInternalAddresses = append(obj.IpsecInternalAddresses, r)\n\t}\n\treturn obj\n}", "func PrivatecaAlphaCaPoolIssuancePolicyBaselineValuesAdditionalExtensionsToProto(o *alpha.CaPoolIssuancePolicyBaselineValuesAdditionalExtensions) *alphapb.PrivatecaAlphaCaPoolIssuancePolicyBaselineValuesAdditionalExtensions {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &alphapb.PrivatecaAlphaCaPoolIssuancePolicyBaselineValuesAdditionalExtensions{}\n\tp.SetObjectId(PrivatecaAlphaCaPoolIssuancePolicyBaselineValuesAdditionalExtensionsObjectIdToProto(o.ObjectId))\n\tp.SetCritical(dcl.ValueOrEmptyBool(o.Critical))\n\tp.SetValue(dcl.ValueOrEmptyString(o.Value))\n\treturn p\n}", "func ContainerawsAlphaAwsClusterWorkloadIdentityConfigToProto(o *alpha.AwsClusterWorkloadIdentityConfig) *alphapb.ContainerawsAlphaAwsClusterWorkloadIdentityConfig {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &alphapb.ContainerawsAlphaAwsClusterWorkloadIdentityConfig{\n\t\tIssuerUri: dcl.ValueOrEmptyString(o.IssuerUri),\n\t\tWorkloadPool: dcl.ValueOrEmptyString(o.WorkloadPool),\n\t\tIdentityProvider: dcl.ValueOrEmptyString(o.IdentityProvider),\n\t}\n\treturn p\n}", "func CloudkmsBetaCryptoKeyVersionTemplateAlgorithmEnumToProto(e *beta.CryptoKeyVersionTemplateAlgorithmEnum) betapb.CloudkmsBetaCryptoKeyVersionTemplateAlgorithmEnum {\n\tif e == nil {\n\t\treturn betapb.CloudkmsBetaCryptoKeyVersionTemplateAlgorithmEnum(0)\n\t}\n\tif v, ok := betapb.CloudkmsBetaCryptoKeyVersionTemplateAlgorithmEnum_value[\"CryptoKeyVersionTemplateAlgorithmEnum\"+string(*e)]; ok {\n\t\treturn betapb.CloudkmsBetaCryptoKeyVersionTemplateAlgorithmEnum(v)\n\t}\n\treturn betapb.CloudkmsBetaCryptoKeyVersionTemplateAlgorithmEnum(0)\n}", "func DataprocAlphaClusterConfigSecurityConfigIdentityConfigToProto(o *alpha.ClusterConfigSecurityConfigIdentityConfig) *alphapb.DataprocAlphaClusterConfigSecurityConfigIdentityConfig {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &alphapb.DataprocAlphaClusterConfigSecurityConfigIdentityConfig{}\n\tmUserServiceAccountMapping := make(map[string]string, len(o.UserServiceAccountMapping))\n\tfor k, r := range o.UserServiceAccountMapping {\n\t\tmUserServiceAccountMapping[k] = r\n\t}\n\tp.SetUserServiceAccountMapping(mUserServiceAccountMapping)\n\treturn p\n}", "func (g *GroupImporterConfig) ToProto() (*configspb.GroupImporterConfig, error) {\n\tgConfig := &configspb.GroupImporterConfig{}\n\tif err := prototext.Unmarshal([]byte(g.ConfigProto), gConfig); err != nil {\n\t\treturn nil, err\n\t}\n\treturn gConfig, nil\n}", "func ClusterToProto(resource *alpha.Cluster) *alphapb.DataprocAlphaCluster {\n\tp := &alphapb.DataprocAlphaCluster{}\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetConfig(DataprocAlphaClusterConfigToProto(resource.Config))\n\tp.SetStatus(DataprocAlphaClusterStatusToProto(resource.Status))\n\tp.SetClusterUuid(dcl.ValueOrEmptyString(resource.ClusterUuid))\n\tp.SetMetrics(DataprocAlphaClusterMetricsToProto(resource.Metrics))\n\tp.SetLocation(dcl.ValueOrEmptyString(resource.Location))\n\tp.SetVirtualClusterConfig(DataprocAlphaClusterVirtualClusterConfigToProto(resource.VirtualClusterConfig))\n\tmLabels := make(map[string]string, len(resource.Labels))\n\tfor k, r := range resource.Labels {\n\t\tmLabels[k] = r\n\t}\n\tp.SetLabels(mLabels)\n\tsStatusHistory := make([]*alphapb.DataprocAlphaClusterStatusHistory, len(resource.StatusHistory))\n\tfor i, r := range resource.StatusHistory {\n\t\tsStatusHistory[i] = DataprocAlphaClusterStatusHistoryToProto(&r)\n\t}\n\tp.SetStatusHistory(sStatusHistory)\n\n\treturn p\n}", "func RunServiceTemplateExecutionEnvironmentEnumToProto(e *run.ServiceTemplateExecutionEnvironmentEnum) runpb.RunServiceTemplateExecutionEnvironmentEnum {\n\tif e == nil {\n\t\treturn runpb.RunServiceTemplateExecutionEnvironmentEnum(0)\n\t}\n\tif v, ok := runpb.RunServiceTemplateExecutionEnvironmentEnum_value[\"ServiceTemplateExecutionEnvironmentEnum\"+string(*e)]; ok {\n\t\treturn runpb.RunServiceTemplateExecutionEnvironmentEnum(v)\n\t}\n\treturn runpb.RunServiceTemplateExecutionEnvironmentEnum(0)\n}", "func InterconnectAttachmentToProto(resource *beta.InterconnectAttachment) *betapb.ComputeBetaInterconnectAttachment {\n\tp := &betapb.ComputeBetaInterconnectAttachment{}\n\tp.SetDescription(dcl.ValueOrEmptyString(resource.Description))\n\tp.SetSelfLink(dcl.ValueOrEmptyString(resource.SelfLink))\n\tp.SetId(dcl.ValueOrEmptyInt64(resource.Id))\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetInterconnect(dcl.ValueOrEmptyString(resource.Interconnect))\n\tp.SetRouter(dcl.ValueOrEmptyString(resource.Router))\n\tp.SetRegion(dcl.ValueOrEmptyString(resource.Region))\n\tp.SetMtu(dcl.ValueOrEmptyInt64(resource.Mtu))\n\tp.SetPrivateInterconnectInfo(ComputeBetaInterconnectAttachmentPrivateInterconnectInfoToProto(resource.PrivateInterconnectInfo))\n\tp.SetOperationalStatus(ComputeBetaInterconnectAttachmentOperationalStatusEnumToProto(resource.OperationalStatus))\n\tp.SetCloudRouterIpAddress(dcl.ValueOrEmptyString(resource.CloudRouterIPAddress))\n\tp.SetCustomerRouterIpAddress(dcl.ValueOrEmptyString(resource.CustomerRouterIPAddress))\n\tp.SetType(ComputeBetaInterconnectAttachmentTypeEnumToProto(resource.Type))\n\tp.SetPairingKey(dcl.ValueOrEmptyString(resource.PairingKey))\n\tp.SetAdminEnabled(dcl.ValueOrEmptyBool(resource.AdminEnabled))\n\tp.SetVlanTag8021Q(dcl.ValueOrEmptyInt64(resource.VlanTag8021q))\n\tp.SetEdgeAvailabilityDomain(ComputeBetaInterconnectAttachmentEdgeAvailabilityDomainEnumToProto(resource.EdgeAvailabilityDomain))\n\tp.SetBandwidth(ComputeBetaInterconnectAttachmentBandwidthEnumToProto(resource.Bandwidth))\n\tp.SetPartnerMetadata(ComputeBetaInterconnectAttachmentPartnerMetadataToProto(resource.PartnerMetadata))\n\tp.SetState(ComputeBetaInterconnectAttachmentStateEnumToProto(resource.State))\n\tp.SetPartnerAsn(dcl.ValueOrEmptyInt64(resource.PartnerAsn))\n\tp.SetEncryption(ComputeBetaInterconnectAttachmentEncryptionEnumToProto(resource.Encryption))\n\tp.SetDataplaneVersion(dcl.ValueOrEmptyInt64(resource.DataplaneVersion))\n\tp.SetSatisfiesPzs(dcl.ValueOrEmptyBool(resource.SatisfiesPzs))\n\tp.SetLabelFingerprint(dcl.ValueOrEmptyString(resource.LabelFingerprint))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tsCandidateSubnets := make([]string, len(resource.CandidateSubnets))\n\tfor i, r := range resource.CandidateSubnets {\n\t\tsCandidateSubnets[i] = r\n\t}\n\tp.SetCandidateSubnets(sCandidateSubnets)\n\tsIpsecInternalAddresses := make([]string, len(resource.IpsecInternalAddresses))\n\tfor i, r := range resource.IpsecInternalAddresses {\n\t\tsIpsecInternalAddresses[i] = r\n\t}\n\tp.SetIpsecInternalAddresses(sIpsecInternalAddresses)\n\tmLabels := make(map[string]string, len(resource.Labels))\n\tfor k, r := range resource.Labels {\n\t\tmLabels[k] = r\n\t}\n\tp.SetLabels(mLabels)\n\n\treturn p\n}", "func AppengineDomainMappingResourceRecordsToProto(o *appengine.DomainMappingResourceRecords) *appenginepb.AppengineDomainMappingResourceRecords {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &appenginepb.AppengineDomainMappingResourceRecords{\n\t\tName: dcl.ValueOrEmptyString(o.Name),\n\t\tRrdata: dcl.ValueOrEmptyString(o.Rrdata),\n\t\tType: AppengineDomainMappingResourceRecordsTypeEnumToProto(o.Type),\n\t}\n\treturn p\n}", "func ComputeSubnetworkLogConfigToProto(o *compute.SubnetworkLogConfig) *computepb.ComputeSubnetworkLogConfig {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &computepb.ComputeSubnetworkLogConfig{}\n\tp.SetAggregationInterval(ComputeSubnetworkLogConfigAggregationIntervalEnumToProto(o.AggregationInterval))\n\tp.SetFlowSampling(dcl.ValueOrEmptyDouble(o.FlowSampling))\n\tp.SetMetadata(ComputeSubnetworkLogConfigMetadataEnumToProto(o.Metadata))\n\treturn p\n}", "func CloudkmsBetaCryptoKeyPrimaryAttestationCertChainsToProto(o *beta.CryptoKeyPrimaryAttestationCertChains) *betapb.CloudkmsBetaCryptoKeyPrimaryAttestationCertChains {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.CloudkmsBetaCryptoKeyPrimaryAttestationCertChains{}\n\tsCaviumCerts := make([]string, len(o.CaviumCerts))\n\tfor i, r := range o.CaviumCerts {\n\t\tsCaviumCerts[i] = r\n\t}\n\tp.SetCaviumCerts(sCaviumCerts)\n\tsGoogleCardCerts := make([]string, len(o.GoogleCardCerts))\n\tfor i, r := range o.GoogleCardCerts {\n\t\tsGoogleCardCerts[i] = r\n\t}\n\tp.SetGoogleCardCerts(sGoogleCardCerts)\n\tsGooglePartitionCerts := make([]string, len(o.GooglePartitionCerts))\n\tfor i, r := range o.GooglePartitionCerts {\n\t\tsGooglePartitionCerts[i] = r\n\t}\n\tp.SetGooglePartitionCerts(sGooglePartitionCerts)\n\treturn p\n}", "func DlpJobTriggerInspectJobInspectConfigLimitsToProto(o *dlp.JobTriggerInspectJobInspectConfigLimits) *dlppb.DlpJobTriggerInspectJobInspectConfigLimits {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &dlppb.DlpJobTriggerInspectJobInspectConfigLimits{}\n\tp.SetMaxFindingsPerItem(dcl.ValueOrEmptyInt64(o.MaxFindingsPerItem))\n\tp.SetMaxFindingsPerRequest(dcl.ValueOrEmptyInt64(o.MaxFindingsPerRequest))\n\tsMaxFindingsPerInfoType := make([]*dlppb.DlpJobTriggerInspectJobInspectConfigLimitsMaxFindingsPerInfoType, len(o.MaxFindingsPerInfoType))\n\tfor i, r := range o.MaxFindingsPerInfoType {\n\t\tsMaxFindingsPerInfoType[i] = DlpJobTriggerInspectJobInspectConfigLimitsMaxFindingsPerInfoTypeToProto(&r)\n\t}\n\tp.SetMaxFindingsPerInfoType(sMaxFindingsPerInfoType)\n\treturn p\n}", "func AwsClusterToProto(resource *alpha.AwsCluster) *alphapb.ContainerawsAlphaAwsCluster {\n\tp := &alphapb.ContainerawsAlphaAwsCluster{\n\t\tName: dcl.ValueOrEmptyString(resource.Name),\n\t\tDescription: dcl.ValueOrEmptyString(resource.Description),\n\t\tNetworking: ContainerawsAlphaAwsClusterNetworkingToProto(resource.Networking),\n\t\tAwsRegion: dcl.ValueOrEmptyString(resource.AwsRegion),\n\t\tControlPlane: ContainerawsAlphaAwsClusterControlPlaneToProto(resource.ControlPlane),\n\t\tAuthorization: ContainerawsAlphaAwsClusterAuthorizationToProto(resource.Authorization),\n\t\tState: ContainerawsAlphaAwsClusterStateEnumToProto(resource.State),\n\t\tEndpoint: dcl.ValueOrEmptyString(resource.Endpoint),\n\t\tUid: dcl.ValueOrEmptyString(resource.Uid),\n\t\tReconciling: dcl.ValueOrEmptyBool(resource.Reconciling),\n\t\tCreateTime: dcl.ValueOrEmptyString(resource.CreateTime),\n\t\tUpdateTime: dcl.ValueOrEmptyString(resource.UpdateTime),\n\t\tEtag: dcl.ValueOrEmptyString(resource.Etag),\n\t\tWorkloadIdentityConfig: ContainerawsAlphaAwsClusterWorkloadIdentityConfigToProto(resource.WorkloadIdentityConfig),\n\t\tProject: dcl.ValueOrEmptyString(resource.Project),\n\t\tLocation: dcl.ValueOrEmptyString(resource.Location),\n\t}\n\n\treturn p\n}", "func DlpBetaDeidentifyTemplateDeidentifyConfigRecordTransformationsFieldTransformationsConditionExpressionsConditionsToProto(o *beta.DeidentifyTemplateDeidentifyConfigRecordTransformationsFieldTransformationsConditionExpressionsConditions) *betapb.DlpBetaDeidentifyTemplateDeidentifyConfigRecordTransformationsFieldTransformationsConditionExpressionsConditions {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.DlpBetaDeidentifyTemplateDeidentifyConfigRecordTransformationsFieldTransformationsConditionExpressionsConditions{}\n\tsConditions := make([]*betapb.DlpBetaDeidentifyTemplateDeidentifyConfigRecordTransformationsFieldTransformationsConditionExpressionsConditionsConditions, len(o.Conditions))\n\tfor i, r := range o.Conditions {\n\t\tsConditions[i] = DlpBetaDeidentifyTemplateDeidentifyConfigRecordTransformationsFieldTransformationsConditionExpressionsConditionsConditionsToProto(&r)\n\t}\n\tp.SetConditions(sConditions)\n\treturn p\n}", "func ContainerazureAlphaClusterWorkloadIdentityConfigToProto(o *alpha.ClusterWorkloadIdentityConfig) *alphapb.ContainerazureAlphaClusterWorkloadIdentityConfig {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &alphapb.ContainerazureAlphaClusterWorkloadIdentityConfig{}\n\tp.SetIssuerUri(dcl.ValueOrEmptyString(o.IssuerUri))\n\tp.SetWorkloadPool(dcl.ValueOrEmptyString(o.WorkloadPool))\n\tp.SetIdentityProvider(dcl.ValueOrEmptyString(o.IdentityProvider))\n\treturn p\n}", "func ComputeFirewallLogConfigToProto(o *compute.FirewallLogConfig) *computepb.ComputeFirewallLogConfig {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &computepb.ComputeFirewallLogConfig{\n\t\tEnable: dcl.ValueOrEmptyBool(o.Enable),\n\t}\n\treturn p\n}", "func ProtoToPrivatecaBetaCertificateTemplateIdentityConstraints(p *betapb.PrivatecaBetaCertificateTemplateIdentityConstraints) *beta.CertificateTemplateIdentityConstraints {\n\tif p == nil {\n\t\treturn nil\n\t}\n\tobj := &beta.CertificateTemplateIdentityConstraints{\n\t\tCelExpression: ProtoToPrivatecaBetaCertificateTemplateIdentityConstraintsCelExpression(p.GetCelExpression()),\n\t\tAllowSubjectPassthrough: dcl.Bool(p.GetAllowSubjectPassthrough()),\n\t\tAllowSubjectAltNamesPassthrough: dcl.Bool(p.GetAllowSubjectAltNamesPassthrough()),\n\t}\n\treturn obj\n}" ]
[ "0.74571794", "0.7233046", "0.6577429", "0.6498429", "0.63388383", "0.6290534", "0.59917104", "0.5907698", "0.5758109", "0.575023", "0.57271165", "0.56313354", "0.5559705", "0.5557", "0.5521528", "0.5480544", "0.54563236", "0.5406191", "0.5405703", "0.5396835", "0.5376432", "0.53671753", "0.5359245", "0.53434813", "0.52837867", "0.52607876", "0.524706", "0.52258277", "0.52254903", "0.5185729", "0.5182038", "0.5177857", "0.51734287", "0.51657236", "0.51580846", "0.515618", "0.51289374", "0.5124284", "0.5113849", "0.510961", "0.51090944", "0.5098815", "0.50984913", "0.5096994", "0.50939494", "0.50735724", "0.50579774", "0.5039904", "0.50367117", "0.5034876", "0.50279814", "0.5024807", "0.5024534", "0.50143707", "0.5006227", "0.49978444", "0.49929342", "0.4978226", "0.4973412", "0.49722216", "0.4968427", "0.49671668", "0.49614725", "0.4942822", "0.4942122", "0.49367034", "0.493605", "0.49306852", "0.49264514", "0.48969817", "0.48965663", "0.4879513", "0.4869676", "0.486741", "0.48619202", "0.486058", "0.48568594", "0.48502827", "0.48498207", "0.4844442", "0.48362786", "0.48339173", "0.48151565", "0.48127615", "0.48103893", "0.48083258", "0.48056358", "0.48041642", "0.48025456", "0.4802444", "0.48023194", "0.4784659", "0.47774848", "0.47680634", "0.47675577", "0.47663677", "0.47583526", "0.47553924", "0.47505847", "0.47481334" ]
0.86607736
0
CredentialAssertionResponseToProto converts a CredentialAssertionResponse to its proto counterpart.
func CredentialAssertionResponseToProto(car *CredentialAssertionResponse) *wantypes.CredentialAssertionResponse { if car == nil { return nil } return &wantypes.CredentialAssertionResponse{ Type: car.Type, RawId: car.RawID, Response: &wantypes.AuthenticatorAssertionResponse{ ClientDataJson: car.AssertionResponse.ClientDataJSON, AuthenticatorData: car.AssertionResponse.AuthenticatorData, Signature: car.AssertionResponse.Signature, UserHandle: car.AssertionResponse.UserHandle, }, Extensions: outputExtensionsToProto(car.Extensions), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CredentialAssertionToProto(assertion *CredentialAssertion) *wantypes.CredentialAssertion {\n\tif assertion == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialAssertion{\n\t\tPublicKey: &wantypes.PublicKeyCredentialRequestOptions{\n\t\t\tChallenge: assertion.Response.Challenge,\n\t\t\tTimeoutMs: int64(assertion.Response.Timeout),\n\t\t\tRpId: assertion.Response.RelyingPartyID,\n\t\t\tAllowCredentials: credentialDescriptorsToProto(assertion.Response.AllowedCredentials),\n\t\t\tExtensions: inputExtensionsToProto(assertion.Response.Extensions),\n\t\t\tUserVerification: string(assertion.Response.UserVerification),\n\t\t},\n\t}\n}", "func CredentialAssertionResponseFromProto(car *wantypes.CredentialAssertionResponse) *CredentialAssertionResponse {\n\tif car == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialAssertionResponse{\n\t\tPublicKeyCredential: PublicKeyCredential{\n\t\t\tCredential: Credential{\n\t\t\t\tID: base64.RawURLEncoding.EncodeToString(car.RawId),\n\t\t\t\tType: car.Type,\n\t\t\t},\n\t\t\tRawID: car.RawId,\n\t\t\tExtensions: outputExtensionsFromProto(car.Extensions),\n\t\t},\n\t\tAssertionResponse: authenticatorAssertionResponseFromProto(car.Response),\n\t}\n}", "func CredentialCreationResponseToProto(ccr *CredentialCreationResponse) *wantypes.CredentialCreationResponse {\n\tif ccr == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialCreationResponse{\n\t\tType: ccr.Type,\n\t\tRawId: ccr.RawID,\n\t\tResponse: &wantypes.AuthenticatorAttestationResponse{\n\t\t\tClientDataJson: ccr.AttestationResponse.ClientDataJSON,\n\t\t\tAttestationObject: ccr.AttestationResponse.AttestationObject,\n\t\t},\n\t\tExtensions: outputExtensionsToProto(ccr.Extensions),\n\t}\n}", "func CredentialAssertionFromProto(assertion *wantypes.CredentialAssertion) *CredentialAssertion {\n\tif assertion == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialAssertion{\n\t\tResponse: publicKeyCredentialRequestOptionsFromProto(assertion.PublicKey),\n\t}\n}", "func CredentialCreationResponseFromProto(ccr *wantypes.CredentialCreationResponse) *CredentialCreationResponse {\n\tif ccr == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialCreationResponse{\n\t\tPublicKeyCredential: PublicKeyCredential{\n\t\t\tCredential: Credential{\n\t\t\t\tID: base64.RawURLEncoding.EncodeToString(ccr.RawId),\n\t\t\t\tType: ccr.Type,\n\t\t\t},\n\t\t\tRawID: ccr.RawId,\n\t\t\tExtensions: outputExtensionsFromProto(ccr.Extensions),\n\t\t},\n\t\tAttestationResponse: authenticatorAttestationResponseFromProto(ccr.Response),\n\t}\n}", "func CredentialCreationToProto(cc *CredentialCreation) *wantypes.CredentialCreation {\n\tif cc == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialCreation{\n\t\tPublicKey: &wantypes.PublicKeyCredentialCreationOptions{\n\t\t\tChallenge: cc.Response.Challenge,\n\t\t\tRp: rpEntityToProto(cc.Response.RelyingParty),\n\t\t\tUser: userEntityToProto(cc.Response.User),\n\t\t\tCredentialParameters: credentialParametersToProto(cc.Response.Parameters),\n\t\t\tTimeoutMs: int64(cc.Response.Timeout),\n\t\t\tExcludeCredentials: credentialDescriptorsToProto(cc.Response.CredentialExcludeList),\n\t\t\tAttestation: string(cc.Response.Attestation),\n\t\t\tExtensions: inputExtensionsToProto(cc.Response.Extensions),\n\t\t\tAuthenticatorSelection: authenticatorSelectionToProto(cc.Response.AuthenticatorSelection),\n\t\t},\n\t}\n}", "func (in *CredentialProviderResponse) DeepCopy() *CredentialProviderResponse {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(CredentialProviderResponse)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func NewGetCredentialsResponseCredential() *GetCredentialsResponseCredential {\n\tthis := GetCredentialsResponseCredential{}\n\treturn &this\n}", "func NewProtoSubscribeResponse(result *chatter.Event) *chatterpb.SubscribeResponse {\n\tmessage := &chatterpb.SubscribeResponse{\n\t\tMessage_: result.Message,\n\t\tAction: result.Action,\n\t\tAddedAt: result.AddedAt,\n\t}\n\treturn message\n}", "func CredentialAssertionFromProtocol(a *protocol.CredentialAssertion) *CredentialAssertion {\n\tif a == nil {\n\t\treturn nil\n\t}\n\n\treturn &CredentialAssertion{\n\t\tResponse: PublicKeyCredentialRequestOptions{\n\t\t\tChallenge: Challenge(a.Response.Challenge),\n\t\t\tTimeout: a.Response.Timeout,\n\t\t\tRelyingPartyID: a.Response.RelyingPartyID,\n\t\t\tAllowedCredentials: credentialDescriptorsFromProtocol(a.Response.AllowedCredentials),\n\t\t\tUserVerification: a.Response.UserVerification,\n\t\t\tExtensions: a.Response.Extensions,\n\t\t},\n\t}\n}", "func EncodeGRPCChangePasswordResponse(_ context.Context, r interface{}) (interface{}, error) {\n\tresp := r.(changePasswordResponse)\n\treturn &pb.ChangePasswordResponse{\n\t\tSuccess: resp.Success,\n\t\tErr: resp.Err,\n\t}, nil\n}", "func ServiceAccountToProto(resource *iam.ServiceAccount) *iampb.IamServiceAccount {\n\tp := &iampb.IamServiceAccount{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetUniqueId(dcl.ValueOrEmptyString(resource.UniqueId))\n\tp.SetEmail(dcl.ValueOrEmptyString(resource.Email))\n\tp.SetDisplayName(dcl.ValueOrEmptyString(resource.DisplayName))\n\tp.SetDescription(dcl.ValueOrEmptyString(resource.Description))\n\tp.SetOauth2ClientId(dcl.ValueOrEmptyString(resource.OAuth2ClientId))\n\tp.SetActasResources(IamServiceAccountActasResourcesToProto(resource.ActasResources))\n\tp.SetDisabled(dcl.ValueOrEmptyBool(resource.Disabled))\n\n\treturn p\n}", "func CertificateTemplateToProto(resource *beta.CertificateTemplate) *betapb.PrivatecaBetaCertificateTemplate {\n\tp := &betapb.PrivatecaBetaCertificateTemplate{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetPredefinedValues(PrivatecaBetaCertificateTemplatePredefinedValuesToProto(resource.PredefinedValues))\n\tp.SetIdentityConstraints(PrivatecaBetaCertificateTemplateIdentityConstraintsToProto(resource.IdentityConstraints))\n\tp.SetPassthroughExtensions(PrivatecaBetaCertificateTemplatePassthroughExtensionsToProto(resource.PassthroughExtensions))\n\tp.SetDescription(dcl.ValueOrEmptyString(resource.Description))\n\tp.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime))\n\tp.SetUpdateTime(dcl.ValueOrEmptyString(resource.UpdateTime))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetLocation(dcl.ValueOrEmptyString(resource.Location))\n\tmLabels := make(map[string]string, len(resource.Labels))\n\tfor k, r := range resource.Labels {\n\t\tmLabels[k] = r\n\t}\n\tp.SetLabels(mLabels)\n\n\treturn p\n}", "func NewProtoLoginResponse(result string) *chatterpb.LoginResponse {\n\tmessage := &chatterpb.LoginResponse{}\n\tmessage.Field = result\n\treturn message\n}", "func DecodeBatchGRPCResponse(ctx context.Context, v interface{}, hdr, trlr metadata.MD) (interface{}, error) {\n\tmessage, ok := v.(*publicpb.BatchGRPCResponse)\n\tif !ok {\n\t\treturn nil, goagrpc.ErrInvalidType(\"public\", \"batchGRPC\", \"*publicpb.BatchGRPCResponse\", v)\n\t}\n\tres := NewBatchGRPCResult(message)\n\treturn res, nil\n}", "func NewBatchGRPCResponse(result []*public.ResponsePayload) *publicpb.BatchGRPCResponse {\n\tmessage := &publicpb.BatchGRPCResponse{}\n\tmessage.Field = make([]*publicpb.ResponsePayload, len(result))\n\tfor i, val := range result {\n\t\tmessage.Field[i] = &publicpb.ResponsePayload{\n\t\t\tFirstField: val.FirstField,\n\t\t\tFourthField: val.FourthField,\n\t\t}\n\t}\n\treturn message\n}", "func PrivatecaBetaCertificateTemplateIdentityConstraintsCelExpressionToProto(o *beta.CertificateTemplateIdentityConstraintsCelExpression) *betapb.PrivatecaBetaCertificateTemplateIdentityConstraintsCelExpression {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.PrivatecaBetaCertificateTemplateIdentityConstraintsCelExpression{}\n\tp.SetExpression(dcl.ValueOrEmptyString(o.Expression))\n\tp.SetTitle(dcl.ValueOrEmptyString(o.Title))\n\tp.SetDescription(dcl.ValueOrEmptyString(o.Description))\n\tp.SetLocation(dcl.ValueOrEmptyString(o.Location))\n\treturn p\n}", "func PrivatecaBetaCertificateTemplatePassthroughExtensionsToProto(o *beta.CertificateTemplatePassthroughExtensions) *betapb.PrivatecaBetaCertificateTemplatePassthroughExtensions {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.PrivatecaBetaCertificateTemplatePassthroughExtensions{}\n\tsKnownExtensions := make([]betapb.PrivatecaBetaCertificateTemplatePassthroughExtensionsKnownExtensionsEnum, len(o.KnownExtensions))\n\tfor i, r := range o.KnownExtensions {\n\t\tsKnownExtensions[i] = betapb.PrivatecaBetaCertificateTemplatePassthroughExtensionsKnownExtensionsEnum(betapb.PrivatecaBetaCertificateTemplatePassthroughExtensionsKnownExtensionsEnum_value[string(r)])\n\t}\n\tp.SetKnownExtensions(sKnownExtensions)\n\tsAdditionalExtensions := make([]*betapb.PrivatecaBetaCertificateTemplatePassthroughExtensionsAdditionalExtensions, len(o.AdditionalExtensions))\n\tfor i, r := range o.AdditionalExtensions {\n\t\tsAdditionalExtensions[i] = PrivatecaBetaCertificateTemplatePassthroughExtensionsAdditionalExtensionsToProto(&r)\n\t}\n\tp.SetAdditionalExtensions(sAdditionalExtensions)\n\treturn p\n}", "func PrivatecaBetaCertificateTemplateIdentityConstraintsToProto(o *beta.CertificateTemplateIdentityConstraints) *betapb.PrivatecaBetaCertificateTemplateIdentityConstraints {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.PrivatecaBetaCertificateTemplateIdentityConstraints{}\n\tp.SetCelExpression(PrivatecaBetaCertificateTemplateIdentityConstraintsCelExpressionToProto(o.CelExpression))\n\tp.SetAllowSubjectPassthrough(dcl.ValueOrEmptyBool(o.AllowSubjectPassthrough))\n\tp.SetAllowSubjectAltNamesPassthrough(dcl.ValueOrEmptyBool(o.AllowSubjectAltNamesPassthrough))\n\treturn p\n}", "func EncodeGRPCLogoutResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(*pb.LogoutResponse)\n\treturn resp, nil\n}", "func (e *execPlugin) decodeResponse(data []byte) (*credentialproviderapi.CredentialProviderResponse, error) {\n\tobj, gvk, err := codecs.UniversalDecoder().Decode(data, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif gvk.Kind != \"CredentialProviderResponse\" {\n\t\treturn nil, fmt.Errorf(\"failed to decode CredentialProviderResponse, unexpected Kind: %q\", gvk.Kind)\n\t}\n\n\tif gvk.Group != credentialproviderapi.GroupName {\n\t\treturn nil, fmt.Errorf(\"failed to decode CredentialProviderResponse, unexpected Group: %s\", gvk.Group)\n\t}\n\n\tif internalResponse, ok := obj.(*credentialproviderapi.CredentialProviderResponse); ok {\n\t\treturn internalResponse, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"unable to convert %T to *CredentialProviderResponse\", obj)\n}", "func decodeGRPCGenerateReportResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.GenerateReportResponse)\n\treturn generateReportResponse{Repository: reply.Repository, Err: str2err(reply.Err)}, nil\n}", "func BytesToResponse(b []byte) Response {\n\tvar r Response\n\tdec := gob.NewDecoder(bytes.NewReader(b))\n\tdec.Decode(&r)\n\n\treturn r\n}", "func BytesToResponse(b []byte) Response {\n\tvar r Response\n\tdec := gob.NewDecoder(bytes.NewReader(b))\n\tdec.Decode(&r)\n\n\treturn r\n}", "func NewProtoListenerResponse() *chatterpb.ListenerResponse {\n\tmessage := &chatterpb.ListenerResponse{}\n\treturn message\n}", "func encodeGRPCGenerateReportResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(generateReportResponse)\n\treturn &pb.GenerateReportReply{V: int64(resp.V), Err: err2str(resp.Err)}, nil\n}", "func decodeGRPCTacResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.TacResponse)\n\treturn endpoints.TacResponse{Res: reply.Res}, nil\n}", "func NewProtoHistoryResponse(result *chatterviews.ChatSummaryView) *chatterpb.HistoryResponse {\n\tmessage := &chatterpb.HistoryResponse{\n\t\tMessage_: *result.Message,\n\t\tSentAt: *result.SentAt,\n\t}\n\tif result.Length != nil {\n\t\tlength := int32(*result.Length)\n\t\tmessage.Length = &length\n\t}\n\treturn message\n}", "func ResourceRecordSetToProto(resource *dns.ResourceRecordSet) *dnspb.DnsResourceRecordSet {\n\tp := &dnspb.DnsResourceRecordSet{\n\t\tDnsName: dcl.ValueOrEmptyString(resource.DnsName),\n\t\tDnsType: dcl.ValueOrEmptyString(resource.DnsType),\n\t\tTtl: dcl.ValueOrEmptyInt64(resource.Ttl),\n\t\tManagedZone: dcl.ValueOrEmptyString(resource.ManagedZone),\n\t\tProject: dcl.ValueOrEmptyString(resource.Project),\n\t}\n\tfor _, r := range resource.Target {\n\t\tp.Target = append(p.Target, r)\n\t}\n\n\treturn p\n}", "func NewProtoEchoerResponse(result string) *chatterpb.EchoerResponse {\n\tmessage := &chatterpb.EchoerResponse{}\n\tmessage.Field = result\n\treturn message\n}", "func NewStreamedBatchGRPCResponse(result *public.ResponsePayload) *publicpb.StreamedBatchGRPCResponse {\n\tmessage := &publicpb.StreamedBatchGRPCResponse{\n\t\tFirstField: result.FirstField,\n\t\tFourthField: result.FourthField,\n\t}\n\treturn message\n}", "func decodeAuthResponse(_ context.Context, reply interface{}) (interface{}, error) {\n\tr, ok := reply.(*pb.AuthReply)\n\tif !ok {\n\t\te := errors.New(\"'AuthReply' Decoder is not impelemented\")\n\t\treturn endpoint1.AuthResponse{Err: e}, e\n\t}\n\treturn endpoint1.AuthResponse{Uuid: r.Uuid, NamespaceID: r.NamespaceID, Roles: r.Roles}, nil\n}", "func ContainerClusterAuthenticatorGroupsConfigToProto(o *container.ClusterAuthenticatorGroupsConfig) *containerpb.ContainerClusterAuthenticatorGroupsConfig {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &containerpb.ContainerClusterAuthenticatorGroupsConfig{\n\t\tEnabled: dcl.ValueOrEmptyBool(o.Enabled),\n\t\tSecurityGroup: dcl.ValueOrEmptyString(o.SecurityGroup),\n\t}\n\treturn p\n}", "func (*CancelTeamSubscriptionResponse) Descriptor() ([]byte, []int) {\n\treturn file_protos_participant_service_proto_rawDescGZIP(), []int{5}\n}", "func ComputeBetaInstanceTemplatePropertiesServiceAccountsToProto(o *beta.InstanceTemplatePropertiesServiceAccounts) *betapb.ComputeBetaInstanceTemplatePropertiesServiceAccounts {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.ComputeBetaInstanceTemplatePropertiesServiceAccounts{\n\t\tEmail: dcl.ValueOrEmptyString(o.Email),\n\t}\n\tfor _, r := range o.Scopes {\n\t\tp.Scopes = append(p.Scopes, r)\n\t}\n\treturn p\n}", "func EncodeGRPCLoginResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(*pb.LoginResponse)\n\treturn resp, nil\n}", "func userToProto(u *domain.User) *protouser.Response {\n\treturn &protouser.Response{\n\t\tApplication: proto.String(string(u.App)),\n\t\tUid: proto.String(u.Uid),\n\t\tIds: idsToStrings(u.Ids),\n\t\tCreatedTimestamp: timeToProto(u.Created),\n\t\tRoles: u.Roles,\n\t\tPasswordChangeTimestamp: timeToProto(u.PasswordChange),\n\t\tAccountExpirationDate: proto.String(string(u.AccountExpirationDate)),\n\t}\n}", "func CloudkmsBetaCryptoKeyVersionTemplateToProto(o *beta.CryptoKeyVersionTemplate) *betapb.CloudkmsBetaCryptoKeyVersionTemplate {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.CloudkmsBetaCryptoKeyVersionTemplate{}\n\tp.SetProtectionLevel(CloudkmsBetaCryptoKeyVersionTemplateProtectionLevelEnumToProto(o.ProtectionLevel))\n\tp.SetAlgorithm(CloudkmsBetaCryptoKeyVersionTemplateAlgorithmEnumToProto(o.Algorithm))\n\treturn p\n}", "func DecodeGRPCGetLinksResponse(_ context.Context, grpcResponse interface{}) (interface{}, error) {\n\tresponse := grpcResponse.(*containerPB.GetLinksResponse)\n\n\tarrayMap := make(map[string][]string)\n\tfor k, v := range response.Links {\n\t\tarrayMap[k] = strings.Split(v, \",\")\n\t}\n\n\treturn &container.GetLinksResponse{\n\t\tError: getError(response.Error),\n\t\tLinks: arrayMap,\n\t}, nil\n}", "func DecodeChangePasswordResponse(ctx context.Context, v interface{}, hdr, trlr metadata.MD) (interface{}, error) {\n\tmessage, ok := v.(*user_methodpb.ChangePasswordResponse)\n\tif !ok {\n\t\treturn nil, goagrpc.ErrInvalidType(\"userMethod\", \"changePassword\", \"*user_methodpb.ChangePasswordResponse\", v)\n\t}\n\tres := NewChangePasswordResult(message)\n\treturn res, nil\n}", "func (*IssueCredentialResponse) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{12}\n}", "func NewCredentialsResponseElement(name string, type_ string, description string, owner string, ownerAccessOnly bool, ) *CredentialsResponseElement {\n\tthis := CredentialsResponseElement{}\n\tthis.Name = name\n\tthis.Type = type_\n\tthis.Description = description\n\tthis.Owner = owner\n\tthis.OwnerAccessOnly = ownerAccessOnly\n\treturn &this\n}", "func SubscriptionToProto(resource *pubsublite.Subscription) *pubsublitepb.PubsubliteSubscription {\n\tp := &pubsublitepb.PubsubliteSubscription{\n\t\tName: dcl.ValueOrEmptyString(resource.Name),\n\t\tTopic: dcl.ValueOrEmptyString(resource.Topic),\n\t\tDeliveryConfig: PubsubliteSubscriptionDeliveryConfigToProto(resource.DeliveryConfig),\n\t\tProject: dcl.ValueOrEmptyString(resource.Project),\n\t\tLocation: dcl.ValueOrEmptyString(resource.Location),\n\t}\n\n\treturn p\n}", "func CryptoKeyToProto(resource *beta.CryptoKey) *betapb.CloudkmsBetaCryptoKey {\n\tp := &betapb.CloudkmsBetaCryptoKey{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetPrimary(CloudkmsBetaCryptoKeyPrimaryToProto(resource.Primary))\n\tp.SetPurpose(CloudkmsBetaCryptoKeyPurposeEnumToProto(resource.Purpose))\n\tp.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime))\n\tp.SetNextRotationTime(dcl.ValueOrEmptyString(resource.NextRotationTime))\n\tp.SetRotationPeriod(dcl.ValueOrEmptyString(resource.RotationPeriod))\n\tp.SetVersionTemplate(CloudkmsBetaCryptoKeyVersionTemplateToProto(resource.VersionTemplate))\n\tp.SetImportOnly(dcl.ValueOrEmptyBool(resource.ImportOnly))\n\tp.SetDestroyScheduledDuration(dcl.ValueOrEmptyString(resource.DestroyScheduledDuration))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetLocation(dcl.ValueOrEmptyString(resource.Location))\n\tp.SetKeyRing(dcl.ValueOrEmptyString(resource.KeyRing))\n\tmLabels := make(map[string]string, len(resource.Labels))\n\tfor k, r := range resource.Labels {\n\t\tmLabels[k] = r\n\t}\n\tp.SetLabels(mLabels)\n\n\treturn p\n}", "func EncodeGRPCGetTokenResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(*pb.GetTokenResp)\n\treturn resp, nil\n}", "func DecodeGRPCGetEnvResponse(_ context.Context, grpcResponse interface{}) (interface{}, error) {\n\tresponse := grpcResponse.(*containerPB.GetEnvResponse)\n\treturn &container.GetEnvResponse{\n\t\tValue: response.Value,\n\t\tError: getError(response.Error),\n\t}, nil\n}", "func EncodeGRPCGetUserByEmailResponse(_ context.Context, r interface{}) (interface{}, error) {\n\tresp := r.(getUserByEmailResponse)\n\tu := &pb.User{\n\t\tId: resp.User.Id,\n\t\tName: resp.User.Name,\n\t\tLastName: resp.User.LastName,\n\t\tEmail: resp.User.Email,\n\t\tRole: resp.User.Role,\n\t}\n\treturn &pb.GetUserByEmailResponse{\n\t\tUser: u,\n\t\tErr: resp.Err,\n\t}, nil\n}", "func EncodeGRPCResponse(_ context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func (m *Mutate) ToProto() proto.Message {\n\tp, _, _ := m.toProto(false, nil)\n\treturn p\n}", "func (c *StatusResponse) ToBytes() []byte {\n\tvar serialized []byte\n\tserialized = append(serialized, byte(len(c.Lines)))\n\tfor _, s := range c.Lines {\n\t\tserialized = append(serialized, message_fields.SerializeString(s, 1024)...)\n\t}\n\treturn serialized\n}", "func (*ChangePasswordResponse) Descriptor() ([]byte, []int) {\n\treturn file_pb_auth_proto_rawDescGZIP(), []int{3}\n}", "func EncodeGRPCGetUserInfoResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(*pb.UserInfo)\n\treturn resp, nil\n}", "func ComputeBetaInterconnectAttachmentPartnerMetadataToProto(o *beta.InterconnectAttachmentPartnerMetadata) *betapb.ComputeBetaInterconnectAttachmentPartnerMetadata {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.ComputeBetaInterconnectAttachmentPartnerMetadata{}\n\tp.SetPartnerName(dcl.ValueOrEmptyString(o.PartnerName))\n\tp.SetInterconnectName(dcl.ValueOrEmptyString(o.InterconnectName))\n\tp.SetPortalUrl(dcl.ValueOrEmptyString(o.PortalUrl))\n\treturn p\n}", "func convertResponse(r *http.Response, resp interface{}) error {\n\tdefer r.Body.Close()\n\n\tbuf := new(bytes.Buffer)\n\tif _, err := buf.ReadFrom(r.Body); err != nil {\n\t\treturn err\n\t}\n\n\tif err := json.Unmarshal(buf.Bytes(), resp); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func EncodeGRPCLoginResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(*pb.Session)\n\treturn resp, nil\n}", "func encodeVerifyResponse(_ context.Context, r interface{}) (interface{}, error) {\n\trs := r.(endpoint.VerifyResponse)\n\n\tif rs.Err != nil {\n\t\treturn &pb.VerifyReply{}, fmt.Errorf(\"Error: %s \", rs.Err.Error())\n\t}\n\n\tpermissions := make([]*pb.Permission, len(rs.Response.Role.Permissions))\n\tfor _, v := range rs.Response.Role.Permissions {\n\t\tpermissions = append(permissions, &pb.Permission{Name: v.Name})\n\t}\n\n\treturn &pb.VerifyReply{\n\t\tUsername: rs.Response.Username,\n\t\tName: rs.Response.Name,\n\t\tLastName: rs.Response.LastName,\n\t\tPhone: rs.Response.Phone,\n\t\tEmail: rs.Response.Email,\n\t\tToken: rs.Response.Token,\n\t\tRole: &pb.Role{\n\t\t\tName: rs.Response.Role.Name,\n\t\t\tPermissions: permissions,\n\t\t},\n\t}, nil\n}", "func NewGetCredentialsResponseCredentialWithDefaults() *GetCredentialsResponseCredential {\n\tthis := GetCredentialsResponseCredential{}\n\treturn &this\n}", "func ProtoToCertificateTemplate(p *betapb.PrivatecaBetaCertificateTemplate) *beta.CertificateTemplate {\n\tobj := &beta.CertificateTemplate{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tPredefinedValues: ProtoToPrivatecaBetaCertificateTemplatePredefinedValues(p.GetPredefinedValues()),\n\t\tIdentityConstraints: ProtoToPrivatecaBetaCertificateTemplateIdentityConstraints(p.GetIdentityConstraints()),\n\t\tPassthroughExtensions: ProtoToPrivatecaBetaCertificateTemplatePassthroughExtensions(p.GetPassthroughExtensions()),\n\t\tDescription: dcl.StringOrNil(p.GetDescription()),\n\t\tCreateTime: dcl.StringOrNil(p.GetCreateTime()),\n\t\tUpdateTime: dcl.StringOrNil(p.GetUpdateTime()),\n\t\tProject: dcl.StringOrNil(p.GetProject()),\n\t\tLocation: dcl.StringOrNil(p.GetLocation()),\n\t}\n\treturn obj\n}", "func (sp *ServiceProvider) AssertResponse(base64Res string) (*Assertion, error) {\n\t// Parse SAML response from base64 encoded payload\n\t//\n\tsamlResponseXML, err := base64.StdEncoding.DecodeString(base64Res)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to base64-decode SAML response\")\n\t}\n\tvar res *Response\n\tif err := xml.Unmarshal(samlResponseXML, &res); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to unmarshal XML document: %s\", string(samlResponseXML))\n\t}\n\n\t// Validate response\n\t//\n\t// Validate destination\n\t// Note: OneLogin triggers this error when the Recipient field\n\t// is left blank (or when not set to the correct ACS endpoint)\n\t// in the OneLogin SAML configuration page. OneLogin returns\n\t// Destination=\"{recipient}\" in the SAML reponse in this case.\n\tif res.Destination != sp.ACSURL {\n\t\treturn nil, errors.Errorf(\"Wrong ACS destination, expected %q, got %q\", sp.ACSURL, res.Destination)\n\t}\n\tif res.Status.StatusCode.Value != \"urn:oasis:names:tc:SAML:2.0:status:Success\" {\n\t\treturn nil, errors.Errorf(\"Unexpected status code: %v\", res.Status.StatusCode.Value)\n\t}\n\n\t// Validates if the assertion matches the ID set in the original SAML AuthnRequest\n\t//\n\t// This check should be performed first before validating the signature since it is a cheap way to discard invalid messages\n\t// TODO: Track request IDs and add option to set them back in the service provider\n\t// This code will always pass since the possible response IDs is hardcoded to have a single empty string element\n\t// expectedResponse := false\n\t// responseIDs := sp.possibleResponseIDs()\n\t// for i := range responseIDs {\n\t// \tif responseIDs[i] == assertion.Subject.SubjectConfirmation.SubjectConfirmationData.InResponseTo {\n\t// \t\texpectedResponse = true\n\t// \t}\n\t// }\n\t// if len(responseIDs) == 1 && responseIDs[0] == \"\" {\n\t// \texpectedResponse = true\n\t// }\n\n\t// if !expectedResponse && len(responseIDs) > 0 {\n\t// \treturn nil, errors.New(\"Unexpected assertion InResponseTo value\")\n\t// }\n\n\t// Save XML raw bytes so later we can reuse it to verify the signature\n\tplainText := samlResponseXML\n\n\t// All SAML Responses are required to have a signature\n\tvalidSignature := false\n\t// Validate response reference\n\t// Before validating the signature with xmlsec, first check if the reference ID is correct\n\t//\n\t// http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf section 5.3\n\tif res.Signature != nil {\n\t\tif err := verifySignatureReference(res.Signature, res.ID); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to validate response signature reference\")\n\t\t}\n\t\tif err := sp.verifySignature(plainText); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to verify message signature: %v\", string(plainText))\n\t\t}\n\t\tvalidSignature = true\n\t}\n\n\t// Check for encrypted assertions\n\t// http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf section 2.3.4\n\tassertion := res.Assertion\n\tif res.EncryptedAssertion != nil {\n\t\tkeyFile, err := sp.PrivkeyFile()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to get private key file\")\n\t\t}\n\n\t\tplainTextAssertion, err := xmlsec.Decrypt(res.EncryptedAssertion.EncryptedData, keyFile)\n\t\tif err != nil {\n\t\t\tif IsSecurityException(err, &sp.SecurityOpts) {\n\t\t\t\treturn nil, errors.Wrap(err, \"failed to decrypt assertion\")\n\t\t\t}\n\t\t}\n\n\t\tassertion = &Assertion{}\n\t\tif err := xml.Unmarshal(plainTextAssertion, assertion); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to unmarshal encrypted assertion: %v\", plainTextAssertion)\n\t\t}\n\n\t\t// Track plain text so later we can verify the signature with xmlsec\n\t\tplainText = plainTextAssertion\n\t}\n\n\tif assertion == nil {\n\t\treturn nil, errors.New(\"missing assertion element\")\n\t}\n\n\t// Validate assertion reference\n\t// Before validating the signature with xmlsec, first check if the reference ID is correct\n\t//\n\t// http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf section 5.3\n\tif assertion.Signature != nil {\n\t\tif err := verifySignatureReference(assertion.Signature, assertion.ID); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to validate assertion signature reference\")\n\t\t}\n\t\tif err := sp.verifySignature(plainText); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to verify message signature: %v\", string(plainText))\n\t\t}\n\t\tvalidSignature = true\n\t}\n\n\tif !validSignature {\n\t\treturn nil, errors.Errorf(\"missing assertion signature\")\n\t}\n\n\t// Validate issuer\n\t// Since assertion could be encrypted we need to wait before validating the issuer\n\t// Only validate issuer if the entityID is set in the IdP metadata\n\t// TODO: the spec lists the Issuer element of an Assertion as required, we shouldn't skip validation\n\tswitch {\n\tcase sp.IdPEntityID == \"\":\n\t\t// Skip issuer validationgit s\n\tcase assertion.Issuer == nil:\n\t\treturn nil, errors.New(`missing Assertion > Issuer`)\n\tcase assertion.Issuer.Value != sp.IdPEntityID:\n\t\treturn nil, errors.Errorf(\"failed to validate assertion issuer: expected %q but got %q\", sp.IdPEntityID, assertion.Issuer.Value)\n\t}\n\n\t// Validate recipient\n\tswitch {\n\tcase assertion.Subject == nil:\n\t\terr = errors.New(`missing Assertion > Subject`)\n\tcase assertion.Subject.SubjectConfirmation == nil:\n\t\terr = errors.New(`missing Assertion > Subject > SubjectConfirmation`)\n\tcase assertion.Subject.SubjectConfirmation.SubjectConfirmationData.Recipient != sp.ACSURL:\n\t\terr = errors.Errorf(\"failed to validate assertion recipient: expected %q but got %q\", sp.ACSURL, assertion.Subject.SubjectConfirmation.SubjectConfirmationData.Recipient)\n\t}\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"invalid assertion recipient\")\n\t}\n\n\t// Make sure we have Conditions\n\tif assertion.Conditions == nil {\n\t\treturn nil, errors.New(`missing Assertion > Conditions`)\n\t}\n\n\t// The NotBefore and NotOnOrAfter attributes specify time limits on the\n\t// validity of the assertion within the context of its profile(s) of use.\n\t// They do not guarantee that the statements in the assertion will be\n\t// correct or accurate throughout the validity period. The NotBefore\n\t// attribute specifies the time instant at which the validity interval\n\t// begins. The NotOnOrAfter attribute specifies the time instant at which\n\t// the validity interval has ended. If the value for either NotBefore or\n\t// NotOnOrAfter is omitted, then it is considered unspecified.\n\tnow := Now()\n\tvalidFrom := assertion.Conditions.NotBefore\n\tif !validFrom.IsZero() && validFrom.After(now.Add(ClockDriftTolerance)) {\n\t\treturn nil, errors.Errorf(\"Assertion conditions are not valid yet, got %v, current time is %v\", validFrom, now)\n\t}\n\tvalidUntil := assertion.Conditions.NotOnOrAfter\n\tif !validUntil.IsZero() && validUntil.Before(now.Add(-ClockDriftTolerance)) {\n\t\treturn nil, errors.Errorf(\"Assertion conditions already expired, got %v current time is %v, extra time is %v\", validUntil, now, now.Add(-ClockDriftTolerance))\n\t}\n\n\t// A time instant at which the subject can no longer be confirmed. The time\n\t// value is encoded in UTC, as described in Section 1.3.3.\n\t//\n\t// Note that the time period specified by the optional NotBefore and\n\t// NotOnOrAfter attributes, if present, SHOULD fall within the overall\n\t// assertion validity period as specified by the element's NotBefore and\n\t// NotOnOrAfter attributes. If both attributes are present, the value for\n\t// NotBefore MUST be less than (earlier than) the value for NotOnOrAfter.\n\tif validUntil := assertion.Subject.SubjectConfirmation.SubjectConfirmationData.NotOnOrAfter; validUntil.Before(now.Add(-ClockDriftTolerance)) {\n\t\terr := errors.Errorf(\"Assertion conditions already expired, got %v current time is %v\", validUntil, now)\n\t\treturn nil, errors.Wrap(err, \"Assertion conditions already expired\")\n\t}\n\n\t// TODO: reenable?\n\t// if assertion.Conditions != nil && assertion.Conditions.AudienceRestriction != nil {\n\t// if assertion.Conditions.AudienceRestriction.Audience.Value != sp.MetadataURL {\n\t// returnt.Errorf(\"Audience restriction mismatch, got %q, expected %q\", assertion.Conditions.AudienceRestriction.Audience.Value, sp.MetadataURL), errors.New(\"Audience restriction mismatch\")\n\t// }\n\t// }\n\n\treturn assertion, nil\n}", "func (tn *ListNamespaceDescriptors) ToProto() proto.Message {\n\treturn &pb.ListNamespaceDescriptorsRequest{\n\t}\n}", "func (fieldMask *AcceptResponse_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}", "func ManagedSslCertificateToProto(resource *beta.ManagedSslCertificate) *betapb.ComputeBetaManagedSslCertificate {\n\tp := &betapb.ComputeBetaManagedSslCertificate{\n\t\tName: dcl.ValueOrEmptyString(resource.Name),\n\t\tId: dcl.ValueOrEmptyInt64(resource.Id),\n\t\tCreationTimestamp: dcl.ValueOrEmptyString(resource.CreationTimestamp),\n\t\tDescription: dcl.ValueOrEmptyString(resource.Description),\n\t\tSelfLink: dcl.ValueOrEmptyString(resource.SelfLink),\n\t\tManaged: ComputeBetaManagedSslCertificateManagedToProto(resource.Managed),\n\t\tType: ComputeBetaManagedSslCertificateTypeEnumToProto(resource.Type),\n\t\tExpireTime: dcl.ValueOrEmptyString(resource.ExpireTime),\n\t\tProject: dcl.ValueOrEmptyString(resource.Project),\n\t}\n\tfor _, r := range resource.SubjectAlternativeNames {\n\t\tp.SubjectAlternativeNames = append(p.SubjectAlternativeNames, r)\n\t}\n\n\treturn p\n}", "func (*ListCredentialsResponse) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{23}\n}", "func DlpBetaDeidentifyTemplateDeidentifyConfigRecordTransformationsToProto(o *beta.DeidentifyTemplateDeidentifyConfigRecordTransformations) *betapb.DlpBetaDeidentifyTemplateDeidentifyConfigRecordTransformations {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.DlpBetaDeidentifyTemplateDeidentifyConfigRecordTransformations{}\n\tsFieldTransformations := make([]*betapb.DlpBetaDeidentifyTemplateDeidentifyConfigRecordTransformationsFieldTransformations, len(o.FieldTransformations))\n\tfor i, r := range o.FieldTransformations {\n\t\tsFieldTransformations[i] = DlpBetaDeidentifyTemplateDeidentifyConfigRecordTransformationsFieldTransformationsToProto(&r)\n\t}\n\tp.SetFieldTransformations(sFieldTransformations)\n\tsRecordSuppressions := make([]*betapb.DlpBetaDeidentifyTemplateDeidentifyConfigRecordTransformationsRecordSuppressions, len(o.RecordSuppressions))\n\tfor i, r := range o.RecordSuppressions {\n\t\tsRecordSuppressions[i] = DlpBetaDeidentifyTemplateDeidentifyConfigRecordTransformationsRecordSuppressionsToProto(&r)\n\t}\n\tp.SetRecordSuppressions(sRecordSuppressions)\n\treturn p\n}", "func decodeRolesResponse(_ context.Context, reply interface{}) (interface{}, error) {\n\tr, ok := reply.(*pb.RolesReply)\n\tif !ok {\n\t\te := errors.New(\"'Account' Decoder is not impelemented\")\n\t\treturn endpoint1.RolesResponse{E1: e}, e\n\t}\n\treturn endpoint1.RolesResponse{S0: r.Roles}, nil\n}", "func EncodeGRPCLoginResponse(_ context.Context, r interface{}) (interface{}, error) {\n\tresp := r.(loginResponse)\n\treturn &pb.LoginResponse{\n\t\tToken: resp.Token,\n\t\tRefreshToken: resp.RefreshToken,\n\t\tErr: resp.Err,\n\t}, nil\n}", "func (m *Mutate) NewResponse() proto.Message {\n\treturn &pb.MutateResponse{}\n}", "func decodeGRPCEchoResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.EchoReply)\n\treturn endpoints.EchoResponse{Rs: reply.Rs}, nil\n}", "func (*AcceptCredentialResponse) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{33}\n}", "func (st *Account) ToProto() *accountpb.Account {\n\tacPb := &accountpb.Account{}\n\tacPb.Nonce = st.nonce\n\tif _, ok := accountpb.AccountType_name[st.accountType]; !ok {\n\t\tpanic(\"unknown account type\")\n\t}\n\tacPb.Type = accountpb.AccountType(st.accountType)\n\tif st.Balance != nil {\n\t\tacPb.Balance = st.Balance.String()\n\t}\n\tacPb.Root = make([]byte, len(st.Root))\n\tcopy(acPb.Root, st.Root[:])\n\tacPb.CodeHash = make([]byte, len(st.CodeHash))\n\tcopy(acPb.CodeHash, st.CodeHash)\n\tacPb.IsCandidate = st.isCandidate\n\tif st.votingWeight != nil {\n\t\tacPb.VotingWeight = st.votingWeight.Bytes()\n\t}\n\treturn acPb\n}", "func ComputeBetaManagedSslCertificateTypeEnumToProto(e *beta.ManagedSslCertificateTypeEnum) betapb.ComputeBetaManagedSslCertificateTypeEnum {\n\tif e == nil {\n\t\treturn betapb.ComputeBetaManagedSslCertificateTypeEnum(0)\n\t}\n\tif v, ok := betapb.ComputeBetaManagedSslCertificateTypeEnum_value[\"ManagedSslCertificateTypeEnum\"+string(*e)]; ok {\n\t\treturn betapb.ComputeBetaManagedSslCertificateTypeEnum(v)\n\t}\n\treturn betapb.ComputeBetaManagedSslCertificateTypeEnum(0)\n}", "func NetworkservicesHttpRouteRulesActionResponseHeaderModifierToProto(o *networkservices.HttpRouteRulesActionResponseHeaderModifier) *networkservicespb.NetworkservicesHttpRouteRulesActionResponseHeaderModifier {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &networkservicespb.NetworkservicesHttpRouteRulesActionResponseHeaderModifier{}\n\tmSet := make(map[string]string, len(o.Set))\n\tfor k, r := range o.Set {\n\t\tmSet[k] = r\n\t}\n\tp.SetSet(mSet)\n\tmAdd := make(map[string]string, len(o.Add))\n\tfor k, r := range o.Add {\n\t\tmAdd[k] = r\n\t}\n\tp.SetAdd(mAdd)\n\tsRemove := make([]string, len(o.Remove))\n\tfor i, r := range o.Remove {\n\t\tsRemove[i] = r\n\t}\n\tp.SetRemove(sRemove)\n\treturn p\n}", "func (fieldMask *ListenResponse_ResumeChannelResponse_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}", "func (*CMsgClientToGCRequestPlusWeeklyChallengeResultResponse) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{274}\n}", "func NewContactResponse() *ContactResponse {\n\tthis := ContactResponse{}\n\treturn &this\n}", "func (x *fastReflection_MsgWithdrawValidatorCommissionResponse) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_MsgWithdrawValidatorCommissionResponse\n}", "func DomainMappingToProto(resource *appengine.DomainMapping) *appenginepb.AppengineDomainMapping {\n\tp := &appenginepb.AppengineDomainMapping{\n\t\tSelfLink: dcl.ValueOrEmptyString(resource.SelfLink),\n\t\tName: dcl.ValueOrEmptyString(resource.Name),\n\t\tSslSettings: AppengineDomainMappingSslSettingsToProto(resource.SslSettings),\n\t\tApp: dcl.ValueOrEmptyString(resource.App),\n\t}\n\tfor _, r := range resource.ResourceRecords {\n\t\tp.ResourceRecords = append(p.ResourceRecords, AppengineDomainMappingResourceRecordsToProto(&r))\n\t}\n\n\treturn p\n}", "func CaPoolToProto(resource *alpha.CaPool) *alphapb.PrivatecaAlphaCaPool {\n\tp := &alphapb.PrivatecaAlphaCaPool{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetTier(PrivatecaAlphaCaPoolTierEnumToProto(resource.Tier))\n\tp.SetIssuancePolicy(PrivatecaAlphaCaPoolIssuancePolicyToProto(resource.IssuancePolicy))\n\tp.SetPublishingOptions(PrivatecaAlphaCaPoolPublishingOptionsToProto(resource.PublishingOptions))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetLocation(dcl.ValueOrEmptyString(resource.Location))\n\tmLabels := make(map[string]string, len(resource.Labels))\n\tfor k, r := range resource.Labels {\n\t\tmLabels[k] = r\n\t}\n\tp.SetLabels(mLabels)\n\n\treturn p\n}", "func decodeGRPCMathOpResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.MathOpReply)\n\treturn mathendpoint2.MathOpResponse{V: reply.V, Err: str2err(reply.Err)}, nil\n}", "func DecodeGRPCInstancesResponse(_ context.Context, grpcResponse interface{}) (interface{}, error) {\n\tresponse := grpcResponse.(*containerPB.InstancesResponse)\n\treturn &container.InstancesResponse{\n\t\tContainers: pbContainersToContainers(response.Instances),\n\t}, nil\n}", "func DeidentifyTemplateToProto(resource *beta.DeidentifyTemplate) *betapb.DlpBetaDeidentifyTemplate {\n\tp := &betapb.DlpBetaDeidentifyTemplate{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetDisplayName(dcl.ValueOrEmptyString(resource.DisplayName))\n\tp.SetDescription(dcl.ValueOrEmptyString(resource.Description))\n\tp.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime))\n\tp.SetUpdateTime(dcl.ValueOrEmptyString(resource.UpdateTime))\n\tp.SetDeidentifyConfig(DlpBetaDeidentifyTemplateDeidentifyConfigToProto(resource.DeidentifyConfig))\n\tp.SetLocationId(dcl.ValueOrEmptyString(resource.LocationId))\n\tp.SetParent(dcl.ValueOrEmptyString(resource.Parent))\n\tp.SetLocation(dcl.ValueOrEmptyString(resource.Location))\n\n\treturn p\n}", "func (x *fastReflection_QueryAccountsResponse) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value {\n\tswitch descriptor.FullName() {\n\tcase \"cosmos.auth.v1beta1.QueryAccountsResponse.accounts\":\n\t\tif len(x.Accounts) == 0 {\n\t\t\treturn protoreflect.ValueOfList(&_QueryAccountsResponse_1_list{})\n\t\t}\n\t\tlistValue := &_QueryAccountsResponse_1_list{list: &x.Accounts}\n\t\treturn protoreflect.ValueOfList(listValue)\n\tcase \"cosmos.auth.v1beta1.QueryAccountsResponse.pagination\":\n\t\tvalue := x.Pagination\n\t\treturn protoreflect.ValueOfMessage(value.ProtoReflect())\n\tdefault:\n\t\tif descriptor.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: cosmos.auth.v1beta1.QueryAccountsResponse\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message cosmos.auth.v1beta1.QueryAccountsResponse does not contain field %s\", descriptor.FullName()))\n\t}\n}", "func (*SubscribeTeamResponse) Descriptor() ([]byte, []int) {\n\treturn file_protos_participant_service_proto_rawDescGZIP(), []int{3}\n}", "func encodeGRPCGreetingResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tres := response.(greeterendpoint.GreetingResponse)\n\treturn &pb.GreetingResponse{Greeting: res.Greeting}, nil\n}", "func decodeGRPCTicResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\t_ = grpcReply.(*pb.TicResponse)\n\treturn endpoints.TicResponse{}, nil\n}", "func (*UnlockAccountResponse) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{24}\n}", "func DecodeForgotPasswordResponse(ctx context.Context, v interface{}, hdr, trlr metadata.MD) (interface{}, error) {\n\tmessage, ok := v.(*user_methodpb.ForgotPasswordResponse)\n\tif !ok {\n\t\treturn nil, goagrpc.ErrInvalidType(\"userMethod\", \"forgotPassword\", \"*user_methodpb.ForgotPasswordResponse\", v)\n\t}\n\tres := NewForgotPasswordResult(message)\n\treturn res, nil\n}", "func PrivatecaBetaCertificateTemplatePassthroughExtensionsKnownExtensionsEnumToProto(e *beta.CertificateTemplatePassthroughExtensionsKnownExtensionsEnum) betapb.PrivatecaBetaCertificateTemplatePassthroughExtensionsKnownExtensionsEnum {\n\tif e == nil {\n\t\treturn betapb.PrivatecaBetaCertificateTemplatePassthroughExtensionsKnownExtensionsEnum(0)\n\t}\n\tif v, ok := betapb.PrivatecaBetaCertificateTemplatePassthroughExtensionsKnownExtensionsEnum_value[\"CertificateTemplatePassthroughExtensionsKnownExtensionsEnum\"+string(*e)]; ok {\n\t\treturn betapb.PrivatecaBetaCertificateTemplatePassthroughExtensionsKnownExtensionsEnum(v)\n\t}\n\treturn betapb.PrivatecaBetaCertificateTemplatePassthroughExtensionsKnownExtensionsEnum(0)\n}", "func (*CMsgClientProvideSurveyResult_Response) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{120, 0}\n}", "func encodeGRPCTacResponse(_ context.Context, grpcReply interface{}) (res interface{}, err error) {\n\treply := grpcReply.(endpoints.TacResponse)\n\treturn &pb.TacResponse{Res: reply.Res}, grpcEncodeError(errors.Cast(reply.Err))\n}", "func (fieldMask *WatchAlertingPoliciesResponse_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}", "func PrivatecaAlphaCaPoolIssuancePolicyIdentityConstraintsToProto(o *alpha.CaPoolIssuancePolicyIdentityConstraints) *alphapb.PrivatecaAlphaCaPoolIssuancePolicyIdentityConstraints {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &alphapb.PrivatecaAlphaCaPoolIssuancePolicyIdentityConstraints{}\n\tp.SetCelExpression(PrivatecaAlphaCaPoolIssuancePolicyIdentityConstraintsCelExpressionToProto(o.CelExpression))\n\tp.SetAllowSubjectPassthrough(dcl.ValueOrEmptyBool(o.AllowSubjectPassthrough))\n\tp.SetAllowSubjectAltNamesPassthrough(dcl.ValueOrEmptyBool(o.AllowSubjectAltNamesPassthrough))\n\treturn p\n}", "func PrivatecaBetaCertificateTemplatePredefinedValuesAdditionalExtensionsToProto(o *beta.CertificateTemplatePredefinedValuesAdditionalExtensions) *betapb.PrivatecaBetaCertificateTemplatePredefinedValuesAdditionalExtensions {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.PrivatecaBetaCertificateTemplatePredefinedValuesAdditionalExtensions{}\n\tp.SetObjectId(PrivatecaBetaCertificateTemplatePredefinedValuesAdditionalExtensionsObjectIdToProto(o.ObjectId))\n\tp.SetCritical(dcl.ValueOrEmptyBool(o.Critical))\n\tp.SetValue(dcl.ValueOrEmptyString(o.Value))\n\treturn p\n}", "func (st *Account) ToProto() *iproto.AccountPb {\n\tacPb := &iproto.AccountPb{}\n\tacPb.Nonce = st.Nonce\n\tif st.Balance != nil {\n\t\tacPb.Balance = st.Balance.Bytes()\n\t}\n\tacPb.Root = make([]byte, hash.HashSize)\n\tcopy(acPb.Root, st.Root[:])\n\tacPb.CodeHash = make([]byte, len(st.CodeHash))\n\tcopy(acPb.CodeHash, st.CodeHash)\n\tacPb.IsCandidate = st.IsCandidate\n\tif st.VotingWeight != nil {\n\t\tacPb.VotingWeight = st.VotingWeight.Bytes()\n\t}\n\tacPb.Votee = st.Votee\n\treturn acPb\n}", "func DecodeStreamedBatchGRPCResponse(ctx context.Context, v interface{}, hdr, trlr metadata.MD) (interface{}, error) {\n\treturn &StreamedBatchGRPCClientStream{\n\t\tstream: v.(publicpb.Public_StreamedBatchGRPCClient),\n\t}, nil\n}", "func ContainerClusterMasterAuthToProto(o *container.ClusterMasterAuth) *containerpb.ContainerClusterMasterAuth {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &containerpb.ContainerClusterMasterAuth{\n\t\tUsername: dcl.ValueOrEmptyString(o.Username),\n\t\tPassword: dcl.ValueOrEmptyString(o.Password),\n\t\tClientCertificateConfig: ContainerClusterMasterAuthClientCertificateConfigToProto(o.ClientCertificateConfig),\n\t\tClusterCaCertificate: dcl.ValueOrEmptyString(o.ClusterCaCertificate),\n\t\tClientCertificate: dcl.ValueOrEmptyString(o.ClientCertificate),\n\t\tClientKey: dcl.ValueOrEmptyString(o.ClientKey),\n\t}\n\treturn p\n}", "func (x *fastReflection_QueryAccountsResponse) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_QueryAccountsResponse\n}", "func ContainerClusterBinaryAuthorizationToProto(o *container.ClusterBinaryAuthorization) *containerpb.ContainerClusterBinaryAuthorization {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &containerpb.ContainerClusterBinaryAuthorization{\n\t\tEnabled: dcl.ValueOrEmptyBool(o.Enabled),\n\t}\n\treturn p\n}", "func (*AccountsResponse) Descriptor() ([]byte, []int) {\n\treturn file_account_proto_rawDescGZIP(), []int{3}\n}", "func AttestorToProto(resource *binaryauthorization.Attestor) *binaryauthorizationpb.BinaryauthorizationAttestor {\n\tp := &binaryauthorizationpb.BinaryauthorizationAttestor{\n\t\tName: dcl.ValueOrEmptyString(resource.Name),\n\t\tDescription: dcl.ValueOrEmptyString(resource.Description),\n\t\tUserOwnedGrafeasNote: BinaryauthorizationAttestorUserOwnedGrafeasNoteToProto(resource.UserOwnedGrafeasNote),\n\t\tUpdateTime: dcl.ValueOrEmptyString(resource.UpdateTime),\n\t\tProject: dcl.ValueOrEmptyString(resource.Project),\n\t}\n\n\treturn p\n}" ]
[ "0.77999973", "0.75196874", "0.716168", "0.63224673", "0.6134078", "0.5806311", "0.55155236", "0.547025", "0.5325929", "0.5290635", "0.52893364", "0.5166631", "0.51124144", "0.5112016", "0.5104857", "0.4943682", "0.48701605", "0.48501328", "0.48420054", "0.48323202", "0.48153365", "0.48052362", "0.47776836", "0.47776836", "0.4746716", "0.47444153", "0.47423357", "0.4727472", "0.47190195", "0.47074378", "0.47070134", "0.4706001", "0.46936873", "0.46910647", "0.46855944", "0.4682806", "0.46827757", "0.4676943", "0.46513537", "0.46507025", "0.46401718", "0.46391386", "0.4633159", "0.46320772", "0.4619116", "0.46189883", "0.46153435", "0.4615206", "0.46136302", "0.45907694", "0.4561577", "0.45591143", "0.4555052", "0.45475245", "0.454342", "0.45423588", "0.45398864", "0.45276767", "0.45266998", "0.45266294", "0.45227075", "0.45099273", "0.45082664", "0.4496812", "0.44931203", "0.44906095", "0.44771588", "0.44750652", "0.44734696", "0.44704437", "0.44671354", "0.4465097", "0.44625157", "0.44599614", "0.44593072", "0.44580036", "0.44579196", "0.4456107", "0.4456011", "0.4450404", "0.4439605", "0.4437896", "0.44343412", "0.44316822", "0.4427954", "0.44267875", "0.44257522", "0.44244802", "0.44202036", "0.44193348", "0.44165808", "0.44128132", "0.4411138", "0.44049448", "0.43960297", "0.43958524", "0.4392836", "0.43911391", "0.43902704", "0.43898675" ]
0.84686226
0
CredentialCreationToProto converts a CredentialCreation to its proto counterpart.
func CredentialCreationToProto(cc *CredentialCreation) *wantypes.CredentialCreation { if cc == nil { return nil } return &wantypes.CredentialCreation{ PublicKey: &wantypes.PublicKeyCredentialCreationOptions{ Challenge: cc.Response.Challenge, Rp: rpEntityToProto(cc.Response.RelyingParty), User: userEntityToProto(cc.Response.User), CredentialParameters: credentialParametersToProto(cc.Response.Parameters), TimeoutMs: int64(cc.Response.Timeout), ExcludeCredentials: credentialDescriptorsToProto(cc.Response.CredentialExcludeList), Attestation: string(cc.Response.Attestation), Extensions: inputExtensionsToProto(cc.Response.Extensions), AuthenticatorSelection: authenticatorSelectionToProto(cc.Response.AuthenticatorSelection), }, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CredentialCreationResponseToProto(ccr *CredentialCreationResponse) *wantypes.CredentialCreationResponse {\n\tif ccr == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialCreationResponse{\n\t\tType: ccr.Type,\n\t\tRawId: ccr.RawID,\n\t\tResponse: &wantypes.AuthenticatorAttestationResponse{\n\t\t\tClientDataJson: ccr.AttestationResponse.ClientDataJSON,\n\t\t\tAttestationObject: ccr.AttestationResponse.AttestationObject,\n\t\t},\n\t\tExtensions: outputExtensionsToProto(ccr.Extensions),\n\t}\n}", "func CredentialCreationFromProto(cc *wantypes.CredentialCreation) *CredentialCreation {\n\tif cc == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialCreation{\n\t\tResponse: publicKeyCredentialCreationOptionsFromProto(cc.PublicKey),\n\t}\n}", "func CredentialCreationResponseFromProto(ccr *wantypes.CredentialCreationResponse) *CredentialCreationResponse {\n\tif ccr == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialCreationResponse{\n\t\tPublicKeyCredential: PublicKeyCredential{\n\t\t\tCredential: Credential{\n\t\t\t\tID: base64.RawURLEncoding.EncodeToString(ccr.RawId),\n\t\t\t\tType: ccr.Type,\n\t\t\t},\n\t\t\tRawID: ccr.RawId,\n\t\t\tExtensions: outputExtensionsFromProto(ccr.Extensions),\n\t\t},\n\t\tAttestationResponse: authenticatorAttestationResponseFromProto(ccr.Response),\n\t}\n}", "func CredentialAssertionToProto(assertion *CredentialAssertion) *wantypes.CredentialAssertion {\n\tif assertion == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialAssertion{\n\t\tPublicKey: &wantypes.PublicKeyCredentialRequestOptions{\n\t\t\tChallenge: assertion.Response.Challenge,\n\t\t\tTimeoutMs: int64(assertion.Response.Timeout),\n\t\t\tRpId: assertion.Response.RelyingPartyID,\n\t\t\tAllowCredentials: credentialDescriptorsToProto(assertion.Response.AllowedCredentials),\n\t\t\tExtensions: inputExtensionsToProto(assertion.Response.Extensions),\n\t\t\tUserVerification: string(assertion.Response.UserVerification),\n\t\t},\n\t}\n}", "func CredentialCreationFromProtocol(cc *protocol.CredentialCreation) *CredentialCreation {\n\tif cc == nil {\n\t\treturn nil\n\t}\n\n\t// Based on our configuration we should always get a protocol.URLEncodedBase64\n\t// user ID, but the go-webauthn/webauthn is capable of generating strings too.\n\tvar userID []byte\n\tif id := cc.Response.User.ID; id != nil {\n\t\tswitch uid := id.(type) {\n\t\tcase protocol.URLEncodedBase64:\n\t\t\tuserID = uid\n\t\tcase string:\n\t\t\tuserID = []byte(uid)\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"Unexpected WebAuthn cc.Response.User.ID type: %T\", id))\n\t\t}\n\t}\n\n\treturn &CredentialCreation{\n\t\tResponse: PublicKeyCredentialCreationOptions{\n\t\t\tChallenge: Challenge(cc.Response.Challenge),\n\t\t\tRelyingParty: RelyingPartyEntity{\n\t\t\t\tCredentialEntity: cc.Response.RelyingParty.CredentialEntity,\n\t\t\t\tID: cc.Response.RelyingParty.ID,\n\t\t\t},\n\t\t\tUser: UserEntity{\n\t\t\t\tCredentialEntity: cc.Response.User.CredentialEntity,\n\t\t\t\tDisplayName: cc.Response.User.Name,\n\t\t\t\tID: userID,\n\t\t\t},\n\t\t\tParameters: credentialParametersFromProtocol(cc.Response.Parameters),\n\t\t\tAuthenticatorSelection: AuthenticatorSelection{\n\t\t\t\tAuthenticatorAttachment: cc.Response.AuthenticatorSelection.AuthenticatorAttachment,\n\t\t\t\tRequireResidentKey: cc.Response.AuthenticatorSelection.RequireResidentKey,\n\t\t\t\tResidentKey: cc.Response.AuthenticatorSelection.ResidentKey,\n\t\t\t\tUserVerification: cc.Response.AuthenticatorSelection.UserVerification,\n\t\t\t},\n\t\t\tTimeout: cc.Response.Timeout,\n\t\t\tCredentialExcludeList: credentialDescriptorsFromProtocol(cc.Response.CredentialExcludeList),\n\t\t\tExtensions: cc.Response.Extensions,\n\t\t\tAttestation: cc.Response.Attestation,\n\t\t},\n\t}\n}", "func CredentialAssertionFromProto(assertion *wantypes.CredentialAssertion) *CredentialAssertion {\n\tif assertion == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialAssertion{\n\t\tResponse: publicKeyCredentialRequestOptionsFromProto(assertion.PublicKey),\n\t}\n}", "func CredentialAssertionResponseToProto(car *CredentialAssertionResponse) *wantypes.CredentialAssertionResponse {\n\tif car == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialAssertionResponse{\n\t\tType: car.Type,\n\t\tRawId: car.RawID,\n\t\tResponse: &wantypes.AuthenticatorAssertionResponse{\n\t\t\tClientDataJson: car.AssertionResponse.ClientDataJSON,\n\t\t\tAuthenticatorData: car.AssertionResponse.AuthenticatorData,\n\t\t\tSignature: car.AssertionResponse.Signature,\n\t\t\tUserHandle: car.AssertionResponse.UserHandle,\n\t\t},\n\t\tExtensions: outputExtensionsToProto(car.Extensions),\n\t}\n}", "func ContainerClusterMasterAuthToProto(o *container.ClusterMasterAuth) *containerpb.ContainerClusterMasterAuth {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &containerpb.ContainerClusterMasterAuth{\n\t\tUsername: dcl.ValueOrEmptyString(o.Username),\n\t\tPassword: dcl.ValueOrEmptyString(o.Password),\n\t\tClientCertificateConfig: ContainerClusterMasterAuthClientCertificateConfigToProto(o.ClientCertificateConfig),\n\t\tClusterCaCertificate: dcl.ValueOrEmptyString(o.ClusterCaCertificate),\n\t\tClientCertificate: dcl.ValueOrEmptyString(o.ClientCertificate),\n\t\tClientKey: dcl.ValueOrEmptyString(o.ClientKey),\n\t}\n\treturn p\n}", "func (n *nativeImpl) MakeCredential(origin string, in *makeCredentialRequest) (*wantypes.CredentialCreationResponse, error) {\n\thwnd, err := getForegroundWindow()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tvar out *webauthnCredentialAttestation\n\tret, _, err := procWebAuthNAuthenticatorMakeCredential.Call(\n\t\tuintptr(hwnd),\n\t\tuintptr(unsafe.Pointer(in.rp)),\n\t\tuintptr(unsafe.Pointer(in.user)),\n\t\tuintptr(unsafe.Pointer(in.credParameters)),\n\t\tuintptr(unsafe.Pointer(in.clientData)),\n\t\tuintptr(unsafe.Pointer(in.opts)),\n\t\tuintptr(unsafe.Pointer(&out)),\n\t)\n\tif ret != 0 {\n\t\treturn nil, trace.Wrap(getErrorNameOrLastErr(ret, err))\n\t}\n\tif out == nil {\n\t\treturn nil, errors.New(\"unexpected nil response from MakeCredential\")\n\t}\n\n\t// Note that we need to copy bytes out of `out` if we want to free object.\n\t// That's why bytesFromCBytes is used.\n\t// We don't care about free error so ignore it explicitly.\n\tdefer func() { _ = freeCredentialAttestation(out) }()\n\n\tcredential := bytesFromCBytes(out.cbCredentialID, out.pbCredentialID)\n\n\treturn &wantypes.CredentialCreationResponse{\n\t\tPublicKeyCredential: wantypes.PublicKeyCredential{\n\t\t\tCredential: wantypes.Credential{\n\t\t\t\tID: base64.RawURLEncoding.EncodeToString(credential),\n\t\t\t\tType: string(protocol.PublicKeyCredentialType),\n\t\t\t},\n\t\t\tRawID: credential,\n\t\t},\n\t\tAttestationResponse: wantypes.AuthenticatorAttestationResponse{\n\t\t\tAuthenticatorResponse: wantypes.AuthenticatorResponse{\n\t\t\t\tClientDataJSON: in.jsonEncodedClientData,\n\t\t\t},\n\t\t\tAttestationObject: bytesFromCBytes(out.cbAttestationObject, out.pbAttestationObject),\n\t\t},\n\t}, nil\n}", "func CertificateTemplateToProto(resource *beta.CertificateTemplate) *betapb.PrivatecaBetaCertificateTemplate {\n\tp := &betapb.PrivatecaBetaCertificateTemplate{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetPredefinedValues(PrivatecaBetaCertificateTemplatePredefinedValuesToProto(resource.PredefinedValues))\n\tp.SetIdentityConstraints(PrivatecaBetaCertificateTemplateIdentityConstraintsToProto(resource.IdentityConstraints))\n\tp.SetPassthroughExtensions(PrivatecaBetaCertificateTemplatePassthroughExtensionsToProto(resource.PassthroughExtensions))\n\tp.SetDescription(dcl.ValueOrEmptyString(resource.Description))\n\tp.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime))\n\tp.SetUpdateTime(dcl.ValueOrEmptyString(resource.UpdateTime))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetLocation(dcl.ValueOrEmptyString(resource.Location))\n\tmLabels := make(map[string]string, len(resource.Labels))\n\tfor k, r := range resource.Labels {\n\t\tmLabels[k] = r\n\t}\n\tp.SetLabels(mLabels)\n\n\treturn p\n}", "func (*Credential) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{10}\n}", "func MustNewAuthenticationMetadataFromProto(message *auth_pb.AuthenticationMetadata) *AuthenticationMetadata {\n\tauthenticationMetadata, err := NewAuthenticationMetadataFromProto(message)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn authenticationMetadata\n}", "func ProtoToCertificateTemplate(p *betapb.PrivatecaBetaCertificateTemplate) *beta.CertificateTemplate {\n\tobj := &beta.CertificateTemplate{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tPredefinedValues: ProtoToPrivatecaBetaCertificateTemplatePredefinedValues(p.GetPredefinedValues()),\n\t\tIdentityConstraints: ProtoToPrivatecaBetaCertificateTemplateIdentityConstraints(p.GetIdentityConstraints()),\n\t\tPassthroughExtensions: ProtoToPrivatecaBetaCertificateTemplatePassthroughExtensions(p.GetPassthroughExtensions()),\n\t\tDescription: dcl.StringOrNil(p.GetDescription()),\n\t\tCreateTime: dcl.StringOrNil(p.GetCreateTime()),\n\t\tUpdateTime: dcl.StringOrNil(p.GetUpdateTime()),\n\t\tProject: dcl.StringOrNil(p.GetProject()),\n\t\tLocation: dcl.StringOrNil(p.GetLocation()),\n\t}\n\treturn obj\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 ConvertCredentialSchema(in ClaimCredentialSchemaInput) claimtypes.CredentialSchema {\n\treturn claimtypes.CredentialSchema{\n\t\tID: in.ID,\n\t\tType: in.Type,\n\t}\n}", "func NewAuthenticationMetadataFromProto(message *auth_pb.AuthenticationMetadata) (*AuthenticationMetadata, error) {\n\t// Create raw value, which stores the contents of the Protobuf\n\t// message as an object normally returned by json.Unmarshal().\n\t// This can be used to do JMESPath matching by the authorization\n\t// layer.\n\tmessageJSON, err := protojson.Marshal(message)\n\tif err != nil {\n\t\treturn nil, util.StatusWrapWithCode(err, codes.InvalidArgument, \"Cannot convert authentication metadata to JSON\")\n\t}\n\tvar raw map[string]any\n\tif err := json.Unmarshal(messageJSON, &raw); err != nil {\n\t\treturn nil, util.StatusWrapWithCode(err, codes.InvalidArgument, \"Cannot parse authentication metadata JSON\")\n\t}\n\n\ttracingAttributes, err := otel.NewKeyValueListFromProto(message.GetTracingAttributes(), \"auth.\")\n\tif err != nil {\n\t\treturn nil, util.StatusWrap(err, \"Cannot create tracing attributes\")\n\t}\n\n\tam := &AuthenticationMetadata{\n\t\traw: raw,\n\t\ttracingAttributes: tracingAttributes,\n\t}\n\tproto.Merge(&am.proto, message)\n\treturn am, nil\n}", "func (m *Mutate) ToProto() proto.Message {\n\tp, _, _ := m.toProto(false, nil)\n\treturn p\n}", "func (*CredentialMessage) Descriptor() ([]byte, []int) {\n\treturn file_task_proto_rawDescGZIP(), []int{1}\n}", "func InstanceTemplateToProto(resource *beta.InstanceTemplate) *betapb.ComputeBetaInstanceTemplate {\n\tp := &betapb.ComputeBetaInstanceTemplate{\n\t\tCreationTimestamp: dcl.ValueOrEmptyString(resource.CreationTimestamp),\n\t\tDescription: dcl.ValueOrEmptyString(resource.Description),\n\t\tId: dcl.ValueOrEmptyInt64(resource.Id),\n\t\tSelfLink: dcl.ValueOrEmptyString(resource.SelfLink),\n\t\tName: dcl.ValueOrEmptyString(resource.Name),\n\t\tProperties: ComputeBetaInstanceTemplatePropertiesToProto(resource.Properties),\n\t\tProject: dcl.ValueOrEmptyString(resource.Project),\n\t}\n\n\treturn p\n}", "func ComputeBetaInstanceTemplatePropertiesServiceAccountsToProto(o *beta.InstanceTemplatePropertiesServiceAccounts) *betapb.ComputeBetaInstanceTemplatePropertiesServiceAccounts {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.ComputeBetaInstanceTemplatePropertiesServiceAccounts{\n\t\tEmail: dcl.ValueOrEmptyString(o.Email),\n\t}\n\tfor _, r := range o.Scopes {\n\t\tp.Scopes = append(p.Scopes, r)\n\t}\n\treturn p\n}", "func (*CredentialAttribute) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{9}\n}", "func InspectTemplateToProto(resource *dlp.InspectTemplate) *dlppb.DlpInspectTemplate {\n\tp := &dlppb.DlpInspectTemplate{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetDisplayName(dcl.ValueOrEmptyString(resource.DisplayName))\n\tp.SetDescription(dcl.ValueOrEmptyString(resource.Description))\n\tp.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime))\n\tp.SetUpdateTime(dcl.ValueOrEmptyString(resource.UpdateTime))\n\tp.SetInspectConfig(DlpInspectTemplateInspectConfigToProto(resource.InspectConfig))\n\tp.SetLocationId(dcl.ValueOrEmptyString(resource.LocationId))\n\tp.SetParent(dcl.ValueOrEmptyString(resource.Parent))\n\tp.SetLocation(dcl.ValueOrEmptyString(resource.Location))\n\n\treturn p\n}", "func (fieldMask *CreateServiceRequest_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}", "func ServiceAccountToProto(resource *iam.ServiceAccount) *iampb.IamServiceAccount {\n\tp := &iampb.IamServiceAccount{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetUniqueId(dcl.ValueOrEmptyString(resource.UniqueId))\n\tp.SetEmail(dcl.ValueOrEmptyString(resource.Email))\n\tp.SetDisplayName(dcl.ValueOrEmptyString(resource.DisplayName))\n\tp.SetDescription(dcl.ValueOrEmptyString(resource.Description))\n\tp.SetOauth2ClientId(dcl.ValueOrEmptyString(resource.OAuth2ClientId))\n\tp.SetActasResources(IamServiceAccountActasResourcesToProto(resource.ActasResources))\n\tp.SetDisabled(dcl.ValueOrEmptyBool(resource.Disabled))\n\n\treturn p\n}", "func (*CreateConversationRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_threads_proto_rawDescGZIP(), []int{2}\n}", "func (*CreateRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_users_v1_users_proto_rawDescGZIP(), []int{0}\n}", "func CredentialAssertionResponseFromProto(car *wantypes.CredentialAssertionResponse) *CredentialAssertionResponse {\n\tif car == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialAssertionResponse{\n\t\tPublicKeyCredential: PublicKeyCredential{\n\t\t\tCredential: Credential{\n\t\t\t\tID: base64.RawURLEncoding.EncodeToString(car.RawId),\n\t\t\t\tType: car.Type,\n\t\t\t},\n\t\t\tRawID: car.RawId,\n\t\t\tExtensions: outputExtensionsFromProto(car.Extensions),\n\t\t},\n\t\tAssertionResponse: authenticatorAssertionResponseFromProto(car.Response),\n\t}\n}", "func (mock *MailgunMock) CreateCredentialCalls() []struct {\n\tLogin string\n\tPassword string\n} {\n\tvar calls []struct {\n\t\tLogin string\n\t\tPassword string\n\t}\n\tlockMailgunMockCreateCredential.RLock()\n\tcalls = mock.calls.CreateCredential\n\tlockMailgunMockCreateCredential.RUnlock()\n\treturn calls\n}", "func AttestorToProto(resource *binaryauthorization.Attestor) *binaryauthorizationpb.BinaryauthorizationAttestor {\n\tp := &binaryauthorizationpb.BinaryauthorizationAttestor{\n\t\tName: dcl.ValueOrEmptyString(resource.Name),\n\t\tDescription: dcl.ValueOrEmptyString(resource.Description),\n\t\tUserOwnedGrafeasNote: BinaryauthorizationAttestorUserOwnedGrafeasNoteToProto(resource.UserOwnedGrafeasNote),\n\t\tUpdateTime: dcl.ValueOrEmptyString(resource.UpdateTime),\n\t\tProject: dcl.ValueOrEmptyString(resource.Project),\n\t}\n\n\treturn p\n}", "func FirewallToProto(resource *compute.Firewall) *computepb.ComputeFirewall {\n\tp := &computepb.ComputeFirewall{\n\t\tCreationTimestamp: dcl.ValueOrEmptyString(resource.CreationTimestamp),\n\t\tDescription: dcl.ValueOrEmptyString(resource.Description),\n\t\tDirection: ComputeFirewallDirectionEnumToProto(resource.Direction),\n\t\tDisabled: dcl.ValueOrEmptyBool(resource.Disabled),\n\t\tId: dcl.ValueOrEmptyString(resource.Id),\n\t\tLogConfig: ComputeFirewallLogConfigToProto(resource.LogConfig),\n\t\tName: dcl.ValueOrEmptyString(resource.Name),\n\t\tNetwork: dcl.ValueOrEmptyString(resource.Network),\n\t\tPriority: dcl.ValueOrEmptyInt64(resource.Priority),\n\t\tSelfLink: dcl.ValueOrEmptyString(resource.SelfLink),\n\t\tProject: dcl.ValueOrEmptyString(resource.Project),\n\t}\n\tfor _, r := range resource.Allowed {\n\t\tp.Allowed = append(p.Allowed, ComputeFirewallAllowedToProto(&r))\n\t}\n\tfor _, r := range resource.Denied {\n\t\tp.Denied = append(p.Denied, ComputeFirewallDeniedToProto(&r))\n\t}\n\tfor _, r := range resource.DestinationRanges {\n\t\tp.DestinationRanges = append(p.DestinationRanges, r)\n\t}\n\tfor _, r := range resource.SourceRanges {\n\t\tp.SourceRanges = append(p.SourceRanges, r)\n\t}\n\tfor _, r := range resource.SourceServiceAccounts {\n\t\tp.SourceServiceAccounts = append(p.SourceServiceAccounts, r)\n\t}\n\tfor _, r := range resource.SourceTags {\n\t\tp.SourceTags = append(p.SourceTags, r)\n\t}\n\tfor _, r := range resource.TargetServiceAccounts {\n\t\tp.TargetServiceAccounts = append(p.TargetServiceAccounts, r)\n\t}\n\tfor _, r := range resource.TargetTags {\n\t\tp.TargetTags = append(p.TargetTags, r)\n\t}\n\n\treturn p\n}", "func (tn *ListNamespaceDescriptors) ToProto() proto.Message {\n\treturn &pb.ListNamespaceDescriptorsRequest{\n\t}\n}", "func VertexaiEndpointEncryptionSpecToProto(o *vertexai.EndpointEncryptionSpec) *vertexaipb.VertexaiEndpointEncryptionSpec {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &vertexaipb.VertexaiEndpointEncryptionSpec{}\n\tp.SetKmsKeyName(dcl.ValueOrEmptyString(o.KmsKeyName))\n\treturn p\n}", "func (*CreateAccountRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{0}\n}", "func (credential *FederatedIdentityCredential) ConvertTo(hub conversion.Hub) error {\n\t// intermediate variable for conversion\n\tvar destination v1beta20220131ps.FederatedIdentityCredential\n\terr := credential.AssignProperties_To_FederatedIdentityCredential(&destination)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"converting to destination from credential\")\n\t}\n\terr = destination.ConvertTo(hub)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"converting from destination to hub\")\n\t}\n\n\treturn nil\n}", "func (*CreateRequest) Descriptor() ([]byte, []int) {\n\treturn file_teams_v1_teams_proto_rawDescGZIP(), []int{2}\n}", "func (c *Client) CreateCredential(in *api.CreateCredentialRequest) (*api.Credential, error) {\n\tout := &api.Credential{}\n\trawURL := fmt.Sprintf(pathCredentials, c.base.String())\n\terr := c.post(rawURL, true, http.StatusCreated, in, out)\n\treturn out, errio.Error(err)\n}", "func ComputeBetaInstanceTemplatePropertiesDisksInitializeParamsToProto(o *beta.InstanceTemplatePropertiesDisksInitializeParams) *betapb.ComputeBetaInstanceTemplatePropertiesDisksInitializeParams {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.ComputeBetaInstanceTemplatePropertiesDisksInitializeParams{\n\t\tDiskName: dcl.ValueOrEmptyString(o.DiskName),\n\t\tDiskSizeGb: dcl.ValueOrEmptyInt64(o.DiskSizeGb),\n\t\tDiskType: dcl.ValueOrEmptyString(o.DiskType),\n\t\tSourceImage: dcl.ValueOrEmptyString(o.SourceImage),\n\t\tSourceSnapshot: dcl.ValueOrEmptyString(o.SourceSnapshot),\n\t\tSourceSnapshotEncryptionKey: ComputeBetaInstanceTemplatePropertiesDisksInitializeParamsSourceSnapshotEncryptionKeyToProto(o.SourceSnapshotEncryptionKey),\n\t\tDescription: dcl.ValueOrEmptyString(o.Description),\n\t\tOnUpdateAction: dcl.ValueOrEmptyString(o.OnUpdateAction),\n\t\tSourceImageEncryptionKey: ComputeBetaInstanceTemplatePropertiesDisksInitializeParamsSourceImageEncryptionKeyToProto(o.SourceImageEncryptionKey),\n\t}\n\tp.Labels = make(map[string]string)\n\tfor k, r := range o.Labels {\n\t\tp.Labels[k] = r\n\t}\n\tfor _, r := range o.ResourcePolicies {\n\t\tp.ResourcePolicies = append(p.ResourcePolicies, r)\n\t}\n\treturn p\n}", "func CloudkmsBetaCryptoKeyVersionTemplateToProto(o *beta.CryptoKeyVersionTemplate) *betapb.CloudkmsBetaCryptoKeyVersionTemplate {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.CloudkmsBetaCryptoKeyVersionTemplate{}\n\tp.SetProtectionLevel(CloudkmsBetaCryptoKeyVersionTemplateProtectionLevelEnumToProto(o.ProtectionLevel))\n\tp.SetAlgorithm(CloudkmsBetaCryptoKeyVersionTemplateAlgorithmEnumToProto(o.Algorithm))\n\treturn p\n}", "func ProtoToFirewall(p *computepb.ComputeFirewall) *compute.Firewall {\n\tobj := &compute.Firewall{\n\t\tCreationTimestamp: dcl.StringOrNil(p.GetCreationTimestamp()),\n\t\tDescription: dcl.StringOrNil(p.Description),\n\t\tDirection: ProtoToComputeFirewallDirectionEnum(p.GetDirection()),\n\t\tDisabled: dcl.Bool(p.Disabled),\n\t\tId: dcl.StringOrNil(p.Id),\n\t\tLogConfig: ProtoToComputeFirewallLogConfig(p.GetLogConfig()),\n\t\tName: dcl.StringOrNil(p.Name),\n\t\tNetwork: dcl.StringOrNil(p.Network),\n\t\tPriority: dcl.Int64OrNil(p.Priority),\n\t\tSelfLink: dcl.StringOrNil(p.SelfLink),\n\t\tProject: dcl.StringOrNil(p.Project),\n\t}\n\tfor _, r := range p.GetAllowed() {\n\t\tobj.Allowed = append(obj.Allowed, *ProtoToComputeFirewallAllowed(r))\n\t}\n\tfor _, r := range p.GetDenied() {\n\t\tobj.Denied = append(obj.Denied, *ProtoToComputeFirewallDenied(r))\n\t}\n\tfor _, r := range p.GetDestinationRanges() {\n\t\tobj.DestinationRanges = append(obj.DestinationRanges, r)\n\t}\n\tfor _, r := range p.GetSourceRanges() {\n\t\tobj.SourceRanges = append(obj.SourceRanges, r)\n\t}\n\tfor _, r := range p.GetSourceServiceAccounts() {\n\t\tobj.SourceServiceAccounts = append(obj.SourceServiceAccounts, r)\n\t}\n\tfor _, r := range p.GetSourceTags() {\n\t\tobj.SourceTags = append(obj.SourceTags, r)\n\t}\n\tfor _, r := range p.GetTargetServiceAccounts() {\n\t\tobj.TargetServiceAccounts = append(obj.TargetServiceAccounts, r)\n\t}\n\tfor _, r := range p.GetTargetTags() {\n\t\tobj.TargetTags = append(obj.TargetTags, r)\n\t}\n\treturn obj\n}", "func SubscriptionToProto(resource *pubsublite.Subscription) *pubsublitepb.PubsubliteSubscription {\n\tp := &pubsublitepb.PubsubliteSubscription{\n\t\tName: dcl.ValueOrEmptyString(resource.Name),\n\t\tTopic: dcl.ValueOrEmptyString(resource.Topic),\n\t\tDeliveryConfig: PubsubliteSubscriptionDeliveryConfigToProto(resource.DeliveryConfig),\n\t\tProject: dcl.ValueOrEmptyString(resource.Project),\n\t\tLocation: dcl.ValueOrEmptyString(resource.Location),\n\t}\n\n\treturn p\n}", "func (in *CredentialSpec) DeepCopy() *CredentialSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(CredentialSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (*Credential) Descriptor() ([]byte, []int) {\n\treturn file_auth_proto_rawDescGZIP(), []int{2}\n}", "func (*CreateRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_wallet_proto_rawDescGZIP(), []int{1}\n}", "func ComputeBetaInstanceTemplatePropertiesSchedulingToProto(o *beta.InstanceTemplatePropertiesScheduling) *betapb.ComputeBetaInstanceTemplatePropertiesScheduling {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.ComputeBetaInstanceTemplatePropertiesScheduling{\n\t\tAutomaticRestart: dcl.ValueOrEmptyBool(o.AutomaticRestart),\n\t\tOnHostMaintenance: dcl.ValueOrEmptyString(o.OnHostMaintenance),\n\t\tPreemptible: dcl.ValueOrEmptyBool(o.Preemptible),\n\t}\n\tfor _, r := range o.NodeAffinities {\n\t\tp.NodeAffinities = append(p.NodeAffinities, ComputeBetaInstanceTemplatePropertiesSchedulingNodeAffinitiesToProto(&r))\n\t}\n\treturn p\n}", "func ProtoToCryptoKey(p *betapb.CloudkmsBetaCryptoKey) *beta.CryptoKey {\n\tobj := &beta.CryptoKey{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tPrimary: ProtoToCloudkmsBetaCryptoKeyPrimary(p.GetPrimary()),\n\t\tPurpose: ProtoToCloudkmsBetaCryptoKeyPurposeEnum(p.GetPurpose()),\n\t\tCreateTime: dcl.StringOrNil(p.GetCreateTime()),\n\t\tNextRotationTime: dcl.StringOrNil(p.GetNextRotationTime()),\n\t\tRotationPeriod: dcl.StringOrNil(p.GetRotationPeriod()),\n\t\tVersionTemplate: ProtoToCloudkmsBetaCryptoKeyVersionTemplate(p.GetVersionTemplate()),\n\t\tImportOnly: dcl.Bool(p.GetImportOnly()),\n\t\tDestroyScheduledDuration: dcl.StringOrNil(p.GetDestroyScheduledDuration()),\n\t\tProject: dcl.StringOrNil(p.GetProject()),\n\t\tLocation: dcl.StringOrNil(p.GetLocation()),\n\t\tKeyRing: dcl.StringOrNil(p.GetKeyRing()),\n\t}\n\treturn obj\n}", "func CryptoKeyToProto(resource *beta.CryptoKey) *betapb.CloudkmsBetaCryptoKey {\n\tp := &betapb.CloudkmsBetaCryptoKey{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetPrimary(CloudkmsBetaCryptoKeyPrimaryToProto(resource.Primary))\n\tp.SetPurpose(CloudkmsBetaCryptoKeyPurposeEnumToProto(resource.Purpose))\n\tp.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime))\n\tp.SetNextRotationTime(dcl.ValueOrEmptyString(resource.NextRotationTime))\n\tp.SetRotationPeriod(dcl.ValueOrEmptyString(resource.RotationPeriod))\n\tp.SetVersionTemplate(CloudkmsBetaCryptoKeyVersionTemplateToProto(resource.VersionTemplate))\n\tp.SetImportOnly(dcl.ValueOrEmptyBool(resource.ImportOnly))\n\tp.SetDestroyScheduledDuration(dcl.ValueOrEmptyString(resource.DestroyScheduledDuration))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetLocation(dcl.ValueOrEmptyString(resource.Location))\n\tp.SetKeyRing(dcl.ValueOrEmptyString(resource.KeyRing))\n\tmLabels := make(map[string]string, len(resource.Labels))\n\tfor k, r := range resource.Labels {\n\t\tmLabels[k] = r\n\t}\n\tp.SetLabels(mLabels)\n\n\treturn p\n}", "func (*IssueCredentialRequest) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{11}\n}", "func (*CreateRequest) Descriptor() ([]byte, []int) {\n\treturn file_account_proto_rawDescGZIP(), []int{0}\n}", "func (*CreateJobRequest) Descriptor() ([]byte, []int) {\n\treturn file_grpc_proto_rawDescGZIP(), []int{1}\n}", "func (*CredentialsProto) Descriptor() ([]byte, []int) {\n\treturn file_Security_proto_rawDescGZIP(), []int{2}\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 ContainerClusterAuthenticatorGroupsConfigToProto(o *container.ClusterAuthenticatorGroupsConfig) *containerpb.ContainerClusterAuthenticatorGroupsConfig {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &containerpb.ContainerClusterAuthenticatorGroupsConfig{\n\t\tEnabled: dcl.ValueOrEmptyBool(o.Enabled),\n\t\tSecurityGroup: dcl.ValueOrEmptyString(o.SecurityGroup),\n\t}\n\treturn p\n}", "func (*PasswordComplexityPolicyCreate) Descriptor() ([]byte, []int) {\n\treturn file_management_proto_rawDescGZIP(), []int{37}\n}", "func (*CreateReq) Descriptor() ([]byte, []int) {\n\treturn file_internal_proto_crypto_proto_rawDescGZIP(), []int{4}\n}", "func ProtoToInspectTemplate(p *dlppb.DlpInspectTemplate) *dlp.InspectTemplate {\n\tobj := &dlp.InspectTemplate{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tDisplayName: dcl.StringOrNil(p.GetDisplayName()),\n\t\tDescription: dcl.StringOrNil(p.GetDescription()),\n\t\tCreateTime: dcl.StringOrNil(p.GetCreateTime()),\n\t\tUpdateTime: dcl.StringOrNil(p.GetUpdateTime()),\n\t\tInspectConfig: ProtoToDlpInspectTemplateInspectConfig(p.GetInspectConfig()),\n\t\tLocationId: dcl.StringOrNil(p.GetLocationId()),\n\t\tParent: dcl.StringOrNil(p.GetParent()),\n\t\tLocation: dcl.StringOrNil(p.GetLocation()),\n\t}\n\treturn obj\n}", "func DeidentifyTemplateToProto(resource *beta.DeidentifyTemplate) *betapb.DlpBetaDeidentifyTemplate {\n\tp := &betapb.DlpBetaDeidentifyTemplate{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetDisplayName(dcl.ValueOrEmptyString(resource.DisplayName))\n\tp.SetDescription(dcl.ValueOrEmptyString(resource.Description))\n\tp.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime))\n\tp.SetUpdateTime(dcl.ValueOrEmptyString(resource.UpdateTime))\n\tp.SetDeidentifyConfig(DlpBetaDeidentifyTemplateDeidentifyConfigToProto(resource.DeidentifyConfig))\n\tp.SetLocationId(dcl.ValueOrEmptyString(resource.LocationId))\n\tp.SetParent(dcl.ValueOrEmptyString(resource.Parent))\n\tp.SetLocation(dcl.ValueOrEmptyString(resource.Location))\n\n\treturn p\n}", "func (*CreateRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_user_proto_rawDescGZIP(), []int{3}\n}", "func ToDescriptorProto(message protoreflect.MessageDescriptor) *descriptorpb.DescriptorProto {\n\tp := &descriptorpb.DescriptorProto{\n\t\tName: proto.String(string(message.Name())),\n\t\tOptions: proto.Clone(message.Options()).(*descriptorpb.MessageOptions),\n\t}\n\tfor i, fields := 0, message.Fields(); i < fields.Len(); i++ {\n\t\tp.Field = append(p.Field, ToFieldDescriptorProto(fields.Get(i)))\n\t}\n\tfor i, exts := 0, message.Extensions(); i < exts.Len(); i++ {\n\t\tp.Extension = append(p.Extension, ToFieldDescriptorProto(exts.Get(i)))\n\t}\n\tfor i, messages := 0, message.Messages(); i < messages.Len(); i++ {\n\t\tp.NestedType = append(p.NestedType, ToDescriptorProto(messages.Get(i)))\n\t}\n\tfor i, enums := 0, message.Enums(); i < enums.Len(); i++ {\n\t\tp.EnumType = append(p.EnumType, ToEnumDescriptorProto(enums.Get(i)))\n\t}\n\tfor i, xranges := 0, message.ExtensionRanges(); i < xranges.Len(); i++ {\n\t\txrange := xranges.Get(i)\n\t\tp.ExtensionRange = append(p.ExtensionRange, &descriptorpb.DescriptorProto_ExtensionRange{\n\t\t\tStart: proto.Int32(int32(xrange[0])),\n\t\t\tEnd: proto.Int32(int32(xrange[1])),\n\t\t\tOptions: proto.Clone(message.ExtensionRangeOptions(i)).(*descriptorpb.ExtensionRangeOptions),\n\t\t})\n\t}\n\tfor i, oneofs := 0, message.Oneofs(); i < oneofs.Len(); i++ {\n\t\tp.OneofDecl = append(p.OneofDecl, ToOneofDescriptorProto(oneofs.Get(i)))\n\t}\n\tfor i, ranges := 0, message.ReservedRanges(); i < ranges.Len(); i++ {\n\t\trrange := ranges.Get(i)\n\t\tp.ReservedRange = append(p.ReservedRange, &descriptorpb.DescriptorProto_ReservedRange{\n\t\t\tStart: proto.Int32(int32(rrange[0])),\n\t\t\tEnd: proto.Int32(int32(rrange[1])),\n\t\t})\n\t}\n\tfor i, names := 0, message.ReservedNames(); i < names.Len(); i++ {\n\t\tp.ReservedName = append(p.ReservedName, string(names.Get(i)))\n\t}\n\treturn p\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}", "func (*CreateConnectionRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_protobuf_spec_connection_user_v1_proto_rawDescGZIP(), []int{12}\n}", "func ComputeBetaInstanceTemplatePropertiesToProto(o *beta.InstanceTemplateProperties) *betapb.ComputeBetaInstanceTemplateProperties {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.ComputeBetaInstanceTemplateProperties{\n\t\tCanIpForward: dcl.ValueOrEmptyBool(o.CanIPForward),\n\t\tDescription: dcl.ValueOrEmptyString(o.Description),\n\t\tMachineType: dcl.ValueOrEmptyString(o.MachineType),\n\t\tMinCpuPlatform: dcl.ValueOrEmptyString(o.MinCpuPlatform),\n\t\tReservationAffinity: ComputeBetaInstanceTemplatePropertiesReservationAffinityToProto(o.ReservationAffinity),\n\t\tShieldedInstanceConfig: ComputeBetaInstanceTemplatePropertiesShieldedInstanceConfigToProto(o.ShieldedInstanceConfig),\n\t\tScheduling: ComputeBetaInstanceTemplatePropertiesSchedulingToProto(o.Scheduling),\n\t}\n\tfor _, r := range o.Disks {\n\t\tp.Disks = append(p.Disks, ComputeBetaInstanceTemplatePropertiesDisksToProto(&r))\n\t}\n\tp.Labels = make(map[string]string)\n\tfor k, r := range o.Labels {\n\t\tp.Labels[k] = r\n\t}\n\tp.Metadata = make(map[string]string)\n\tfor k, r := range o.Metadata {\n\t\tp.Metadata[k] = r\n\t}\n\tfor _, r := range o.GuestAccelerators {\n\t\tp.GuestAccelerators = append(p.GuestAccelerators, ComputeBetaInstanceTemplatePropertiesGuestAcceleratorsToProto(&r))\n\t}\n\tfor _, r := range o.NetworkInterfaces {\n\t\tp.NetworkInterfaces = append(p.NetworkInterfaces, ComputeBetaInstanceTemplatePropertiesNetworkInterfacesToProto(&r))\n\t}\n\tfor _, r := range o.ServiceAccounts {\n\t\tp.ServiceAccounts = append(p.ServiceAccounts, ComputeBetaInstanceTemplatePropertiesServiceAccountsToProto(&r))\n\t}\n\tfor _, r := range o.Tags {\n\t\tp.Tags = append(p.Tags, r)\n\t}\n\treturn p\n}", "func (*CreateRoleRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_role_pb_request_proto_rawDescGZIP(), []int{0}\n}", "func (u *User) ToProto() *api.StateUser {\n\tuser := new(api.StateUser)\n\tuser.Host = string(u.Host)\n\tuser.Realname = u.Realname\n\n\treturn user\n}", "func (*CreateRoleRequest) Descriptor() ([]byte, []int) {\n\treturn file_protodef_user_user_proto_rawDescGZIP(), []int{9}\n}", "func (*CreatePermissionRequest) Descriptor() ([]byte, []int) {\n\treturn file_protodef_user_user_proto_rawDescGZIP(), []int{17}\n}", "func (*ListCredentialsRequest) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{22}\n}", "func (*CallCredentials) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_v1_ssl_ssl_proto_rawDescGZIP(), []int{4}\n}", "func (op *Operation) ToProto(wrappedID string) *api.UploadOperation {\n\tvar ref *api.ObjectRef\n\tif op.Status == api.UploadStatus_PUBLISHED {\n\t\tref = &api.ObjectRef{\n\t\t\tHashAlgo: op.HashAlgo,\n\t\t\tHexDigest: op.HexDigest,\n\t\t}\n\t}\n\treturn &api.UploadOperation{\n\t\tOperationId: wrappedID,\n\t\tUploadUrl: op.UploadURL,\n\t\tStatus: op.Status,\n\t\tObject: ref,\n\t\tErrorMessage: op.Error,\n\t}\n}", "func AssignmentToProto(resource *alpha.Assignment) *alphapb.BigqueryreservationAlphaAssignment {\n\tp := &alphapb.BigqueryreservationAlphaAssignment{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetAssignee(dcl.ValueOrEmptyString(resource.Assignee))\n\tp.SetJobType(BigqueryreservationAlphaAssignmentJobTypeEnumToProto(resource.JobType))\n\tp.SetState(BigqueryreservationAlphaAssignmentStateEnumToProto(resource.State))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetLocation(dcl.ValueOrEmptyString(resource.Location))\n\tp.SetReservation(dcl.ValueOrEmptyString(resource.Reservation))\n\n\treturn p\n}", "func (a *OidcApiService) CreateVerifiableCredential(ctx context.Context) ApiCreateVerifiableCredentialRequest {\n\treturn ApiCreateVerifiableCredentialRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (*CreateUserRequest) Descriptor() ([]byte, []int) {\n\treturn file_grpc_user_proto_rawDescGZIP(), []int{6}\n}", "func (*Credentials) Descriptor() ([]byte, []int) {\n\treturn file_GrpcServices_auth_proto_rawDescGZIP(), []int{0}\n}", "func (*CreateRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_contact_proto_rawDescGZIP(), []int{6}\n}", "func (*OperationCreateAccount) Descriptor() ([]byte, []int) {\n\treturn file_chain_proto_rawDescGZIP(), []int{26}\n}", "func (*CreateAccountRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_account_v1_account_proto_rawDescGZIP(), []int{0}\n}", "func (*CMsgClientToGCPrivateChatInfoRequest) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_chat_proto_rawDescGZIP(), []int{5}\n}", "func (credential *FederatedIdentityCredential) GetSpec() genruntime.ConvertibleSpec {\n\treturn &credential.Spec\n}", "func ReservationToProto(resource *alpha.Reservation) *alphapb.BigqueryreservationAlphaReservation {\n\tp := &alphapb.BigqueryreservationAlphaReservation{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetSlotCapacity(dcl.ValueOrEmptyInt64(resource.SlotCapacity))\n\tp.SetIgnoreIdleSlots(dcl.ValueOrEmptyBool(resource.IgnoreIdleSlots))\n\tp.SetCreationTime(dcl.ValueOrEmptyString(resource.CreationTime))\n\tp.SetUpdateTime(dcl.ValueOrEmptyString(resource.UpdateTime))\n\tp.SetMaxConcurrency(dcl.ValueOrEmptyInt64(resource.MaxConcurrency))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetLocation(dcl.ValueOrEmptyString(resource.Location))\n\n\treturn p\n}", "func (*CreateChatRoomRequest) Descriptor() ([]byte, []int) {\n\treturn file_chat_chat_proto_rawDescGZIP(), []int{1}\n}", "func (*AcceptCredentialRequest) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{32}\n}", "func makeGrpcUser(user model.User) *mygrpc.User {\n\treturn &mygrpc.User{\n\t\tID: uint32(user.ID),\n\t\tBirthDate: user.BirthDate,\n\t\tEmail: user.Email,\n\t\tFirstName: user.FirstName,\n\t\tLastName: user.LastName,\n\t\tCreatedAt: timestamppb.New(user.CreatedAt),\n\t\tUpdatedAt: timestamppb.New(user.UpdatedAt),\n\t}\n}", "func (*CreateResult) Descriptor() ([]byte, []int) {\n\treturn file_api_users_v1_users_proto_rawDescGZIP(), []int{1}\n}", "func (*ChangePasswordRequest) Descriptor() ([]byte, []int) {\n\treturn file_pb_auth_proto_rawDescGZIP(), []int{2}\n}", "func (*CreateWorkflowRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_flow_grpc_workflows_proto_rawDescGZIP(), []int{6}\n}", "func ContainerClusterBinaryAuthorizationToProto(o *container.ClusterBinaryAuthorization) *containerpb.ContainerClusterBinaryAuthorization {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &containerpb.ContainerClusterBinaryAuthorization{\n\t\tEnabled: dcl.ValueOrEmptyBool(o.Enabled),\n\t}\n\treturn p\n}", "func (*CreateUserRequest) Descriptor() ([]byte, []int) {\n\treturn edgelq_iam_proto_v1alpha_user_service_proto_rawDescGZIP(), []int{9}\n}", "func CredentialAssertionFromProtocol(a *protocol.CredentialAssertion) *CredentialAssertion {\n\tif a == nil {\n\t\treturn nil\n\t}\n\n\treturn &CredentialAssertion{\n\t\tResponse: PublicKeyCredentialRequestOptions{\n\t\t\tChallenge: Challenge(a.Response.Challenge),\n\t\t\tTimeout: a.Response.Timeout,\n\t\t\tRelyingPartyID: a.Response.RelyingPartyID,\n\t\t\tAllowedCredentials: credentialDescriptorsFromProtocol(a.Response.AllowedCredentials),\n\t\t\tUserVerification: a.Response.UserVerification,\n\t\t\tExtensions: a.Response.Extensions,\n\t\t},\n\t}\n}", "func ContainerClusterConditionsToProto(o *container.ClusterConditions) *containerpb.ContainerClusterConditions {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &containerpb.ContainerClusterConditions{\n\t\tCode: dcl.ValueOrEmptyString(o.Code),\n\t\tMessage: dcl.ValueOrEmptyString(o.Message),\n\t}\n\treturn p\n}", "func (*CreateMessageRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_threads_proto_rawDescGZIP(), []int{12}\n}", "func (policy *StorageAccounts_ManagementPolicy_Spec) ConvertSpecFrom(source genruntime.ConvertibleSpec) error {\n\tsrc, ok := source.(*v1beta20210401s.StorageAccounts_ManagementPolicy_Spec)\n\tif ok {\n\t\t// Populate our instance from source\n\t\treturn policy.AssignProperties_From_StorageAccounts_ManagementPolicy_Spec(src)\n\t}\n\n\t// Convert to an intermediate form\n\tsrc = &v1beta20210401s.StorageAccounts_ManagementPolicy_Spec{}\n\terr := src.ConvertSpecFrom(source)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"initial step of conversion in ConvertSpecFrom()\")\n\t}\n\n\t// Update our instance from src\n\terr = policy.AssignProperties_From_StorageAccounts_ManagementPolicy_Spec(src)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"final step of conversion in ConvertSpecFrom()\")\n\t}\n\n\treturn nil\n}", "func RunServiceTemplateToProto(o *run.ServiceTemplate) *runpb.RunServiceTemplate {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &runpb.RunServiceTemplate{}\n\tp.SetRevision(dcl.ValueOrEmptyString(o.Revision))\n\tp.SetScaling(RunServiceTemplateScalingToProto(o.Scaling))\n\tp.SetVpcAccess(RunServiceTemplateVPCAccessToProto(o.VPCAccess))\n\tp.SetContainerConcurrency(dcl.ValueOrEmptyInt64(o.ContainerConcurrency))\n\tp.SetTimeout(dcl.ValueOrEmptyString(o.Timeout))\n\tp.SetServiceAccount(dcl.ValueOrEmptyString(o.ServiceAccount))\n\tp.SetConfidential(dcl.ValueOrEmptyBool(o.Confidential))\n\tp.SetExecutionEnvironment(RunServiceTemplateExecutionEnvironmentEnumToProto(o.ExecutionEnvironment))\n\tmLabels := make(map[string]string, len(o.Labels))\n\tfor k, r := range o.Labels {\n\t\tmLabels[k] = r\n\t}\n\tp.SetLabels(mLabels)\n\tmAnnotations := make(map[string]string, len(o.Annotations))\n\tfor k, r := range o.Annotations {\n\t\tmAnnotations[k] = r\n\t}\n\tp.SetAnnotations(mAnnotations)\n\tsContainers := make([]*runpb.RunServiceTemplateContainers, len(o.Containers))\n\tfor i, r := range o.Containers {\n\t\tsContainers[i] = RunServiceTemplateContainersToProto(&r)\n\t}\n\tp.SetContainers(sContainers)\n\tsVolumes := make([]*runpb.RunServiceTemplateVolumes, len(o.Volumes))\n\tfor i, r := range o.Volumes {\n\t\tsVolumes[i] = RunServiceTemplateVolumesToProto(&r)\n\t}\n\tp.SetVolumes(sVolumes)\n\treturn p\n}", "func (*ValidateClientCredentialRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_micro_pb_request_proto_rawDescGZIP(), []int{0}\n}", "func VertexaiModelEncryptionSpecToProto(o *vertexai.ModelEncryptionSpec) *vertexaipb.VertexaiModelEncryptionSpec {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &vertexaipb.VertexaiModelEncryptionSpec{}\n\tp.SetKmsKeyName(dcl.ValueOrEmptyString(o.KmsKeyName))\n\treturn p\n}", "func (*CreateConversationResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_threads_proto_rawDescGZIP(), []int{3}\n}", "func ToFieldDescriptorProto(field protoreflect.FieldDescriptor) *descriptorpb.FieldDescriptorProto {\n\tp := &descriptorpb.FieldDescriptorProto{\n\t\tName: proto.String(string(field.Name())),\n\t\tNumber: proto.Int32(int32(field.Number())),\n\t\tLabel: descriptorpb.FieldDescriptorProto_Label(field.Cardinality()).Enum(),\n\t\tOptions: proto.Clone(field.Options()).(*descriptorpb.FieldOptions),\n\t}\n\tif field.IsExtension() {\n\t\tp.Extendee = fullNameOf(field.ContainingMessage())\n\t}\n\tif field.Kind().IsValid() {\n\t\tp.Type = descriptorpb.FieldDescriptorProto_Type(field.Kind()).Enum()\n\t}\n\tif field.Enum() != nil {\n\t\tp.TypeName = fullNameOf(field.Enum())\n\t}\n\tif field.Message() != nil {\n\t\tp.TypeName = fullNameOf(field.Message())\n\t}\n\tif field.HasJSONName() {\n\t\t// A bug in older versions of protoc would always populate the\n\t\t// \"json_name\" option for extensions when it is meaningless.\n\t\t// When it did so, it would always use the camel-cased field name.\n\t\tif field.IsExtension() {\n\t\t\tp.JsonName = proto.String(strs.JSONCamelCase(string(field.Name())))\n\t\t} else {\n\t\t\tp.JsonName = proto.String(field.JSONName())\n\t\t}\n\t}\n\tif field.Syntax() == protoreflect.Proto3 && field.HasOptionalKeyword() {\n\t\tp.Proto3Optional = proto.Bool(true)\n\t}\n\tif field.HasDefault() {\n\t\tdef, err := defval.Marshal(field.Default(), field.DefaultEnumValue(), field.Kind(), defval.Descriptor)\n\t\tif err != nil && field.DefaultEnumValue() != nil {\n\t\t\tdef = string(field.DefaultEnumValue().Name()) // occurs for unresolved enum values\n\t\t} else if err != nil {\n\t\t\tpanic(fmt.Sprintf(\"%v: %v\", field.FullName(), err))\n\t\t}\n\t\tp.DefaultValue = proto.String(def)\n\t}\n\tif oneof := field.ContainingOneof(); oneof != nil {\n\t\tp.OneofIndex = proto.Int32(int32(oneof.Index()))\n\t}\n\treturn p\n}", "func (*CreatePermssionRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_role_pb_request_proto_rawDescGZIP(), []int{1}\n}", "func CreateSyncData() (*syncmsg.ProtoSyncEntityMessageRequest, error) {\n\tcreator := syncmsg.NewCreator()\n\trecord1 := &syncmsg.ProtoRecord{\n\t\tFields: []*syncmsg.ProtoField{\n\t\t\t//Important: these field names need to be in alphabetical order\n\t\t\t//contactIdField, dateOfBirthField, firstNameField, heightFtField, heightInchField, lastNameField,\n\t\t\t//preferredHeightField,\n\t\t\tcreator.CreateStringProtoField(\"contactId\", \"C441B7F6-D3E8-4E7F-9A3B-1BD4BAB6FA48\"),\n\t\t\tcreator.CreateTimeProtoField(\"dateOfBirth\", creator.FormatTimeFromString(\"1990-04-29 00:00:00.000\")),\n\t\t\tcreator.CreateStringProtoField(\"firstName\", \"John\"),\n\t\t\tcreator.CreateInt64ProtoField(\"heightFt\", 6),\n\t\t\tcreator.CreateDoubleProtoField(\"heightInch\", 2.5),\n\t\t\tcreator.CreateStringProtoField(\"lastName\", \"Doe\"),\n\t\t\tcreator.CreateInt64ProtoField(\"preferredHeight\", 1),\n\t\t},\n\t}\n\tif len(creator.Errors) != 0 {\n\t\trequest := &syncmsg.ProtoSyncEntityMessageRequest{}\n\t\treturn request, syncmsg.NewCreatorError(creator.Errors)\n\t}\n\trecord2LastKnown := &syncmsg.ProtoRecord{\n\t\tFields: []*syncmsg.ProtoField{\n\t\t\t//Important: these field names need to be in alphabetical order\n\t\t\tcreator.CreateStringProtoField(\"contactId\", \"911DD745-8916-41C4-9973-F8B38A501602\"),\n\t\t\tcreator.CreateTimeProtoField(\"dateOfBirth\", creator.FormatTimeFromString(\"1994-07-10 00:00:00.000\")),\n\t\t\tcreator.CreateStringProtoField(\"firstName\", \"Henry\"),\n\t\t\tcreator.CreateInt64ProtoField(\"heightFt\", 5),\n\t\t\tcreator.CreateDoubleProtoField(\"heightInch\", 5.5),\n\t\t\tcreator.CreateStringProtoField(\"lastName\", \"Adins\"),\n\t\t\tcreator.CreateInt64ProtoField(\"preferredHeight\", 1),\n\t\t},\n\t}\n\tif len(creator.Errors) != 0 {\n\t\trequest := &syncmsg.ProtoSyncEntityMessageRequest{}\n\t\treturn request, syncmsg.NewCreatorError(creator.Errors)\n\t}\n\trecord2 := &syncmsg.ProtoRecord{\n\t\tFields: []*syncmsg.ProtoField{\n\t\t\t//Important: these field names need to be in alphabetical order\n\t\t\tcreator.CreateStringProtoField(\"contactId\", \"911DD745-8916-41C4-9973-F8B38A501602\"),\n\t\t\tcreator.CreateTimeProtoField(\"dateOfBirth\", creator.FormatTimeFromString(\"1994-07-10 00:00:00.000\")),\n\t\t\tcreator.CreateStringProtoField(\"firstName\", \"Henry\"),\n\t\t\tcreator.CreateInt64ProtoField(\"heightFt\", 5),\n\t\t\tcreator.CreateDoubleProtoField(\"heightInch\", 5.5),\n\t\t\tcreator.CreateStringProtoField(\"lastName\", \"Adkins\"),\n\t\t\tcreator.CreateInt64ProtoField(\"preferredHeight\", 1),\n\t\t},\n\t}\n\tif len(creator.Errors) != 0 {\n\t\trequest := &syncmsg.ProtoSyncEntityMessageRequest{}\n\t\treturn request, syncmsg.NewCreatorError(creator.Errors)\n\t}\n\n\t/*\n\t\trecord3 := &syncmsg.ProtoRecord{\n\t\t\tFields: []*syncmsg.ProtoField{\n\t\t\t\t//Important: these field names need to be in alphabetical order\n\t\t\t\tcreateStringProtoField(\"contactId\", \"42FC5EBC-088D-4DC2-BDBD-D89FA170E5C6\"),\n\t\t\t\tcreateTimeProtoField(\"dateOfBirth\", createDateFromString(\"1992-01-23 00:00:00.000\")),\n\t\t\t\tcreateStringProtoField(\"firstName\", \"John\"),\n\t\t\t\tcreateInt64ProtoField(\"heightFt\", 5),\n\t\t\t\tcreateDoubleProtoField(\"heightInch\", 9),\n\t\t\t\tcreateStringProtoField(\"lastName\", \"Doe\"),\n\t\t\t\tcreateInt64ProtoField(\"preferredHeight\", 1),\n\t\t\t},\n\t\t}\n\t*/\n\trecord1Bytes, err := proto.Marshal(record1)\n\tif err != nil {\n\t\tsyncutil.Error(\"marshaling error: \", err)\n\t\treturn &syncmsg.ProtoSyncEntityMessageRequest{}, err\n\t}\n\trecord2Bytes, err := proto.Marshal(record2)\n\tif err != nil {\n\t\tsyncutil.Error(\"marshaling error: \", err)\n\t\treturn &syncmsg.ProtoSyncEntityMessageRequest{}, err\n\t}\n\trecord2LastKnownBytes, err := proto.Marshal(record2LastKnown)\n\tif err != nil {\n\t\tsyncutil.Error(\"marshaling error: \", err)\n\t\treturn &syncmsg.ProtoSyncEntityMessageRequest{}, err\n\t}\n\trequestData := &syncmsg.ProtoSyncEntityMessageRequest{\n\t\tIsDelete: proto.Bool(false),\n\t\tTransactionBindId: proto.String(\"0F16AEED-E4B4-483E-A7A3-CCABA831FE6E\"),\n\t\tItems: []*syncmsg.ProtoSyncDataMessagesRequest{\n\t\t\t&syncmsg.ProtoSyncDataMessagesRequest{\n\t\t\t\tEntityPluralName: proto.String(\"Contacts\"),\n\t\t\t\tMsgs: []*syncmsg.ProtoSyncDataMessageRequest{\n\t\t\t\t\t&syncmsg.ProtoSyncDataMessageRequest{\n\t\t\t\t\t\tRecordId: proto.String(\"B6581A36-804D-45AC-B2E2-F6DA265AF7DE\"),\n\t\t\t\t\t\tRecordHash: proto.String(Hash256Bytes(record1Bytes)),\n\t\t\t\t\t\tLastKnownPeerHash: nil,\n\t\t\t\t\t\tSentSyncState: syncmsg.SentSyncStateEnum(syncmsg.SentSyncStateEnum_PersistedFirstTimeSentToPeer).Enum(),\n\t\t\t\t\t\tRecordBytesSize: proto.Uint32(uint32(len(record1Bytes))),\n\t\t\t\t\t\tRecordData: record1Bytes,\n\t\t\t\t\t},\n\t\t\t\t\t&syncmsg.ProtoSyncDataMessageRequest{\n\t\t\t\t\t\tRecordId: proto.String(\"911DD745-8916-41C4-9973-F8B38A501602\"),\n\t\t\t\t\t\tRecordHash: proto.String(Hash256Bytes(record2Bytes)),\n\t\t\t\t\t\tLastKnownPeerHash: proto.String(Hash256Bytes(record2LastKnownBytes)),\n\t\t\t\t\t\tSentSyncState: syncmsg.SentSyncStateEnum(syncmsg.SentSyncStateEnum_PersistedStandardSentToPeer).Enum(),\n\t\t\t\t\t\tRecordBytesSize: proto.Uint32(uint32(len(record2Bytes))),\n\t\t\t\t\t\tRecordData: record2Bytes,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t/*\n\t\t\t\t&ProtoSyncDataMessagesRequest{\n\t\t\t\t\tSyncEntityName: proto.String(\"Contact\"),\n\t\t\t\t\tMsgs: []*ProtoSyncDataMessageRequest{\n\t\t\t\t\t\t&ProtoSyncDataMessageRequest{\n\t\t\t\t\t\t\tRecordId: proto.String(\"RecordId2\"),\n\t\t\t\t\t\t\tRecordHash: proto.String(\"RecordHash2\"),\n\t\t\t\t\t\t\tLastKnownPeerHash: nil,\n\t\t\t\t\t\t\tSentSyncState: SentSyncStateEnum(SentSyncStateEnum_FirstTimeSentToPeer).Enum(),\n\t\t\t\t\t\t\tRecordBytesSize: proto.Uint32(uint32(len(record2Bytes))),\n\t\t\t\t\t\t\tRecordData: record2Bytes,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t*/\n\t\t},\n\t}\n\treturn requestData, nil\n}", "func (cc *CredentialCreation) Validate() error {\n\tswitch {\n\tcase cc == nil:\n\t\treturn trace.BadParameter(\"credential creation required\")\n\tcase len(cc.Response.Challenge) == 0:\n\t\treturn trace.BadParameter(\"credential creation challenge required\")\n\tcase cc.Response.RelyingParty.ID == \"\":\n\t\treturn trace.BadParameter(\"credential creation relying party ID required\")\n\tcase len(cc.Response.RelyingParty.Name) == 0:\n\t\treturn trace.BadParameter(\"relying party name required\")\n\tcase len(cc.Response.User.Name) == 0:\n\t\treturn trace.BadParameter(\"user name required\")\n\tcase len(cc.Response.User.DisplayName) == 0:\n\t\treturn trace.BadParameter(\"user display name required\")\n\tcase len(cc.Response.User.ID) == 0:\n\t\treturn trace.BadParameter(\"user ID required\")\n\tdefault:\n\t\treturn nil\n\t}\n}", "func ProtoToServiceAccount(p *iampb.IamServiceAccount) *iam.ServiceAccount {\n\tobj := &iam.ServiceAccount{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tProject: dcl.StringOrNil(p.GetProject()),\n\t\tUniqueId: dcl.StringOrNil(p.GetUniqueId()),\n\t\tEmail: dcl.StringOrNil(p.GetEmail()),\n\t\tDisplayName: dcl.StringOrNil(p.GetDisplayName()),\n\t\tDescription: dcl.StringOrNil(p.GetDescription()),\n\t\tOAuth2ClientId: dcl.StringOrNil(p.GetOauth2ClientId()),\n\t\tActasResources: ProtoToIamServiceAccountActasResources(p.GetActasResources()),\n\t\tDisabled: dcl.Bool(p.GetDisabled()),\n\t}\n\treturn obj\n}", "func (commit *Commit) ToProto() *tmproto.Commit {\n\tif commit == nil {\n\t\treturn nil\n\t}\n\n\tc := new(tmproto.Commit)\n\tsigs := make([]tmproto.CommitSig, len(commit.Signatures))\n\tfor i := range commit.Signatures {\n\t\tsigs[i] = *commit.Signatures[i].ToProto()\n\t}\n\tc.Signatures = sigs\n\n\tc.Height = commit.Height\n\tc.Round = commit.Round\n\tc.BlockID = commit.BlockID.ToProto()\n\n\treturn c\n}" ]
[ "0.7853255", "0.7436043", "0.6886519", "0.6403674", "0.6206073", "0.5689377", "0.566673", "0.5385823", "0.5263375", "0.5230518", "0.51713413", "0.5163685", "0.5157063", "0.5118613", "0.5106233", "0.5077851", "0.50734395", "0.5052029", "0.5017867", "0.50151336", "0.5014979", "0.50126487", "0.5011141", "0.498673", "0.49581107", "0.49380338", "0.49324408", "0.49309912", "0.49278203", "0.4921466", "0.49120829", "0.49073622", "0.49063218", "0.4876235", "0.4873376", "0.48693794", "0.4861315", "0.48447964", "0.48423597", "0.48422205", "0.4834875", "0.48338425", "0.4829496", "0.4824932", "0.48247695", "0.48202825", "0.48155075", "0.48067954", "0.47916132", "0.47871032", "0.47830594", "0.4780339", "0.47782567", "0.47741622", "0.4762922", "0.47490823", "0.474237", "0.47404623", "0.47331333", "0.4730402", "0.47256246", "0.47201043", "0.47110432", "0.47102875", "0.47089002", "0.47021803", "0.47008687", "0.46880963", "0.46871093", "0.4685965", "0.46834967", "0.4680786", "0.46805605", "0.46766222", "0.46757272", "0.46736306", "0.46695784", "0.4669545", "0.4667565", "0.46672845", "0.46509436", "0.46493807", "0.46451837", "0.46417302", "0.4636826", "0.46113265", "0.46109277", "0.46053573", "0.46046868", "0.4604187", "0.4600934", "0.4600129", "0.4594782", "0.45935386", "0.45899296", "0.45890844", "0.4588671", "0.45859042", "0.4580459", "0.45751348" ]
0.86673677
0
CredentialCreationResponseToProto converts a CredentialCreationResponse to its proto counterpart.
func CredentialCreationResponseToProto(ccr *CredentialCreationResponse) *wantypes.CredentialCreationResponse { if ccr == nil { return nil } return &wantypes.CredentialCreationResponse{ Type: ccr.Type, RawId: ccr.RawID, Response: &wantypes.AuthenticatorAttestationResponse{ ClientDataJson: ccr.AttestationResponse.ClientDataJSON, AttestationObject: ccr.AttestationResponse.AttestationObject, }, Extensions: outputExtensionsToProto(ccr.Extensions), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CredentialCreationToProto(cc *CredentialCreation) *wantypes.CredentialCreation {\n\tif cc == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialCreation{\n\t\tPublicKey: &wantypes.PublicKeyCredentialCreationOptions{\n\t\t\tChallenge: cc.Response.Challenge,\n\t\t\tRp: rpEntityToProto(cc.Response.RelyingParty),\n\t\t\tUser: userEntityToProto(cc.Response.User),\n\t\t\tCredentialParameters: credentialParametersToProto(cc.Response.Parameters),\n\t\t\tTimeoutMs: int64(cc.Response.Timeout),\n\t\t\tExcludeCredentials: credentialDescriptorsToProto(cc.Response.CredentialExcludeList),\n\t\t\tAttestation: string(cc.Response.Attestation),\n\t\t\tExtensions: inputExtensionsToProto(cc.Response.Extensions),\n\t\t\tAuthenticatorSelection: authenticatorSelectionToProto(cc.Response.AuthenticatorSelection),\n\t\t},\n\t}\n}", "func CredentialCreationResponseFromProto(ccr *wantypes.CredentialCreationResponse) *CredentialCreationResponse {\n\tif ccr == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialCreationResponse{\n\t\tPublicKeyCredential: PublicKeyCredential{\n\t\t\tCredential: Credential{\n\t\t\t\tID: base64.RawURLEncoding.EncodeToString(ccr.RawId),\n\t\t\t\tType: ccr.Type,\n\t\t\t},\n\t\t\tRawID: ccr.RawId,\n\t\t\tExtensions: outputExtensionsFromProto(ccr.Extensions),\n\t\t},\n\t\tAttestationResponse: authenticatorAttestationResponseFromProto(ccr.Response),\n\t}\n}", "func CredentialAssertionResponseToProto(car *CredentialAssertionResponse) *wantypes.CredentialAssertionResponse {\n\tif car == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialAssertionResponse{\n\t\tType: car.Type,\n\t\tRawId: car.RawID,\n\t\tResponse: &wantypes.AuthenticatorAssertionResponse{\n\t\t\tClientDataJson: car.AssertionResponse.ClientDataJSON,\n\t\t\tAuthenticatorData: car.AssertionResponse.AuthenticatorData,\n\t\t\tSignature: car.AssertionResponse.Signature,\n\t\t\tUserHandle: car.AssertionResponse.UserHandle,\n\t\t},\n\t\tExtensions: outputExtensionsToProto(car.Extensions),\n\t}\n}", "func CredentialCreationFromProto(cc *wantypes.CredentialCreation) *CredentialCreation {\n\tif cc == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialCreation{\n\t\tResponse: publicKeyCredentialCreationOptionsFromProto(cc.PublicKey),\n\t}\n}", "func CredentialAssertionResponseFromProto(car *wantypes.CredentialAssertionResponse) *CredentialAssertionResponse {\n\tif car == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialAssertionResponse{\n\t\tPublicKeyCredential: PublicKeyCredential{\n\t\t\tCredential: Credential{\n\t\t\t\tID: base64.RawURLEncoding.EncodeToString(car.RawId),\n\t\t\t\tType: car.Type,\n\t\t\t},\n\t\t\tRawID: car.RawId,\n\t\t\tExtensions: outputExtensionsFromProto(car.Extensions),\n\t\t},\n\t\tAssertionResponse: authenticatorAssertionResponseFromProto(car.Response),\n\t}\n}", "func CredentialAssertionToProto(assertion *CredentialAssertion) *wantypes.CredentialAssertion {\n\tif assertion == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialAssertion{\n\t\tPublicKey: &wantypes.PublicKeyCredentialRequestOptions{\n\t\t\tChallenge: assertion.Response.Challenge,\n\t\t\tTimeoutMs: int64(assertion.Response.Timeout),\n\t\t\tRpId: assertion.Response.RelyingPartyID,\n\t\t\tAllowCredentials: credentialDescriptorsToProto(assertion.Response.AllowedCredentials),\n\t\t\tExtensions: inputExtensionsToProto(assertion.Response.Extensions),\n\t\t\tUserVerification: string(assertion.Response.UserVerification),\n\t\t},\n\t}\n}", "func NewProtoSubscribeResponse(result *chatter.Event) *chatterpb.SubscribeResponse {\n\tmessage := &chatterpb.SubscribeResponse{\n\t\tMessage_: result.Message,\n\t\tAction: result.Action,\n\t\tAddedAt: result.AddedAt,\n\t}\n\treturn message\n}", "func CredentialCreationFromProtocol(cc *protocol.CredentialCreation) *CredentialCreation {\n\tif cc == nil {\n\t\treturn nil\n\t}\n\n\t// Based on our configuration we should always get a protocol.URLEncodedBase64\n\t// user ID, but the go-webauthn/webauthn is capable of generating strings too.\n\tvar userID []byte\n\tif id := cc.Response.User.ID; id != nil {\n\t\tswitch uid := id.(type) {\n\t\tcase protocol.URLEncodedBase64:\n\t\t\tuserID = uid\n\t\tcase string:\n\t\t\tuserID = []byte(uid)\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"Unexpected WebAuthn cc.Response.User.ID type: %T\", id))\n\t\t}\n\t}\n\n\treturn &CredentialCreation{\n\t\tResponse: PublicKeyCredentialCreationOptions{\n\t\t\tChallenge: Challenge(cc.Response.Challenge),\n\t\t\tRelyingParty: RelyingPartyEntity{\n\t\t\t\tCredentialEntity: cc.Response.RelyingParty.CredentialEntity,\n\t\t\t\tID: cc.Response.RelyingParty.ID,\n\t\t\t},\n\t\t\tUser: UserEntity{\n\t\t\t\tCredentialEntity: cc.Response.User.CredentialEntity,\n\t\t\t\tDisplayName: cc.Response.User.Name,\n\t\t\t\tID: userID,\n\t\t\t},\n\t\t\tParameters: credentialParametersFromProtocol(cc.Response.Parameters),\n\t\t\tAuthenticatorSelection: AuthenticatorSelection{\n\t\t\t\tAuthenticatorAttachment: cc.Response.AuthenticatorSelection.AuthenticatorAttachment,\n\t\t\t\tRequireResidentKey: cc.Response.AuthenticatorSelection.RequireResidentKey,\n\t\t\t\tResidentKey: cc.Response.AuthenticatorSelection.ResidentKey,\n\t\t\t\tUserVerification: cc.Response.AuthenticatorSelection.UserVerification,\n\t\t\t},\n\t\t\tTimeout: cc.Response.Timeout,\n\t\t\tCredentialExcludeList: credentialDescriptorsFromProtocol(cc.Response.CredentialExcludeList),\n\t\t\tExtensions: cc.Response.Extensions,\n\t\t\tAttestation: cc.Response.Attestation,\n\t\t},\n\t}\n}", "func NewProtoLoginResponse(result string) *chatterpb.LoginResponse {\n\tmessage := &chatterpb.LoginResponse{}\n\tmessage.Field = result\n\treturn message\n}", "func CreateDescribeChannelParticipantsResponse() (response *DescribeChannelParticipantsResponse) {\n\tresponse = &DescribeChannelParticipantsResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateSubmitOperationCredentialsResponse() (response *SubmitOperationCredentialsResponse) {\n\tresponse = &SubmitOperationCredentialsResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CredentialAssertionFromProto(assertion *wantypes.CredentialAssertion) *CredentialAssertion {\n\tif assertion == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialAssertion{\n\t\tResponse: publicKeyCredentialRequestOptionsFromProto(assertion.PublicKey),\n\t}\n}", "func (m *Mutate) NewResponse() proto.Message {\n\treturn &pb.MutateResponse{}\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_teams_v1_teams_proto_rawDescGZIP(), []int{4}\n}", "func EncodeGRPCChangePasswordResponse(_ context.Context, r interface{}) (interface{}, error) {\n\tresp := r.(changePasswordResponse)\n\treturn &pb.ChangePasswordResponse{\n\t\tSuccess: resp.Success,\n\t\tErr: resp.Err,\n\t}, nil\n}", "func (*CreateConversationResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_threads_proto_rawDescGZIP(), []int{3}\n}", "func encodeGRPCGenerateReportResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(generateReportResponse)\n\treturn &pb.GenerateReportReply{V: int64(resp.V), Err: err2str(resp.Err)}, nil\n}", "func (*MultiCreateCertificatesV1Response) Descriptor() ([]byte, []int) {\n\treturn file_api_ocp_certificate_api_ocp_certificate_api_proto_rawDescGZIP(), []int{1}\n}", "func NewProtoHistoryResponse(result *chatterviews.ChatSummaryView) *chatterpb.HistoryResponse {\n\tmessage := &chatterpb.HistoryResponse{\n\t\tMessage_: *result.Message,\n\t\tSentAt: *result.SentAt,\n\t}\n\tif result.Length != nil {\n\t\tlength := int32(*result.Length)\n\t\tmessage.Length = &length\n\t}\n\treturn message\n}", "func NewBatchGRPCResponse(result []*public.ResponsePayload) *publicpb.BatchGRPCResponse {\n\tmessage := &publicpb.BatchGRPCResponse{}\n\tmessage.Field = make([]*publicpb.ResponsePayload, len(result))\n\tfor i, val := range result {\n\t\tmessage.Field[i] = &publicpb.ResponsePayload{\n\t\t\tFirstField: val.FirstField,\n\t\t\tFourthField: val.FourthField,\n\t\t}\n\t}\n\treturn message\n}", "func (*IssueCredentialResponse) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{12}\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_account_proto_rawDescGZIP(), []int{1}\n}", "func EncodeGRPCNewUserResponse(_ context.Context, r interface{}) (interface{}, error) {\n\tresp := r.(newUserResponse)\n\treturn &pb.NewUserResponse{\n\t\tId: resp.Id,\n\t\tErr: resp.Err,\n\t}, nil\n}", "func (*ListCredentialsResponse) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{23}\n}", "func (*CreateCertificateV1Response) Descriptor() ([]byte, []int) {\n\treturn file_api_ocp_certificate_api_ocp_certificate_api_proto_rawDescGZIP(), []int{3}\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_wallet_proto_rawDescGZIP(), []int{2}\n}", "func (*AcceptCredentialResponse) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{33}\n}", "func CreateCreateFabricChannelResponse() (response *CreateFabricChannelResponse) {\n\tresponse = &CreateFabricChannelResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (*CreateTokenResponse) Descriptor() ([]byte, []int) {\n\treturn file_pb_auth_proto_rawDescGZIP(), []int{4}\n}", "func decodeGRPCGenerateReportResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.GenerateReportResponse)\n\treturn generateReportResponse{Repository: reply.Repository, Err: str2err(reply.Err)}, nil\n}", "func (*ChangePasswordResponse) Descriptor() ([]byte, []int) {\n\treturn file_pb_auth_proto_rawDescGZIP(), []int{3}\n}", "func NewGetCredentialsResponseCredential() *GetCredentialsResponseCredential {\n\tthis := GetCredentialsResponseCredential{}\n\treturn &this\n}", "func (n *nativeImpl) MakeCredential(origin string, in *makeCredentialRequest) (*wantypes.CredentialCreationResponse, error) {\n\thwnd, err := getForegroundWindow()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tvar out *webauthnCredentialAttestation\n\tret, _, err := procWebAuthNAuthenticatorMakeCredential.Call(\n\t\tuintptr(hwnd),\n\t\tuintptr(unsafe.Pointer(in.rp)),\n\t\tuintptr(unsafe.Pointer(in.user)),\n\t\tuintptr(unsafe.Pointer(in.credParameters)),\n\t\tuintptr(unsafe.Pointer(in.clientData)),\n\t\tuintptr(unsafe.Pointer(in.opts)),\n\t\tuintptr(unsafe.Pointer(&out)),\n\t)\n\tif ret != 0 {\n\t\treturn nil, trace.Wrap(getErrorNameOrLastErr(ret, err))\n\t}\n\tif out == nil {\n\t\treturn nil, errors.New(\"unexpected nil response from MakeCredential\")\n\t}\n\n\t// Note that we need to copy bytes out of `out` if we want to free object.\n\t// That's why bytesFromCBytes is used.\n\t// We don't care about free error so ignore it explicitly.\n\tdefer func() { _ = freeCredentialAttestation(out) }()\n\n\tcredential := bytesFromCBytes(out.cbCredentialID, out.pbCredentialID)\n\n\treturn &wantypes.CredentialCreationResponse{\n\t\tPublicKeyCredential: wantypes.PublicKeyCredential{\n\t\t\tCredential: wantypes.Credential{\n\t\t\t\tID: base64.RawURLEncoding.EncodeToString(credential),\n\t\t\t\tType: string(protocol.PublicKeyCredentialType),\n\t\t\t},\n\t\t\tRawID: credential,\n\t\t},\n\t\tAttestationResponse: wantypes.AuthenticatorAttestationResponse{\n\t\t\tAuthenticatorResponse: wantypes.AuthenticatorResponse{\n\t\t\t\tClientDataJSON: in.jsonEncodedClientData,\n\t\t\t},\n\t\t\tAttestationObject: bytesFromCBytes(out.cbAttestationObject, out.pbAttestationObject),\n\t\t},\n\t}, nil\n}", "func (*CreateUserResponse) Descriptor() ([]byte, []int) {\n\treturn file_pb_auth_proto_rawDescGZIP(), []int{1}\n}", "func (*CreateSubscriptionResponse) Descriptor() ([]byte, []int) {\n\treturn file_toit_api_data_proto_rawDescGZIP(), []int{3}\n}", "func decodeCreateResponse(_ context.Context, reply interface{}) (interface{}, error) {\n\tresp, found := reply.(*pb.CreateReply)\n\tif !found {\n\t\treturn nil, fmt.Errorf(\"pb CreateReply type assertion error\")\n\t}\n\treturn endpoint1.CreateResponse{E1: nil, UUID: resp.Uuid}, nil\n}", "func encodeGRPCGreetingResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tres := response.(greeterendpoint.GreetingResponse)\n\treturn &pb.GreetingResponse{Greeting: res.Greeting}, nil\n}", "func (in *CredentialProviderResponse) DeepCopy() *CredentialProviderResponse {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(CredentialProviderResponse)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func CreateModifyCallRatioResponse() (response *ModifyCallRatioResponse) {\n\tresponse = &ModifyCallRatioResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (b *BitcoinClient) createRPCBitcoinResponse(res string) *RPCBitcoinResponse {\n\tvar rpcBitcoinResponse RPCBitcoinResponse\n\tjson.Unmarshal([]byte(res), &rpcBitcoinResponse)\n\n\treturn &rpcBitcoinResponse\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_contact_proto_rawDescGZIP(), []int{7}\n}", "func (a *OidcApiService) CreateVerifiableCredential(ctx context.Context) ApiCreateVerifiableCredentialRequest {\n\treturn ApiCreateVerifiableCredentialRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (*CUserAccount_CreateFriendInviteToken_Response) Descriptor() ([]byte, []int) {\n\treturn file_steammessages_useraccount_steamclient_proto_rawDescGZIP(), []int{7}\n}", "func CreateDescribeCertificatesResponse() (response *DescribeCertificatesResponse) {\n\tresponse = &DescribeCertificatesResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (*Room_CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_chat_chat_proto_rawDescGZIP(), []int{0, 1}\n}", "func (*CreateAccountReply) Descriptor() ([]byte, []int) {\n\treturn file_api_account_v1_account_proto_rawDescGZIP(), []int{1}\n}", "func CreateResponse(resultCode uint32, internalCommand []byte) ([]byte, error) {\n\t// Response frame:\n\t// - uint32 (size of response)\n\t// - []byte (response)\n\t// - uint32 (code)\n\tvar buf bytes.Buffer\n\n\tif err := binary.Write(&buf, binary.BigEndian, uint32(len(internalCommand))); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif _, err := buf.Write(internalCommand); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := binary.Write(&buf, binary.BigEndian, resultCode); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_task_v1_task_proto_rawDescGZIP(), []int{2}\n}", "func (*GenerateTemplateResponse) Descriptor() ([]byte, []int) {\n\treturn file_buf_alpha_registry_v1alpha1_generate_proto_rawDescGZIP(), []int{6}\n}", "func NewProtoEchoerResponse(result string) *chatterpb.EchoerResponse {\n\tmessage := &chatterpb.EchoerResponse{}\n\tmessage.Field = result\n\treturn message\n}", "func (*AuthenticationResponse) Descriptor() ([]byte, []int) {\n\treturn file_box_account_proto_rawDescGZIP(), []int{2}\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_audit_proto_rawDescGZIP(), []int{1}\n}", "func (*CancelTeamSubscriptionResponse) Descriptor() ([]byte, []int) {\n\treturn file_protos_participant_service_proto_rawDescGZIP(), []int{5}\n}", "func (*CreateTicketResponse) Descriptor() ([]byte, []int) {\n\treturn file_shared_proto_ticket_ticket_proto_rawDescGZIP(), []int{2}\n}", "func (*PollCredentialOffersResponse) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{31}\n}", "func userToProto(u *domain.User) *protouser.Response {\n\treturn &protouser.Response{\n\t\tApplication: proto.String(string(u.App)),\n\t\tUid: proto.String(u.Uid),\n\t\tIds: idsToStrings(u.Ids),\n\t\tCreatedTimestamp: timeToProto(u.Created),\n\t\tRoles: u.Roles,\n\t\tPasswordChangeTimestamp: timeToProto(u.PasswordChange),\n\t\tAccountExpirationDate: proto.String(string(u.AccountExpirationDate)),\n\t}\n}", "func (*CreateWorkflowResponse) Descriptor() ([]byte, []int) {\n\treturn file_pkg_flow_grpc_workflows_proto_rawDescGZIP(), []int{7}\n}", "func (*PaymentCreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_infrastructure_api_rpc_payment_v1_billing_rpc_proto_rawDescGZIP(), []int{4}\n}", "func UnmarshalCreateChannelsResponse(m map[string]json.RawMessage, result interface{}) (err error) {\n\tobj := new(CreateChannelsResponse)\n\terr = core.UnmarshalPrimitive(m, \"channel_id\", &obj.ChannelID)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"status_code\", &obj.StatusCode)\n\tif err != nil {\n\t\treturn\n\t}\n\treflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj))\n\treturn\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_versions_v1_versions_proto_rawDescGZIP(), []int{4}\n}", "func (*SinglePasswordValidationResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{127}\n}", "func CreateSyncUsersResponse() (response *SyncUsersResponse) {\n\tresponse = &SyncUsersResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (*CreateConnectionResponse) Descriptor() ([]byte, []int) {\n\treturn file_api_protobuf_spec_connection_user_v1_proto_rawDescGZIP(), []int{13}\n}", "func CreateRegisterAuthenticatorResponse() (response *RegisterAuthenticatorResponse) {\n\tresponse = &RegisterAuthenticatorResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_api_api_proto_rawDescGZIP(), []int{2}\n}", "func (*CMsgClientToGCRequestPlusWeeklyChallengeResultResponse) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{274}\n}", "func (*GeneratedResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_auth_proto_rawDescGZIP(), []int{1}\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_engine_proto_rawDescGZIP(), []int{3}\n}", "func (*CreateAccountRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{0}\n}", "func (*CreateRequest) Descriptor() ([]byte, []int) {\n\treturn file_teams_v1_teams_proto_rawDescGZIP(), []int{2}\n}", "func (*AddAuthenticationResponse) Descriptor() ([]byte, []int) {\n\treturn file_server_pb_UserService_proto_rawDescGZIP(), []int{4}\n}", "func (*CreateOrganizationResponse) Descriptor() ([]byte, []int) {\n\treturn file_toit_api_auth_proto_rawDescGZIP(), []int{7}\n}", "func decodeGRPCGenerateReportRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.GenerateReportRequest)\n\treturn generateReportRequest{Username: req.Username, Token: req.Token, RepositoryName: req.RepositoryName}, nil\n}", "func (*CreateTokenResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_user_user_proto_rawDescGZIP(), []int{11}\n}", "func EncodeGRPCLoginResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(*pb.LoginResponse)\n\treturn resp, nil\n}", "func NewSnapmirrorCreateResponse() *SnapmirrorCreateResponse {\n\treturn &SnapmirrorCreateResponse{}\n}", "func CreateCreateSubscribeRelationResponse() (response *CreateSubscribeRelationResponse) {\n\tresponse = &CreateSubscribeRelationResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CertificateTemplateToProto(resource *beta.CertificateTemplate) *betapb.PrivatecaBetaCertificateTemplate {\n\tp := &betapb.PrivatecaBetaCertificateTemplate{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetPredefinedValues(PrivatecaBetaCertificateTemplatePredefinedValuesToProto(resource.PredefinedValues))\n\tp.SetIdentityConstraints(PrivatecaBetaCertificateTemplateIdentityConstraintsToProto(resource.IdentityConstraints))\n\tp.SetPassthroughExtensions(PrivatecaBetaCertificateTemplatePassthroughExtensionsToProto(resource.PassthroughExtensions))\n\tp.SetDescription(dcl.ValueOrEmptyString(resource.Description))\n\tp.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime))\n\tp.SetUpdateTime(dcl.ValueOrEmptyString(resource.UpdateTime))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetLocation(dcl.ValueOrEmptyString(resource.Location))\n\tmLabels := make(map[string]string, len(resource.Labels))\n\tfor k, r := range resource.Labels {\n\t\tmLabels[k] = r\n\t}\n\tp.SetLabels(mLabels)\n\n\treturn p\n}", "func encodeCreateKeyPersonResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tres := response.(endpoints.CreateKeyPersonResponse)\n\terr := getError(res.Err)\n\tif err == nil {\n\t\treturn res.KeyPerson.ToProto(), nil\n\t}\n\treturn nil, err\n}", "func (*PrimeNumberDecompositionResponse) Descriptor() ([]byte, []int) {\n\treturn file_grpc_grpcpb_grpc_proto_rawDescGZIP(), []int{1}\n}", "func (*CreateOrderResponse) Descriptor() ([]byte, []int) {\n\treturn file_services_grpcPb_grpc_proto_rawDescGZIP(), []int{22}\n}", "func (*CreateMessageResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_threads_proto_rawDescGZIP(), []int{13}\n}", "func (ps *GetProcedureState) NewResponse() proto.Message {\n\treturn &pb.GetProcedureResultResponse{}\n}", "func ContainerClusterMasterAuthToProto(o *container.ClusterMasterAuth) *containerpb.ContainerClusterMasterAuth {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &containerpb.ContainerClusterMasterAuth{\n\t\tUsername: dcl.ValueOrEmptyString(o.Username),\n\t\tPassword: dcl.ValueOrEmptyString(o.Password),\n\t\tClientCertificateConfig: ContainerClusterMasterAuthClientCertificateConfigToProto(o.ClientCertificateConfig),\n\t\tClusterCaCertificate: dcl.ValueOrEmptyString(o.ClusterCaCertificate),\n\t\tClientCertificate: dcl.ValueOrEmptyString(o.ClientCertificate),\n\t\tClientKey: dcl.ValueOrEmptyString(o.ClientKey),\n\t}\n\treturn p\n}", "func CreateCreateFaceGroupResponse() (response *CreateFaceGroupResponse) {\n\tresponse = &CreateFaceGroupResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func NewAuthenticationMetadataFromProto(message *auth_pb.AuthenticationMetadata) (*AuthenticationMetadata, error) {\n\t// Create raw value, which stores the contents of the Protobuf\n\t// message as an object normally returned by json.Unmarshal().\n\t// This can be used to do JMESPath matching by the authorization\n\t// layer.\n\tmessageJSON, err := protojson.Marshal(message)\n\tif err != nil {\n\t\treturn nil, util.StatusWrapWithCode(err, codes.InvalidArgument, \"Cannot convert authentication metadata to JSON\")\n\t}\n\tvar raw map[string]any\n\tif err := json.Unmarshal(messageJSON, &raw); err != nil {\n\t\treturn nil, util.StatusWrapWithCode(err, codes.InvalidArgument, \"Cannot parse authentication metadata JSON\")\n\t}\n\n\ttracingAttributes, err := otel.NewKeyValueListFromProto(message.GetTracingAttributes(), \"auth.\")\n\tif err != nil {\n\t\treturn nil, util.StatusWrap(err, \"Cannot create tracing attributes\")\n\t}\n\n\tam := &AuthenticationMetadata{\n\t\traw: raw,\n\t\ttracingAttributes: tracingAttributes,\n\t}\n\tproto.Merge(&am.proto, message)\n\treturn am, nil\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_weather_proto_rawDescGZIP(), []int{3}\n}", "func encodeCreateCompanyResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tres := response.(endpoints.CreateCompanyResponse)\n\terr := getError(res.Err)\n\tif err == nil {\n\t\treturn res.Company.ToProto(), nil\n\t}\n\treturn nil, err\n}", "func (fieldMask *CreateServiceRequest_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}", "func (*CreateUserResponse) Descriptor() ([]byte, []int) {\n\treturn file_buf_alpha_registry_v1alpha1_user_proto_rawDescGZIP(), []int{2}\n}", "func (*CreateTokenResponse) Descriptor() ([]byte, []int) {\n\treturn file_service_proto_rawDescGZIP(), []int{2}\n}", "func (*MultiCreateCheckResponse) Descriptor() ([]byte, []int) {\n\treturn file_api_ocp_check_api_ocp_check_api_proto_rawDescGZIP(), []int{7}\n}", "func (*CBroadcast_WebRTCStartResult_Response) Descriptor() ([]byte, []int) {\n\treturn file_steammessages_broadcast_steamclient_proto_rawDescGZIP(), []int{46}\n}", "func (*WebhookResponse) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_dialogflow_v2beta1_webhook_proto_rawDescGZIP(), []int{1}\n}", "func NewProtoListenerResponse() *chatterpb.ListenerResponse {\n\tmessage := &chatterpb.ListenerResponse{}\n\treturn message\n}", "func (mock *MailgunMock) CreateCredentialCalls() []struct {\n\tLogin string\n\tPassword string\n} {\n\tvar calls []struct {\n\t\tLogin string\n\t\tPassword string\n\t}\n\tlockMailgunMockCreateCredential.RLock()\n\tcalls = mock.calls.CreateCredential\n\tlockMailgunMockCreateCredential.RUnlock()\n\treturn calls\n}", "func (*LoginResponse) Descriptor() ([]byte, []int) {\n\treturn file_pb_authentication_proto_rawDescGZIP(), []int{2}\n}", "func (*CreateCheckResponse) Descriptor() ([]byte, []int) {\n\treturn file_api_ocp_check_api_ocp_check_api_proto_rawDescGZIP(), []int{5}\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_mods_v1_mods_proto_rawDescGZIP(), []int{4}\n}", "func (*CreateGroupResponse) Descriptor() ([]byte, []int) {\n\treturn file_userGroups_proto_rawDescGZIP(), []int{2}\n}" ]
[ "0.78583616", "0.7849964", "0.7063098", "0.6521318", "0.6473246", "0.62918735", "0.5673684", "0.55803907", "0.556813", "0.549089", "0.54130495", "0.53861296", "0.5301925", "0.52858174", "0.5277383", "0.52336776", "0.5227287", "0.522161", "0.521726", "0.52074724", "0.52071023", "0.5163953", "0.51635236", "0.5121114", "0.5098321", "0.5092531", "0.5080887", "0.5075986", "0.5073977", "0.50686896", "0.50683194", "0.5028628", "0.50256175", "0.5018824", "0.5017436", "0.49996907", "0.49890366", "0.49861047", "0.49753872", "0.49621516", "0.49536446", "0.49529934", "0.49483347", "0.49462134", "0.49394995", "0.48792568", "0.48790035", "0.48755327", "0.48733598", "0.487062", "0.4859982", "0.4858326", "0.48581755", "0.48557848", "0.4852665", "0.48513228", "0.48508897", "0.4848136", "0.48435107", "0.48425943", "0.48406708", "0.4834661", "0.48323298", "0.48266625", "0.4825755", "0.4813053", "0.4811909", "0.48105064", "0.48024333", "0.47989574", "0.47982788", "0.47971678", "0.4796294", "0.47894508", "0.47820574", "0.477114", "0.47613713", "0.4753618", "0.47497946", "0.47453463", "0.47453433", "0.47442964", "0.47416762", "0.47400302", "0.47400296", "0.47384667", "0.47351786", "0.47302714", "0.4725948", "0.47203702", "0.47184214", "0.4717385", "0.4716339", "0.4714234", "0.4711234", "0.4709578", "0.47095138", "0.47077414", "0.47052717", "0.47048917" ]
0.86787826
0
CredentialAssertionFromProto converts a CredentialAssertion proto to its lib counterpart.
func CredentialAssertionFromProto(assertion *wantypes.CredentialAssertion) *CredentialAssertion { if assertion == nil { return nil } return &CredentialAssertion{ Response: publicKeyCredentialRequestOptionsFromProto(assertion.PublicKey), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CredentialAssertionResponseFromProto(car *wantypes.CredentialAssertionResponse) *CredentialAssertionResponse {\n\tif car == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialAssertionResponse{\n\t\tPublicKeyCredential: PublicKeyCredential{\n\t\t\tCredential: Credential{\n\t\t\t\tID: base64.RawURLEncoding.EncodeToString(car.RawId),\n\t\t\t\tType: car.Type,\n\t\t\t},\n\t\t\tRawID: car.RawId,\n\t\t\tExtensions: outputExtensionsFromProto(car.Extensions),\n\t\t},\n\t\tAssertionResponse: authenticatorAssertionResponseFromProto(car.Response),\n\t}\n}", "func CredentialAssertionToProto(assertion *CredentialAssertion) *wantypes.CredentialAssertion {\n\tif assertion == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialAssertion{\n\t\tPublicKey: &wantypes.PublicKeyCredentialRequestOptions{\n\t\t\tChallenge: assertion.Response.Challenge,\n\t\t\tTimeoutMs: int64(assertion.Response.Timeout),\n\t\t\tRpId: assertion.Response.RelyingPartyID,\n\t\t\tAllowCredentials: credentialDescriptorsToProto(assertion.Response.AllowedCredentials),\n\t\t\tExtensions: inputExtensionsToProto(assertion.Response.Extensions),\n\t\t\tUserVerification: string(assertion.Response.UserVerification),\n\t\t},\n\t}\n}", "func CredentialCreationFromProto(cc *wantypes.CredentialCreation) *CredentialCreation {\n\tif cc == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialCreation{\n\t\tResponse: publicKeyCredentialCreationOptionsFromProto(cc.PublicKey),\n\t}\n}", "func CredentialAssertionFromProtocol(a *protocol.CredentialAssertion) *CredentialAssertion {\n\tif a == nil {\n\t\treturn nil\n\t}\n\n\treturn &CredentialAssertion{\n\t\tResponse: PublicKeyCredentialRequestOptions{\n\t\t\tChallenge: Challenge(a.Response.Challenge),\n\t\t\tTimeout: a.Response.Timeout,\n\t\t\tRelyingPartyID: a.Response.RelyingPartyID,\n\t\t\tAllowedCredentials: credentialDescriptorsFromProtocol(a.Response.AllowedCredentials),\n\t\t\tUserVerification: a.Response.UserVerification,\n\t\t\tExtensions: a.Response.Extensions,\n\t\t},\n\t}\n}", "func CredentialCreationResponseFromProto(ccr *wantypes.CredentialCreationResponse) *CredentialCreationResponse {\n\tif ccr == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialCreationResponse{\n\t\tPublicKeyCredential: PublicKeyCredential{\n\t\t\tCredential: Credential{\n\t\t\t\tID: base64.RawURLEncoding.EncodeToString(ccr.RawId),\n\t\t\t\tType: ccr.Type,\n\t\t\t},\n\t\t\tRawID: ccr.RawId,\n\t\t\tExtensions: outputExtensionsFromProto(ccr.Extensions),\n\t\t},\n\t\tAttestationResponse: authenticatorAttestationResponseFromProto(ccr.Response),\n\t}\n}", "func NewAuthenticationMetadataFromProto(message *auth_pb.AuthenticationMetadata) (*AuthenticationMetadata, error) {\n\t// Create raw value, which stores the contents of the Protobuf\n\t// message as an object normally returned by json.Unmarshal().\n\t// This can be used to do JMESPath matching by the authorization\n\t// layer.\n\tmessageJSON, err := protojson.Marshal(message)\n\tif err != nil {\n\t\treturn nil, util.StatusWrapWithCode(err, codes.InvalidArgument, \"Cannot convert authentication metadata to JSON\")\n\t}\n\tvar raw map[string]any\n\tif err := json.Unmarshal(messageJSON, &raw); err != nil {\n\t\treturn nil, util.StatusWrapWithCode(err, codes.InvalidArgument, \"Cannot parse authentication metadata JSON\")\n\t}\n\n\ttracingAttributes, err := otel.NewKeyValueListFromProto(message.GetTracingAttributes(), \"auth.\")\n\tif err != nil {\n\t\treturn nil, util.StatusWrap(err, \"Cannot create tracing attributes\")\n\t}\n\n\tam := &AuthenticationMetadata{\n\t\traw: raw,\n\t\ttracingAttributes: tracingAttributes,\n\t}\n\tproto.Merge(&am.proto, message)\n\treturn am, nil\n}", "func CredentialAssertionResponseToProto(car *CredentialAssertionResponse) *wantypes.CredentialAssertionResponse {\n\tif car == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialAssertionResponse{\n\t\tType: car.Type,\n\t\tRawId: car.RawID,\n\t\tResponse: &wantypes.AuthenticatorAssertionResponse{\n\t\t\tClientDataJson: car.AssertionResponse.ClientDataJSON,\n\t\t\tAuthenticatorData: car.AssertionResponse.AuthenticatorData,\n\t\t\tSignature: car.AssertionResponse.Signature,\n\t\t\tUserHandle: car.AssertionResponse.UserHandle,\n\t\t},\n\t\tExtensions: outputExtensionsToProto(car.Extensions),\n\t}\n}", "func CredentialCreationToProto(cc *CredentialCreation) *wantypes.CredentialCreation {\n\tif cc == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialCreation{\n\t\tPublicKey: &wantypes.PublicKeyCredentialCreationOptions{\n\t\t\tChallenge: cc.Response.Challenge,\n\t\t\tRp: rpEntityToProto(cc.Response.RelyingParty),\n\t\t\tUser: userEntityToProto(cc.Response.User),\n\t\t\tCredentialParameters: credentialParametersToProto(cc.Response.Parameters),\n\t\t\tTimeoutMs: int64(cc.Response.Timeout),\n\t\t\tExcludeCredentials: credentialDescriptorsToProto(cc.Response.CredentialExcludeList),\n\t\t\tAttestation: string(cc.Response.Attestation),\n\t\t\tExtensions: inputExtensionsToProto(cc.Response.Extensions),\n\t\t\tAuthenticatorSelection: authenticatorSelectionToProto(cc.Response.AuthenticatorSelection),\n\t\t},\n\t}\n}", "func (st *Account) FromProto(acPb *accountpb.Account) {\n\tst.nonce = acPb.Nonce\n\tif _, ok := accountpb.AccountType_name[int32(acPb.Type.Number())]; !ok {\n\t\tpanic(\"unknown account type\")\n\t}\n\tst.accountType = int32(acPb.Type.Number())\n\tif acPb.Balance == \"\" {\n\t\tst.Balance = big.NewInt(0)\n\t} else {\n\t\tbalance, ok := new(big.Int).SetString(acPb.Balance, 10)\n\t\tif !ok {\n\t\t\tpanic(errors.Errorf(\"invalid balance %s\", acPb.Balance))\n\t\t}\n\t\tst.Balance = balance\n\t}\n\tcopy(st.Root[:], acPb.Root)\n\tst.CodeHash = nil\n\tif acPb.CodeHash != nil {\n\t\tst.CodeHash = make([]byte, len(acPb.CodeHash))\n\t\tcopy(st.CodeHash, acPb.CodeHash)\n\t}\n\tst.isCandidate = acPb.IsCandidate\n\tst.votingWeight = big.NewInt(0)\n\tif acPb.VotingWeight != nil {\n\t\tst.votingWeight.SetBytes(acPb.VotingWeight)\n\t}\n}", "func CredentialCreationResponseToProto(ccr *CredentialCreationResponse) *wantypes.CredentialCreationResponse {\n\tif ccr == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialCreationResponse{\n\t\tType: ccr.Type,\n\t\tRawId: ccr.RawID,\n\t\tResponse: &wantypes.AuthenticatorAttestationResponse{\n\t\t\tClientDataJson: ccr.AttestationResponse.ClientDataJSON,\n\t\t\tAttestationObject: ccr.AttestationResponse.AttestationObject,\n\t\t},\n\t\tExtensions: outputExtensionsToProto(ccr.Extensions),\n\t}\n}", "func FromProto(msg proto.Message) (*repb.Digest, error) {\n\tblob, err := proto.Marshal(msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn FromBlob(blob), nil\n}", "func FromProto(req *metrov1.StreamingPullRequest) (*AcknowledgeRequest, *ModifyAckDeadlineRequest, error) {\n\tif len(req.ModifyDeadlineAckIds) != len(req.ModifyDeadlineSeconds) {\n\t\treturn nil, nil, fmt.Errorf(\"length of modify_deadline_ack_ids and modify_deadline_seconds not same\")\n\t}\n\tar := &AcknowledgeRequest{\n\t\treq.AckIds,\n\t}\n\tmr := &ModifyAckDeadlineRequest{\n\t\treq.ModifyDeadlineSeconds,\n\t\treq.ModifyDeadlineAckIds,\n\t}\n\treturn ar, mr, nil\n}", "func (vi *ValidatorInfo) FromProto(pb *pbtypes.ValidatorInfo) error {\n\tcopy(vi.AccountAddress[:], pb.AccountAddress)\n\tvi.ConsensusPubkey = pb.ConsensusPublicKey\n\tvi.ConsensusVotingPower = pb.ConsensusVotingPower\n\tvi.NetworkSigningPubkey = pb.NetworkSigningPublicKey\n\tvi.NetworkIdentityPubkey = pb.NetworkIdentityPublicKey\n\treturn nil\n}", "func NewLeaseFromProto(a *poolrpc.Lease) *Lease {\n\tvar opHash chainhash.Hash\n\tcopy(opHash[:], a.ChannelPoint.Txid)\n\n\tchanPoint := fmt.Sprintf(\"%v:%d\", opHash, a.ChannelPoint.OutputIndex)\n\treturn &Lease{\n\t\tChannelPoint: chanPoint,\n\t\tChannelAmtSat: a.ChannelAmtSat,\n\t\tChannelDurationBlocks: a.ChannelDurationBlocks,\n\t\tChannelLeaseExpiry: a.ChannelLeaseExpiry,\n\t\tChannelRemoteNodeKey: hex.EncodeToString(a.ChannelRemoteNodeKey),\n\t\tChannelNodeTier: a.ChannelNodeTier.String(),\n\t\tPremiumSat: a.PremiumSat,\n\t\tClearingRatePrice: a.ClearingRatePrice,\n\t\tOrderFixedRate: a.OrderFixedRate,\n\t\tExecutionFeeSat: a.ExecutionFeeSat,\n\t\tChainFeeSat: a.ChainFeeSat,\n\t\tOrderNonce: hex.EncodeToString(a.OrderNonce),\n\t\tMatchedOrderNonce: hex.EncodeToString(a.MatchedOrderNonce),\n\t\tPurchased: a.Purchased,\n\t\tSelfChanBalance: a.SelfChanBalance,\n\t\tSidecarChannel: a.SidecarChannel,\n\t}\n}", "func (st *Account) FromProto(acPb *iproto.AccountPb) {\n\tst.Nonce = acPb.Nonce\n\tst.Balance = big.NewInt(0)\n\tif acPb.Balance != nil {\n\t\tst.Balance.SetBytes(acPb.Balance)\n\t}\n\tcopy(st.Root[:], acPb.Root)\n\tst.CodeHash = nil\n\tif acPb.CodeHash != nil {\n\t\tst.CodeHash = make([]byte, len(acPb.CodeHash))\n\t\tcopy(st.CodeHash, acPb.CodeHash)\n\t}\n\tst.IsCandidate = acPb.IsCandidate\n\tst.VotingWeight = big.NewInt(0)\n\tif acPb.VotingWeight != nil {\n\t\tst.VotingWeight.SetBytes(acPb.VotingWeight)\n\t}\n\tst.Votee = acPb.Votee\n}", "func FromProto(msg proto.Message) (Transaction, error) {\n\ttx := msg.(*ledger.TransactionInput)\n\n\tvar da ptypes.DynamicAny\n\terr := ptypes.UnmarshalAny(tx.GetBody(), &da)\n\tif err != nil {\n\t\treturn Transaction{}, err\n\t}\n\n\treturn Transaction{\n\t\tContractID: executor.ContractID(tx.ContractID),\n\t\tAction: executor.Action(tx.Action),\n\t\tArg: da.Message,\n\t}, nil\n}", "func ProtoToKey(p *recaptchaenterprisepb.RecaptchaenterpriseKey) *recaptchaenterprise.Key {\n\tobj := &recaptchaenterprise.Key{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tDisplayName: dcl.StringOrNil(p.GetDisplayName()),\n\t\tWebSettings: ProtoToRecaptchaenterpriseKeyWebSettings(p.GetWebSettings()),\n\t\tAndroidSettings: ProtoToRecaptchaenterpriseKeyAndroidSettings(p.GetAndroidSettings()),\n\t\tIosSettings: ProtoToRecaptchaenterpriseKeyIosSettings(p.GetIosSettings()),\n\t\tCreateTime: dcl.StringOrNil(p.GetCreateTime()),\n\t\tTestingOptions: ProtoToRecaptchaenterpriseKeyTestingOptions(p.GetTestingOptions()),\n\t\tProject: dcl.StringOrNil(p.GetProject()),\n\t}\n\treturn obj\n}", "func MustNewAuthenticationMetadataFromProto(message *auth_pb.AuthenticationMetadata) *AuthenticationMetadata {\n\tauthenticationMetadata, err := NewAuthenticationMetadataFromProto(message)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn authenticationMetadata\n}", "func unmarshalCredential(raw []byte) (*credential, error) {\n\tif len(raw) < 10 {\n\t\treturn nil, errors.New(\"tls: Delegated Credential is not valid: invalid length\")\n\t}\n\n\ts := cryptobyte.String(raw)\n\tvar t uint32\n\tif !s.ReadUint32(&t) {\n\t\treturn nil, errors.New(\"tls: Delegated Credential is not valid\")\n\t}\n\tvalidTime := time.Duration(t) * time.Second\n\n\tvar pubAlgo uint16\n\tif !s.ReadUint16(&pubAlgo) {\n\t\treturn nil, errors.New(\"tls: Delegated Credential is not valid\")\n\t}\n\talgo := SignatureScheme(pubAlgo)\n\n\tvar pubLen uint32\n\ts.ReadUint24(&pubLen)\n\n\tpubKey, err := x509.ParsePKIXPublicKey(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &credential{validTime, algo, pubKey}, nil\n}", "func ProtoToCertificateTemplate(p *betapb.PrivatecaBetaCertificateTemplate) *beta.CertificateTemplate {\n\tobj := &beta.CertificateTemplate{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tPredefinedValues: ProtoToPrivatecaBetaCertificateTemplatePredefinedValues(p.GetPredefinedValues()),\n\t\tIdentityConstraints: ProtoToPrivatecaBetaCertificateTemplateIdentityConstraints(p.GetIdentityConstraints()),\n\t\tPassthroughExtensions: ProtoToPrivatecaBetaCertificateTemplatePassthroughExtensions(p.GetPassthroughExtensions()),\n\t\tDescription: dcl.StringOrNil(p.GetDescription()),\n\t\tCreateTime: dcl.StringOrNil(p.GetCreateTime()),\n\t\tUpdateTime: dcl.StringOrNil(p.GetUpdateTime()),\n\t\tProject: dcl.StringOrNil(p.GetProject()),\n\t\tLocation: dcl.StringOrNil(p.GetLocation()),\n\t}\n\treturn obj\n}", "func CommitFromProto(cp *tmproto.Commit) (*Commit, error) {\n\tif cp == nil {\n\t\treturn nil, errors.New(\"nil Commit\")\n\t}\n\n\tvar (\n\t\tcommit = new(Commit)\n\t)\n\n\tbi, err := BlockIDFromProto(&cp.BlockID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsigs := make([]CommitSig, len(cp.Signatures))\n\tfor i := range cp.Signatures {\n\t\tif err := sigs[i].FromProto(cp.Signatures[i]); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tcommit.Signatures = sigs\n\n\tcommit.Height = cp.Height\n\tcommit.Round = cp.Round\n\tcommit.BlockID = *bi\n\n\treturn commit, commit.ValidateBasic()\n}", "func CommitFromProto(cp *tmproto.Commit) (*Commit, error) {\n\tif cp == nil {\n\t\treturn nil, errors.New(\"nil Commit\")\n\t}\n\n\tvar (\n\t\tcommit = new(Commit)\n\t)\n\n\tbi, err := BlockIDFromProto(&cp.BlockID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsi, err := StateIDFromProto(&cp.StateID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcommit.QuorumHash = cp.QuorumHash\n\tcommit.ThresholdBlockSignature = cp.ThresholdBlockSignature\n\tcommit.ThresholdStateSignature = cp.ThresholdStateSignature\n\n\tcommit.Height = cp.Height\n\tcommit.Round = cp.Round\n\tcommit.BlockID = *bi\n\tcommit.StateID = *si\n\n\treturn commit, commit.ValidateBasic()\n}", "func (cs *CommitSig) FromProto(csp tmproto.CommitSig) error {\n\n\tcs.BlockIDFlag = BlockIDFlag(csp.BlockIdFlag)\n\tcs.ValidatorAddress = csp.ValidatorAddress\n\tcs.Timestamp = csp.Timestamp\n\tcs.Signature = csp.Signature\n\n\treturn cs.ValidateBasic()\n}", "func FromProto(sandboxpb *types.Sandbox) Sandbox {\n\truntime := RuntimeOpts{\n\t\tName: sandboxpb.Runtime.Name,\n\t\tOptions: sandboxpb.Runtime.Options,\n\t}\n\n\textensions := make(map[string]typeurl.Any)\n\tfor k, v := range sandboxpb.Extensions {\n\t\tv := v\n\t\textensions[k] = v\n\t}\n\n\treturn Sandbox{\n\t\tID: sandboxpb.SandboxID,\n\t\tLabels: sandboxpb.Labels,\n\t\tRuntime: runtime,\n\t\tSpec: sandboxpb.Spec,\n\t\tCreatedAt: protobuf.FromTimestamp(sandboxpb.CreatedAt),\n\t\tUpdatedAt: protobuf.FromTimestamp(sandboxpb.UpdatedAt),\n\t\tExtensions: extensions,\n\t}\n}", "func ProtoToCryptoKey(p *betapb.CloudkmsBetaCryptoKey) *beta.CryptoKey {\n\tobj := &beta.CryptoKey{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tPrimary: ProtoToCloudkmsBetaCryptoKeyPrimary(p.GetPrimary()),\n\t\tPurpose: ProtoToCloudkmsBetaCryptoKeyPurposeEnum(p.GetPurpose()),\n\t\tCreateTime: dcl.StringOrNil(p.GetCreateTime()),\n\t\tNextRotationTime: dcl.StringOrNil(p.GetNextRotationTime()),\n\t\tRotationPeriod: dcl.StringOrNil(p.GetRotationPeriod()),\n\t\tVersionTemplate: ProtoToCloudkmsBetaCryptoKeyVersionTemplate(p.GetVersionTemplate()),\n\t\tImportOnly: dcl.Bool(p.GetImportOnly()),\n\t\tDestroyScheduledDuration: dcl.StringOrNil(p.GetDestroyScheduledDuration()),\n\t\tProject: dcl.StringOrNil(p.GetProject()),\n\t\tLocation: dcl.StringOrNil(p.GetLocation()),\n\t\tKeyRing: dcl.StringOrNil(p.GetKeyRing()),\n\t}\n\treturn obj\n}", "func (a *Accumulator) FromProto(pb *pbtypes.AccumulatorProof) error {\r\n\ta.Siblings = siblingsWithPlaceholder(pb.Siblings, sha3libra.AccumulatorPlaceholderHash)\r\n\treturn nil\r\n}", "func ProtoToServiceAccount(p *iampb.IamServiceAccount) *iam.ServiceAccount {\n\tobj := &iam.ServiceAccount{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tProject: dcl.StringOrNil(p.GetProject()),\n\t\tUniqueId: dcl.StringOrNil(p.GetUniqueId()),\n\t\tEmail: dcl.StringOrNil(p.GetEmail()),\n\t\tDisplayName: dcl.StringOrNil(p.GetDisplayName()),\n\t\tDescription: dcl.StringOrNil(p.GetDescription()),\n\t\tOAuth2ClientId: dcl.StringOrNil(p.GetOauth2ClientId()),\n\t\tActasResources: ProtoToIamServiceAccountActasResources(p.GetActasResources()),\n\t\tDisabled: dcl.Bool(p.GetDisabled()),\n\t}\n\treturn obj\n}", "func NewUserFromProto(user *accounts_proto.User) *User {\n\treturn &User{User: *user}\n}", "func TestFromProto(msg proto.Message) *repb.Digest {\n\tblob, err := proto.Marshal(msg)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn FromBlob(blob)\n}", "func CredentialCreationFromProtocol(cc *protocol.CredentialCreation) *CredentialCreation {\n\tif cc == nil {\n\t\treturn nil\n\t}\n\n\t// Based on our configuration we should always get a protocol.URLEncodedBase64\n\t// user ID, but the go-webauthn/webauthn is capable of generating strings too.\n\tvar userID []byte\n\tif id := cc.Response.User.ID; id != nil {\n\t\tswitch uid := id.(type) {\n\t\tcase protocol.URLEncodedBase64:\n\t\t\tuserID = uid\n\t\tcase string:\n\t\t\tuserID = []byte(uid)\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"Unexpected WebAuthn cc.Response.User.ID type: %T\", id))\n\t\t}\n\t}\n\n\treturn &CredentialCreation{\n\t\tResponse: PublicKeyCredentialCreationOptions{\n\t\t\tChallenge: Challenge(cc.Response.Challenge),\n\t\t\tRelyingParty: RelyingPartyEntity{\n\t\t\t\tCredentialEntity: cc.Response.RelyingParty.CredentialEntity,\n\t\t\t\tID: cc.Response.RelyingParty.ID,\n\t\t\t},\n\t\t\tUser: UserEntity{\n\t\t\t\tCredentialEntity: cc.Response.User.CredentialEntity,\n\t\t\t\tDisplayName: cc.Response.User.Name,\n\t\t\t\tID: userID,\n\t\t\t},\n\t\t\tParameters: credentialParametersFromProtocol(cc.Response.Parameters),\n\t\t\tAuthenticatorSelection: AuthenticatorSelection{\n\t\t\t\tAuthenticatorAttachment: cc.Response.AuthenticatorSelection.AuthenticatorAttachment,\n\t\t\t\tRequireResidentKey: cc.Response.AuthenticatorSelection.RequireResidentKey,\n\t\t\t\tResidentKey: cc.Response.AuthenticatorSelection.ResidentKey,\n\t\t\t\tUserVerification: cc.Response.AuthenticatorSelection.UserVerification,\n\t\t\t},\n\t\t\tTimeout: cc.Response.Timeout,\n\t\t\tCredentialExcludeList: credentialDescriptorsFromProtocol(cc.Response.CredentialExcludeList),\n\t\t\tExtensions: cc.Response.Extensions,\n\t\t\tAttestation: cc.Response.Attestation,\n\t\t},\n\t}\n}", "func DeserializeFromTensorProto(pb *tensor_go_proto.TensorProto) *Tensor {\n\tdims := GetDimFromTensorProto(pb)\n\tif int(DimProduct(dims))*int(DtypeSize[pb.GetDtype()]) != len(pb.GetTensorContent()) {\n\t\treturn nil\n\t}\n\n\treturn &Tensor{\n\t\tBuffer: pb.GetTensorContent(),\n\t\tDims: dims,\n\t\tDtype: pb.GetDtype(),\n\t}\n}", "func ProtoToAttestor(p *binaryauthorizationpb.BinaryauthorizationAttestor) *binaryauthorization.Attestor {\n\tobj := &binaryauthorization.Attestor{\n\t\tName: dcl.StringOrNil(p.Name),\n\t\tDescription: dcl.StringOrNil(p.Description),\n\t\tUserOwnedGrafeasNote: ProtoToBinaryauthorizationAttestorUserOwnedGrafeasNote(p.GetUserOwnedGrafeasNote()),\n\t\tUpdateTime: dcl.StringOrNil(p.GetUpdateTime()),\n\t\tProject: dcl.StringOrNil(p.Project),\n\t}\n\treturn obj\n}", "func CommentFromProto(sprint *ticket_svc_sprint.SprintComment) *SprintComment {\n\ttrans := &SprintComment{}\n\n\tcopier.Copy(trans, sprint)\n\n\treturn trans\n}", "func (data *EvidenceData) FromProto(eviData *tmproto.EvidenceList) error {\n\tif eviData == nil {\n\t\treturn errors.New(\"nil evidenceData\")\n\t}\n\n\teviBzs := make(EvidenceList, len(eviData.Evidence))\n\tfor i := range eviData.Evidence {\n\t\tevi, err := EvidenceFromProto(&eviData.Evidence[i])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\teviBzs[i] = evi\n\t}\n\tdata.Evidence = eviBzs\n\tdata.byteSize = int64(eviData.Size())\n\n\treturn nil\n}", "func (data *EvidenceData) FromProto(eviData *tmproto.EvidenceList) error {\n\tif eviData == nil {\n\t\treturn errors.New(\"nil evidenceData\")\n\t}\n\n\teviBzs := make(EvidenceList, len(eviData.Evidence))\n\tfor i := range eviData.Evidence {\n\t\tevi, err := EvidenceFromProto(&eviData.Evidence[i])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\teviBzs[i] = evi\n\t}\n\tdata.Evidence = eviBzs\n\tdata.byteSize = int64(eviData.Size())\n\n\treturn nil\n}", "func NewDataBlobFromProto(blob *commonpb.DataBlob) *serialization.DataBlob {\n\tswitch blob.GetEncodingType() {\n\tcase commonpb.EncodingType_JSON:\n\t\treturn &serialization.DataBlob{\n\t\t\tEncoding: common.EncodingTypeJSON,\n\t\t\tData: blob.Data,\n\t\t}\n\tcase commonpb.EncodingType_Proto3:\n\t\treturn &serialization.DataBlob{\n\t\t\tEncoding: common.EncodingTypeProto3,\n\t\t\tData: blob.Data,\n\t\t}\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"NewDataBlobFromProto seeing unsupported enconding type: %v\", blob.GetEncodingType()))\n\t}\n}", "func NewConfigFromProto(p *protos.SchedulerConfig) *Config {\n\tc := NewConfig()\n\tif p.BotExpiration != nil {\n\t\tc.BotExpiration = tutils.Duration(p.BotExpiration)\n\t}\n\tc.DisablePreemption = p.DisablePreemption\n\tfor aid, ac := range p.AccountConfigs {\n\t\tc.AccountConfigs[AccountID(aid)] = NewAccountConfig(\n\t\t\tint(ac.MaxFanout), ac.MaxChargeSeconds, ac.ChargeRate, ac.DisableFreeTasks)\n\t}\n\treturn c\n}", "func protoToEndpointAuth(prep *protoep.Endpoint) []*domain.EndpointAuth {\n\tret := make([]*domain.EndpointAuth, 0)\n\n\tfor _, grant := range prep.GetGranted() {\n\t\tret = append(ret, &domain.EndpointAuth{\n\t\t\tServiceName: prep.GetService(),\n\t\t\tEndpointName: prep.GetEndpoint(),\n\t\t\tAllowedService: grant.GetName(),\n\t\t\tRole: grant.GetRole(),\n\t\t})\n\t}\n\n\treturn ret\n}", "func RecordFromProtobuf(partitionKeyIndex *uint64, hashKeyIndex *uint64, payload proto.Message, tags ...*Tag) (*Record, error) {\n\tvar record = &Record{}\n\tdata, err := proto.Marshal(payload)\n\tif err != nil {\n\t\treturn record, fmt.Errorf(\"Error marshaling payload.\\t\", err)\n\t}\n\trecord.PartitionKeyIndex = partitionKeyIndex\n\trecord.ExplicitHashKeyIndex = hashKeyIndex\n\trecord.Data = data\n\treturn record, nil\n}", "func ProtoToSubscription(p *pubsublitepb.PubsubliteSubscription) *pubsublite.Subscription {\n\tobj := &pubsublite.Subscription{\n\t\tName: dcl.StringOrNil(p.Name),\n\t\tTopic: dcl.StringOrNil(p.Topic),\n\t\tDeliveryConfig: ProtoToPubsubliteSubscriptionDeliveryConfig(p.GetDeliveryConfig()),\n\t\tProject: dcl.StringOrNil(p.Project),\n\t\tLocation: dcl.StringOrNil(p.Location),\n\t}\n\treturn obj\n}", "func (p *Pipeline) FromProto(pb pipelinepb.AppliedPipeline) error {\n\tnumOps := len(pb.Ops)\n\tif cap(p.Operations) >= numOps {\n\t\tp.Operations = p.Operations[:numOps]\n\t} else {\n\t\tp.Operations = make([]OpUnion, numOps)\n\t}\n\tfor i := 0; i < numOps; i++ {\n\t\tif err := p.Operations[i].FromProto(pb.Ops[i]); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func RecordFromProto(rec *pb.Log_Record, key crypto.DecryptionKey) (net.Record, error) {\n\tif key == nil {\n\t\treturn nil, fmt.Errorf(\"decryption key is required\")\n\t}\n\n\trnode, err := cbornode.Decode(rec.RecordNode, mh.SHA2_256, -1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tenode, err := cbornode.Decode(rec.EventNode, mh.SHA2_256, -1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thnode, err := cbornode.Decode(rec.HeaderNode, mh.SHA2_256, -1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbody, err := cbornode.Decode(rec.BodyNode, mh.SHA2_256, -1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdecoded, err := DecodeBlock(rnode, key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trobj := new(record)\n\tif err = cbornode.DecodeInto(decoded.RawData(), robj); err != nil {\n\t\treturn nil, err\n\t}\n\n\teobj := new(event)\n\tif err = cbornode.DecodeInto(enode.RawData(), eobj); err != nil {\n\t\treturn nil, err\n\t}\n\tevent := &Event{\n\t\tNode: enode,\n\t\tobj: eobj,\n\t\theader: &EventHeader{\n\t\t\tNode: hnode,\n\t\t},\n\t\tbody: body,\n\t}\n\treturn &Record{\n\t\tNode: rnode,\n\t\tobj: robj,\n\t\tblock: event,\n\t}, nil\n}", "func ProtoToDeidentifyTemplate(p *betapb.DlpBetaDeidentifyTemplate) *beta.DeidentifyTemplate {\n\tobj := &beta.DeidentifyTemplate{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tDisplayName: dcl.StringOrNil(p.GetDisplayName()),\n\t\tDescription: dcl.StringOrNil(p.GetDescription()),\n\t\tCreateTime: dcl.StringOrNil(p.GetCreateTime()),\n\t\tUpdateTime: dcl.StringOrNil(p.GetUpdateTime()),\n\t\tDeidentifyConfig: ProtoToDlpBetaDeidentifyTemplateDeidentifyConfig(p.GetDeidentifyConfig()),\n\t\tLocationId: dcl.StringOrNil(p.GetLocationId()),\n\t\tParent: dcl.StringOrNil(p.GetParent()),\n\t\tLocation: dcl.StringOrNil(p.GetLocation()),\n\t}\n\treturn obj\n}", "func FromGRPC(ctx context.Context) (*Client, bool) {\n\tif p, ok := peer.FromContext(ctx); ok {\n\t\tip := parseIP(p.Addr.String())\n\t\tif ip != \"\" {\n\t\t\treturn &Client{ip}, true\n\t\t}\n\t}\n\treturn nil, false\n}", "func ProtoToInterconnectAttachment(p *betapb.ComputeBetaInterconnectAttachment) *beta.InterconnectAttachment {\n\tobj := &beta.InterconnectAttachment{\n\t\tDescription: dcl.StringOrNil(p.GetDescription()),\n\t\tSelfLink: dcl.StringOrNil(p.GetSelfLink()),\n\t\tId: dcl.Int64OrNil(p.GetId()),\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tInterconnect: dcl.StringOrNil(p.GetInterconnect()),\n\t\tRouter: dcl.StringOrNil(p.GetRouter()),\n\t\tRegion: dcl.StringOrNil(p.GetRegion()),\n\t\tMtu: dcl.Int64OrNil(p.GetMtu()),\n\t\tPrivateInterconnectInfo: ProtoToComputeBetaInterconnectAttachmentPrivateInterconnectInfo(p.GetPrivateInterconnectInfo()),\n\t\tOperationalStatus: ProtoToComputeBetaInterconnectAttachmentOperationalStatusEnum(p.GetOperationalStatus()),\n\t\tCloudRouterIPAddress: dcl.StringOrNil(p.GetCloudRouterIpAddress()),\n\t\tCustomerRouterIPAddress: dcl.StringOrNil(p.GetCustomerRouterIpAddress()),\n\t\tType: ProtoToComputeBetaInterconnectAttachmentTypeEnum(p.GetType()),\n\t\tPairingKey: dcl.StringOrNil(p.GetPairingKey()),\n\t\tAdminEnabled: dcl.Bool(p.GetAdminEnabled()),\n\t\tVlanTag8021q: dcl.Int64OrNil(p.GetVlanTag8021Q()),\n\t\tEdgeAvailabilityDomain: ProtoToComputeBetaInterconnectAttachmentEdgeAvailabilityDomainEnum(p.GetEdgeAvailabilityDomain()),\n\t\tBandwidth: ProtoToComputeBetaInterconnectAttachmentBandwidthEnum(p.GetBandwidth()),\n\t\tPartnerMetadata: ProtoToComputeBetaInterconnectAttachmentPartnerMetadata(p.GetPartnerMetadata()),\n\t\tState: ProtoToComputeBetaInterconnectAttachmentStateEnum(p.GetState()),\n\t\tPartnerAsn: dcl.Int64OrNil(p.GetPartnerAsn()),\n\t\tEncryption: ProtoToComputeBetaInterconnectAttachmentEncryptionEnum(p.GetEncryption()),\n\t\tDataplaneVersion: dcl.Int64OrNil(p.GetDataplaneVersion()),\n\t\tSatisfiesPzs: dcl.Bool(p.GetSatisfiesPzs()),\n\t\tLabelFingerprint: dcl.StringOrNil(p.GetLabelFingerprint()),\n\t\tProject: dcl.StringOrNil(p.GetProject()),\n\t}\n\tfor _, r := range p.GetCandidateSubnets() {\n\t\tobj.CandidateSubnets = append(obj.CandidateSubnets, r)\n\t}\n\tfor _, r := range p.GetIpsecInternalAddresses() {\n\t\tobj.IpsecInternalAddresses = append(obj.IpsecInternalAddresses, r)\n\t}\n\treturn obj\n}", "func ServiceAccountToProto(resource *iam.ServiceAccount) *iampb.IamServiceAccount {\n\tp := &iampb.IamServiceAccount{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetUniqueId(dcl.ValueOrEmptyString(resource.UniqueId))\n\tp.SetEmail(dcl.ValueOrEmptyString(resource.Email))\n\tp.SetDisplayName(dcl.ValueOrEmptyString(resource.DisplayName))\n\tp.SetDescription(dcl.ValueOrEmptyString(resource.Description))\n\tp.SetOauth2ClientId(dcl.ValueOrEmptyString(resource.OAuth2ClientId))\n\tp.SetActasResources(IamServiceAccountActasResourcesToProto(resource.ActasResources))\n\tp.SetDisabled(dcl.ValueOrEmptyBool(resource.Disabled))\n\n\treturn p\n}", "func NewFromGRPC(conn *grpc.ClientConn, log *zap.Logger, timeout time.Duration) (api.Peer, error) {\n\tl := log.Named(`NewFromGRPC`)\n\tp := &peer{conn: conn, log: log.Named(`peer`), timeout: timeout}\n\tif err := p.initEndorserClient(); err != nil {\n\t\tl.Error(`Failed to initialize endorser client`, zap.Error(err))\n\t\treturn nil, errors.Wrap(err, `failed to initialize EndorserClient`)\n\t}\n\treturn p, nil\n}", "func ProtoToCaPool(p *alphapb.PrivatecaAlphaCaPool) *alpha.CaPool {\n\tobj := &alpha.CaPool{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tTier: ProtoToPrivatecaAlphaCaPoolTierEnum(p.GetTier()),\n\t\tIssuancePolicy: ProtoToPrivatecaAlphaCaPoolIssuancePolicy(p.GetIssuancePolicy()),\n\t\tPublishingOptions: ProtoToPrivatecaAlphaCaPoolPublishingOptions(p.GetPublishingOptions()),\n\t\tProject: dcl.StringOrNil(p.GetProject()),\n\t\tLocation: dcl.StringOrNil(p.GetLocation()),\n\t}\n\treturn obj\n}", "func CertificateTemplateToProto(resource *beta.CertificateTemplate) *betapb.PrivatecaBetaCertificateTemplate {\n\tp := &betapb.PrivatecaBetaCertificateTemplate{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetPredefinedValues(PrivatecaBetaCertificateTemplatePredefinedValuesToProto(resource.PredefinedValues))\n\tp.SetIdentityConstraints(PrivatecaBetaCertificateTemplateIdentityConstraintsToProto(resource.IdentityConstraints))\n\tp.SetPassthroughExtensions(PrivatecaBetaCertificateTemplatePassthroughExtensionsToProto(resource.PassthroughExtensions))\n\tp.SetDescription(dcl.ValueOrEmptyString(resource.Description))\n\tp.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime))\n\tp.SetUpdateTime(dcl.ValueOrEmptyString(resource.UpdateTime))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetLocation(dcl.ValueOrEmptyString(resource.Location))\n\tmLabels := make(map[string]string, len(resource.Labels))\n\tfor k, r := range resource.Labels {\n\t\tmLabels[k] = r\n\t}\n\tp.SetLabels(mLabels)\n\n\treturn p\n}", "func DataFromProto(dp *tmproto.Data) (Data, error) {\n\tif dp == nil {\n\t\treturn Data{}, errors.New(\"nil data\")\n\t}\n\tdata := new(Data)\n\n\tif len(dp.Txs) > 0 {\n\t\ttxBzs := make(Txs, len(dp.Txs))\n\t\tfor i := range dp.Txs {\n\t\t\ttxBzs[i] = Tx(dp.Txs[i])\n\t\t}\n\t\tdata.Txs = txBzs\n\t} else {\n\t\tdata.Txs = Txs{}\n\t}\n\n\treturn *data, nil\n}", "func DataFromProto(dp *tmproto.Data) (Data, error) {\n\tif dp == nil {\n\t\treturn Data{}, errors.New(\"nil data\")\n\t}\n\tdata := new(Data)\n\n\tif len(dp.Txs) > 0 {\n\t\ttxBzs := make(Txs, len(dp.Txs))\n\t\tfor i := range dp.Txs {\n\t\t\ttxBzs[i] = Tx(dp.Txs[i])\n\t\t}\n\t\tdata.Txs = txBzs\n\t} else {\n\t\tdata.Txs = Txs{}\n\t}\n\n\treturn *data, nil\n}", "func (app *adapter) FromBytes(bytes []byte) (PrivateKey, error) {\n\tpk, err := x509.ParsePKCS1PrivateKey(bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn app.builder.WithPK(*pk).Now()\n}", "func CryptoKeyToProto(resource *beta.CryptoKey) *betapb.CloudkmsBetaCryptoKey {\n\tp := &betapb.CloudkmsBetaCryptoKey{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetPrimary(CloudkmsBetaCryptoKeyPrimaryToProto(resource.Primary))\n\tp.SetPurpose(CloudkmsBetaCryptoKeyPurposeEnumToProto(resource.Purpose))\n\tp.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime))\n\tp.SetNextRotationTime(dcl.ValueOrEmptyString(resource.NextRotationTime))\n\tp.SetRotationPeriod(dcl.ValueOrEmptyString(resource.RotationPeriod))\n\tp.SetVersionTemplate(CloudkmsBetaCryptoKeyVersionTemplateToProto(resource.VersionTemplate))\n\tp.SetImportOnly(dcl.ValueOrEmptyBool(resource.ImportOnly))\n\tp.SetDestroyScheduledDuration(dcl.ValueOrEmptyString(resource.DestroyScheduledDuration))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetLocation(dcl.ValueOrEmptyString(resource.Location))\n\tp.SetKeyRing(dcl.ValueOrEmptyString(resource.KeyRing))\n\tmLabels := make(map[string]string, len(resource.Labels))\n\tfor k, r := range resource.Labels {\n\t\tmLabels[k] = r\n\t}\n\tp.SetLabels(mLabels)\n\n\treturn p\n}", "func ProtoToPrivatecaBetaCertificateTemplateIdentityConstraints(p *betapb.PrivatecaBetaCertificateTemplateIdentityConstraints) *beta.CertificateTemplateIdentityConstraints {\n\tif p == nil {\n\t\treturn nil\n\t}\n\tobj := &beta.CertificateTemplateIdentityConstraints{\n\t\tCelExpression: ProtoToPrivatecaBetaCertificateTemplateIdentityConstraintsCelExpression(p.GetCelExpression()),\n\t\tAllowSubjectPassthrough: dcl.Bool(p.GetAllowSubjectPassthrough()),\n\t\tAllowSubjectAltNamesPassthrough: dcl.Bool(p.GetAllowSubjectAltNamesPassthrough()),\n\t}\n\treturn obj\n}", "func AttestorToProto(resource *binaryauthorization.Attestor) *binaryauthorizationpb.BinaryauthorizationAttestor {\n\tp := &binaryauthorizationpb.BinaryauthorizationAttestor{\n\t\tName: dcl.ValueOrEmptyString(resource.Name),\n\t\tDescription: dcl.ValueOrEmptyString(resource.Description),\n\t\tUserOwnedGrafeasNote: BinaryauthorizationAttestorUserOwnedGrafeasNoteToProto(resource.UserOwnedGrafeasNote),\n\t\tUpdateTime: dcl.ValueOrEmptyString(resource.UpdateTime),\n\t\tProject: dcl.ValueOrEmptyString(resource.Project),\n\t}\n\n\treturn p\n}", "func ProtoToRecaptchaenterpriseKeyTestingOptions(p *recaptchaenterprisepb.RecaptchaenterpriseKeyTestingOptions) *recaptchaenterprise.KeyTestingOptions {\n\tif p == nil {\n\t\treturn nil\n\t}\n\tobj := &recaptchaenterprise.KeyTestingOptions{\n\t\tTestingScore: dcl.Float64OrNil(p.GetTestingScore()),\n\t\tTestingChallenge: ProtoToRecaptchaenterpriseKeyTestingOptionsTestingChallengeEnum(p.GetTestingChallenge()),\n\t}\n\treturn obj\n}", "func ProtoToManagedSslCertificate(p *betapb.ComputeBetaManagedSslCertificate) *beta.ManagedSslCertificate {\n\tobj := &beta.ManagedSslCertificate{\n\t\tName: dcl.StringOrNil(p.Name),\n\t\tId: dcl.Int64OrNil(p.Id),\n\t\tCreationTimestamp: dcl.StringOrNil(p.CreationTimestamp),\n\t\tDescription: dcl.StringOrNil(p.Description),\n\t\tSelfLink: dcl.StringOrNil(p.SelfLink),\n\t\tManaged: ProtoToComputeBetaManagedSslCertificateManaged(p.GetManaged()),\n\t\tType: ProtoToComputeBetaManagedSslCertificateTypeEnum(p.GetType()),\n\t\tExpireTime: dcl.StringOrNil(p.ExpireTime),\n\t\tProject: dcl.StringOrNil(p.Project),\n\t}\n\tfor _, r := range p.GetSubjectAlternativeNames() {\n\t\tobj.SubjectAlternativeNames = append(obj.SubjectAlternativeNames, r)\n\t}\n\treturn obj\n}", "func ProtoToCloudkmsBetaCryptoKeyVersionTemplate(p *betapb.CloudkmsBetaCryptoKeyVersionTemplate) *beta.CryptoKeyVersionTemplate {\n\tif p == nil {\n\t\treturn nil\n\t}\n\tobj := &beta.CryptoKeyVersionTemplate{\n\t\tProtectionLevel: ProtoToCloudkmsBetaCryptoKeyVersionTemplateProtectionLevelEnum(p.GetProtectionLevel()),\n\t\tAlgorithm: ProtoToCloudkmsBetaCryptoKeyVersionTemplateAlgorithmEnum(p.GetAlgorithm()),\n\t}\n\treturn obj\n}", "func NewAccountConfigFromProto(c *protos.AccountConfig) *AccountConfig {\n\treturn NewAccountConfig(\n\t\tint(c.MaxFanout),\n\t\tc.MaxChargeSeconds,\n\t\tc.ChargeRate,\n\t\tc.DisableFreeTasks,\n\t)\n}", "func (op *RollupOp) FromProto(pb pipelinepb.AppliedRollupOp) error {\n\top.AggregationID.FromProto(pb.AggregationId)\n\top.ID = pb.Id\n\treturn nil\n}", "func ComputeBetaInstanceTemplatePropertiesServiceAccountsToProto(o *beta.InstanceTemplatePropertiesServiceAccounts) *betapb.ComputeBetaInstanceTemplatePropertiesServiceAccounts {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.ComputeBetaInstanceTemplatePropertiesServiceAccounts{\n\t\tEmail: dcl.ValueOrEmptyString(o.Email),\n\t}\n\tfor _, r := range o.Scopes {\n\t\tp.Scopes = append(p.Scopes, r)\n\t}\n\treturn p\n}", "func KeyToProto(resource *recaptchaenterprise.Key) *recaptchaenterprisepb.RecaptchaenterpriseKey {\n\tp := &recaptchaenterprisepb.RecaptchaenterpriseKey{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetDisplayName(dcl.ValueOrEmptyString(resource.DisplayName))\n\tp.SetWebSettings(RecaptchaenterpriseKeyWebSettingsToProto(resource.WebSettings))\n\tp.SetAndroidSettings(RecaptchaenterpriseKeyAndroidSettingsToProto(resource.AndroidSettings))\n\tp.SetIosSettings(RecaptchaenterpriseKeyIosSettingsToProto(resource.IosSettings))\n\tp.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime))\n\tp.SetTestingOptions(RecaptchaenterpriseKeyTestingOptionsToProto(resource.TestingOptions))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tmLabels := make(map[string]string, len(resource.Labels))\n\tfor k, r := range resource.Labels {\n\t\tmLabels[k] = r\n\t}\n\tp.SetLabels(mLabels)\n\n\treturn p\n}", "func InterconnectAttachmentToProto(resource *beta.InterconnectAttachment) *betapb.ComputeBetaInterconnectAttachment {\n\tp := &betapb.ComputeBetaInterconnectAttachment{}\n\tp.SetDescription(dcl.ValueOrEmptyString(resource.Description))\n\tp.SetSelfLink(dcl.ValueOrEmptyString(resource.SelfLink))\n\tp.SetId(dcl.ValueOrEmptyInt64(resource.Id))\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetInterconnect(dcl.ValueOrEmptyString(resource.Interconnect))\n\tp.SetRouter(dcl.ValueOrEmptyString(resource.Router))\n\tp.SetRegion(dcl.ValueOrEmptyString(resource.Region))\n\tp.SetMtu(dcl.ValueOrEmptyInt64(resource.Mtu))\n\tp.SetPrivateInterconnectInfo(ComputeBetaInterconnectAttachmentPrivateInterconnectInfoToProto(resource.PrivateInterconnectInfo))\n\tp.SetOperationalStatus(ComputeBetaInterconnectAttachmentOperationalStatusEnumToProto(resource.OperationalStatus))\n\tp.SetCloudRouterIpAddress(dcl.ValueOrEmptyString(resource.CloudRouterIPAddress))\n\tp.SetCustomerRouterIpAddress(dcl.ValueOrEmptyString(resource.CustomerRouterIPAddress))\n\tp.SetType(ComputeBetaInterconnectAttachmentTypeEnumToProto(resource.Type))\n\tp.SetPairingKey(dcl.ValueOrEmptyString(resource.PairingKey))\n\tp.SetAdminEnabled(dcl.ValueOrEmptyBool(resource.AdminEnabled))\n\tp.SetVlanTag8021Q(dcl.ValueOrEmptyInt64(resource.VlanTag8021q))\n\tp.SetEdgeAvailabilityDomain(ComputeBetaInterconnectAttachmentEdgeAvailabilityDomainEnumToProto(resource.EdgeAvailabilityDomain))\n\tp.SetBandwidth(ComputeBetaInterconnectAttachmentBandwidthEnumToProto(resource.Bandwidth))\n\tp.SetPartnerMetadata(ComputeBetaInterconnectAttachmentPartnerMetadataToProto(resource.PartnerMetadata))\n\tp.SetState(ComputeBetaInterconnectAttachmentStateEnumToProto(resource.State))\n\tp.SetPartnerAsn(dcl.ValueOrEmptyInt64(resource.PartnerAsn))\n\tp.SetEncryption(ComputeBetaInterconnectAttachmentEncryptionEnumToProto(resource.Encryption))\n\tp.SetDataplaneVersion(dcl.ValueOrEmptyInt64(resource.DataplaneVersion))\n\tp.SetSatisfiesPzs(dcl.ValueOrEmptyBool(resource.SatisfiesPzs))\n\tp.SetLabelFingerprint(dcl.ValueOrEmptyString(resource.LabelFingerprint))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tsCandidateSubnets := make([]string, len(resource.CandidateSubnets))\n\tfor i, r := range resource.CandidateSubnets {\n\t\tsCandidateSubnets[i] = r\n\t}\n\tp.SetCandidateSubnets(sCandidateSubnets)\n\tsIpsecInternalAddresses := make([]string, len(resource.IpsecInternalAddresses))\n\tfor i, r := range resource.IpsecInternalAddresses {\n\t\tsIpsecInternalAddresses[i] = r\n\t}\n\tp.SetIpsecInternalAddresses(sIpsecInternalAddresses)\n\tmLabels := make(map[string]string, len(resource.Labels))\n\tfor k, r := range resource.Labels {\n\t\tmLabels[k] = r\n\t}\n\tp.SetLabels(mLabels)\n\n\treturn p\n}", "func ProtoToComputeBetaInstanceTemplatePropertiesServiceAccounts(p *betapb.ComputeBetaInstanceTemplatePropertiesServiceAccounts) *beta.InstanceTemplatePropertiesServiceAccounts {\n\tif p == nil {\n\t\treturn nil\n\t}\n\tobj := &beta.InstanceTemplatePropertiesServiceAccounts{\n\t\tEmail: dcl.StringOrNil(p.Email),\n\t}\n\tfor _, r := range p.GetScopes() {\n\t\tobj.Scopes = append(obj.Scopes, r)\n\t}\n\treturn obj\n}", "func FromProto(t *pbMerkle.Tree, newContentObject func() IContent) *Tree {\n\treturn &Tree{\n\t\tdepth: int(t.Depth),\n\t\trootNode: nodeFromProto(t.GetRootNode(), newContentObject),\n\t}\n}", "func FromProtoValue(val protoreflect.Value) (rel.Value, error) {\n\tswitch message := val.Interface().(type) {\n\tcase protoreflect.Message:\n\t\tvar attrs []rel.Attr\n\t\tvar err error\n\t\tmessage.Range(func(desc protoreflect.FieldDescriptor, val protoreflect.Value) bool {\n\t\t\tvar item rel.Value\n\t\t\titem, err = FromProtoValue(val)\n\t\t\tif err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tfieldName := string(desc.Name())\n\t\t\titemNum, isNum := item.(rel.Number)\n\t\t\tif desc.Enum() != nil && isNum {\n\t\t\t\t// item is protoreflect.EnumNumber\n\t\t\t\tif num, success := itemNum.Int(); success {\n\t\t\t\t\ten := protoreflect.EnumNumber(num)\n\t\t\t\t\tname := desc.Enum().Values().ByNumber(en).Name()\n\t\t\t\t\tattrs = append(attrs, rel.NewStringAttr(fieldName, []rune(name)))\n\t\t\t\t} else {\n\t\t\t\t\tattrs = append(attrs, rel.NewAttr(fieldName, item))\n\t\t\t\t}\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tattrs = append(attrs, rel.NewAttr(fieldName, item))\n\t\t\treturn true\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn rel.NewTuple(attrs...), nil\n\n\tcase protoreflect.Map:\n\t\tentries := make([]rel.DictEntryTuple, 0, val.Map().Len())\n\t\tvar err error\n\t\tval.Map().Range(func(key protoreflect.MapKey, value protoreflect.Value) bool {\n\t\t\tvar val rel.Value\n\t\t\tval, err = FromProtoValue(value)\n\t\t\tif err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tat := rel.NewString([]rune(key.String()))\n\t\t\tentries = append(entries, rel.NewDictEntryTuple(at, val))\n\t\t\treturn true\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn rel.NewDict(false, entries...)\n\n\tcase protoreflect.List:\n\t\tlist := make([]rel.Value, 0, message.Len())\n\t\tfor i := 0; i < message.Len(); i++ {\n\t\t\titem, err := FromProtoValue(message.Get(i))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tlist = append(list, item)\n\t\t}\n\t\treturn rel.NewArray(list...), nil\n\n\tcase string, bool, int, int32, int64, uint, uint32, uint64, float32, float64:\n\t\treturn rel.NewValue(message)\n\n\tcase protoreflect.EnumNumber:\n\t\t// type EnumNumber int32\n\t\treturn rel.NewValue(int32(message))\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"%v (%[1]T) not supported\", message)\n\t}\n}", "func CloudkmsBetaCryptoKeyVersionTemplateToProto(o *beta.CryptoKeyVersionTemplate) *betapb.CloudkmsBetaCryptoKeyVersionTemplate {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.CloudkmsBetaCryptoKeyVersionTemplate{}\n\tp.SetProtectionLevel(CloudkmsBetaCryptoKeyVersionTemplateProtectionLevelEnumToProto(o.ProtectionLevel))\n\tp.SetAlgorithm(CloudkmsBetaCryptoKeyVersionTemplateAlgorithmEnumToProto(o.Algorithm))\n\treturn p\n}", "func FromProto(s *spb.Status) *Status {\n\treturn status.FromProto(s)\n}", "func FromProto(s *spb.Status) *Status {\n\treturn status.FromProto(s)\n}", "func ProtoToRecaptchaenterpriseKeyAndroidSettings(p *recaptchaenterprisepb.RecaptchaenterpriseKeyAndroidSettings) *recaptchaenterprise.KeyAndroidSettings {\n\tif p == nil {\n\t\treturn nil\n\t}\n\tobj := &recaptchaenterprise.KeyAndroidSettings{\n\t\tAllowAllPackageNames: dcl.Bool(p.GetAllowAllPackageNames()),\n\t}\n\tfor _, r := range p.GetAllowedPackageNames() {\n\t\tobj.AllowedPackageNames = append(obj.AllowedPackageNames, r)\n\t}\n\treturn obj\n}", "func (vs *ValidatorSet) FromProto(pb *pbtypes.ValidatorSet) error {\n\terr := lcs.Unmarshal(pb.Bytes, vs)\n\treturn err\n}", "func HeaderFromProto(ph *tmproto.Header) (Header, error) {\n\tif ph == nil {\n\t\treturn Header{}, errors.New(\"nil Header\")\n\t}\n\n\th := new(Header)\n\n\tbi, err := BlockIDFromProto(&ph.LastBlockId)\n\tif err != nil {\n\t\treturn Header{}, err\n\t}\n\n\th.Version = ph.Version\n\th.ChainID = ph.ChainID\n\th.Height = ph.Height\n\th.Time = ph.Time\n\th.Height = ph.Height\n\th.LastBlockID = *bi\n\th.ValidatorsHash = ph.ValidatorsHash\n\th.NextValidatorsHash = ph.NextValidatorsHash\n\th.ConsensusHash = ph.ConsensusHash\n\th.AppHash = ph.AppHash\n\th.DataHash = ph.DataHash\n\th.EvidenceHash = ph.EvidenceHash\n\th.LastResultsHash = ph.LastResultsHash\n\th.LastCommitHash = ph.LastCommitHash\n\th.ProposerAddress = ph.ProposerAddress\n\n\treturn *h, h.ValidateBasic()\n}", "func HeaderFromProto(ph *tmproto.Header) (Header, error) {\n\tif ph == nil {\n\t\treturn Header{}, errors.New(\"nil Header\")\n\t}\n\n\th := new(Header)\n\n\tbi, err := BlockIDFromProto(&ph.LastBlockId)\n\tif err != nil {\n\t\treturn Header{}, err\n\t}\n\n\th.Version = ph.Version\n\th.ChainID = ph.ChainID\n\th.Height = ph.Height\n\th.Time = ph.Time\n\th.Height = ph.Height\n\th.LastBlockID = *bi\n\th.ValidatorsHash = ph.ValidatorsHash\n\th.NextValidatorsHash = ph.NextValidatorsHash\n\th.ConsensusHash = ph.ConsensusHash\n\th.AppHash = ph.AppHash\n\th.DataHash = ph.DataHash\n\th.EvidenceHash = ph.EvidenceHash\n\th.LastResultsHash = ph.LastResultsHash\n\th.LastCommitHash = ph.LastCommitHash\n\th.ProposerAddress = ph.ProposerAddress\n\n\treturn *h, h.ValidateBasic()\n}", "func FromProto(s *spb.Status) *Status {\n\treturn &Status{s: proto.Clone(s).(*spb.Status)}\n}", "func (e *Entity) loadFromP2PProtobuf(data *entitypb.Entity) error {\n\tdids, err := identity.BytesToDIDs(data.Identity)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\te.Identity = dids[0]\n\te.LegalName = data.LegalName\n\te.Addresses = data.Addresses\n\te.PaymentDetails = data.PaymentDetails\n\te.Contacts = data.Contacts\n\treturn nil\n}", "func (m *modeKinds) FromProto(proto *api.ModeKinds) error {\n\tif proto.UserPrefixes != nil {\n\t\tm.userPrefixes = make([][2]rune, len(proto.UserPrefixes))\n\t\tfor i, prefix := range proto.UserPrefixes {\n\t\t\tif len(prefix.Char) != 1 || len(prefix.Symbol) != 1 {\n\t\t\t\treturn errors.New(\"user_prefixes is an array of length 2 of 1 character strings\")\n\t\t\t}\n\n\t\t\tm.userPrefixes[i] = [2]rune{\n\t\t\t\trune(prefix.Symbol[0]),\n\t\t\t\trune(prefix.Char[0]),\n\t\t\t}\n\t\t}\n\t}\n\tif proto.ChannelModes != nil {\n\t\tm.channelModes = make(map[rune]int, len(proto.ChannelModes))\n\t\tfor k, v := range proto.ChannelModes {\n\t\t\tif len(k) != 1 {\n\t\t\t\treturn errors.New(\"channel_modes is a map of characters to integers\")\n\t\t\t}\n\t\t\tm.channelModes[rune(k[0])] = int(v)\n\t\t}\n\t}\n\n\treturn nil\n}", "func RecaptchaenterpriseKeyTestingOptionsToProto(o *recaptchaenterprise.KeyTestingOptions) *recaptchaenterprisepb.RecaptchaenterpriseKeyTestingOptions {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &recaptchaenterprisepb.RecaptchaenterpriseKeyTestingOptions{}\n\tp.SetTestingScore(dcl.ValueOrEmptyDouble(o.TestingScore))\n\tp.SetTestingChallenge(RecaptchaenterpriseKeyTestingOptionsTestingChallengeEnumToProto(o.TestingChallenge))\n\treturn p\n}", "func ProtoToSignature(pb *Signature) (interfaces.Signature, error) {\n\tif pb == nil {\n\t\treturn nil, errors.New(\"nil proto signature\")\n\t}\n\tvar length = len(pb.Raw)\n\tif length == SignatureLengthBLS {\n\t\tsig, err := chiapos.NewG2ElementFromBytes(pb.Raw)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn sig, nil\n\t} else if SignatureLengthS256Min <= length && length <= SignatureLengthS256Max {\n\t\tsig, err := pocec.ParseDERSignature(pb.Raw, pocec.S256())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn sig, nil\n\t} else {\n\t\treturn nil, errors.New(\"unknown signature length\")\n\t}\n}", "func DeidentifyTemplateToProto(resource *beta.DeidentifyTemplate) *betapb.DlpBetaDeidentifyTemplate {\n\tp := &betapb.DlpBetaDeidentifyTemplate{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetDisplayName(dcl.ValueOrEmptyString(resource.DisplayName))\n\tp.SetDescription(dcl.ValueOrEmptyString(resource.Description))\n\tp.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime))\n\tp.SetUpdateTime(dcl.ValueOrEmptyString(resource.UpdateTime))\n\tp.SetDeidentifyConfig(DlpBetaDeidentifyTemplateDeidentifyConfigToProto(resource.DeidentifyConfig))\n\tp.SetLocationId(dcl.ValueOrEmptyString(resource.LocationId))\n\tp.SetParent(dcl.ValueOrEmptyString(resource.Parent))\n\tp.SetLocation(dcl.ValueOrEmptyString(resource.Location))\n\n\treturn p\n}", "func ProtoToComputeSubnetworkLogConfig(p *computepb.ComputeSubnetworkLogConfig) *compute.SubnetworkLogConfig {\n\tif p == nil {\n\t\treturn nil\n\t}\n\tobj := &compute.SubnetworkLogConfig{\n\t\tAggregationInterval: ProtoToComputeSubnetworkLogConfigAggregationIntervalEnum(p.GetAggregationInterval()),\n\t\tFlowSampling: dcl.Float64OrNil(p.GetFlowSampling()),\n\t\tMetadata: ProtoToComputeSubnetworkLogConfigMetadataEnum(p.GetMetadata()),\n\t}\n\treturn obj\n}", "func ConvertCredentialSchema(in ClaimCredentialSchemaInput) claimtypes.CredentialSchema {\n\treturn claimtypes.CredentialSchema{\n\t\tID: in.ID,\n\t\tType: in.Type,\n\t}\n}", "func HeaderFromProto(ph *tmproto.Header) (Header, error) {\n\tif ph == nil {\n\t\treturn Header{}, errors.New(\"nil Header\")\n\t}\n\n\th := new(Header)\n\n\tbi, err := BlockIDFromProto(&ph.LastBlockId)\n\tif err != nil {\n\t\treturn Header{}, err\n\t}\n\n\th.Version = ph.Version\n\th.ChainID = ph.ChainID\n\th.Height = ph.Height\n\th.CoreChainLockedHeight = ph.CoreChainLockedHeight\n\th.Time = ph.Time\n\th.Height = ph.Height\n\th.LastBlockID = *bi\n\th.ValidatorsHash = ph.ValidatorsHash\n\th.NextValidatorsHash = ph.NextValidatorsHash\n\th.ConsensusHash = ph.ConsensusHash\n\th.AppHash = ph.AppHash\n\th.DataHash = ph.DataHash\n\th.EvidenceHash = ph.EvidenceHash\n\th.LastResultsHash = ph.LastResultsHash\n\th.LastCommitHash = ph.LastCommitHash\n\th.ProposerProTxHash = ph.ProposerProTxHash\n\n\treturn *h, h.ValidateBasic()\n}", "func AuthKeyFromBytes(key []byte) (*ecdsa.PrivateKey, error) {\n\tvar err error\n\n\t// Parse PEM block\n\tvar block *pem.Block\n\tif block, _ = pem.Decode(key); block == nil {\n\t\treturn nil, errors.New(\"token: AuthKey must be a valid .p8 PEM file\")\n\t}\n\n\t// Parse the key\n\tvar parsedKey interface{}\n\tif parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar pkey *ecdsa.PrivateKey\n\tvar ok bool\n\tif pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok {\n\t\treturn nil, errors.New(\"token: AuthKey must be of type ecdsa.PrivateKey\")\n\t}\n\n\treturn pkey, nil\n}", "func StateIDFromProto(sID *tmproto.StateID) (*StateID, error) {\n\tif sID == nil {\n\t\treturn nil, errors.New(\"nil StateID\")\n\t}\n\n\tstateID := new(StateID)\n\n\tstateID.LastAppHash = sID.LastAppHash\n\n\treturn stateID, stateID.ValidateBasic()\n}", "func protoDec(t reflect.Type, in []byte) (T, error) {\n\tvar p protoreflect.ProtoMessage\n\tswitch it := reflect.New(t.Elem()).Interface().(type) {\n\tcase protoreflect.ProtoMessage:\n\t\tp = it\n\tcase protov1.Message:\n\t\tp = protov1.MessageV2(it)\n\t}\n\terr := protov2.UnmarshalOptions{}.Unmarshal(in, p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn p, nil\n}", "func NewFromBytes(certBytes []byte) (certInfo CertInfo, err error) {\n\n\tcertInfo = CertInfo{}\n\tcertInfo.TimeFormat = timeFormat\n\n\terr = certInfo.fromBytes(certBytes)\n\treturn\n}", "func ProtoToInspectTemplate(p *dlppb.DlpInspectTemplate) *dlp.InspectTemplate {\n\tobj := &dlp.InspectTemplate{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tDisplayName: dcl.StringOrNil(p.GetDisplayName()),\n\t\tDescription: dcl.StringOrNil(p.GetDescription()),\n\t\tCreateTime: dcl.StringOrNil(p.GetCreateTime()),\n\t\tUpdateTime: dcl.StringOrNil(p.GetUpdateTime()),\n\t\tInspectConfig: ProtoToDlpInspectTemplateInspectConfig(p.GetInspectConfig()),\n\t\tLocationId: dcl.StringOrNil(p.GetLocationId()),\n\t\tParent: dcl.StringOrNil(p.GetParent()),\n\t\tLocation: dcl.StringOrNil(p.GetLocation()),\n\t}\n\treturn obj\n}", "func loadCredential(r io.Reader) (*Credentials, error) {\n\tvar c Credentials\n\tif err := json.NewDecoder(r).Decode(&c); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &c, nil\n}", "func SubscriptionToProto(resource *pubsublite.Subscription) *pubsublitepb.PubsubliteSubscription {\n\tp := &pubsublitepb.PubsubliteSubscription{\n\t\tName: dcl.ValueOrEmptyString(resource.Name),\n\t\tTopic: dcl.ValueOrEmptyString(resource.Topic),\n\t\tDeliveryConfig: PubsubliteSubscriptionDeliveryConfigToProto(resource.DeliveryConfig),\n\t\tProject: dcl.ValueOrEmptyString(resource.Project),\n\t\tLocation: dcl.ValueOrEmptyString(resource.Location),\n\t}\n\n\treturn p\n}", "func RecaptchaenterpriseKeyTestingOptionsTestingChallengeEnumToProto(e *recaptchaenterprise.KeyTestingOptionsTestingChallengeEnum) recaptchaenterprisepb.RecaptchaenterpriseKeyTestingOptionsTestingChallengeEnum {\n\tif e == nil {\n\t\treturn recaptchaenterprisepb.RecaptchaenterpriseKeyTestingOptionsTestingChallengeEnum(0)\n\t}\n\tif v, ok := recaptchaenterprisepb.RecaptchaenterpriseKeyTestingOptionsTestingChallengeEnum_value[\"KeyTestingOptionsTestingChallengeEnum\"+string(*e)]; ok {\n\t\treturn recaptchaenterprisepb.RecaptchaenterpriseKeyTestingOptionsTestingChallengeEnum(v)\n\t}\n\treturn recaptchaenterprisepb.RecaptchaenterpriseKeyTestingOptionsTestingChallengeEnum(0)\n}", "func BlockFromProto(bp *tmproto.Block) (*Block, error) {\n\tif bp == nil {\n\t\treturn nil, errors.New(\"nil block\")\n\t}\n\n\tb := new(Block)\n\th, err := HeaderFromProto(&bp.Header)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.Header = h\n\tdata, err := DataFromProto(&bp.Data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.Data = data\n\tif err := b.Evidence.FromProto(&bp.Evidence); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcoreChainLock, err := CoreChainLockFromProto(bp.CoreChainLock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb.CoreChainLock = coreChainLock\n\n\tif bp.LastCommit != nil {\n\t\tlc, err := CommitFromProto(bp.LastCommit)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tb.LastCommit = lc\n\t}\n\n\treturn b, b.ValidateBasic()\n}", "func (u *OpUnion) FromProto(pb pipelinepb.AppliedPipelineOp) error {\n\tswitch pb.Type {\n\tcase pipelinepb.AppliedPipelineOp_TRANSFORMATION:\n\t\tu.Type = pipeline.TransformationOpType\n\t\tif u.Rollup.ID != nil {\n\t\t\tu.Rollup.ID = u.Rollup.ID[:0]\n\t\t}\n\t\tu.Rollup.AggregationID[0] = aggregation.DefaultID[0]\n\t\treturn u.Transformation.FromProto(pb.Transformation)\n\tcase pipelinepb.AppliedPipelineOp_ROLLUP:\n\t\tu.Type = pipeline.RollupOpType\n\t\tu.Transformation.Type = transformation.UnknownType\n\t\treturn u.Rollup.FromProto(pb.Rollup)\n\tdefault:\n\t\treturn errUnknownOpType\n\t}\n}", "func BlockFromProto(bp *tmproto.Block) (*Block, error) {\n\tif bp == nil {\n\t\treturn nil, errors.New(\"nil block\")\n\t}\n\n\tb := new(Block)\n\th, err := HeaderFromProto(&bp.Header)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.Header = h\n\tdata, err := DataFromProto(&bp.Data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.Data = data\n\tif err := b.Evidence.FromProto(&bp.Evidence); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif bp.LastCommit != nil {\n\t\tlc, err := CommitFromProto(bp.LastCommit)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tb.LastCommit = lc\n\t}\n\n\treturn b, b.ValidateBasic()\n}", "func RecaptchaenterpriseKeyAndroidSettingsToProto(o *recaptchaenterprise.KeyAndroidSettings) *recaptchaenterprisepb.RecaptchaenterpriseKeyAndroidSettings {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &recaptchaenterprisepb.RecaptchaenterpriseKeyAndroidSettings{}\n\tp.SetAllowAllPackageNames(dcl.ValueOrEmptyBool(o.AllowAllPackageNames))\n\tsAllowedPackageNames := make([]string, len(o.AllowedPackageNames))\n\tfor i, r := range o.AllowedPackageNames {\n\t\tsAllowedPackageNames[i] = r\n\t}\n\tp.SetAllowedPackageNames(sAllowedPackageNames)\n\treturn p\n}", "func FromStub(stub shim.ChaincodeStubInterface) (*CertIdentity, error) {\n\tclientIdentity, err := cid.New(stub)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(`client identity from stub: %w`, err)\n\t}\n\tmspID, err := clientIdentity.GetMSPID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcert, err := clientIdentity.GetX509Certificate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &CertIdentity{mspID, cert}, nil\n}", "func NewProtoLoginResponse(result string) *chatterpb.LoginResponse {\n\tmessage := &chatterpb.LoginResponse{}\n\tmessage.Field = result\n\treturn message\n}", "func PrivatecaBetaCertificateTemplateIdentityConstraintsToProto(o *beta.CertificateTemplateIdentityConstraints) *betapb.PrivatecaBetaCertificateTemplateIdentityConstraints {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &betapb.PrivatecaBetaCertificateTemplateIdentityConstraints{}\n\tp.SetCelExpression(PrivatecaBetaCertificateTemplateIdentityConstraintsCelExpressionToProto(o.CelExpression))\n\tp.SetAllowSubjectPassthrough(dcl.ValueOrEmptyBool(o.AllowSubjectPassthrough))\n\tp.SetAllowSubjectAltNamesPassthrough(dcl.ValueOrEmptyBool(o.AllowSubjectAltNamesPassthrough))\n\treturn p\n}", "func ProtoToInstanceTemplate(p *betapb.ComputeBetaInstanceTemplate) *beta.InstanceTemplate {\n\tobj := &beta.InstanceTemplate{\n\t\tCreationTimestamp: dcl.StringOrNil(p.GetCreationTimestamp()),\n\t\tDescription: dcl.StringOrNil(p.Description),\n\t\tId: dcl.Int64OrNil(p.Id),\n\t\tSelfLink: dcl.StringOrNil(p.SelfLink),\n\t\tName: dcl.StringOrNil(p.Name),\n\t\tProperties: ProtoToComputeBetaInstanceTemplateProperties(p.GetProperties()),\n\t\tProject: dcl.StringOrNil(p.Project),\n\t}\n\treturn obj\n}", "func NewGrpcClientFromCert(c *net.CertManager, opts ...grpc.DialOption) *Client {\n\treturn &Client{client: net.NewGrpcClientFromCertManager(c, opts...)}\n}", "func NewProtoConverter(limits *models.Limits) *BrokerRowProtoConverter {\n\treturn &BrokerRowProtoConverter{\n\t\tflatBuilder: flatbuffers.NewBuilder(1024 + 512),\n\t\tkeys: make([]flatbuffers.UOffsetT, 0, 32),\n\t\tvalues: make([]flatbuffers.UOffsetT, 0, 32),\n\t\tfieldNames: make([]flatbuffers.UOffsetT, 0, 32),\n\t\tkvs: make([]flatbuffers.UOffsetT, 0, 32),\n\t\tfields: make([]flatbuffers.UOffsetT, 0, 32),\n\t\tlimits: limits,\n\t}\n}" ]
[ "0.7431579", "0.7430996", "0.69857", "0.69834393", "0.66492873", "0.65091896", "0.63220865", "0.60344005", "0.57588685", "0.5737976", "0.56534", "0.5622571", "0.5621915", "0.56124455", "0.55954367", "0.554616", "0.5524874", "0.55207145", "0.5483683", "0.54677933", "0.53528214", "0.5347747", "0.53061074", "0.5284599", "0.5272473", "0.5264556", "0.5258561", "0.52365565", "0.51616883", "0.5143073", "0.51153606", "0.5089172", "0.50876033", "0.5073027", "0.5073027", "0.50256705", "0.5018406", "0.49841943", "0.4953652", "0.49505958", "0.4949614", "0.491832", "0.49148828", "0.49022573", "0.48953336", "0.488496", "0.48741853", "0.48540866", "0.4848905", "0.48468226", "0.48468226", "0.48465613", "0.48267904", "0.4820696", "0.48152623", "0.48147905", "0.48139328", "0.48128998", "0.48000246", "0.47974762", "0.4784463", "0.4775662", "0.4768663", "0.47652203", "0.47647575", "0.47564963", "0.47513902", "0.47510305", "0.47510305", "0.47351786", "0.47305727", "0.47225246", "0.47225246", "0.47189704", "0.47167918", "0.47165266", "0.4711548", "0.46853864", "0.46813545", "0.46748614", "0.46682474", "0.46644497", "0.46455154", "0.46271172", "0.4619433", "0.46096283", "0.46035412", "0.46016544", "0.45954937", "0.4588734", "0.45718575", "0.45648047", "0.45634148", "0.45564047", "0.4552984", "0.45502242", "0.455004", "0.45332417", "0.4532829", "0.45279086" ]
0.8768559
0
CredentialAssertionResponseFromProto converts a CredentialAssertionResponse proto to its lib counterpart.
func CredentialAssertionResponseFromProto(car *wantypes.CredentialAssertionResponse) *CredentialAssertionResponse { if car == nil { return nil } return &CredentialAssertionResponse{ PublicKeyCredential: PublicKeyCredential{ Credential: Credential{ ID: base64.RawURLEncoding.EncodeToString(car.RawId), Type: car.Type, }, RawID: car.RawId, Extensions: outputExtensionsFromProto(car.Extensions), }, AssertionResponse: authenticatorAssertionResponseFromProto(car.Response), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CredentialAssertionResponseToProto(car *CredentialAssertionResponse) *wantypes.CredentialAssertionResponse {\n\tif car == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialAssertionResponse{\n\t\tType: car.Type,\n\t\tRawId: car.RawID,\n\t\tResponse: &wantypes.AuthenticatorAssertionResponse{\n\t\t\tClientDataJson: car.AssertionResponse.ClientDataJSON,\n\t\t\tAuthenticatorData: car.AssertionResponse.AuthenticatorData,\n\t\t\tSignature: car.AssertionResponse.Signature,\n\t\t\tUserHandle: car.AssertionResponse.UserHandle,\n\t\t},\n\t\tExtensions: outputExtensionsToProto(car.Extensions),\n\t}\n}", "func CredentialAssertionFromProto(assertion *wantypes.CredentialAssertion) *CredentialAssertion {\n\tif assertion == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialAssertion{\n\t\tResponse: publicKeyCredentialRequestOptionsFromProto(assertion.PublicKey),\n\t}\n}", "func CredentialCreationResponseFromProto(ccr *wantypes.CredentialCreationResponse) *CredentialCreationResponse {\n\tif ccr == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialCreationResponse{\n\t\tPublicKeyCredential: PublicKeyCredential{\n\t\t\tCredential: Credential{\n\t\t\t\tID: base64.RawURLEncoding.EncodeToString(ccr.RawId),\n\t\t\t\tType: ccr.Type,\n\t\t\t},\n\t\t\tRawID: ccr.RawId,\n\t\t\tExtensions: outputExtensionsFromProto(ccr.Extensions),\n\t\t},\n\t\tAttestationResponse: authenticatorAttestationResponseFromProto(ccr.Response),\n\t}\n}", "func CredentialAssertionToProto(assertion *CredentialAssertion) *wantypes.CredentialAssertion {\n\tif assertion == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialAssertion{\n\t\tPublicKey: &wantypes.PublicKeyCredentialRequestOptions{\n\t\t\tChallenge: assertion.Response.Challenge,\n\t\t\tTimeoutMs: int64(assertion.Response.Timeout),\n\t\t\tRpId: assertion.Response.RelyingPartyID,\n\t\t\tAllowCredentials: credentialDescriptorsToProto(assertion.Response.AllowedCredentials),\n\t\t\tExtensions: inputExtensionsToProto(assertion.Response.Extensions),\n\t\t\tUserVerification: string(assertion.Response.UserVerification),\n\t\t},\n\t}\n}", "func CredentialCreationResponseToProto(ccr *CredentialCreationResponse) *wantypes.CredentialCreationResponse {\n\tif ccr == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialCreationResponse{\n\t\tType: ccr.Type,\n\t\tRawId: ccr.RawID,\n\t\tResponse: &wantypes.AuthenticatorAttestationResponse{\n\t\t\tClientDataJson: ccr.AttestationResponse.ClientDataJSON,\n\t\t\tAttestationObject: ccr.AttestationResponse.AttestationObject,\n\t\t},\n\t\tExtensions: outputExtensionsToProto(ccr.Extensions),\n\t}\n}", "func CredentialAssertionFromProtocol(a *protocol.CredentialAssertion) *CredentialAssertion {\n\tif a == nil {\n\t\treturn nil\n\t}\n\n\treturn &CredentialAssertion{\n\t\tResponse: PublicKeyCredentialRequestOptions{\n\t\t\tChallenge: Challenge(a.Response.Challenge),\n\t\t\tTimeout: a.Response.Timeout,\n\t\t\tRelyingPartyID: a.Response.RelyingPartyID,\n\t\t\tAllowedCredentials: credentialDescriptorsFromProtocol(a.Response.AllowedCredentials),\n\t\t\tUserVerification: a.Response.UserVerification,\n\t\t\tExtensions: a.Response.Extensions,\n\t\t},\n\t}\n}", "func NewProtoLoginResponse(result string) *chatterpb.LoginResponse {\n\tmessage := &chatterpb.LoginResponse{}\n\tmessage.Field = result\n\treturn message\n}", "func CredentialCreationFromProto(cc *wantypes.CredentialCreation) *CredentialCreation {\n\tif cc == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialCreation{\n\t\tResponse: publicKeyCredentialCreationOptionsFromProto(cc.PublicKey),\n\t}\n}", "func NewAuthenticationMetadataFromProto(message *auth_pb.AuthenticationMetadata) (*AuthenticationMetadata, error) {\n\t// Create raw value, which stores the contents of the Protobuf\n\t// message as an object normally returned by json.Unmarshal().\n\t// This can be used to do JMESPath matching by the authorization\n\t// layer.\n\tmessageJSON, err := protojson.Marshal(message)\n\tif err != nil {\n\t\treturn nil, util.StatusWrapWithCode(err, codes.InvalidArgument, \"Cannot convert authentication metadata to JSON\")\n\t}\n\tvar raw map[string]any\n\tif err := json.Unmarshal(messageJSON, &raw); err != nil {\n\t\treturn nil, util.StatusWrapWithCode(err, codes.InvalidArgument, \"Cannot parse authentication metadata JSON\")\n\t}\n\n\ttracingAttributes, err := otel.NewKeyValueListFromProto(message.GetTracingAttributes(), \"auth.\")\n\tif err != nil {\n\t\treturn nil, util.StatusWrap(err, \"Cannot create tracing attributes\")\n\t}\n\n\tam := &AuthenticationMetadata{\n\t\traw: raw,\n\t\ttracingAttributes: tracingAttributes,\n\t}\n\tproto.Merge(&am.proto, message)\n\treturn am, nil\n}", "func decodeAuthResponse(_ context.Context, reply interface{}) (interface{}, error) {\n\tr, ok := reply.(*pb.AuthReply)\n\tif !ok {\n\t\te := errors.New(\"'AuthReply' Decoder is not impelemented\")\n\t\treturn endpoint1.AuthResponse{Err: e}, e\n\t}\n\treturn endpoint1.AuthResponse{Uuid: r.Uuid, NamespaceID: r.NamespaceID, Roles: r.Roles}, nil\n}", "func NewProtoSubscribeResponse(result *chatter.Event) *chatterpb.SubscribeResponse {\n\tmessage := &chatterpb.SubscribeResponse{\n\t\tMessage_: result.Message,\n\t\tAction: result.Action,\n\t\tAddedAt: result.AddedAt,\n\t}\n\treturn message\n}", "func CredentialCreationToProto(cc *CredentialCreation) *wantypes.CredentialCreation {\n\tif cc == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialCreation{\n\t\tPublicKey: &wantypes.PublicKeyCredentialCreationOptions{\n\t\t\tChallenge: cc.Response.Challenge,\n\t\t\tRp: rpEntityToProto(cc.Response.RelyingParty),\n\t\t\tUser: userEntityToProto(cc.Response.User),\n\t\t\tCredentialParameters: credentialParametersToProto(cc.Response.Parameters),\n\t\t\tTimeoutMs: int64(cc.Response.Timeout),\n\t\t\tExcludeCredentials: credentialDescriptorsToProto(cc.Response.CredentialExcludeList),\n\t\t\tAttestation: string(cc.Response.Attestation),\n\t\t\tExtensions: inputExtensionsToProto(cc.Response.Extensions),\n\t\t\tAuthenticatorSelection: authenticatorSelectionToProto(cc.Response.AuthenticatorSelection),\n\t\t},\n\t}\n}", "func (e *execPlugin) decodeResponse(data []byte) (*credentialproviderapi.CredentialProviderResponse, error) {\n\tobj, gvk, err := codecs.UniversalDecoder().Decode(data, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif gvk.Kind != \"CredentialProviderResponse\" {\n\t\treturn nil, fmt.Errorf(\"failed to decode CredentialProviderResponse, unexpected Kind: %q\", gvk.Kind)\n\t}\n\n\tif gvk.Group != credentialproviderapi.GroupName {\n\t\treturn nil, fmt.Errorf(\"failed to decode CredentialProviderResponse, unexpected Group: %s\", gvk.Group)\n\t}\n\n\tif internalResponse, ok := obj.(*credentialproviderapi.CredentialProviderResponse); ok {\n\t\treturn internalResponse, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"unable to convert %T to *CredentialProviderResponse\", obj)\n}", "func NewGetCredentialsResponseCredential() *GetCredentialsResponseCredential {\n\tthis := GetCredentialsResponseCredential{}\n\treturn &this\n}", "func DecodeBatchGRPCResponse(ctx context.Context, v interface{}, hdr, trlr metadata.MD) (interface{}, error) {\n\tmessage, ok := v.(*publicpb.BatchGRPCResponse)\n\tif !ok {\n\t\treturn nil, goagrpc.ErrInvalidType(\"public\", \"batchGRPC\", \"*publicpb.BatchGRPCResponse\", v)\n\t}\n\tres := NewBatchGRPCResult(message)\n\treturn res, nil\n}", "func decodeGRPCGenerateReportResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.GenerateReportResponse)\n\treturn generateReportResponse{Repository: reply.Repository, Err: str2err(reply.Err)}, nil\n}", "func decodeRolesResponse(_ context.Context, reply interface{}) (interface{}, error) {\n\tr, ok := reply.(*pb.RolesReply)\n\tif !ok {\n\t\te := errors.New(\"'Account' Decoder is not impelemented\")\n\t\treturn endpoint1.RolesResponse{E1: e}, e\n\t}\n\treturn endpoint1.RolesResponse{S0: r.Roles}, nil\n}", "func decodeGRPCTacResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.TacResponse)\n\treturn endpoints.TacResponse{Res: reply.Res}, nil\n}", "func decodeGRPCMathOpResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.MathOpReply)\n\treturn mathendpoint2.MathOpResponse{V: reply.V, Err: str2err(reply.Err)}, nil\n}", "func (in *CredentialProviderResponse) DeepCopy() *CredentialProviderResponse {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(CredentialProviderResponse)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func decodeGRPCEchoResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.EchoReply)\n\treturn endpoints.EchoResponse{Rs: reply.Rs}, nil\n}", "func NewProtoHistoryResponse(result *chatterviews.ChatSummaryView) *chatterpb.HistoryResponse {\n\tmessage := &chatterpb.HistoryResponse{\n\t\tMessage_: *result.Message,\n\t\tSentAt: *result.SentAt,\n\t}\n\tif result.Length != nil {\n\t\tlength := int32(*result.Length)\n\t\tmessage.Length = &length\n\t}\n\treturn message\n}", "func decodeSigninResponse(_ context.Context, reply interface{}) (interface{}, error) {\n\tr, found := reply.(*pb.SigninReply)\n\tif !found {\n\t\te := fmt.Errorf(\"pb CreateReply type assertion error\")\n\t\treturn &endpoint1.SigninResponse{\n\t\t\tE1: e,\n\t\t}, e\n\t}\n\treturn endpoint1.SigninResponse{S0: r.Token}, nil\n}", "func NewBatchGRPCResponse(result []*public.ResponsePayload) *publicpb.BatchGRPCResponse {\n\tmessage := &publicpb.BatchGRPCResponse{}\n\tmessage.Field = make([]*publicpb.ResponsePayload, len(result))\n\tfor i, val := range result {\n\t\tmessage.Field[i] = &publicpb.ResponsePayload{\n\t\t\tFirstField: val.FirstField,\n\t\t\tFourthField: val.FourthField,\n\t\t}\n\t}\n\treturn message\n}", "func NewProtoEchoerResponse(result string) *chatterpb.EchoerResponse {\n\tmessage := &chatterpb.EchoerResponse{}\n\tmessage.Field = result\n\treturn message\n}", "func NewProtoListenerResponse() *chatterpb.ListenerResponse {\n\tmessage := &chatterpb.ListenerResponse{}\n\treturn message\n}", "func decodeUserInfoResponse(_ context.Context, reply interface{}) (interface{}, error) {\n\tr, ok := reply.(*pb.UserInfoReply)\n\tif !ok {\n\t\te := errors.New(\"pb UserInfoReply type assertion error\")\n\t\treturn nil, e\n\t}\n\treturn endpoint1.UserInfoResponse{Roles: r.Roles, OrgName: r.OrgName}, nil\n}", "func DecodeChangePasswordResponse(ctx context.Context, v interface{}, hdr, trlr metadata.MD) (interface{}, error) {\n\tmessage, ok := v.(*user_methodpb.ChangePasswordResponse)\n\tif !ok {\n\t\treturn nil, goagrpc.ErrInvalidType(\"userMethod\", \"changePassword\", \"*user_methodpb.ChangePasswordResponse\", v)\n\t}\n\tres := NewChangePasswordResult(message)\n\treturn res, nil\n}", "func convertResponse(r *http.Response, resp interface{}) error {\n\tdefer r.Body.Close()\n\n\tbuf := new(bytes.Buffer)\n\tif _, err := buf.ReadFrom(r.Body); err != nil {\n\t\treturn err\n\t}\n\n\tif err := json.Unmarshal(buf.Bytes(), resp); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func DecodeGRPCExecuteResponse(_ context.Context, grpcResponse interface{}) (interface{}, error) {\n\tresponse := grpcResponse.(*containerPB.ExecuteResponse)\n\treturn &container.ExecuteResponse{\n\t\tError: getError(response.Error),\n\t\tResponse: response.Response,\n\t}, nil\n}", "func DecodeGRPCGetEnvResponse(_ context.Context, grpcResponse interface{}) (interface{}, error) {\n\tresponse := grpcResponse.(*containerPB.GetEnvResponse)\n\treturn &container.GetEnvResponse{\n\t\tValue: response.Value,\n\t\tError: getError(response.Error),\n\t}, nil\n}", "func DecodeLoginResponse(_ context.Context, r interface{}) (interface{}, error) {\n\tresp := r.(*pb.LoginResponse)\n\treturn LoginResponse{\n\t\tJwt: resp.Jwt,\n\t}, nil\n}", "func DecodeStreamedBatchGRPCResponse(ctx context.Context, v interface{}, hdr, trlr metadata.MD) (interface{}, error) {\n\treturn &StreamedBatchGRPCClientStream{\n\t\tstream: v.(publicpb.Public_StreamedBatchGRPCClient),\n\t}, nil\n}", "func DecodeLoginResponse(ctx context.Context, v interface{}, hdr, trlr metadata.MD) (interface{}, error) {\n\tmessage, ok := v.(*user_methodpb.LoginResponse)\n\tif !ok {\n\t\treturn nil, goagrpc.ErrInvalidType(\"userMethod\", \"login\", \"*user_methodpb.LoginResponse\", v)\n\t}\n\tres := NewLoginResult(message)\n\treturn res, nil\n}", "func parseIssuerResponse(pres *presentproof.Presentation,\n\tvdriReg vdrapi.Registry, docLoader ld.DocumentLoader) (*verifiable.Credential, error) {\n\tif len(pres.PresentationsAttach) == 0 {\n\t\treturn nil, fmt.Errorf(\"%w: expected at least 1 attachment but got 0\", errInvalidCredential)\n\t}\n\n\tattachment := pres.PresentationsAttach[0]\n\n\tvpBytes, err := attachment.Data.Fetch()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to fetch contents of attachment with id %s : %w\", attachment.ID, err)\n\t}\n\n\tvp, err := verifiable.ParsePresentation(\n\t\tvpBytes,\n\t\tverifiable.WithPresPublicKeyFetcher(verifiable.NewVDRKeyResolver(vdriReg).PublicKeyFetcher()),\n\t\tverifiable.WithPresJSONLDDocumentLoader(docLoader),\n\t)\n\tif err != nil {\n\t\treturn nil,\n\t\t\tfmt.Errorf(\"%w: failed to parse verifiable presentation %s: %s\", errInvalidCredential, vpBytes, err.Error())\n\t}\n\n\tif len(vp.Credentials()) != 1 {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"%w: expected one credential in the issuer's VP but got %d\", errInvalidCredential, len(vp.Credentials()))\n\t}\n\n\trawCred, err := vp.MarshalledCredentials()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal issuer's vp credentials: %w\", err)\n\t}\n\n\tdata, err := verifiable.ParseCredential(\n\t\trawCred[0],\n\t\tverifiable.WithPublicKeyFetcher(verifiable.NewVDRKeyResolver(vdriReg).PublicKeyFetcher()),\n\t\tverifiable.WithJSONLDDocumentLoader(docLoader),\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse issuer's credential: %w\", err)\n\t}\n\n\treturn data, nil\n}", "func unmarshalCredentialsResponseBodyToUserCredentials(v *CredentialsResponseBody) *user.Credentials {\n\tres := &user.Credentials{\n\t\tToken: *v.Token,\n\t\tExpiresIn: *v.ExpiresIn,\n\t}\n\n\treturn res\n}", "func (sp *ServiceProvider) AssertResponse(base64Res string) (*Assertion, error) {\n\t// Parse SAML response from base64 encoded payload\n\t//\n\tsamlResponseXML, err := base64.StdEncoding.DecodeString(base64Res)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to base64-decode SAML response\")\n\t}\n\tvar res *Response\n\tif err := xml.Unmarshal(samlResponseXML, &res); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to unmarshal XML document: %s\", string(samlResponseXML))\n\t}\n\n\t// Validate response\n\t//\n\t// Validate destination\n\t// Note: OneLogin triggers this error when the Recipient field\n\t// is left blank (or when not set to the correct ACS endpoint)\n\t// in the OneLogin SAML configuration page. OneLogin returns\n\t// Destination=\"{recipient}\" in the SAML reponse in this case.\n\tif res.Destination != sp.ACSURL {\n\t\treturn nil, errors.Errorf(\"Wrong ACS destination, expected %q, got %q\", sp.ACSURL, res.Destination)\n\t}\n\tif res.Status.StatusCode.Value != \"urn:oasis:names:tc:SAML:2.0:status:Success\" {\n\t\treturn nil, errors.Errorf(\"Unexpected status code: %v\", res.Status.StatusCode.Value)\n\t}\n\n\t// Validates if the assertion matches the ID set in the original SAML AuthnRequest\n\t//\n\t// This check should be performed first before validating the signature since it is a cheap way to discard invalid messages\n\t// TODO: Track request IDs and add option to set them back in the service provider\n\t// This code will always pass since the possible response IDs is hardcoded to have a single empty string element\n\t// expectedResponse := false\n\t// responseIDs := sp.possibleResponseIDs()\n\t// for i := range responseIDs {\n\t// \tif responseIDs[i] == assertion.Subject.SubjectConfirmation.SubjectConfirmationData.InResponseTo {\n\t// \t\texpectedResponse = true\n\t// \t}\n\t// }\n\t// if len(responseIDs) == 1 && responseIDs[0] == \"\" {\n\t// \texpectedResponse = true\n\t// }\n\n\t// if !expectedResponse && len(responseIDs) > 0 {\n\t// \treturn nil, errors.New(\"Unexpected assertion InResponseTo value\")\n\t// }\n\n\t// Save XML raw bytes so later we can reuse it to verify the signature\n\tplainText := samlResponseXML\n\n\t// All SAML Responses are required to have a signature\n\tvalidSignature := false\n\t// Validate response reference\n\t// Before validating the signature with xmlsec, first check if the reference ID is correct\n\t//\n\t// http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf section 5.3\n\tif res.Signature != nil {\n\t\tif err := verifySignatureReference(res.Signature, res.ID); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to validate response signature reference\")\n\t\t}\n\t\tif err := sp.verifySignature(plainText); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to verify message signature: %v\", string(plainText))\n\t\t}\n\t\tvalidSignature = true\n\t}\n\n\t// Check for encrypted assertions\n\t// http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf section 2.3.4\n\tassertion := res.Assertion\n\tif res.EncryptedAssertion != nil {\n\t\tkeyFile, err := sp.PrivkeyFile()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to get private key file\")\n\t\t}\n\n\t\tplainTextAssertion, err := xmlsec.Decrypt(res.EncryptedAssertion.EncryptedData, keyFile)\n\t\tif err != nil {\n\t\t\tif IsSecurityException(err, &sp.SecurityOpts) {\n\t\t\t\treturn nil, errors.Wrap(err, \"failed to decrypt assertion\")\n\t\t\t}\n\t\t}\n\n\t\tassertion = &Assertion{}\n\t\tif err := xml.Unmarshal(plainTextAssertion, assertion); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to unmarshal encrypted assertion: %v\", plainTextAssertion)\n\t\t}\n\n\t\t// Track plain text so later we can verify the signature with xmlsec\n\t\tplainText = plainTextAssertion\n\t}\n\n\tif assertion == nil {\n\t\treturn nil, errors.New(\"missing assertion element\")\n\t}\n\n\t// Validate assertion reference\n\t// Before validating the signature with xmlsec, first check if the reference ID is correct\n\t//\n\t// http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf section 5.3\n\tif assertion.Signature != nil {\n\t\tif err := verifySignatureReference(assertion.Signature, assertion.ID); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to validate assertion signature reference\")\n\t\t}\n\t\tif err := sp.verifySignature(plainText); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to verify message signature: %v\", string(plainText))\n\t\t}\n\t\tvalidSignature = true\n\t}\n\n\tif !validSignature {\n\t\treturn nil, errors.Errorf(\"missing assertion signature\")\n\t}\n\n\t// Validate issuer\n\t// Since assertion could be encrypted we need to wait before validating the issuer\n\t// Only validate issuer if the entityID is set in the IdP metadata\n\t// TODO: the spec lists the Issuer element of an Assertion as required, we shouldn't skip validation\n\tswitch {\n\tcase sp.IdPEntityID == \"\":\n\t\t// Skip issuer validationgit s\n\tcase assertion.Issuer == nil:\n\t\treturn nil, errors.New(`missing Assertion > Issuer`)\n\tcase assertion.Issuer.Value != sp.IdPEntityID:\n\t\treturn nil, errors.Errorf(\"failed to validate assertion issuer: expected %q but got %q\", sp.IdPEntityID, assertion.Issuer.Value)\n\t}\n\n\t// Validate recipient\n\tswitch {\n\tcase assertion.Subject == nil:\n\t\terr = errors.New(`missing Assertion > Subject`)\n\tcase assertion.Subject.SubjectConfirmation == nil:\n\t\terr = errors.New(`missing Assertion > Subject > SubjectConfirmation`)\n\tcase assertion.Subject.SubjectConfirmation.SubjectConfirmationData.Recipient != sp.ACSURL:\n\t\terr = errors.Errorf(\"failed to validate assertion recipient: expected %q but got %q\", sp.ACSURL, assertion.Subject.SubjectConfirmation.SubjectConfirmationData.Recipient)\n\t}\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"invalid assertion recipient\")\n\t}\n\n\t// Make sure we have Conditions\n\tif assertion.Conditions == nil {\n\t\treturn nil, errors.New(`missing Assertion > Conditions`)\n\t}\n\n\t// The NotBefore and NotOnOrAfter attributes specify time limits on the\n\t// validity of the assertion within the context of its profile(s) of use.\n\t// They do not guarantee that the statements in the assertion will be\n\t// correct or accurate throughout the validity period. The NotBefore\n\t// attribute specifies the time instant at which the validity interval\n\t// begins. The NotOnOrAfter attribute specifies the time instant at which\n\t// the validity interval has ended. If the value for either NotBefore or\n\t// NotOnOrAfter is omitted, then it is considered unspecified.\n\tnow := Now()\n\tvalidFrom := assertion.Conditions.NotBefore\n\tif !validFrom.IsZero() && validFrom.After(now.Add(ClockDriftTolerance)) {\n\t\treturn nil, errors.Errorf(\"Assertion conditions are not valid yet, got %v, current time is %v\", validFrom, now)\n\t}\n\tvalidUntil := assertion.Conditions.NotOnOrAfter\n\tif !validUntil.IsZero() && validUntil.Before(now.Add(-ClockDriftTolerance)) {\n\t\treturn nil, errors.Errorf(\"Assertion conditions already expired, got %v current time is %v, extra time is %v\", validUntil, now, now.Add(-ClockDriftTolerance))\n\t}\n\n\t// A time instant at which the subject can no longer be confirmed. The time\n\t// value is encoded in UTC, as described in Section 1.3.3.\n\t//\n\t// Note that the time period specified by the optional NotBefore and\n\t// NotOnOrAfter attributes, if present, SHOULD fall within the overall\n\t// assertion validity period as specified by the element's NotBefore and\n\t// NotOnOrAfter attributes. If both attributes are present, the value for\n\t// NotBefore MUST be less than (earlier than) the value for NotOnOrAfter.\n\tif validUntil := assertion.Subject.SubjectConfirmation.SubjectConfirmationData.NotOnOrAfter; validUntil.Before(now.Add(-ClockDriftTolerance)) {\n\t\terr := errors.Errorf(\"Assertion conditions already expired, got %v current time is %v\", validUntil, now)\n\t\treturn nil, errors.Wrap(err, \"Assertion conditions already expired\")\n\t}\n\n\t// TODO: reenable?\n\t// if assertion.Conditions != nil && assertion.Conditions.AudienceRestriction != nil {\n\t// if assertion.Conditions.AudienceRestriction.Audience.Value != sp.MetadataURL {\n\t// returnt.Errorf(\"Audience restriction mismatch, got %q, expected %q\", assertion.Conditions.AudienceRestriction.Audience.Value, sp.MetadataURL), errors.New(\"Audience restriction mismatch\")\n\t// }\n\t// }\n\n\treturn assertion, nil\n}", "func DecodeForgotPasswordResponse(ctx context.Context, v interface{}, hdr, trlr metadata.MD) (interface{}, error) {\n\tmessage, ok := v.(*user_methodpb.ForgotPasswordResponse)\n\tif !ok {\n\t\treturn nil, goagrpc.ErrInvalidType(\"userMethod\", \"forgotPassword\", \"*user_methodpb.ForgotPasswordResponse\", v)\n\t}\n\tres := NewForgotPasswordResult(message)\n\treturn res, nil\n}", "func buildResponseConvertData(response, result *expr.AttributeExpr, svcCtx *codegen.AttributeContext, hdrs, trlrs []*MetadataData, e *expr.GRPCEndpointExpr, sd *ServiceData, svr bool) *ConvertData {\n\tif !svr && (e.MethodExpr.IsStreaming() || isEmpty(e.MethodExpr.Result.Type)) {\n\t\treturn nil\n\t}\n\n\tvar (\n\t\tsvc = sd.Service\n\t)\n\n\tif svr {\n\t\t// server side\n\n\t\tvar data *InitData\n\t\t{\n\t\t\tdata = buildInitData(result, response, \"result\", \"message\", svcCtx, true, svr, false, sd)\n\t\t\tdata.Description = fmt.Sprintf(\"%s builds the gRPC response type from the result of the %q endpoint of the %q service.\", data.Name, e.Name(), svc.Name)\n\t\t}\n\t\treturn &ConvertData{\n\t\t\tSrcName: svcCtx.Scope.Name(result, svcCtx.Pkg(result), svcCtx.Pointer, svcCtx.UseDefault),\n\t\t\tSrcRef: svcCtx.Scope.Ref(result, svcCtx.Pkg(result)),\n\t\t\tTgtName: protoBufGoFullTypeName(response, sd.PkgName, sd.Scope),\n\t\t\tTgtRef: protoBufGoFullTypeRef(response, sd.PkgName, sd.Scope),\n\t\t\tInit: data,\n\t\t}\n\t}\n\n\t// client side\n\n\tvar data *InitData\n\t{\n\t\tdata = buildInitData(response, result, \"message\", \"result\", svcCtx, false, svr, false, sd)\n\t\tdata.Name = fmt.Sprintf(\"New%sResult\", codegen.Goify(e.Name(), true))\n\t\tdata.Description = fmt.Sprintf(\"%s builds the result type of the %q endpoint of the %q service from the gRPC response type.\", data.Name, e.Name(), svc.Name)\n\t\tfor _, m := range hdrs {\n\t\t\t// pass the headers as arguments to result constructor in client\n\t\t\tdata.Args = append(data.Args, &InitArgData{\n\t\t\t\tName: m.VarName,\n\t\t\t\tRef: m.VarName,\n\t\t\t\tFieldName: m.FieldName,\n\t\t\t\tFieldType: m.FieldType,\n\t\t\t\tTypeName: m.TypeName,\n\t\t\t\tTypeRef: m.TypeRef,\n\t\t\t\tType: m.Type,\n\t\t\t\tPointer: m.Pointer,\n\t\t\t\tRequired: m.Required,\n\t\t\t\tValidate: m.Validate,\n\t\t\t\tExample: m.Example,\n\t\t\t})\n\t\t}\n\t\tfor _, m := range trlrs {\n\t\t\t// pass the trailers as arguments to result constructor in client\n\t\t\tdata.Args = append(data.Args, &InitArgData{\n\t\t\t\tName: m.VarName,\n\t\t\t\tRef: m.VarName,\n\t\t\t\tFieldName: m.FieldName,\n\t\t\t\tFieldType: m.FieldType,\n\t\t\t\tTypeName: m.TypeName,\n\t\t\t\tTypeRef: m.TypeRef,\n\t\t\t\tType: m.Type,\n\t\t\t\tPointer: m.Pointer,\n\t\t\t\tRequired: m.Required,\n\t\t\t\tValidate: m.Validate,\n\t\t\t\tExample: m.Example,\n\t\t\t})\n\t\t}\n\t}\n\treturn &ConvertData{\n\t\tSrcName: protoBufGoFullTypeName(response, sd.PkgName, sd.Scope),\n\t\tSrcRef: protoBufGoFullTypeRef(response, sd.PkgName, sd.Scope),\n\t\tTgtName: svcCtx.Scope.Name(result, svcCtx.Pkg(result), svcCtx.Pointer, svcCtx.UseDefault),\n\t\tTgtRef: svcCtx.Scope.Ref(result, svcCtx.Pkg(result)),\n\t\tInit: data,\n\t\tValidation: addValidation(response, \"message\", sd, false),\n\t}\n}", "func decodeGRPCConcatResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.ConcatReply)\n\treturn endpoints.ConcatResponse{Rs: reply.Rs}, nil\n}", "func NewCredentialsResponseElement(name string, type_ string, description string, owner string, ownerAccessOnly bool, ) *CredentialsResponseElement {\n\tthis := CredentialsResponseElement{}\n\tthis.Name = name\n\tthis.Type = type_\n\tthis.Description = description\n\tthis.Owner = owner\n\tthis.OwnerAccessOnly = ownerAccessOnly\n\treturn &this\n}", "func unmarshalCredential(raw []byte) (*credential, error) {\n\tif len(raw) < 10 {\n\t\treturn nil, errors.New(\"tls: Delegated Credential is not valid: invalid length\")\n\t}\n\n\ts := cryptobyte.String(raw)\n\tvar t uint32\n\tif !s.ReadUint32(&t) {\n\t\treturn nil, errors.New(\"tls: Delegated Credential is not valid\")\n\t}\n\tvalidTime := time.Duration(t) * time.Second\n\n\tvar pubAlgo uint16\n\tif !s.ReadUint16(&pubAlgo) {\n\t\treturn nil, errors.New(\"tls: Delegated Credential is not valid\")\n\t}\n\talgo := SignatureScheme(pubAlgo)\n\n\tvar pubLen uint32\n\ts.ReadUint24(&pubLen)\n\n\tpubKey, err := x509.ParsePKIXPublicKey(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &credential{validTime, algo, pubKey}, nil\n}", "func DecodeGRPCInstancesResponse(_ context.Context, grpcResponse interface{}) (interface{}, error) {\n\tresponse := grpcResponse.(*containerPB.InstancesResponse)\n\treturn &container.InstancesResponse{\n\t\tContainers: pbContainersToContainers(response.Instances),\n\t}, nil\n}", "func DecodeGrpcRespLicenseSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func BytesToResponse(b []byte) Response {\n\tvar r Response\n\tdec := gob.NewDecoder(bytes.NewReader(b))\n\tdec.Decode(&r)\n\n\treturn r\n}", "func BytesToResponse(b []byte) Response {\n\tvar r Response\n\tdec := gob.NewDecoder(bytes.NewReader(b))\n\tdec.Decode(&r)\n\n\treturn r\n}", "func DecodeGrpcRespRDSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeActivateResponse(ctx context.Context, v interface{}, hdr, trlr metadata.MD) (interface{}, error) {\n\tmessage, ok := v.(*user_methodpb.ActivateResponse)\n\tif !ok {\n\t\treturn nil, goagrpc.ErrInvalidType(\"userMethod\", \"activate\", \"*user_methodpb.ActivateResponse\", v)\n\t}\n\tres := NewActivateResult(message)\n\treturn res, nil\n}", "func NewTimeBucketQueryResultsFromProto(\n\tpbRes *servicepb.TimeBucketQueryResults,\n) (*TimeBucketQueryResults, error) {\n\tif pbRes == nil {\n\t\treturn nil, errNilTimeBucketQueryResultsProto\n\t}\n\tbuckets := make([]TimeBucketQueryResult, 0, len(pbRes.Buckets))\n\tfor _, pbBucket := range pbRes.Buckets {\n\t\tbucket := TimeBucketQueryResult{\n\t\t\tStartAtNanos: pbBucket.StartAtNanos,\n\t\t\tValue: int(pbBucket.Value),\n\t\t}\n\t\tbuckets = append(buckets, bucket)\n\t}\n\treturn &TimeBucketQueryResults{\n\t\tGranularityNanos: pbRes.GranularityNanos,\n\t\tBuckets: buckets,\n\t}, nil\n}", "func ParseRotateSksCcmCredentialsResponse(rsp *http.Response) (*RotateSksCcmCredentialsResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &RotateSksCcmCredentialsResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 200:\n\t\tvar dest Operation\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON200 = &dest\n\n\t}\n\n\treturn response, nil\n}", "func ParseGetDomainAuthCodeResponse(rsp *http.Response) (*GetDomainAuthCodeResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &GetDomainAuthCodeResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 200:\n\t\tvar dest ScalewayDomainV2alpha2GetDomainAuthCodeResponse\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON200 = &dest\n\n\t}\n\n\treturn response, nil\n}", "func DecodeChangeEmailResponse(ctx context.Context, v interface{}, hdr, trlr metadata.MD) (interface{}, error) {\n\tmessage, ok := v.(*user_methodpb.ChangeEmailResponse)\n\tif !ok {\n\t\treturn nil, goagrpc.ErrInvalidType(\"userMethod\", \"changeEmail\", \"*user_methodpb.ChangeEmailResponse\", v)\n\t}\n\tres := NewChangeEmailResult(message)\n\treturn res, nil\n}", "func FromProto(req *metrov1.StreamingPullRequest) (*AcknowledgeRequest, *ModifyAckDeadlineRequest, error) {\n\tif len(req.ModifyDeadlineAckIds) != len(req.ModifyDeadlineSeconds) {\n\t\treturn nil, nil, fmt.Errorf(\"length of modify_deadline_ack_ids and modify_deadline_seconds not same\")\n\t}\n\tar := &AcknowledgeRequest{\n\t\treq.AckIds,\n\t}\n\tmr := &ModifyAckDeadlineRequest{\n\t\treq.ModifyDeadlineSeconds,\n\t\treq.ModifyDeadlineAckIds,\n\t}\n\treturn ar, mr, nil\n}", "func (c Client) decodeResponse(resp interface{}) error {\n\treturn c.Decoder.Decode(&resp)\n}", "func decodeGRPCSumResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.SumReply)\n\treturn endpoints.SumResponse{Rs: reply.Rs}, nil\n}", "func protoToStructure(output interface{}, result *proto.TorrentResponse, err error) error {\n if err != nil {\n return err\n }\n err = json.Unmarshal(result.Result, &output)\n if err != nil {\n return errors.UnmarshalError.ToError(err)\n }\n return nil\n}", "func DecodeGRPCGetLinksResponse(_ context.Context, grpcResponse interface{}) (interface{}, error) {\n\tresponse := grpcResponse.(*containerPB.GetLinksResponse)\n\n\tarrayMap := make(map[string][]string)\n\tfor k, v := range response.Links {\n\t\tarrayMap[k] = strings.Split(v, \",\")\n\t}\n\n\treturn &container.GetLinksResponse{\n\t\tError: getError(response.Error),\n\t\tLinks: arrayMap,\n\t}, nil\n}", "func DiscoveryResponseToV2(r *discoverypb.DiscoveryResponse) *xdspb2.DiscoveryResponse {\n\tb := proto.NewBuffer(nil)\n\tb.SetDeterministic(true)\n\terr := b.Marshal(r)\n\n\terr = err\n\tx := &xdspb2.DiscoveryResponse{}\n\tif err := proto.Unmarshal(b.Bytes(), x); err != nil {\n\t\tlog.Fatalln(\"Failed to parse DiscoveryResponse:\", err)\n\t}\n\n\tx.TypeUrl = v2edsURL\n\tfor i := range x.GetResources() {\n\t\tx.Resources[i].TypeUrl = v2edsURL\n\t}\n\tlog.Printf(\"RESPONSE TO V2 %v\", x)\n\n\treturn x\n}", "func protoDec(t reflect.Type, in []byte) (T, error) {\n\tvar p protoreflect.ProtoMessage\n\tswitch it := reflect.New(t.Elem()).Interface().(type) {\n\tcase protoreflect.ProtoMessage:\n\t\tp = it\n\tcase protov1.Message:\n\t\tp = protov1.MessageV2(it)\n\t}\n\terr := protov2.UnmarshalOptions{}.Unmarshal(in, p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn p, nil\n}", "func userToProto(u *domain.User) *protouser.Response {\n\treturn &protouser.Response{\n\t\tApplication: proto.String(string(u.App)),\n\t\tUid: proto.String(u.Uid),\n\t\tIds: idsToStrings(u.Ids),\n\t\tCreatedTimestamp: timeToProto(u.Created),\n\t\tRoles: u.Roles,\n\t\tPasswordChangeTimestamp: timeToProto(u.PasswordChange),\n\t\tAccountExpirationDate: proto.String(string(u.AccountExpirationDate)),\n\t}\n}", "func decodeGRPCTicResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\t_ = grpcReply.(*pb.TicResponse)\n\treturn endpoints.TicResponse{}, nil\n}", "func NewUnlockConnectorResponse(status UnlockStatus) *UnlockConnectorResponse {\n\treturn &UnlockConnectorResponse{Status: status}\n}", "func DecodeInitResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.InitResponse)\n\tinit := service.InitKeys{\n\t\tKeys: reply.Keys,\n\t\tKeysB64: reply.KeysBase64,\n\t\tRecoveryKeys: reply.RecoveryKeys,\n\t\tRecoveryKeysB64: reply.RecoveryKeysBase64,\n\t\tRootToken: reply.RootToken,\n\t}\n\treturn endpoints.InitResponse{Init: init, Err: service.String2Error(reply.Err)}, nil\n}", "func ResponseToStruct(res *http.Response, v interface{}) error {\n\tvar reader io.ReadCloser\n\tvar err error\n\tswitch res.Header.Get(\"Content-Encoding\") {\n\tcase gzipHeader:\n\t\treader, err = gzip.NewReader(res.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer reader.Close()\n\tcase deflateHeader:\n\t\treader = flate.NewReader(res.Body)\n\t\tdefer reader.Close()\n\tdefault:\n\t\treader = res.Body\n\t}\n\n\tdecoder := gojay.BorrowDecoder(reader)\n\tdefer decoder.Release()\n\n\terr = decoder.Decode(&v)\n\tif err != nil {\n\t\treturn json.NewDecoder(reader).Decode(v)\n\t}\n\n\treturn nil\n}", "func (*CancelTeamSubscriptionResponse) Descriptor() ([]byte, []int) {\n\treturn file_protos_participant_service_proto_rawDescGZIP(), []int{5}\n}", "func (st *Account) FromProto(acPb *accountpb.Account) {\n\tst.nonce = acPb.Nonce\n\tif _, ok := accountpb.AccountType_name[int32(acPb.Type.Number())]; !ok {\n\t\tpanic(\"unknown account type\")\n\t}\n\tst.accountType = int32(acPb.Type.Number())\n\tif acPb.Balance == \"\" {\n\t\tst.Balance = big.NewInt(0)\n\t} else {\n\t\tbalance, ok := new(big.Int).SetString(acPb.Balance, 10)\n\t\tif !ok {\n\t\t\tpanic(errors.Errorf(\"invalid balance %s\", acPb.Balance))\n\t\t}\n\t\tst.Balance = balance\n\t}\n\tcopy(st.Root[:], acPb.Root)\n\tst.CodeHash = nil\n\tif acPb.CodeHash != nil {\n\t\tst.CodeHash = make([]byte, len(acPb.CodeHash))\n\t\tcopy(st.CodeHash, acPb.CodeHash)\n\t}\n\tst.isCandidate = acPb.IsCandidate\n\tst.votingWeight = big.NewInt(0)\n\tif acPb.VotingWeight != nil {\n\t\tst.votingWeight.SetBytes(acPb.VotingWeight)\n\t}\n}", "func ProtoToCertificateTemplate(p *betapb.PrivatecaBetaCertificateTemplate) *beta.CertificateTemplate {\n\tobj := &beta.CertificateTemplate{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tPredefinedValues: ProtoToPrivatecaBetaCertificateTemplatePredefinedValues(p.GetPredefinedValues()),\n\t\tIdentityConstraints: ProtoToPrivatecaBetaCertificateTemplateIdentityConstraints(p.GetIdentityConstraints()),\n\t\tPassthroughExtensions: ProtoToPrivatecaBetaCertificateTemplatePassthroughExtensions(p.GetPassthroughExtensions()),\n\t\tDescription: dcl.StringOrNil(p.GetDescription()),\n\t\tCreateTime: dcl.StringOrNil(p.GetCreateTime()),\n\t\tUpdateTime: dcl.StringOrNil(p.GetUpdateTime()),\n\t\tProject: dcl.StringOrNil(p.GetProject()),\n\t\tLocation: dcl.StringOrNil(p.GetLocation()),\n\t}\n\treturn obj\n}", "func (sp *SAMLServiceProvider) ValidateEncodedResponse(encodedResponse string) (*etree.Element, error) {\n\traw, err := base64.StdEncoding.DecodeString(encodedResponse)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdoc := etree.NewDocument()\n\terr = doc.ReadFromBytes(raw)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse, err := sp.validationContext().Validate(doc.Root())\n\tif err != nil && !sp.SkipSignatureValidation || response == nil {\n\t\treturn nil, err\n\t}\n\n\terr = sp.Validate(response)\n\tif err == nil {\n\t\t//If there was no error, then return the response\n\t\treturn response, nil\n\t}\n\n\t//If an error aside from missing assertion, return it.\n\tif err != ErrMissingAssertion {\n\t\treturn nil, err\n\t}\n\n\t//If the error indicated a missing assertion, proceed to attempt decryption\n\t//of encrypted assertion.\n\tres, err := NewResponseFromReader(bytes.NewReader(raw))\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error getting response: %v\", err)\n\t}\n\n\t//This is the tls.Certificate we'll use to decrypt\n\tvar decryptCert tls.Certificate\n\n\tswitch crt := sp.SPKeyStore.(type) {\n\tcase dsig.TLSCertKeyStore:\n\t\t//Get the tls.Certificate directly if possible\n\t\tdecryptCert = tls.Certificate(crt)\n\tdefault:\n\t\t//Otherwise, construct one from the results of GetKeyPair\n\t\tpk, cert, err := sp.SPKeyStore.GetKeyPair()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error getting keypair: %v\", err)\n\t\t}\n\n\t\tdecryptCert = tls.Certificate{\n\t\t\tCertificate: [][]byte{cert},\n\t\t\tPrivateKey: pk,\n\t\t}\n\t}\n\n\t//Decrypt the xml contents of the assertion\n\tdocBytes, err := res.Decrypt(decryptCert)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error decrypting assertion: %v\", err)\n\t}\n\n\t//Read the assertion and return it\n\tresDoc := etree.NewDocument()\n\terr = resDoc.ReadFromBytes(docBytes)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error reading decrypted assertion: %v\", err)\n\t}\n\n\tel := etree.NewElement(\"DecryptedAssertion\")\n\tel.AddChild(resDoc.Root())\n\n\treturn el, nil\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 (c *CreatePDPContextResponse) DecodeFromBytes(b []byte) error {\n\tlog.Println(\"CreatePDPContextResponse.DecodeFromBytes is deprecated. use CreatePDPContextResponse.UnmarshalBinary instead\")\n\treturn c.UnmarshalBinary(b)\n}", "func decodeSignoutResponse(_ context.Context, reply interface{}) (interface{}, error) {\n\tr := reply.(*pb.SignoutReply)\n\tif r.Result {\n\t\treturn &endpoint1.SignoutResponse{E0: nil}, nil\n\t}\n\treturn nil, errors.New(\"'Account' Decoder is not impelemented\")\n}", "func NewResponseReverter(w dns.ResponseWriter, r *dns.Msg, listNames []string) *ResponseReverter {\n\treturn &ResponseReverter{\n\t\tResponseWriter: w,\n\t\toriginalQuestion: r.Question[0],\n\t\tlistNames: listNames,\n\t}\n}", "func NewContactResponse() *ContactResponse {\n\tthis := ContactResponse{}\n\treturn &this\n}", "func DecodeGRPCSetEnvResponse(_ context.Context, grpcResponse interface{}) (interface{}, error) {\n\tresponse := grpcResponse.(*containerPB.SetEnvResponse)\n\treturn &container.SetEnvResponse{\n\t\tError: getError(response.Error),\n\t}, nil\n}", "func NewResultFromResponse(response *abci.ResponseDeliverTx) ABCIResult {\r\n\treturn ABCIResult{\r\n\t\tCode: response.Code,\r\n\t\tData: response.Data,\r\n\t}\r\n}", "func ParseResponse(r io.Reader, maxSize int32) (*Response, error) {\n\tt, err := readResponseType(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar data []byte\n\tswitch t {\n\tcase Ok, Error:\n\t\tsize, err := readSize(r)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif size > uint32(maxSize) {\n\t\t\treturn nil, ErrTooLarge\n\t\t}\n\n\t\tdata = make([]byte, int(size))\n\t\tif _, err := io.ReadFull(r, data); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"proto: can't read response data: %s\", err)\n\t\t}\n\tdefault:\n\t\treturn nil, ErrInvalidResponse\n\t}\n\n\treturn &Response{Type: t, Data: data}, nil\n}", "func DecodeGRPCRemoveLinkResponse(_ context.Context, grpcResponse interface{}) (interface{}, error) {\n\tresponse := grpcResponse.(*containerPB.RemoveLinkResponse)\n\treturn &container.RemoveLinkResponse{\n\t\tError: getError(response.Error),\n\t}, nil\n}", "func (n *nativeImpl) GetAssertion(origin string, in *getAssertionRequest) (*wantypes.CredentialAssertionResponse, error) {\n\thwnd, err := getForegroundWindow()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tvar out *webauthnAssertion\n\tret, _, err := procWebAuthNAuthenticatorGetAssertion.Call(\n\t\tuintptr(hwnd),\n\t\tuintptr(unsafe.Pointer(in.rpID)),\n\t\tuintptr(unsafe.Pointer(in.clientData)),\n\t\tuintptr(unsafe.Pointer(in.opts)),\n\t\tuintptr(unsafe.Pointer(&out)),\n\t)\n\tif ret != 0 {\n\t\treturn nil, trace.Wrap(getErrorNameOrLastErr(ret, err))\n\t}\n\tif out == nil {\n\t\treturn nil, errors.New(\"unexpected nil response from GetAssertion\")\n\t}\n\n\t// Note that we need to copy bytes out of `out` if we want to free object.\n\t// That's why bytesFromCBytes is used.\n\t// We don't care about free error so ignore it explicitly.\n\tdefer func() { _ = freeAssertion(out) }()\n\n\tauthData := bytesFromCBytes(out.cbAuthenticatorData, out.pbAuthenticatorData)\n\tsignature := bytesFromCBytes(out.cbSignature, out.pbSignature)\n\tuserID := bytesFromCBytes(out.cbUserID, out.pbUserID)\n\tcredential := bytesFromCBytes(out.Credential.cbID, out.Credential.pbID)\n\tcredType := windows.UTF16PtrToString(out.Credential.pwszCredentialType)\n\n\treturn &wantypes.CredentialAssertionResponse{\n\t\tPublicKeyCredential: wantypes.PublicKeyCredential{\n\t\t\tRawID: credential,\n\t\t\tCredential: wantypes.Credential{\n\t\t\t\tID: base64.RawURLEncoding.EncodeToString(credential),\n\t\t\t\tType: credType,\n\t\t\t},\n\t\t},\n\t\tAssertionResponse: wantypes.AuthenticatorAssertionResponse{\n\t\t\tAuthenticatorData: authData,\n\t\t\tSignature: signature,\n\t\t\tUserHandle: userID,\n\t\t\tAuthenticatorResponse: wantypes.AuthenticatorResponse{\n\t\t\t\tClientDataJSON: in.jsonEncodedClientData,\n\t\t\t},\n\t\t},\n\t}, nil\n}", "func ParseVerifyEndpointResponse(rsp *http.Response) (*VerifyEndpointResponse, error) {\n\tbodyBytes, err := io.ReadAll(rsp.Body)\n\tdefer func() { _ = rsp.Body.Close() }()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &VerifyEndpointResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\treturn response, nil\n}", "func decodeGRPCNameResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.NameReply)\n\treturn loginendpoint.LoginResponse{V: string(reply.V), Err: str2err(reply.Err)}, nil\n}", "func EncodeGRPCChangePasswordResponse(_ context.Context, r interface{}) (interface{}, error) {\n\tresp := r.(changePasswordResponse)\n\treturn &pb.ChangePasswordResponse{\n\t\tSuccess: resp.Success,\n\t\tErr: resp.Err,\n\t}, nil\n}", "func NewStreamedBatchGRPCResponse(result *public.ResponsePayload) *publicpb.StreamedBatchGRPCResponse {\n\tmessage := &publicpb.StreamedBatchGRPCResponse{\n\t\tFirstField: result.FirstField,\n\t\tFourthField: result.FourthField,\n\t}\n\treturn message\n}", "func (x *CMsgGCToClientPrivateChatResponse_Result) UnmarshalJSON(b []byte) error {\n\tnum, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*x = CMsgGCToClientPrivateChatResponse_Result(num)\n\treturn nil\n}", "func UnmarshalSharedDatasetResponse(m map[string]json.RawMessage, result interface{}) (err error) {\n\tobj := new(SharedDatasetResponse)\n\terr = core.UnmarshalPrimitive(m, \"account\", &obj.Account)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"created_at\", &obj.CreatedAt)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"created_by\", &obj.CreatedBy)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"description\", &obj.Description)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"effected_workspace_ids\", &obj.EffectedWorkspaceIds)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"resource_group\", &obj.ResourceGroup)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalModel(m, \"shared_dataset_data\", &obj.SharedDatasetData, UnmarshalSharedDatasetData)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"shared_dataset_id\", &obj.SharedDatasetID)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"shared_dataset_name\", &obj.SharedDatasetName)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"shared_dataset_type\", &obj.SharedDatasetType)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"state\", &obj.State)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"tags\", &obj.Tags)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"updated_at\", &obj.UpdatedAt)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"updated_by\", &obj.UpdatedBy)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"version\", &obj.Version)\n\tif err != nil {\n\t\treturn\n\t}\n\treflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj))\n\treturn\n}", "func EncodeGRPCLogoutResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(*pb.LogoutResponse)\n\treturn resp, nil\n}", "func encodeVerifyResponse(_ context.Context, r interface{}) (interface{}, error) {\n\trs := r.(endpoint.VerifyResponse)\n\n\tif rs.Err != nil {\n\t\treturn &pb.VerifyReply{}, fmt.Errorf(\"Error: %s \", rs.Err.Error())\n\t}\n\n\tpermissions := make([]*pb.Permission, len(rs.Response.Role.Permissions))\n\tfor _, v := range rs.Response.Role.Permissions {\n\t\tpermissions = append(permissions, &pb.Permission{Name: v.Name})\n\t}\n\n\treturn &pb.VerifyReply{\n\t\tUsername: rs.Response.Username,\n\t\tName: rs.Response.Name,\n\t\tLastName: rs.Response.LastName,\n\t\tPhone: rs.Response.Phone,\n\t\tEmail: rs.Response.Email,\n\t\tToken: rs.Response.Token,\n\t\tRole: &pb.Role{\n\t\t\tName: rs.Response.Role.Name,\n\t\t\tPermissions: permissions,\n\t\t},\n\t}, nil\n}", "func NewGetCredentialsResponseCredentialWithDefaults() *GetCredentialsResponseCredential {\n\tthis := GetCredentialsResponseCredential{}\n\treturn &this\n}", "func ProtoToDeidentifyTemplate(p *betapb.DlpBetaDeidentifyTemplate) *beta.DeidentifyTemplate {\n\tobj := &beta.DeidentifyTemplate{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tDisplayName: dcl.StringOrNil(p.GetDisplayName()),\n\t\tDescription: dcl.StringOrNil(p.GetDescription()),\n\t\tCreateTime: dcl.StringOrNil(p.GetCreateTime()),\n\t\tUpdateTime: dcl.StringOrNil(p.GetUpdateTime()),\n\t\tDeidentifyConfig: ProtoToDlpBetaDeidentifyTemplateDeidentifyConfig(p.GetDeidentifyConfig()),\n\t\tLocationId: dcl.StringOrNil(p.GetLocationId()),\n\t\tParent: dcl.StringOrNil(p.GetParent()),\n\t\tLocation: dcl.StringOrNil(p.GetLocation()),\n\t}\n\treturn obj\n}", "func (r Resource) credentialToSecret(cred credential, response *restful.Response) *corev1.Secret {\n\t// Create new secret struct\n\tsecret := corev1.Secret{}\n\tsecret.Type = corev1.SecretTypeOpaque\n\tsecret.ObjectMeta.Namespace = r.Defaults.Namespace\n\tsecret.ObjectMeta.Name = cred.Name\n\tsecret.Data = make(map[string][]byte)\n\tsecret.Data[\"accessToken\"] = []byte(cred.AccessToken)\n\tif cred.SecretToken != \"\" {\n\t\tsecret.Data[\"secretToken\"] = []byte(cred.SecretToken)\n\t} else {\n\t\tsecret.Data[\"secretToken\"] = getRandomSecretToken()\n\t}\n\treturn &secret\n}", "func protoToEndpointAuth(prep *protoep.Endpoint) []*domain.EndpointAuth {\n\tret := make([]*domain.EndpointAuth, 0)\n\n\tfor _, grant := range prep.GetGranted() {\n\t\tret = append(ret, &domain.EndpointAuth{\n\t\t\tServiceName: prep.GetService(),\n\t\t\tEndpointName: prep.GetEndpoint(),\n\t\t\tAllowedService: grant.GetName(),\n\t\t\tRole: grant.GetRole(),\n\t\t})\n\t}\n\n\treturn ret\n}", "func DecodeGrpcRespBGPAuthStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func UnmarshalVersionResponse(m map[string]json.RawMessage, result interface{}) (err error) {\n\tobj := new(VersionResponse)\n\terr = core.UnmarshalPrimitive(m, \"builddate\", &obj.Builddate)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"buildno\", &obj.Buildno)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"commitsha\", &obj.Commitsha)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"helm_provider_version\", &obj.HelmProviderVersion)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"helm_version\", &obj.HelmVersion)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"supported_template_types\", &obj.SupportedTemplateTypes)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"terraform_provider_version\", &obj.TerraformProviderVersion)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"terraform_version\", &obj.TerraformVersion)\n\tif err != nil {\n\t\treturn\n\t}\n\treflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj))\n\treturn\n}", "func decodeResponse(r io.Reader, reply interface{}) error {\n\tvar c response\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(r)\n\tif err := json.Unmarshal(buf.Bytes(), &c); err != nil {\n\t\treturn fmt.Errorf(\"cannot decode response body = %s, err = %v\", buf.String(), err)\n\t}\n\tif c.Error != nil {\n\t\treturn &errObj{Data: c.Error}\n\t}\n\tif c.Result == nil {\n\t\treturn ErrNullResult\n\t}\n\treturn json.Unmarshal(*c.Result, reply)\n}", "func DecodeGrpcRespDSCProfileSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func FromDescribeClusterResponse(t *types.DescribeClusterResponse) *admin.DescribeClusterResponse {\n\tif t == nil {\n\t\treturn nil\n\t}\n\treturn &admin.DescribeClusterResponse{\n\t\tSupportedClientVersions: FromSupportedClientVersions(t.SupportedClientVersions),\n\t\tMembershipInfo: FromMembershipInfo(t.MembershipInfo),\n\t\tPersistenceInfo: FromPersistenceInfoMap(t.PersistenceInfo),\n\t}\n}", "func UnmarshalCreateAccountResponse(m map[string]json.RawMessage, result interface{}) (err error) {\n\tobj := new(CreateAccountResponse)\n\terr = core.UnmarshalPrimitive(m, \"account_id\", &obj.AccountID)\n\tif err != nil {\n\t\treturn\n\t}\n\treflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj))\n\treturn\n}", "func (*IssueCredentialResponse) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{12}\n}", "func UnmarshalListAccountsResponse(m map[string]json.RawMessage, result interface{}) (err error) {\n\tobj := new(ListAccountsResponse)\n\terr = core.UnmarshalPrimitive(m, \"rows_count\", &obj.RowsCount)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"next_url\", &obj.NextURL)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalModel(m, \"resources\", &obj.Resources, UnmarshalAccount)\n\tif err != nil {\n\t\treturn\n\t}\n\treflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj))\n\treturn\n}", "func (res *pbResponse) Unmarshal(data []byte) error {\n\tvar length = uint64(len(data))\n\tvar offset uint64\n\tvar n uint64\n\tvar tag uint64\n\tvar fieldNumber int\n\tvar wireType uint8\n\tfor {\n\t\tif offset < length {\n\t\t\ttag = uint64(data[offset])\n\t\t\toffset++\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t\tfieldNumber = int(tag >> 3)\n\t\twireType = uint8(tag & 0x7)\n\t\tswitch fieldNumber {\n\t\tcase 1:\n\t\t\tif wireType != 0 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Seq\", wireType)\n\t\t\t}\n\t\t\tn = code.DecodeVarint(data[offset:], &res.Seq)\n\t\t\toffset += n\n\t\tcase 2:\n\t\t\tif wireType != 2 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Error\", wireType)\n\t\t\t}\n\t\t\tn = code.DecodeString(data[offset:], &res.Error)\n\t\t\toffset += n\n\t\tcase 3:\n\t\t\tif wireType != 2 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Reply\", wireType)\n\t\t\t}\n\t\t\tn = code.DecodeBytes(data[offset:], &res.Reply)\n\t\t\toffset += n\n\t\t}\n\t}\n\treturn nil\n}", "func DecodeGrpcRespLicenseStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}" ]
[ "0.76067215", "0.75107986", "0.7340281", "0.6968172", "0.6617178", "0.6093907", "0.58568245", "0.5712558", "0.5702413", "0.56552935", "0.5585264", "0.5423334", "0.5421431", "0.5325256", "0.5320269", "0.5177555", "0.5125212", "0.5091248", "0.50174576", "0.5015089", "0.49780425", "0.49571192", "0.49396834", "0.48949695", "0.48935968", "0.48887995", "0.484191", "0.48266068", "0.48129073", "0.48119205", "0.4791778", "0.479118", "0.47815144", "0.47722045", "0.47653025", "0.4761048", "0.47475606", "0.47465926", "0.47428954", "0.47416702", "0.47213253", "0.47101682", "0.47099325", "0.46873018", "0.4685852", "0.4685852", "0.46779007", "0.46757212", "0.46753457", "0.4674338", "0.46733305", "0.46479696", "0.46475637", "0.46416697", "0.46376964", "0.46363", "0.46308765", "0.46301106", "0.46276313", "0.46199733", "0.46165648", "0.46067455", "0.46029443", "0.45993584", "0.45984524", "0.4565923", "0.4560593", "0.4553886", "0.45494226", "0.45481312", "0.45475146", "0.45461297", "0.454249", "0.45249355", "0.45223483", "0.45204648", "0.45202956", "0.4518038", "0.45082846", "0.4506659", "0.45014188", "0.4492427", "0.44883442", "0.44709", "0.44706762", "0.4467359", "0.44619244", "0.44596592", "0.44545272", "0.4450302", "0.44496152", "0.4447838", "0.44448414", "0.4440392", "0.44387406", "0.44289595", "0.4415506", "0.44120336", "0.4408447", "0.44017145" ]
0.8518914
0
CredentialCreationFromProto converts a CredentialCreation proto to its lib counterpart.
func CredentialCreationFromProto(cc *wantypes.CredentialCreation) *CredentialCreation { if cc == nil { return nil } return &CredentialCreation{ Response: publicKeyCredentialCreationOptionsFromProto(cc.PublicKey), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CredentialCreationResponseFromProto(ccr *wantypes.CredentialCreationResponse) *CredentialCreationResponse {\n\tif ccr == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialCreationResponse{\n\t\tPublicKeyCredential: PublicKeyCredential{\n\t\t\tCredential: Credential{\n\t\t\t\tID: base64.RawURLEncoding.EncodeToString(ccr.RawId),\n\t\t\t\tType: ccr.Type,\n\t\t\t},\n\t\t\tRawID: ccr.RawId,\n\t\t\tExtensions: outputExtensionsFromProto(ccr.Extensions),\n\t\t},\n\t\tAttestationResponse: authenticatorAttestationResponseFromProto(ccr.Response),\n\t}\n}", "func CredentialCreationToProto(cc *CredentialCreation) *wantypes.CredentialCreation {\n\tif cc == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialCreation{\n\t\tPublicKey: &wantypes.PublicKeyCredentialCreationOptions{\n\t\t\tChallenge: cc.Response.Challenge,\n\t\t\tRp: rpEntityToProto(cc.Response.RelyingParty),\n\t\t\tUser: userEntityToProto(cc.Response.User),\n\t\t\tCredentialParameters: credentialParametersToProto(cc.Response.Parameters),\n\t\t\tTimeoutMs: int64(cc.Response.Timeout),\n\t\t\tExcludeCredentials: credentialDescriptorsToProto(cc.Response.CredentialExcludeList),\n\t\t\tAttestation: string(cc.Response.Attestation),\n\t\t\tExtensions: inputExtensionsToProto(cc.Response.Extensions),\n\t\t\tAuthenticatorSelection: authenticatorSelectionToProto(cc.Response.AuthenticatorSelection),\n\t\t},\n\t}\n}", "func CredentialAssertionFromProto(assertion *wantypes.CredentialAssertion) *CredentialAssertion {\n\tif assertion == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialAssertion{\n\t\tResponse: publicKeyCredentialRequestOptionsFromProto(assertion.PublicKey),\n\t}\n}", "func NewAuthenticationMetadataFromProto(message *auth_pb.AuthenticationMetadata) (*AuthenticationMetadata, error) {\n\t// Create raw value, which stores the contents of the Protobuf\n\t// message as an object normally returned by json.Unmarshal().\n\t// This can be used to do JMESPath matching by the authorization\n\t// layer.\n\tmessageJSON, err := protojson.Marshal(message)\n\tif err != nil {\n\t\treturn nil, util.StatusWrapWithCode(err, codes.InvalidArgument, \"Cannot convert authentication metadata to JSON\")\n\t}\n\tvar raw map[string]any\n\tif err := json.Unmarshal(messageJSON, &raw); err != nil {\n\t\treturn nil, util.StatusWrapWithCode(err, codes.InvalidArgument, \"Cannot parse authentication metadata JSON\")\n\t}\n\n\ttracingAttributes, err := otel.NewKeyValueListFromProto(message.GetTracingAttributes(), \"auth.\")\n\tif err != nil {\n\t\treturn nil, util.StatusWrap(err, \"Cannot create tracing attributes\")\n\t}\n\n\tam := &AuthenticationMetadata{\n\t\traw: raw,\n\t\ttracingAttributes: tracingAttributes,\n\t}\n\tproto.Merge(&am.proto, message)\n\treturn am, nil\n}", "func CredentialCreationFromProtocol(cc *protocol.CredentialCreation) *CredentialCreation {\n\tif cc == nil {\n\t\treturn nil\n\t}\n\n\t// Based on our configuration we should always get a protocol.URLEncodedBase64\n\t// user ID, but the go-webauthn/webauthn is capable of generating strings too.\n\tvar userID []byte\n\tif id := cc.Response.User.ID; id != nil {\n\t\tswitch uid := id.(type) {\n\t\tcase protocol.URLEncodedBase64:\n\t\t\tuserID = uid\n\t\tcase string:\n\t\t\tuserID = []byte(uid)\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"Unexpected WebAuthn cc.Response.User.ID type: %T\", id))\n\t\t}\n\t}\n\n\treturn &CredentialCreation{\n\t\tResponse: PublicKeyCredentialCreationOptions{\n\t\t\tChallenge: Challenge(cc.Response.Challenge),\n\t\t\tRelyingParty: RelyingPartyEntity{\n\t\t\t\tCredentialEntity: cc.Response.RelyingParty.CredentialEntity,\n\t\t\t\tID: cc.Response.RelyingParty.ID,\n\t\t\t},\n\t\t\tUser: UserEntity{\n\t\t\t\tCredentialEntity: cc.Response.User.CredentialEntity,\n\t\t\t\tDisplayName: cc.Response.User.Name,\n\t\t\t\tID: userID,\n\t\t\t},\n\t\t\tParameters: credentialParametersFromProtocol(cc.Response.Parameters),\n\t\t\tAuthenticatorSelection: AuthenticatorSelection{\n\t\t\t\tAuthenticatorAttachment: cc.Response.AuthenticatorSelection.AuthenticatorAttachment,\n\t\t\t\tRequireResidentKey: cc.Response.AuthenticatorSelection.RequireResidentKey,\n\t\t\t\tResidentKey: cc.Response.AuthenticatorSelection.ResidentKey,\n\t\t\t\tUserVerification: cc.Response.AuthenticatorSelection.UserVerification,\n\t\t\t},\n\t\t\tTimeout: cc.Response.Timeout,\n\t\t\tCredentialExcludeList: credentialDescriptorsFromProtocol(cc.Response.CredentialExcludeList),\n\t\t\tExtensions: cc.Response.Extensions,\n\t\t\tAttestation: cc.Response.Attestation,\n\t\t},\n\t}\n}", "func CredentialCreationResponseToProto(ccr *CredentialCreationResponse) *wantypes.CredentialCreationResponse {\n\tif ccr == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialCreationResponse{\n\t\tType: ccr.Type,\n\t\tRawId: ccr.RawID,\n\t\tResponse: &wantypes.AuthenticatorAttestationResponse{\n\t\t\tClientDataJson: ccr.AttestationResponse.ClientDataJSON,\n\t\t\tAttestationObject: ccr.AttestationResponse.AttestationObject,\n\t\t},\n\t\tExtensions: outputExtensionsToProto(ccr.Extensions),\n\t}\n}", "func MustNewAuthenticationMetadataFromProto(message *auth_pb.AuthenticationMetadata) *AuthenticationMetadata {\n\tauthenticationMetadata, err := NewAuthenticationMetadataFromProto(message)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn authenticationMetadata\n}", "func FromProto(msg proto.Message) (*repb.Digest, error) {\n\tblob, err := proto.Marshal(msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn FromBlob(blob), nil\n}", "func CredentialAssertionResponseFromProto(car *wantypes.CredentialAssertionResponse) *CredentialAssertionResponse {\n\tif car == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialAssertionResponse{\n\t\tPublicKeyCredential: PublicKeyCredential{\n\t\t\tCredential: Credential{\n\t\t\t\tID: base64.RawURLEncoding.EncodeToString(car.RawId),\n\t\t\t\tType: car.Type,\n\t\t\t},\n\t\t\tRawID: car.RawId,\n\t\t\tExtensions: outputExtensionsFromProto(car.Extensions),\n\t\t},\n\t\tAssertionResponse: authenticatorAssertionResponseFromProto(car.Response),\n\t}\n}", "func NewUserFromProto(user *accounts_proto.User) *User {\n\treturn &User{User: *user}\n}", "func FromProto(req *metrov1.StreamingPullRequest) (*AcknowledgeRequest, *ModifyAckDeadlineRequest, error) {\n\tif len(req.ModifyDeadlineAckIds) != len(req.ModifyDeadlineSeconds) {\n\t\treturn nil, nil, fmt.Errorf(\"length of modify_deadline_ack_ids and modify_deadline_seconds not same\")\n\t}\n\tar := &AcknowledgeRequest{\n\t\treq.AckIds,\n\t}\n\tmr := &ModifyAckDeadlineRequest{\n\t\treq.ModifyDeadlineSeconds,\n\t\treq.ModifyDeadlineAckIds,\n\t}\n\treturn ar, mr, nil\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 (st *Account) FromProto(acPb *accountpb.Account) {\n\tst.nonce = acPb.Nonce\n\tif _, ok := accountpb.AccountType_name[int32(acPb.Type.Number())]; !ok {\n\t\tpanic(\"unknown account type\")\n\t}\n\tst.accountType = int32(acPb.Type.Number())\n\tif acPb.Balance == \"\" {\n\t\tst.Balance = big.NewInt(0)\n\t} else {\n\t\tbalance, ok := new(big.Int).SetString(acPb.Balance, 10)\n\t\tif !ok {\n\t\t\tpanic(errors.Errorf(\"invalid balance %s\", acPb.Balance))\n\t\t}\n\t\tst.Balance = balance\n\t}\n\tcopy(st.Root[:], acPb.Root)\n\tst.CodeHash = nil\n\tif acPb.CodeHash != nil {\n\t\tst.CodeHash = make([]byte, len(acPb.CodeHash))\n\t\tcopy(st.CodeHash, acPb.CodeHash)\n\t}\n\tst.isCandidate = acPb.IsCandidate\n\tst.votingWeight = big.NewInt(0)\n\tif acPb.VotingWeight != nil {\n\t\tst.votingWeight.SetBytes(acPb.VotingWeight)\n\t}\n}", "func FromProto(msg proto.Message) (Transaction, error) {\n\ttx := msg.(*ledger.TransactionInput)\n\n\tvar da ptypes.DynamicAny\n\terr := ptypes.UnmarshalAny(tx.GetBody(), &da)\n\tif err != nil {\n\t\treturn Transaction{}, err\n\t}\n\n\treturn Transaction{\n\t\tContractID: executor.ContractID(tx.ContractID),\n\t\tAction: executor.Action(tx.Action),\n\t\tArg: da.Message,\n\t}, nil\n}", "func unmarshalCredential(raw []byte) (*credential, error) {\n\tif len(raw) < 10 {\n\t\treturn nil, errors.New(\"tls: Delegated Credential is not valid: invalid length\")\n\t}\n\n\ts := cryptobyte.String(raw)\n\tvar t uint32\n\tif !s.ReadUint32(&t) {\n\t\treturn nil, errors.New(\"tls: Delegated Credential is not valid\")\n\t}\n\tvalidTime := time.Duration(t) * time.Second\n\n\tvar pubAlgo uint16\n\tif !s.ReadUint16(&pubAlgo) {\n\t\treturn nil, errors.New(\"tls: Delegated Credential is not valid\")\n\t}\n\talgo := SignatureScheme(pubAlgo)\n\n\tvar pubLen uint32\n\ts.ReadUint24(&pubLen)\n\n\tpubKey, err := x509.ParsePKIXPublicKey(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &credential{validTime, algo, pubKey}, nil\n}", "func NewLeaseFromProto(a *poolrpc.Lease) *Lease {\n\tvar opHash chainhash.Hash\n\tcopy(opHash[:], a.ChannelPoint.Txid)\n\n\tchanPoint := fmt.Sprintf(\"%v:%d\", opHash, a.ChannelPoint.OutputIndex)\n\treturn &Lease{\n\t\tChannelPoint: chanPoint,\n\t\tChannelAmtSat: a.ChannelAmtSat,\n\t\tChannelDurationBlocks: a.ChannelDurationBlocks,\n\t\tChannelLeaseExpiry: a.ChannelLeaseExpiry,\n\t\tChannelRemoteNodeKey: hex.EncodeToString(a.ChannelRemoteNodeKey),\n\t\tChannelNodeTier: a.ChannelNodeTier.String(),\n\t\tPremiumSat: a.PremiumSat,\n\t\tClearingRatePrice: a.ClearingRatePrice,\n\t\tOrderFixedRate: a.OrderFixedRate,\n\t\tExecutionFeeSat: a.ExecutionFeeSat,\n\t\tChainFeeSat: a.ChainFeeSat,\n\t\tOrderNonce: hex.EncodeToString(a.OrderNonce),\n\t\tMatchedOrderNonce: hex.EncodeToString(a.MatchedOrderNonce),\n\t\tPurchased: a.Purchased,\n\t\tSelfChanBalance: a.SelfChanBalance,\n\t\tSidecarChannel: a.SidecarChannel,\n\t}\n}", "func (st *Account) FromProto(acPb *iproto.AccountPb) {\n\tst.Nonce = acPb.Nonce\n\tst.Balance = big.NewInt(0)\n\tif acPb.Balance != nil {\n\t\tst.Balance.SetBytes(acPb.Balance)\n\t}\n\tcopy(st.Root[:], acPb.Root)\n\tst.CodeHash = nil\n\tif acPb.CodeHash != nil {\n\t\tst.CodeHash = make([]byte, len(acPb.CodeHash))\n\t\tcopy(st.CodeHash, acPb.CodeHash)\n\t}\n\tst.IsCandidate = acPb.IsCandidate\n\tst.VotingWeight = big.NewInt(0)\n\tif acPb.VotingWeight != nil {\n\t\tst.VotingWeight.SetBytes(acPb.VotingWeight)\n\t}\n\tst.Votee = acPb.Votee\n}", "func CommitFromProto(cp *tmproto.Commit) (*Commit, error) {\n\tif cp == nil {\n\t\treturn nil, errors.New(\"nil Commit\")\n\t}\n\n\tvar (\n\t\tcommit = new(Commit)\n\t)\n\n\tbi, err := BlockIDFromProto(&cp.BlockID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsi, err := StateIDFromProto(&cp.StateID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcommit.QuorumHash = cp.QuorumHash\n\tcommit.ThresholdBlockSignature = cp.ThresholdBlockSignature\n\tcommit.ThresholdStateSignature = cp.ThresholdStateSignature\n\n\tcommit.Height = cp.Height\n\tcommit.Round = cp.Round\n\tcommit.BlockID = *bi\n\tcommit.StateID = *si\n\n\treturn commit, commit.ValidateBasic()\n}", "func CredentialAssertionToProto(assertion *CredentialAssertion) *wantypes.CredentialAssertion {\n\tif assertion == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialAssertion{\n\t\tPublicKey: &wantypes.PublicKeyCredentialRequestOptions{\n\t\t\tChallenge: assertion.Response.Challenge,\n\t\t\tTimeoutMs: int64(assertion.Response.Timeout),\n\t\t\tRpId: assertion.Response.RelyingPartyID,\n\t\t\tAllowCredentials: credentialDescriptorsToProto(assertion.Response.AllowedCredentials),\n\t\t\tExtensions: inputExtensionsToProto(assertion.Response.Extensions),\n\t\t\tUserVerification: string(assertion.Response.UserVerification),\n\t\t},\n\t}\n}", "func (vi *ValidatorInfo) FromProto(pb *pbtypes.ValidatorInfo) error {\n\tcopy(vi.AccountAddress[:], pb.AccountAddress)\n\tvi.ConsensusPubkey = pb.ConsensusPublicKey\n\tvi.ConsensusVotingPower = pb.ConsensusVotingPower\n\tvi.NetworkSigningPubkey = pb.NetworkSigningPublicKey\n\tvi.NetworkIdentityPubkey = pb.NetworkIdentityPublicKey\n\treturn nil\n}", "func FromProto(sandboxpb *types.Sandbox) Sandbox {\n\truntime := RuntimeOpts{\n\t\tName: sandboxpb.Runtime.Name,\n\t\tOptions: sandboxpb.Runtime.Options,\n\t}\n\n\textensions := make(map[string]typeurl.Any)\n\tfor k, v := range sandboxpb.Extensions {\n\t\tv := v\n\t\textensions[k] = v\n\t}\n\n\treturn Sandbox{\n\t\tID: sandboxpb.SandboxID,\n\t\tLabels: sandboxpb.Labels,\n\t\tRuntime: runtime,\n\t\tSpec: sandboxpb.Spec,\n\t\tCreatedAt: protobuf.FromTimestamp(sandboxpb.CreatedAt),\n\t\tUpdatedAt: protobuf.FromTimestamp(sandboxpb.UpdatedAt),\n\t\tExtensions: extensions,\n\t}\n}", "func CredentialAssertionFromProtocol(a *protocol.CredentialAssertion) *CredentialAssertion {\n\tif a == nil {\n\t\treturn nil\n\t}\n\n\treturn &CredentialAssertion{\n\t\tResponse: PublicKeyCredentialRequestOptions{\n\t\t\tChallenge: Challenge(a.Response.Challenge),\n\t\t\tTimeout: a.Response.Timeout,\n\t\t\tRelyingPartyID: a.Response.RelyingPartyID,\n\t\t\tAllowedCredentials: credentialDescriptorsFromProtocol(a.Response.AllowedCredentials),\n\t\t\tUserVerification: a.Response.UserVerification,\n\t\t\tExtensions: a.Response.Extensions,\n\t\t},\n\t}\n}", "func CommitFromProto(cp *tmproto.Commit) (*Commit, error) {\n\tif cp == nil {\n\t\treturn nil, errors.New(\"nil Commit\")\n\t}\n\n\tvar (\n\t\tcommit = new(Commit)\n\t)\n\n\tbi, err := BlockIDFromProto(&cp.BlockID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsigs := make([]CommitSig, len(cp.Signatures))\n\tfor i := range cp.Signatures {\n\t\tif err := sigs[i].FromProto(cp.Signatures[i]); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tcommit.Signatures = sigs\n\n\tcommit.Height = cp.Height\n\tcommit.Round = cp.Round\n\tcommit.BlockID = *bi\n\n\treturn commit, commit.ValidateBasic()\n}", "func (n *nativeImpl) MakeCredential(origin string, in *makeCredentialRequest) (*wantypes.CredentialCreationResponse, error) {\n\thwnd, err := getForegroundWindow()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tvar out *webauthnCredentialAttestation\n\tret, _, err := procWebAuthNAuthenticatorMakeCredential.Call(\n\t\tuintptr(hwnd),\n\t\tuintptr(unsafe.Pointer(in.rp)),\n\t\tuintptr(unsafe.Pointer(in.user)),\n\t\tuintptr(unsafe.Pointer(in.credParameters)),\n\t\tuintptr(unsafe.Pointer(in.clientData)),\n\t\tuintptr(unsafe.Pointer(in.opts)),\n\t\tuintptr(unsafe.Pointer(&out)),\n\t)\n\tif ret != 0 {\n\t\treturn nil, trace.Wrap(getErrorNameOrLastErr(ret, err))\n\t}\n\tif out == nil {\n\t\treturn nil, errors.New(\"unexpected nil response from MakeCredential\")\n\t}\n\n\t// Note that we need to copy bytes out of `out` if we want to free object.\n\t// That's why bytesFromCBytes is used.\n\t// We don't care about free error so ignore it explicitly.\n\tdefer func() { _ = freeCredentialAttestation(out) }()\n\n\tcredential := bytesFromCBytes(out.cbCredentialID, out.pbCredentialID)\n\n\treturn &wantypes.CredentialCreationResponse{\n\t\tPublicKeyCredential: wantypes.PublicKeyCredential{\n\t\t\tCredential: wantypes.Credential{\n\t\t\t\tID: base64.RawURLEncoding.EncodeToString(credential),\n\t\t\t\tType: string(protocol.PublicKeyCredentialType),\n\t\t\t},\n\t\t\tRawID: credential,\n\t\t},\n\t\tAttestationResponse: wantypes.AuthenticatorAttestationResponse{\n\t\t\tAuthenticatorResponse: wantypes.AuthenticatorResponse{\n\t\t\t\tClientDataJSON: in.jsonEncodedClientData,\n\t\t\t},\n\t\t\tAttestationObject: bytesFromCBytes(out.cbAttestationObject, out.pbAttestationObject),\n\t\t},\n\t}, nil\n}", "func fromJSONPb(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\tvar ctor starlark.Value\n\tvar text starlark.String\n\tif err := starlark.UnpackArgs(\"from_jsonpb\", args, kwargs, \"ctor\", &ctor, \"text\", &text); err != nil {\n\t\treturn nil, err\n\t}\n\n\tc, ok := ctor.(*messageCtor)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"from_jsonpb: got %s, expecting a proto message constructor\", ctor.Type())\n\t}\n\ttyp := c.typ\n\n\tprotoMsg := typ.NewProtoMessage().Interface().(proto.Message)\n\tu := jsonpb.Unmarshaler{AllowUnknownFields: true}\n\tif err := u.Unmarshal(strings.NewReader(text.GoString()), protoMsg); err != nil {\n\t\treturn nil, fmt.Errorf(\"from_jsonpb: %s\", err)\n\t}\n\n\tmsg := NewMessage(typ)\n\tif err := msg.FromProto(protoMsg); err != nil {\n\t\treturn nil, fmt.Errorf(\"from_jsonpb: %s\", err)\n\t}\n\treturn msg, nil\n}", "func (p *Pipeline) FromProto(pb pipelinepb.AppliedPipeline) error {\n\tnumOps := len(pb.Ops)\n\tif cap(p.Operations) >= numOps {\n\t\tp.Operations = p.Operations[:numOps]\n\t} else {\n\t\tp.Operations = make([]OpUnion, numOps)\n\t}\n\tfor i := 0; i < numOps; i++ {\n\t\tif err := p.Operations[i].FromProto(pb.Ops[i]); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (m *modeKinds) FromProto(proto *api.ModeKinds) error {\n\tif proto.UserPrefixes != nil {\n\t\tm.userPrefixes = make([][2]rune, len(proto.UserPrefixes))\n\t\tfor i, prefix := range proto.UserPrefixes {\n\t\t\tif len(prefix.Char) != 1 || len(prefix.Symbol) != 1 {\n\t\t\t\treturn errors.New(\"user_prefixes is an array of length 2 of 1 character strings\")\n\t\t\t}\n\n\t\t\tm.userPrefixes[i] = [2]rune{\n\t\t\t\trune(prefix.Symbol[0]),\n\t\t\t\trune(prefix.Char[0]),\n\t\t\t}\n\t\t}\n\t}\n\tif proto.ChannelModes != nil {\n\t\tm.channelModes = make(map[rune]int, len(proto.ChannelModes))\n\t\tfor k, v := range proto.ChannelModes {\n\t\t\tif len(k) != 1 {\n\t\t\t\treturn errors.New(\"channel_modes is a map of characters to integers\")\n\t\t\t}\n\t\t\tm.channelModes[rune(k[0])] = int(v)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (cs *CommitSig) FromProto(csp tmproto.CommitSig) error {\n\n\tcs.BlockIDFlag = BlockIDFlag(csp.BlockIdFlag)\n\tcs.ValidatorAddress = csp.ValidatorAddress\n\tcs.Timestamp = csp.Timestamp\n\tcs.Signature = csp.Signature\n\n\treturn cs.ValidateBasic()\n}", "func TestFromProto(msg proto.Message) *repb.Digest {\n\tblob, err := proto.Marshal(msg)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn FromBlob(blob)\n}", "func (op *RollupOp) FromProto(pb pipelinepb.AppliedRollupOp) error {\n\top.AggregationID.FromProto(pb.AggregationId)\n\top.ID = pb.Id\n\treturn nil\n}", "func NewFromGRPC(conn *grpc.ClientConn, log *zap.Logger, timeout time.Duration) (api.Peer, error) {\n\tl := log.Named(`NewFromGRPC`)\n\tp := &peer{conn: conn, log: log.Named(`peer`), timeout: timeout}\n\tif err := p.initEndorserClient(); err != nil {\n\t\tl.Error(`Failed to initialize endorser client`, zap.Error(err))\n\t\treturn nil, errors.Wrap(err, `failed to initialize EndorserClient`)\n\t}\n\treturn p, nil\n}", "func FromProto(t *pbMerkle.Tree, newContentObject func() IContent) *Tree {\n\treturn &Tree{\n\t\tdepth: int(t.Depth),\n\t\trootNode: nodeFromProto(t.GetRootNode(), newContentObject),\n\t}\n}", "func ProtoToCertificateTemplate(p *betapb.PrivatecaBetaCertificateTemplate) *beta.CertificateTemplate {\n\tobj := &beta.CertificateTemplate{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tPredefinedValues: ProtoToPrivatecaBetaCertificateTemplatePredefinedValues(p.GetPredefinedValues()),\n\t\tIdentityConstraints: ProtoToPrivatecaBetaCertificateTemplateIdentityConstraints(p.GetIdentityConstraints()),\n\t\tPassthroughExtensions: ProtoToPrivatecaBetaCertificateTemplatePassthroughExtensions(p.GetPassthroughExtensions()),\n\t\tDescription: dcl.StringOrNil(p.GetDescription()),\n\t\tCreateTime: dcl.StringOrNil(p.GetCreateTime()),\n\t\tUpdateTime: dcl.StringOrNil(p.GetUpdateTime()),\n\t\tProject: dcl.StringOrNil(p.GetProject()),\n\t\tLocation: dcl.StringOrNil(p.GetLocation()),\n\t}\n\treturn obj\n}", "func (a *Accumulator) FromProto(pb *pbtypes.AccumulatorProof) error {\r\n\ta.Siblings = siblingsWithPlaceholder(pb.Siblings, sha3libra.AccumulatorPlaceholderHash)\r\n\treturn nil\r\n}", "func (credential *FederatedIdentityCredential) ConvertFrom(hub conversion.Hub) error {\n\t// intermediate variable for conversion\n\tvar source v1beta20220131ps.FederatedIdentityCredential\n\n\terr := source.ConvertFrom(hub)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"converting from hub to source\")\n\t}\n\n\terr = credential.AssignProperties_From_FederatedIdentityCredential(&source)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"converting from source to credential\")\n\t}\n\n\treturn nil\n}", "func HeaderFromProto(ph *tmproto.Header) (Header, error) {\n\tif ph == nil {\n\t\treturn Header{}, errors.New(\"nil Header\")\n\t}\n\n\th := new(Header)\n\n\tbi, err := BlockIDFromProto(&ph.LastBlockId)\n\tif err != nil {\n\t\treturn Header{}, err\n\t}\n\n\th.Version = ph.Version\n\th.ChainID = ph.ChainID\n\th.Height = ph.Height\n\th.Time = ph.Time\n\th.Height = ph.Height\n\th.LastBlockID = *bi\n\th.ValidatorsHash = ph.ValidatorsHash\n\th.NextValidatorsHash = ph.NextValidatorsHash\n\th.ConsensusHash = ph.ConsensusHash\n\th.AppHash = ph.AppHash\n\th.DataHash = ph.DataHash\n\th.EvidenceHash = ph.EvidenceHash\n\th.LastResultsHash = ph.LastResultsHash\n\th.LastCommitHash = ph.LastCommitHash\n\th.ProposerAddress = ph.ProposerAddress\n\n\treturn *h, h.ValidateBasic()\n}", "func HeaderFromProto(ph *tmproto.Header) (Header, error) {\n\tif ph == nil {\n\t\treturn Header{}, errors.New(\"nil Header\")\n\t}\n\n\th := new(Header)\n\n\tbi, err := BlockIDFromProto(&ph.LastBlockId)\n\tif err != nil {\n\t\treturn Header{}, err\n\t}\n\n\th.Version = ph.Version\n\th.ChainID = ph.ChainID\n\th.Height = ph.Height\n\th.Time = ph.Time\n\th.Height = ph.Height\n\th.LastBlockID = *bi\n\th.ValidatorsHash = ph.ValidatorsHash\n\th.NextValidatorsHash = ph.NextValidatorsHash\n\th.ConsensusHash = ph.ConsensusHash\n\th.AppHash = ph.AppHash\n\th.DataHash = ph.DataHash\n\th.EvidenceHash = ph.EvidenceHash\n\th.LastResultsHash = ph.LastResultsHash\n\th.LastCommitHash = ph.LastCommitHash\n\th.ProposerAddress = ph.ProposerAddress\n\n\treturn *h, h.ValidateBasic()\n}", "func NewConfigFromProto(p *protos.SchedulerConfig) *Config {\n\tc := NewConfig()\n\tif p.BotExpiration != nil {\n\t\tc.BotExpiration = tutils.Duration(p.BotExpiration)\n\t}\n\tc.DisablePreemption = p.DisablePreemption\n\tfor aid, ac := range p.AccountConfigs {\n\t\tc.AccountConfigs[AccountID(aid)] = NewAccountConfig(\n\t\t\tint(ac.MaxFanout), ac.MaxChargeSeconds, ac.ChargeRate, ac.DisableFreeTasks)\n\t}\n\treturn c\n}", "func FromProto(s *spb.Status) *Status {\n\treturn &Status{s: proto.Clone(s).(*spb.Status)}\n}", "func HeaderFromProto(ph *tmproto.Header) (Header, error) {\n\tif ph == nil {\n\t\treturn Header{}, errors.New(\"nil Header\")\n\t}\n\n\th := new(Header)\n\n\tbi, err := BlockIDFromProto(&ph.LastBlockId)\n\tif err != nil {\n\t\treturn Header{}, err\n\t}\n\n\th.Version = ph.Version\n\th.ChainID = ph.ChainID\n\th.Height = ph.Height\n\th.CoreChainLockedHeight = ph.CoreChainLockedHeight\n\th.Time = ph.Time\n\th.Height = ph.Height\n\th.LastBlockID = *bi\n\th.ValidatorsHash = ph.ValidatorsHash\n\th.NextValidatorsHash = ph.NextValidatorsHash\n\th.ConsensusHash = ph.ConsensusHash\n\th.AppHash = ph.AppHash\n\th.DataHash = ph.DataHash\n\th.EvidenceHash = ph.EvidenceHash\n\th.LastResultsHash = ph.LastResultsHash\n\th.LastCommitHash = ph.LastCommitHash\n\th.ProposerProTxHash = ph.ProposerProTxHash\n\n\treturn *h, h.ValidateBasic()\n}", "func (credential *FederatedIdentityCredential) ValidateCreate() (admission.Warnings, error) {\n\tvalidations := credential.createValidations()\n\tvar temp any = credential\n\tif runtimeValidator, ok := temp.(genruntime.Validator); ok {\n\t\tvalidations = append(validations, runtimeValidator.CreateValidations()...)\n\t}\n\treturn genruntime.ValidateCreate(validations)\n}", "func FromProto(s *spb.Status) *Status {\n\treturn status.FromProto(s)\n}", "func FromProto(s *spb.Status) *Status {\n\treturn status.FromProto(s)\n}", "func ConvertCredentialSchema(in ClaimCredentialSchemaInput) claimtypes.CredentialSchema {\n\treturn claimtypes.CredentialSchema{\n\t\tID: in.ID,\n\t\tType: in.Type,\n\t}\n}", "func FromProto(pbMsg proto.Message) Codes {\n\tif msg, ok := pbMsg.(*types.Status); ok {\n\t\tif msg.Message == \"\" || msg.Message == strconv.FormatInt(int64(msg.Code), 10) {\n\t\t\t// NOTE: if message is empty convert to pure Code, will get message from config center.\n\t\t\treturn Code(msg.Code)\n\t\t}\n\t\treturn &Status{s: msg}\n\t}\n\treturn Errorf(ServerErr, \"invalid proto message get %v\", pbMsg)\n}", "func FromGRPC(ctx context.Context) (*Client, bool) {\n\tif p, ok := peer.FromContext(ctx); ok {\n\t\tip := parseIP(p.Addr.String())\n\t\tif ip != \"\" {\n\t\t\treturn &Client{ip}, true\n\t\t}\n\t}\n\treturn nil, false\n}", "func (credential *UserAssignedIdentities_FederatedIdentityCredential_Spec) ConvertSpecFrom(source genruntime.ConvertibleSpec) error {\n\tsrc, ok := source.(*v1beta20220131ps.UserAssignedIdentities_FederatedIdentityCredential_Spec)\n\tif ok {\n\t\t// Populate our instance from source\n\t\treturn credential.AssignProperties_From_UserAssignedIdentities_FederatedIdentityCredential_Spec(src)\n\t}\n\n\t// Convert to an intermediate form\n\tsrc = &v1beta20220131ps.UserAssignedIdentities_FederatedIdentityCredential_Spec{}\n\terr := src.ConvertSpecFrom(source)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"initial step of conversion in ConvertSpecFrom()\")\n\t}\n\n\t// Update our instance from src\n\terr = credential.AssignProperties_From_UserAssignedIdentities_FederatedIdentityCredential_Spec(src)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"final step of conversion in ConvertSpecFrom()\")\n\t}\n\n\treturn nil\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 FromProtoValue(val protoreflect.Value) (rel.Value, error) {\n\tswitch message := val.Interface().(type) {\n\tcase protoreflect.Message:\n\t\tvar attrs []rel.Attr\n\t\tvar err error\n\t\tmessage.Range(func(desc protoreflect.FieldDescriptor, val protoreflect.Value) bool {\n\t\t\tvar item rel.Value\n\t\t\titem, err = FromProtoValue(val)\n\t\t\tif err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tfieldName := string(desc.Name())\n\t\t\titemNum, isNum := item.(rel.Number)\n\t\t\tif desc.Enum() != nil && isNum {\n\t\t\t\t// item is protoreflect.EnumNumber\n\t\t\t\tif num, success := itemNum.Int(); success {\n\t\t\t\t\ten := protoreflect.EnumNumber(num)\n\t\t\t\t\tname := desc.Enum().Values().ByNumber(en).Name()\n\t\t\t\t\tattrs = append(attrs, rel.NewStringAttr(fieldName, []rune(name)))\n\t\t\t\t} else {\n\t\t\t\t\tattrs = append(attrs, rel.NewAttr(fieldName, item))\n\t\t\t\t}\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tattrs = append(attrs, rel.NewAttr(fieldName, item))\n\t\t\treturn true\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn rel.NewTuple(attrs...), nil\n\n\tcase protoreflect.Map:\n\t\tentries := make([]rel.DictEntryTuple, 0, val.Map().Len())\n\t\tvar err error\n\t\tval.Map().Range(func(key protoreflect.MapKey, value protoreflect.Value) bool {\n\t\t\tvar val rel.Value\n\t\t\tval, err = FromProtoValue(value)\n\t\t\tif err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tat := rel.NewString([]rune(key.String()))\n\t\t\tentries = append(entries, rel.NewDictEntryTuple(at, val))\n\t\t\treturn true\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn rel.NewDict(false, entries...)\n\n\tcase protoreflect.List:\n\t\tlist := make([]rel.Value, 0, message.Len())\n\t\tfor i := 0; i < message.Len(); i++ {\n\t\t\titem, err := FromProtoValue(message.Get(i))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tlist = append(list, item)\n\t\t}\n\t\treturn rel.NewArray(list...), nil\n\n\tcase string, bool, int, int32, int64, uint, uint32, uint64, float32, float64:\n\t\treturn rel.NewValue(message)\n\n\tcase protoreflect.EnumNumber:\n\t\t// type EnumNumber int32\n\t\treturn rel.NewValue(int32(message))\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"%v (%[1]T) not supported\", message)\n\t}\n}", "func ProtoFromFieldDescriptor(d protoreflect.FieldDescriptor) *descriptorpb.FieldDescriptorProto {\n\ttype canProto interface {\n\t\tFieldDescriptorProto() *descriptorpb.FieldDescriptorProto\n\t}\n\tif res, ok := d.(canProto); ok {\n\t\treturn res.FieldDescriptorProto()\n\t}\n\tif res, ok := d.(DescriptorProtoWrapper); ok {\n\t\tif fd, ok := res.AsProto().(*descriptorpb.FieldDescriptorProto); ok {\n\t\t\treturn fd\n\t\t}\n\t}\n\treturn protodesc.ToFieldDescriptorProto(d)\n}", "func ProtoToKey(p *recaptchaenterprisepb.RecaptchaenterpriseKey) *recaptchaenterprise.Key {\n\tobj := &recaptchaenterprise.Key{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tDisplayName: dcl.StringOrNil(p.GetDisplayName()),\n\t\tWebSettings: ProtoToRecaptchaenterpriseKeyWebSettings(p.GetWebSettings()),\n\t\tAndroidSettings: ProtoToRecaptchaenterpriseKeyAndroidSettings(p.GetAndroidSettings()),\n\t\tIosSettings: ProtoToRecaptchaenterpriseKeyIosSettings(p.GetIosSettings()),\n\t\tCreateTime: dcl.StringOrNil(p.GetCreateTime()),\n\t\tTestingOptions: ProtoToRecaptchaenterpriseKeyTestingOptions(p.GetTestingOptions()),\n\t\tProject: dcl.StringOrNil(p.GetProject()),\n\t}\n\treturn obj\n}", "func (*Credential) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{10}\n}", "func (*CredentialsProto) Descriptor() ([]byte, []int) {\n\treturn file_Security_proto_rawDescGZIP(), []int{2}\n}", "func newProtobuf(typeName string) *protobuf {\n\treturn &protobuf{\n\t\tprotobufFieldSequence: newProtobufFieldSequence(false),\n\t\tTypeName: typeName,\n\t}\n}", "func (policy *StorageAccounts_ManagementPolicy_Spec) ConvertSpecFrom(source genruntime.ConvertibleSpec) error {\n\tsrc, ok := source.(*v1beta20210401s.StorageAccounts_ManagementPolicy_Spec)\n\tif ok {\n\t\t// Populate our instance from source\n\t\treturn policy.AssignProperties_From_StorageAccounts_ManagementPolicy_Spec(src)\n\t}\n\n\t// Convert to an intermediate form\n\tsrc = &v1beta20210401s.StorageAccounts_ManagementPolicy_Spec{}\n\terr := src.ConvertSpecFrom(source)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"initial step of conversion in ConvertSpecFrom()\")\n\t}\n\n\t// Update our instance from src\n\terr = policy.AssignProperties_From_StorageAccounts_ManagementPolicy_Spec(src)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"final step of conversion in ConvertSpecFrom()\")\n\t}\n\n\treturn 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}", "func (policy *StorageAccounts_ManagementPolicy_Spec) ConvertSpecFrom(source genruntime.ConvertibleSpec) error {\n\tsrc, ok := source.(*v20220901s.StorageAccounts_ManagementPolicy_Spec)\n\tif ok {\n\t\t// Populate our instance from source\n\t\treturn policy.AssignProperties_From_StorageAccounts_ManagementPolicy_Spec(src)\n\t}\n\n\t// Convert to an intermediate form\n\tsrc = &v20220901s.StorageAccounts_ManagementPolicy_Spec{}\n\terr := src.ConvertSpecFrom(source)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"initial step of conversion in ConvertSpecFrom()\")\n\t}\n\n\t// Update our instance from src\n\terr = policy.AssignProperties_From_StorageAccounts_ManagementPolicy_Spec(src)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"final step of conversion in ConvertSpecFrom()\")\n\t}\n\n\treturn nil\n}", "func (cc *CredentialCreation) Validate() error {\n\tswitch {\n\tcase cc == nil:\n\t\treturn trace.BadParameter(\"credential creation required\")\n\tcase len(cc.Response.Challenge) == 0:\n\t\treturn trace.BadParameter(\"credential creation challenge required\")\n\tcase cc.Response.RelyingParty.ID == \"\":\n\t\treturn trace.BadParameter(\"credential creation relying party ID required\")\n\tcase len(cc.Response.RelyingParty.Name) == 0:\n\t\treturn trace.BadParameter(\"relying party name required\")\n\tcase len(cc.Response.User.Name) == 0:\n\t\treturn trace.BadParameter(\"user name required\")\n\tcase len(cc.Response.User.DisplayName) == 0:\n\t\treturn trace.BadParameter(\"user display name required\")\n\tcase len(cc.Response.User.ID) == 0:\n\t\treturn trace.BadParameter(\"user ID required\")\n\tdefault:\n\t\treturn nil\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 (a *OidcApiService) CreateVerifiableCredential(ctx context.Context) ApiCreateVerifiableCredentialRequest {\n\treturn ApiCreateVerifiableCredentialRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func ProtoToInspectTemplate(p *dlppb.DlpInspectTemplate) *dlp.InspectTemplate {\n\tobj := &dlp.InspectTemplate{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tDisplayName: dcl.StringOrNil(p.GetDisplayName()),\n\t\tDescription: dcl.StringOrNil(p.GetDescription()),\n\t\tCreateTime: dcl.StringOrNil(p.GetCreateTime()),\n\t\tUpdateTime: dcl.StringOrNil(p.GetUpdateTime()),\n\t\tInspectConfig: ProtoToDlpInspectTemplateInspectConfig(p.GetInspectConfig()),\n\t\tLocationId: dcl.StringOrNil(p.GetLocationId()),\n\t\tParent: dcl.StringOrNil(p.GetParent()),\n\t\tLocation: dcl.StringOrNil(p.GetLocation()),\n\t}\n\treturn obj\n}", "func DescriptorFromBytes(data []byte) (*Descriptor, error) {\n\tvar d Descriptor\n\tif err := json.Unmarshal(data, &d); err != nil {\n\t\treturn nil, fmt.Errorf(\"descriptor: parsing failed: %v\", err)\n\t}\n\treturn &d, nil\n}", "func (c *Client) CreateCredential(in *api.CreateCredentialRequest) (*api.Credential, error) {\n\tout := &api.Credential{}\n\trawURL := fmt.Sprintf(pathCredentials, c.base.String())\n\terr := c.post(rawURL, true, http.StatusCreated, in, out)\n\treturn out, errio.Error(err)\n}", "func CreateFromSpec(spec *Spec) *Signer {\n\tsigner := New()\n\n\tsigner.SetCredential(spec.AccessKeyID, spec.AccessKeySecret)\n\n\tif spec.Literal != nil {\n\t\tsigner.SetLiteral(spec.Literal)\n\t}\n\n\tif spec.HeaderHoisting != nil {\n\t\tsigner.SetHeaderHoisting(spec.HeaderHoisting)\n\t}\n\n\tsigner.IgnoreHeader(spec.IgnoredHeaders...)\n\tsigner.ExcludeBody(spec.ExcludeBody)\n\n\tif ttl, e := time.ParseDuration(spec.TTL); e == nil {\n\t\tsigner.SetTTL(ttl)\n\t}\n\n\tif len(spec.AccessKeys) > 0 {\n\t\tsigner.SetAccessKeyStore(idSecretMap(spec.AccessKeys))\n\t}\n\treturn signer\n}", "func (u *OpUnion) FromProto(pb pipelinepb.AppliedPipelineOp) error {\n\tswitch pb.Type {\n\tcase pipelinepb.AppliedPipelineOp_TRANSFORMATION:\n\t\tu.Type = pipeline.TransformationOpType\n\t\tif u.Rollup.ID != nil {\n\t\t\tu.Rollup.ID = u.Rollup.ID[:0]\n\t\t}\n\t\tu.Rollup.AggregationID[0] = aggregation.DefaultID[0]\n\t\treturn u.Transformation.FromProto(pb.Transformation)\n\tcase pipelinepb.AppliedPipelineOp_ROLLUP:\n\t\tu.Type = pipeline.RollupOpType\n\t\tu.Transformation.Type = transformation.UnknownType\n\t\treturn u.Rollup.FromProto(pb.Rollup)\n\tdefault:\n\t\treturn errUnknownOpType\n\t}\n}", "func ProtoToDeidentifyTemplate(p *betapb.DlpBetaDeidentifyTemplate) *beta.DeidentifyTemplate {\n\tobj := &beta.DeidentifyTemplate{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tDisplayName: dcl.StringOrNil(p.GetDisplayName()),\n\t\tDescription: dcl.StringOrNil(p.GetDescription()),\n\t\tCreateTime: dcl.StringOrNil(p.GetCreateTime()),\n\t\tUpdateTime: dcl.StringOrNil(p.GetUpdateTime()),\n\t\tDeidentifyConfig: ProtoToDlpBetaDeidentifyTemplateDeidentifyConfig(p.GetDeidentifyConfig()),\n\t\tLocationId: dcl.StringOrNil(p.GetLocationId()),\n\t\tParent: dcl.StringOrNil(p.GetParent()),\n\t\tLocation: dcl.StringOrNil(p.GetLocation()),\n\t}\n\treturn obj\n}", "func makeGrpcUser(user model.User) *mygrpc.User {\n\treturn &mygrpc.User{\n\t\tID: uint32(user.ID),\n\t\tBirthDate: user.BirthDate,\n\t\tEmail: user.Email,\n\t\tFirstName: user.FirstName,\n\t\tLastName: user.LastName,\n\t\tCreatedAt: timestamppb.New(user.CreatedAt),\n\t\tUpdatedAt: timestamppb.New(user.UpdatedAt),\n\t}\n}", "func RecordFromProtobuf(partitionKeyIndex *uint64, hashKeyIndex *uint64, payload proto.Message, tags ...*Tag) (*Record, error) {\n\tvar record = &Record{}\n\tdata, err := proto.Marshal(payload)\n\tif err != nil {\n\t\treturn record, fmt.Errorf(\"Error marshaling payload.\\t\", err)\n\t}\n\trecord.PartitionKeyIndex = partitionKeyIndex\n\trecord.ExplicitHashKeyIndex = hashKeyIndex\n\trecord.Data = data\n\treturn record, nil\n}", "func OperationsFromProto(pb []pipelinepb.AppliedPipelineOp, ops []OpUnion) error {\n\tnumOps := len(pb)\n\tif numOps != len(ops) {\n\t\treturn errOperationsLengthMismatch\n\t}\n\tfor i := 0; i < numOps; i++ {\n\t\tu := &ops[i]\n\t\tu.Type = pipeline.OpType(pb[i].Type + 1)\n\t\tswitch u.Type {\n\t\tcase pipeline.TransformationOpType:\n\t\t\tif u.Rollup.ID != nil {\n\t\t\t\tu.Rollup.ID = u.Rollup.ID[:0]\n\t\t\t}\n\t\t\tu.Rollup.AggregationID[0] = aggregation.DefaultID[0]\n\t\t\tif pb[i].Transformation.Type == transformationpb.TransformationType_UNKNOWN {\n\t\t\t\treturn errNilTransformationOpProto\n\t\t\t}\n\t\t\tif err := u.Transformation.Type.FromProto(pb[i].Transformation.Type); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase pipeline.RollupOpType:\n\t\t\tu.Transformation.Type = transformation.UnknownType\n\t\t\tif pb == nil {\n\t\t\t\treturn errNilAppliedRollupOpProto\n\t\t\t}\n\t\t\tu.Rollup.AggregationID[0] = pb[i].Rollup.AggregationId.Id\n\t\t\tu.Rollup.ID = pb[i].Rollup.Id\n\t\tdefault:\n\t\t\treturn errUnknownOpType\n\t\t}\n\t}\n\treturn nil\n}", "func ProtoToFirewall(p *computepb.ComputeFirewall) *compute.Firewall {\n\tobj := &compute.Firewall{\n\t\tCreationTimestamp: dcl.StringOrNil(p.GetCreationTimestamp()),\n\t\tDescription: dcl.StringOrNil(p.Description),\n\t\tDirection: ProtoToComputeFirewallDirectionEnum(p.GetDirection()),\n\t\tDisabled: dcl.Bool(p.Disabled),\n\t\tId: dcl.StringOrNil(p.Id),\n\t\tLogConfig: ProtoToComputeFirewallLogConfig(p.GetLogConfig()),\n\t\tName: dcl.StringOrNil(p.Name),\n\t\tNetwork: dcl.StringOrNil(p.Network),\n\t\tPriority: dcl.Int64OrNil(p.Priority),\n\t\tSelfLink: dcl.StringOrNil(p.SelfLink),\n\t\tProject: dcl.StringOrNil(p.Project),\n\t}\n\tfor _, r := range p.GetAllowed() {\n\t\tobj.Allowed = append(obj.Allowed, *ProtoToComputeFirewallAllowed(r))\n\t}\n\tfor _, r := range p.GetDenied() {\n\t\tobj.Denied = append(obj.Denied, *ProtoToComputeFirewallDenied(r))\n\t}\n\tfor _, r := range p.GetDestinationRanges() {\n\t\tobj.DestinationRanges = append(obj.DestinationRanges, r)\n\t}\n\tfor _, r := range p.GetSourceRanges() {\n\t\tobj.SourceRanges = append(obj.SourceRanges, r)\n\t}\n\tfor _, r := range p.GetSourceServiceAccounts() {\n\t\tobj.SourceServiceAccounts = append(obj.SourceServiceAccounts, r)\n\t}\n\tfor _, r := range p.GetSourceTags() {\n\t\tobj.SourceTags = append(obj.SourceTags, r)\n\t}\n\tfor _, r := range p.GetTargetServiceAccounts() {\n\t\tobj.TargetServiceAccounts = append(obj.TargetServiceAccounts, r)\n\t}\n\tfor _, r := range p.GetTargetTags() {\n\t\tobj.TargetTags = append(obj.TargetTags, r)\n\t}\n\treturn obj\n}", "func newGenericProtobufField(fieldType protobufFieldType) *genericProtobufField {\n\treturn &genericProtobufField{FieldType: fieldType}\n}", "func (service *PrivateLinkService_Spec) ConvertSpecFrom(source genruntime.ConvertibleSpec) error {\n\tif source == service {\n\t\treturn errors.New(\"attempted conversion between unrelated implementations of github.com/Azure/azure-service-operator/v2/pkg/genruntime/ConvertibleSpec\")\n\t}\n\n\treturn source.ConvertSpecTo(service)\n}", "func (*CredentialAttribute) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{9}\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 (*CredentialMessage) Descriptor() ([]byte, []int) {\n\treturn file_task_proto_rawDescGZIP(), []int{1}\n}", "func NewProtoLoginResponse(result string) *chatterpb.LoginResponse {\n\tmessage := &chatterpb.LoginResponse{}\n\tmessage.Field = result\n\treturn message\n}", "func (id *PeerID) CreateFromBytes(slice []byte) (ID, error) {\n\tif slice == nil {\n\t\treturn &PeerID{}, fmt.Errorf(\"Byte slice is nil. Cannot create ID\")\n\t}\n\n\tlogrus.Debugln(\"Creating id from the bytes:\", slice)\n\n\treturn &PeerID{slice, len(slice)}, nil\n}", "func (*Credential) Descriptor() ([]byte, []int) {\n\treturn file_auth_proto_rawDescGZIP(), []int{2}\n}", "func NewFromBytes(certBytes []byte) (certInfo CertInfo, err error) {\n\n\tcertInfo = CertInfo{}\n\tcertInfo.TimeFormat = timeFormat\n\n\terr = certInfo.fromBytes(certBytes)\n\treturn\n}", "func NewDataBlobFromProto(blob *commonpb.DataBlob) *serialization.DataBlob {\n\tswitch blob.GetEncodingType() {\n\tcase commonpb.EncodingType_JSON:\n\t\treturn &serialization.DataBlob{\n\t\t\tEncoding: common.EncodingTypeJSON,\n\t\t\tData: blob.Data,\n\t\t}\n\tcase commonpb.EncodingType_Proto3:\n\t\treturn &serialization.DataBlob{\n\t\t\tEncoding: common.EncodingTypeProto3,\n\t\t\tData: blob.Data,\n\t\t}\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"NewDataBlobFromProto seeing unsupported enconding type: %v\", blob.GetEncodingType()))\n\t}\n}", "func BlockFromProto(bp *tmproto.Block) (*Block, error) {\n\tif bp == nil {\n\t\treturn nil, errors.New(\"nil block\")\n\t}\n\n\tb := new(Block)\n\th, err := HeaderFromProto(&bp.Header)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.Header = h\n\tdata, err := DataFromProto(&bp.Data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.Data = data\n\tif err := b.Evidence.FromProto(&bp.Evidence); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcoreChainLock, err := CoreChainLockFromProto(bp.CoreChainLock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb.CoreChainLock = coreChainLock\n\n\tif bp.LastCommit != nil {\n\t\tlc, err := CommitFromProto(bp.LastCommit)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tb.LastCommit = lc\n\t}\n\n\treturn b, b.ValidateBasic()\n}", "func ProtoToCryptoKey(p *betapb.CloudkmsBetaCryptoKey) *beta.CryptoKey {\n\tobj := &beta.CryptoKey{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tPrimary: ProtoToCloudkmsBetaCryptoKeyPrimary(p.GetPrimary()),\n\t\tPurpose: ProtoToCloudkmsBetaCryptoKeyPurposeEnum(p.GetPurpose()),\n\t\tCreateTime: dcl.StringOrNil(p.GetCreateTime()),\n\t\tNextRotationTime: dcl.StringOrNil(p.GetNextRotationTime()),\n\t\tRotationPeriod: dcl.StringOrNil(p.GetRotationPeriod()),\n\t\tVersionTemplate: ProtoToCloudkmsBetaCryptoKeyVersionTemplate(p.GetVersionTemplate()),\n\t\tImportOnly: dcl.Bool(p.GetImportOnly()),\n\t\tDestroyScheduledDuration: dcl.StringOrNil(p.GetDestroyScheduledDuration()),\n\t\tProject: dcl.StringOrNil(p.GetProject()),\n\t\tLocation: dcl.StringOrNil(p.GetLocation()),\n\t\tKeyRing: dcl.StringOrNil(p.GetKeyRing()),\n\t}\n\treturn obj\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 NewProtoConverter(limits *models.Limits) *BrokerRowProtoConverter {\n\treturn &BrokerRowProtoConverter{\n\t\tflatBuilder: flatbuffers.NewBuilder(1024 + 512),\n\t\tkeys: make([]flatbuffers.UOffsetT, 0, 32),\n\t\tvalues: make([]flatbuffers.UOffsetT, 0, 32),\n\t\tfieldNames: make([]flatbuffers.UOffsetT, 0, 32),\n\t\tkvs: make([]flatbuffers.UOffsetT, 0, 32),\n\t\tfields: make([]flatbuffers.UOffsetT, 0, 32),\n\t\tlimits: limits,\n\t}\n}", "func ProtoToInstanceTemplate(p *betapb.ComputeBetaInstanceTemplate) *beta.InstanceTemplate {\n\tobj := &beta.InstanceTemplate{\n\t\tCreationTimestamp: dcl.StringOrNil(p.GetCreationTimestamp()),\n\t\tDescription: dcl.StringOrNil(p.Description),\n\t\tId: dcl.Int64OrNil(p.Id),\n\t\tSelfLink: dcl.StringOrNil(p.SelfLink),\n\t\tName: dcl.StringOrNil(p.Name),\n\t\tProperties: ProtoToComputeBetaInstanceTemplateProperties(p.GetProperties()),\n\t\tProject: dcl.StringOrNil(p.Project),\n\t}\n\treturn obj\n}", "func BuilderFromProto(in *insightV1.SearchMessagesRequest) (*Builder, error) {\n\tb := NewFilter()\n\n\tif in.GetServiceType() != \"\" {\n\t\tb.WithServiceType(in.GetServiceType())\n\t}\n\n\tif in.GetService() != \"\" {\n\t\tb.WithService(in.GetService())\n\t}\n\n\tif in.GetIdentity() != \"\" {\n\t\tb.WithIdentity(in.GetIdentity())\n\t}\n\n\t// FIXME\n\tif in.GetSeverity() != insightV1.SeverityLevel_DEBUG {\n\t\tb.WithSeverity(in.GetSeverity())\n\t}\n\n\tif in.GetDetails() != nil {\n\t\td := utils.ValueMapFrom(in.GetDetails())\n\n\t\tb.WithDetails(d)\n\t}\n\n\tif in.GetBefore() != nil {\n\t\tts, err := ptypes.Timestamp(in.GetBefore())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tb.WithBefore(ts)\n\t}\n\n\tif in.GetNotBefore() != nil {\n\t\tts, err := ptypes.Timestamp(in.GetNotBefore())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tb.WithNotBefore(ts)\n\t}\n\n\tif in.GetAfter() != nil {\n\t\tts, err := ptypes.Timestamp(in.GetAfter())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tb.WithAfter(ts)\n\t}\n\n\tif in.GetNotAfter() != nil {\n\t\tts, err := ptypes.Timestamp(in.GetNotAfter())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tb.WithNotAfter(ts)\n\t}\n\n\treturn b, nil\n}", "func CreateFromUnstructured(ctx context.Context, client client.Client, namespace, name string, secretNameWithPrefix bool, class string, objs []*unstructured.Unstructured, keepObjects bool, injectedLabels map[string]string) error {\n\tvar data []byte\n\tfor _, obj := range objs {\n\t\tbytes, err := obj.MarshalJSON()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"marshal failed for '%s/%s' for secret '%s/%s': %w\", obj.GetNamespace(), obj.GetName(), namespace, name, err)\n\t\t}\n\t\tdata = append(data, []byte(\"\\n---\\n\")...)\n\t\tdata = append(data, bytes...)\n\t}\n\treturn Create(ctx, client, namespace, name, secretNameWithPrefix, class, map[string][]byte{name: data}, &keepObjects, injectedLabels, pointer.Bool(false))\n}", "func ProtoToAttestor(p *binaryauthorizationpb.BinaryauthorizationAttestor) *binaryauthorization.Attestor {\n\tobj := &binaryauthorization.Attestor{\n\t\tName: dcl.StringOrNil(p.Name),\n\t\tDescription: dcl.StringOrNil(p.Description),\n\t\tUserOwnedGrafeasNote: ProtoToBinaryauthorizationAttestorUserOwnedGrafeasNote(p.GetUserOwnedGrafeasNote()),\n\t\tUpdateTime: dcl.StringOrNil(p.GetUpdateTime()),\n\t\tProject: dcl.StringOrNil(p.Project),\n\t}\n\treturn obj\n}", "func NewProtoLoginRequest() *chatterpb.LoginRequest {\n\tmessage := &chatterpb.LoginRequest{}\n\treturn message\n}", "func BlockFromProto(bp *tmproto.Block) (*Block, error) {\n\tif bp == nil {\n\t\treturn nil, errors.New(\"nil block\")\n\t}\n\n\tb := new(Block)\n\th, err := HeaderFromProto(&bp.Header)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.Header = h\n\tdata, err := DataFromProto(&bp.Data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.Data = data\n\tif err := b.Evidence.FromProto(&bp.Evidence); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif bp.LastCommit != nil {\n\t\tlc, err := CommitFromProto(bp.LastCommit)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tb.LastCommit = lc\n\t}\n\n\treturn b, b.ValidateBasic()\n}", "func (*PasswordComplexityPolicyCreate) Descriptor() ([]byte, []int) {\n\treturn file_management_proto_rawDescGZIP(), []int{37}\n}", "func (*CallCredentials) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_v1_ssl_ssl_proto_rawDescGZIP(), []int{4}\n}", "func CommentFromProto(sprint *ticket_svc_sprint.SprintComment) *SprintComment {\n\ttrans := &SprintComment{}\n\n\tcopier.Copy(trans, sprint)\n\n\treturn trans\n}", "func (account *DatabaseAccount_Spec) ConvertSpecFrom(source genruntime.ConvertibleSpec) error {\n\tsrc, ok := source.(*v20210515s.DatabaseAccount_Spec)\n\tif ok {\n\t\t// Populate our instance from source\n\t\treturn account.AssignProperties_From_DatabaseAccount_Spec(src)\n\t}\n\n\t// Convert to an intermediate form\n\tsrc = &v20210515s.DatabaseAccount_Spec{}\n\terr := src.ConvertSpecFrom(source)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"initial step of conversion in ConvertSpecFrom()\")\n\t}\n\n\t// Update our instance from src\n\terr = account.AssignProperties_From_DatabaseAccount_Spec(src)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"final step of conversion in ConvertSpecFrom()\")\n\t}\n\n\treturn nil\n}", "func (c *Credentials) Create(ctx context.Context, credential *envelope.Credential) (*envelope.Credential, error) {\n\tresp := &envelope.Credential{}\n\terr := c.client.RoundTrip(ctx, \"POST\", \"/credentials\", nil, credential, &resp)\n\treturn resp, err\n}", "func (e *Entity) createP2PProtobuf() *entitypb.Entity {\n\tdids := identity.DIDsToBytes(e.Identity)\n\treturn &entitypb.Entity{\n\t\tIdentity: dids[0],\n\t\tLegalName: e.LegalName,\n\t\tAddresses: e.Addresses,\n\t\tPaymentDetails: e.PaymentDetails,\n\t\tContacts: e.Contacts,\n\t}\n}", "func ParseCredential(ctx context.Context) Credential {\n\tvar credential Credential\n\n\tmd, ok := metadata.FromIncomingContext(ctx)\n\tif !ok {\n\t\treturn credential\n\t}\n\n\tapps, tokens := md[appKey], md[tokenKey]\n\tif len(apps) == 0 || len(tokens) == 0 {\n\t\treturn credential\n\t}\n\n\tapp, token := apps[0], tokens[0]\n\tif len(app) == 0 || len(token) == 0 {\n\t\treturn credential\n\t}\n\n\tcredential.App = app\n\tcredential.Token = token\n\n\treturn credential\n}", "func (*ValidateClientCredentialRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_micro_pb_request_proto_rawDescGZIP(), []int{0}\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 ContainerClusterMasterAuthToProto(o *container.ClusterMasterAuth) *containerpb.ContainerClusterMasterAuth {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &containerpb.ContainerClusterMasterAuth{\n\t\tUsername: dcl.ValueOrEmptyString(o.Username),\n\t\tPassword: dcl.ValueOrEmptyString(o.Password),\n\t\tClientCertificateConfig: ContainerClusterMasterAuthClientCertificateConfigToProto(o.ClientCertificateConfig),\n\t\tClusterCaCertificate: dcl.ValueOrEmptyString(o.ClusterCaCertificate),\n\t\tClientCertificate: dcl.ValueOrEmptyString(o.ClientCertificate),\n\t\tClientKey: dcl.ValueOrEmptyString(o.ClientKey),\n\t}\n\treturn p\n}" ]
[ "0.77852", "0.7673165", "0.7087914", "0.6934679", "0.68827397", "0.67722136", "0.6361961", "0.602129", "0.591723", "0.58584166", "0.5693408", "0.5690987", "0.5658552", "0.5642539", "0.5617722", "0.5571336", "0.5562646", "0.55291426", "0.5476078", "0.54715914", "0.54699343", "0.54465586", "0.5413693", "0.5413198", "0.53850895", "0.53696764", "0.53099734", "0.5239521", "0.52248144", "0.5198192", "0.51790696", "0.5159425", "0.5145351", "0.5138997", "0.5126836", "0.5119476", "0.5119476", "0.5117394", "0.5096096", "0.5088221", "0.50879925", "0.50863034", "0.50863034", "0.50627756", "0.5055319", "0.5049887", "0.5024227", "0.49870408", "0.49833924", "0.49743968", "0.4972834", "0.49595657", "0.49502537", "0.49487087", "0.4919626", "0.49196035", "0.4917874", "0.4905765", "0.49049985", "0.4889655", "0.48892194", "0.48847505", "0.48671076", "0.48664752", "0.4852614", "0.48462802", "0.48459184", "0.48419198", "0.48414096", "0.4841029", "0.48214385", "0.48129278", "0.48076355", "0.48048306", "0.48040664", "0.47890088", "0.4776069", "0.4774097", "0.47710443", "0.47698352", "0.4767388", "0.47614795", "0.4757554", "0.4748502", "0.47460523", "0.47454152", "0.47402123", "0.47379512", "0.4736901", "0.47363442", "0.4734256", "0.47332153", "0.47272167", "0.47256783", "0.47218138", "0.47108483", "0.4696312", "0.46950316", "0.46906793", "0.4689413" ]
0.8701645
0
CredentialCreationResponseFromProto converts a CredentialCreationResponse proto to its lib counterpart.
func CredentialCreationResponseFromProto(ccr *wantypes.CredentialCreationResponse) *CredentialCreationResponse { if ccr == nil { return nil } return &CredentialCreationResponse{ PublicKeyCredential: PublicKeyCredential{ Credential: Credential{ ID: base64.RawURLEncoding.EncodeToString(ccr.RawId), Type: ccr.Type, }, RawID: ccr.RawId, Extensions: outputExtensionsFromProto(ccr.Extensions), }, AttestationResponse: authenticatorAttestationResponseFromProto(ccr.Response), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CredentialCreationResponseToProto(ccr *CredentialCreationResponse) *wantypes.CredentialCreationResponse {\n\tif ccr == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialCreationResponse{\n\t\tType: ccr.Type,\n\t\tRawId: ccr.RawID,\n\t\tResponse: &wantypes.AuthenticatorAttestationResponse{\n\t\t\tClientDataJson: ccr.AttestationResponse.ClientDataJSON,\n\t\t\tAttestationObject: ccr.AttestationResponse.AttestationObject,\n\t\t},\n\t\tExtensions: outputExtensionsToProto(ccr.Extensions),\n\t}\n}", "func CredentialCreationFromProto(cc *wantypes.CredentialCreation) *CredentialCreation {\n\tif cc == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialCreation{\n\t\tResponse: publicKeyCredentialCreationOptionsFromProto(cc.PublicKey),\n\t}\n}", "func CredentialAssertionResponseFromProto(car *wantypes.CredentialAssertionResponse) *CredentialAssertionResponse {\n\tif car == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialAssertionResponse{\n\t\tPublicKeyCredential: PublicKeyCredential{\n\t\t\tCredential: Credential{\n\t\t\t\tID: base64.RawURLEncoding.EncodeToString(car.RawId),\n\t\t\t\tType: car.Type,\n\t\t\t},\n\t\t\tRawID: car.RawId,\n\t\t\tExtensions: outputExtensionsFromProto(car.Extensions),\n\t\t},\n\t\tAssertionResponse: authenticatorAssertionResponseFromProto(car.Response),\n\t}\n}", "func CredentialCreationToProto(cc *CredentialCreation) *wantypes.CredentialCreation {\n\tif cc == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialCreation{\n\t\tPublicKey: &wantypes.PublicKeyCredentialCreationOptions{\n\t\t\tChallenge: cc.Response.Challenge,\n\t\t\tRp: rpEntityToProto(cc.Response.RelyingParty),\n\t\t\tUser: userEntityToProto(cc.Response.User),\n\t\t\tCredentialParameters: credentialParametersToProto(cc.Response.Parameters),\n\t\t\tTimeoutMs: int64(cc.Response.Timeout),\n\t\t\tExcludeCredentials: credentialDescriptorsToProto(cc.Response.CredentialExcludeList),\n\t\t\tAttestation: string(cc.Response.Attestation),\n\t\t\tExtensions: inputExtensionsToProto(cc.Response.Extensions),\n\t\t\tAuthenticatorSelection: authenticatorSelectionToProto(cc.Response.AuthenticatorSelection),\n\t\t},\n\t}\n}", "func CredentialAssertionFromProto(assertion *wantypes.CredentialAssertion) *CredentialAssertion {\n\tif assertion == nil {\n\t\treturn nil\n\t}\n\treturn &CredentialAssertion{\n\t\tResponse: publicKeyCredentialRequestOptionsFromProto(assertion.PublicKey),\n\t}\n}", "func CredentialAssertionResponseToProto(car *CredentialAssertionResponse) *wantypes.CredentialAssertionResponse {\n\tif car == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialAssertionResponse{\n\t\tType: car.Type,\n\t\tRawId: car.RawID,\n\t\tResponse: &wantypes.AuthenticatorAssertionResponse{\n\t\t\tClientDataJson: car.AssertionResponse.ClientDataJSON,\n\t\t\tAuthenticatorData: car.AssertionResponse.AuthenticatorData,\n\t\t\tSignature: car.AssertionResponse.Signature,\n\t\t\tUserHandle: car.AssertionResponse.UserHandle,\n\t\t},\n\t\tExtensions: outputExtensionsToProto(car.Extensions),\n\t}\n}", "func NewAuthenticationMetadataFromProto(message *auth_pb.AuthenticationMetadata) (*AuthenticationMetadata, error) {\n\t// Create raw value, which stores the contents of the Protobuf\n\t// message as an object normally returned by json.Unmarshal().\n\t// This can be used to do JMESPath matching by the authorization\n\t// layer.\n\tmessageJSON, err := protojson.Marshal(message)\n\tif err != nil {\n\t\treturn nil, util.StatusWrapWithCode(err, codes.InvalidArgument, \"Cannot convert authentication metadata to JSON\")\n\t}\n\tvar raw map[string]any\n\tif err := json.Unmarshal(messageJSON, &raw); err != nil {\n\t\treturn nil, util.StatusWrapWithCode(err, codes.InvalidArgument, \"Cannot parse authentication metadata JSON\")\n\t}\n\n\ttracingAttributes, err := otel.NewKeyValueListFromProto(message.GetTracingAttributes(), \"auth.\")\n\tif err != nil {\n\t\treturn nil, util.StatusWrap(err, \"Cannot create tracing attributes\")\n\t}\n\n\tam := &AuthenticationMetadata{\n\t\traw: raw,\n\t\ttracingAttributes: tracingAttributes,\n\t}\n\tproto.Merge(&am.proto, message)\n\treturn am, nil\n}", "func NewProtoLoginResponse(result string) *chatterpb.LoginResponse {\n\tmessage := &chatterpb.LoginResponse{}\n\tmessage.Field = result\n\treturn message\n}", "func CredentialCreationFromProtocol(cc *protocol.CredentialCreation) *CredentialCreation {\n\tif cc == nil {\n\t\treturn nil\n\t}\n\n\t// Based on our configuration we should always get a protocol.URLEncodedBase64\n\t// user ID, but the go-webauthn/webauthn is capable of generating strings too.\n\tvar userID []byte\n\tif id := cc.Response.User.ID; id != nil {\n\t\tswitch uid := id.(type) {\n\t\tcase protocol.URLEncodedBase64:\n\t\t\tuserID = uid\n\t\tcase string:\n\t\t\tuserID = []byte(uid)\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"Unexpected WebAuthn cc.Response.User.ID type: %T\", id))\n\t\t}\n\t}\n\n\treturn &CredentialCreation{\n\t\tResponse: PublicKeyCredentialCreationOptions{\n\t\t\tChallenge: Challenge(cc.Response.Challenge),\n\t\t\tRelyingParty: RelyingPartyEntity{\n\t\t\t\tCredentialEntity: cc.Response.RelyingParty.CredentialEntity,\n\t\t\t\tID: cc.Response.RelyingParty.ID,\n\t\t\t},\n\t\t\tUser: UserEntity{\n\t\t\t\tCredentialEntity: cc.Response.User.CredentialEntity,\n\t\t\t\tDisplayName: cc.Response.User.Name,\n\t\t\t\tID: userID,\n\t\t\t},\n\t\t\tParameters: credentialParametersFromProtocol(cc.Response.Parameters),\n\t\t\tAuthenticatorSelection: AuthenticatorSelection{\n\t\t\t\tAuthenticatorAttachment: cc.Response.AuthenticatorSelection.AuthenticatorAttachment,\n\t\t\t\tRequireResidentKey: cc.Response.AuthenticatorSelection.RequireResidentKey,\n\t\t\t\tResidentKey: cc.Response.AuthenticatorSelection.ResidentKey,\n\t\t\t\tUserVerification: cc.Response.AuthenticatorSelection.UserVerification,\n\t\t\t},\n\t\t\tTimeout: cc.Response.Timeout,\n\t\t\tCredentialExcludeList: credentialDescriptorsFromProtocol(cc.Response.CredentialExcludeList),\n\t\t\tExtensions: cc.Response.Extensions,\n\t\t\tAttestation: cc.Response.Attestation,\n\t\t},\n\t}\n}", "func NewProtoSubscribeResponse(result *chatter.Event) *chatterpb.SubscribeResponse {\n\tmessage := &chatterpb.SubscribeResponse{\n\t\tMessage_: result.Message,\n\t\tAction: result.Action,\n\t\tAddedAt: result.AddedAt,\n\t}\n\treturn message\n}", "func decodeCreateResponse(_ context.Context, reply interface{}) (interface{}, error) {\n\tresp, found := reply.(*pb.CreateReply)\n\tif !found {\n\t\treturn nil, fmt.Errorf(\"pb CreateReply type assertion error\")\n\t}\n\treturn endpoint1.CreateResponse{E1: nil, UUID: resp.Uuid}, nil\n}", "func CredentialAssertionToProto(assertion *CredentialAssertion) *wantypes.CredentialAssertion {\n\tif assertion == nil {\n\t\treturn nil\n\t}\n\treturn &wantypes.CredentialAssertion{\n\t\tPublicKey: &wantypes.PublicKeyCredentialRequestOptions{\n\t\t\tChallenge: assertion.Response.Challenge,\n\t\t\tTimeoutMs: int64(assertion.Response.Timeout),\n\t\t\tRpId: assertion.Response.RelyingPartyID,\n\t\t\tAllowCredentials: credentialDescriptorsToProto(assertion.Response.AllowedCredentials),\n\t\t\tExtensions: inputExtensionsToProto(assertion.Response.Extensions),\n\t\t\tUserVerification: string(assertion.Response.UserVerification),\n\t\t},\n\t}\n}", "func MustNewAuthenticationMetadataFromProto(message *auth_pb.AuthenticationMetadata) *AuthenticationMetadata {\n\tauthenticationMetadata, err := NewAuthenticationMetadataFromProto(message)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn authenticationMetadata\n}", "func decodeGRPCGenerateReportResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.GenerateReportResponse)\n\treturn generateReportResponse{Repository: reply.Repository, Err: str2err(reply.Err)}, nil\n}", "func NewProtoHistoryResponse(result *chatterviews.ChatSummaryView) *chatterpb.HistoryResponse {\n\tmessage := &chatterpb.HistoryResponse{\n\t\tMessage_: *result.Message,\n\t\tSentAt: *result.SentAt,\n\t}\n\tif result.Length != nil {\n\t\tlength := int32(*result.Length)\n\t\tmessage.Length = &length\n\t}\n\treturn message\n}", "func decodeCreateResponse(_ context.Context, reply interface{}) (interface{}, error) {\n\treturn nil, errors.New(\"'Users' Decoder is not impelemented\")\n}", "func (n *nativeImpl) MakeCredential(origin string, in *makeCredentialRequest) (*wantypes.CredentialCreationResponse, error) {\n\thwnd, err := getForegroundWindow()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tvar out *webauthnCredentialAttestation\n\tret, _, err := procWebAuthNAuthenticatorMakeCredential.Call(\n\t\tuintptr(hwnd),\n\t\tuintptr(unsafe.Pointer(in.rp)),\n\t\tuintptr(unsafe.Pointer(in.user)),\n\t\tuintptr(unsafe.Pointer(in.credParameters)),\n\t\tuintptr(unsafe.Pointer(in.clientData)),\n\t\tuintptr(unsafe.Pointer(in.opts)),\n\t\tuintptr(unsafe.Pointer(&out)),\n\t)\n\tif ret != 0 {\n\t\treturn nil, trace.Wrap(getErrorNameOrLastErr(ret, err))\n\t}\n\tif out == nil {\n\t\treturn nil, errors.New(\"unexpected nil response from MakeCredential\")\n\t}\n\n\t// Note that we need to copy bytes out of `out` if we want to free object.\n\t// That's why bytesFromCBytes is used.\n\t// We don't care about free error so ignore it explicitly.\n\tdefer func() { _ = freeCredentialAttestation(out) }()\n\n\tcredential := bytesFromCBytes(out.cbCredentialID, out.pbCredentialID)\n\n\treturn &wantypes.CredentialCreationResponse{\n\t\tPublicKeyCredential: wantypes.PublicKeyCredential{\n\t\t\tCredential: wantypes.Credential{\n\t\t\t\tID: base64.RawURLEncoding.EncodeToString(credential),\n\t\t\t\tType: string(protocol.PublicKeyCredentialType),\n\t\t\t},\n\t\t\tRawID: credential,\n\t\t},\n\t\tAttestationResponse: wantypes.AuthenticatorAttestationResponse{\n\t\t\tAuthenticatorResponse: wantypes.AuthenticatorResponse{\n\t\t\t\tClientDataJSON: in.jsonEncodedClientData,\n\t\t\t},\n\t\t\tAttestationObject: bytesFromCBytes(out.cbAttestationObject, out.pbAttestationObject),\n\t\t},\n\t}, nil\n}", "func (c *CreatePDPContextResponse) DecodeFromBytes(b []byte) error {\n\tlog.Println(\"CreatePDPContextResponse.DecodeFromBytes is deprecated. use CreatePDPContextResponse.UnmarshalBinary instead\")\n\treturn c.UnmarshalBinary(b)\n}", "func CredentialAssertionFromProtocol(a *protocol.CredentialAssertion) *CredentialAssertion {\n\tif a == nil {\n\t\treturn nil\n\t}\n\n\treturn &CredentialAssertion{\n\t\tResponse: PublicKeyCredentialRequestOptions{\n\t\t\tChallenge: Challenge(a.Response.Challenge),\n\t\t\tTimeout: a.Response.Timeout,\n\t\t\tRelyingPartyID: a.Response.RelyingPartyID,\n\t\t\tAllowedCredentials: credentialDescriptorsFromProtocol(a.Response.AllowedCredentials),\n\t\t\tUserVerification: a.Response.UserVerification,\n\t\t\tExtensions: a.Response.Extensions,\n\t\t},\n\t}\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_teams_v1_teams_proto_rawDescGZIP(), []int{4}\n}", "func (*CreateTokenResponse) Descriptor() ([]byte, []int) {\n\treturn file_pb_auth_proto_rawDescGZIP(), []int{4}\n}", "func UnmarshalCreateAccountResponse(m map[string]json.RawMessage, result interface{}) (err error) {\n\tobj := new(CreateAccountResponse)\n\terr = core.UnmarshalPrimitive(m, \"account_id\", &obj.AccountID)\n\tif err != nil {\n\t\treturn\n\t}\n\treflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj))\n\treturn\n}", "func (m *Mutate) NewResponse() proto.Message {\n\treturn &pb.MutateResponse{}\n}", "func ParseCreateanewPartyCallControlResponse(rsp *http.Response) (*CreateanewPartyCallControlResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &CreateanewPartyCallControlResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 201:\n\t\tvar dest []Thenewlycreateditemorempty55\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON201 = &dest\n\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 422:\n\t\tvar dest Anerror\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON422 = &dest\n\n\t}\n\n\treturn response, nil\n}", "func UnmarshalCreateChannelsResponse(m map[string]json.RawMessage, result interface{}) (err error) {\n\tobj := new(CreateChannelsResponse)\n\terr = core.UnmarshalPrimitive(m, \"channel_id\", &obj.ChannelID)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"status_code\", &obj.StatusCode)\n\tif err != nil {\n\t\treturn\n\t}\n\treflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj))\n\treturn\n}", "func (c *CreateBearerResponse) DecodeFromBytes(b []byte) error {\n\tlog.Println(\"CreateBearerResponse.DecodeFromBytes is deprecated. use CreateBearerResponse.UnmarshalBinary instead\")\n\treturn c.UnmarshalBinary(b)\n}", "func NewBatchGRPCResponse(result []*public.ResponsePayload) *publicpb.BatchGRPCResponse {\n\tmessage := &publicpb.BatchGRPCResponse{}\n\tmessage.Field = make([]*publicpb.ResponsePayload, len(result))\n\tfor i, val := range result {\n\t\tmessage.Field[i] = &publicpb.ResponsePayload{\n\t\t\tFirstField: val.FirstField,\n\t\t\tFourthField: val.FourthField,\n\t\t}\n\t}\n\treturn message\n}", "func buildResponseConvertData(response, result *expr.AttributeExpr, svcCtx *codegen.AttributeContext, hdrs, trlrs []*MetadataData, e *expr.GRPCEndpointExpr, sd *ServiceData, svr bool) *ConvertData {\n\tif !svr && (e.MethodExpr.IsStreaming() || isEmpty(e.MethodExpr.Result.Type)) {\n\t\treturn nil\n\t}\n\n\tvar (\n\t\tsvc = sd.Service\n\t)\n\n\tif svr {\n\t\t// server side\n\n\t\tvar data *InitData\n\t\t{\n\t\t\tdata = buildInitData(result, response, \"result\", \"message\", svcCtx, true, svr, false, sd)\n\t\t\tdata.Description = fmt.Sprintf(\"%s builds the gRPC response type from the result of the %q endpoint of the %q service.\", data.Name, e.Name(), svc.Name)\n\t\t}\n\t\treturn &ConvertData{\n\t\t\tSrcName: svcCtx.Scope.Name(result, svcCtx.Pkg(result), svcCtx.Pointer, svcCtx.UseDefault),\n\t\t\tSrcRef: svcCtx.Scope.Ref(result, svcCtx.Pkg(result)),\n\t\t\tTgtName: protoBufGoFullTypeName(response, sd.PkgName, sd.Scope),\n\t\t\tTgtRef: protoBufGoFullTypeRef(response, sd.PkgName, sd.Scope),\n\t\t\tInit: data,\n\t\t}\n\t}\n\n\t// client side\n\n\tvar data *InitData\n\t{\n\t\tdata = buildInitData(response, result, \"message\", \"result\", svcCtx, false, svr, false, sd)\n\t\tdata.Name = fmt.Sprintf(\"New%sResult\", codegen.Goify(e.Name(), true))\n\t\tdata.Description = fmt.Sprintf(\"%s builds the result type of the %q endpoint of the %q service from the gRPC response type.\", data.Name, e.Name(), svc.Name)\n\t\tfor _, m := range hdrs {\n\t\t\t// pass the headers as arguments to result constructor in client\n\t\t\tdata.Args = append(data.Args, &InitArgData{\n\t\t\t\tName: m.VarName,\n\t\t\t\tRef: m.VarName,\n\t\t\t\tFieldName: m.FieldName,\n\t\t\t\tFieldType: m.FieldType,\n\t\t\t\tTypeName: m.TypeName,\n\t\t\t\tTypeRef: m.TypeRef,\n\t\t\t\tType: m.Type,\n\t\t\t\tPointer: m.Pointer,\n\t\t\t\tRequired: m.Required,\n\t\t\t\tValidate: m.Validate,\n\t\t\t\tExample: m.Example,\n\t\t\t})\n\t\t}\n\t\tfor _, m := range trlrs {\n\t\t\t// pass the trailers as arguments to result constructor in client\n\t\t\tdata.Args = append(data.Args, &InitArgData{\n\t\t\t\tName: m.VarName,\n\t\t\t\tRef: m.VarName,\n\t\t\t\tFieldName: m.FieldName,\n\t\t\t\tFieldType: m.FieldType,\n\t\t\t\tTypeName: m.TypeName,\n\t\t\t\tTypeRef: m.TypeRef,\n\t\t\t\tType: m.Type,\n\t\t\t\tPointer: m.Pointer,\n\t\t\t\tRequired: m.Required,\n\t\t\t\tValidate: m.Validate,\n\t\t\t\tExample: m.Example,\n\t\t\t})\n\t\t}\n\t}\n\treturn &ConvertData{\n\t\tSrcName: protoBufGoFullTypeName(response, sd.PkgName, sd.Scope),\n\t\tSrcRef: protoBufGoFullTypeRef(response, sd.PkgName, sd.Scope),\n\t\tTgtName: svcCtx.Scope.Name(result, svcCtx.Pkg(result), svcCtx.Pointer, svcCtx.UseDefault),\n\t\tTgtRef: svcCtx.Scope.Ref(result, svcCtx.Pkg(result)),\n\t\tInit: data,\n\t\tValidation: addValidation(response, \"message\", sd, false),\n\t}\n}", "func CreateSubmitOperationCredentialsResponse() (response *SubmitOperationCredentialsResponse) {\n\tresponse = &SubmitOperationCredentialsResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (b *BitcoinClient) createRPCBitcoinResponse(res string) *RPCBitcoinResponse {\n\tvar rpcBitcoinResponse RPCBitcoinResponse\n\tjson.Unmarshal([]byte(res), &rpcBitcoinResponse)\n\n\treturn &rpcBitcoinResponse\n}", "func NewProtoEchoerResponse(result string) *chatterpb.EchoerResponse {\n\tmessage := &chatterpb.EchoerResponse{}\n\tmessage.Field = result\n\treturn message\n}", "func decodeAuthResponse(_ context.Context, reply interface{}) (interface{}, error) {\n\tr, ok := reply.(*pb.AuthReply)\n\tif !ok {\n\t\te := errors.New(\"'AuthReply' Decoder is not impelemented\")\n\t\treturn endpoint1.AuthResponse{Err: e}, e\n\t}\n\treturn endpoint1.AuthResponse{Uuid: r.Uuid, NamespaceID: r.NamespaceID, Roles: r.Roles}, nil\n}", "func (*CreateUserResponse) Descriptor() ([]byte, []int) {\n\treturn file_pb_auth_proto_rawDescGZIP(), []int{1}\n}", "func (*IssueCredentialResponse) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{12}\n}", "func decodeGRPCGenerateReportRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.GenerateReportRequest)\n\treturn generateReportRequest{Username: req.Username, Token: req.Token, RepositoryName: req.RepositoryName}, nil\n}", "func DecodeInitResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.InitResponse)\n\tinit := service.InitKeys{\n\t\tKeys: reply.Keys,\n\t\tKeysB64: reply.KeysBase64,\n\t\tRecoveryKeys: reply.RecoveryKeys,\n\t\tRecoveryKeysB64: reply.RecoveryKeysBase64,\n\t\tRootToken: reply.RootToken,\n\t}\n\treturn endpoints.InitResponse{Init: init, Err: service.String2Error(reply.Err)}, nil\n}", "func unmarshalCredential(raw []byte) (*credential, error) {\n\tif len(raw) < 10 {\n\t\treturn nil, errors.New(\"tls: Delegated Credential is not valid: invalid length\")\n\t}\n\n\ts := cryptobyte.String(raw)\n\tvar t uint32\n\tif !s.ReadUint32(&t) {\n\t\treturn nil, errors.New(\"tls: Delegated Credential is not valid\")\n\t}\n\tvalidTime := time.Duration(t) * time.Second\n\n\tvar pubAlgo uint16\n\tif !s.ReadUint16(&pubAlgo) {\n\t\treturn nil, errors.New(\"tls: Delegated Credential is not valid\")\n\t}\n\talgo := SignatureScheme(pubAlgo)\n\n\tvar pubLen uint32\n\ts.ReadUint24(&pubLen)\n\n\tpubKey, err := x509.ParsePKIXPublicKey(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &credential{validTime, algo, pubKey}, nil\n}", "func ParseCreateanewCallControlResponse(rsp *http.Response) (*CreateanewCallControlResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &CreateanewCallControlResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 201:\n\t\tvar dest []Thenewlycreateditemorempty53\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON201 = &dest\n\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 422:\n\t\tvar dest Anerror\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON422 = &dest\n\n\t}\n\n\treturn response, nil\n}", "func FromProto(req *metrov1.StreamingPullRequest) (*AcknowledgeRequest, *ModifyAckDeadlineRequest, error) {\n\tif len(req.ModifyDeadlineAckIds) != len(req.ModifyDeadlineSeconds) {\n\t\treturn nil, nil, fmt.Errorf(\"length of modify_deadline_ack_ids and modify_deadline_seconds not same\")\n\t}\n\tar := &AcknowledgeRequest{\n\t\treq.AckIds,\n\t}\n\tmr := &ModifyAckDeadlineRequest{\n\t\treq.ModifyDeadlineSeconds,\n\t\treq.ModifyDeadlineAckIds,\n\t}\n\treturn ar, mr, nil\n}", "func CreateDescribeChannelParticipantsResponse() (response *DescribeChannelParticipantsResponse) {\n\tresponse = &DescribeChannelParticipantsResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_account_proto_rawDescGZIP(), []int{1}\n}", "func (*CreateConversationResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_threads_proto_rawDescGZIP(), []int{3}\n}", "func NewProtoListenerResponse() *chatterpb.ListenerResponse {\n\tmessage := &chatterpb.ListenerResponse{}\n\treturn message\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_wallet_proto_rawDescGZIP(), []int{2}\n}", "func (e *execPlugin) decodeResponse(data []byte) (*credentialproviderapi.CredentialProviderResponse, error) {\n\tobj, gvk, err := codecs.UniversalDecoder().Decode(data, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif gvk.Kind != \"CredentialProviderResponse\" {\n\t\treturn nil, fmt.Errorf(\"failed to decode CredentialProviderResponse, unexpected Kind: %q\", gvk.Kind)\n\t}\n\n\tif gvk.Group != credentialproviderapi.GroupName {\n\t\treturn nil, fmt.Errorf(\"failed to decode CredentialProviderResponse, unexpected Group: %s\", gvk.Group)\n\t}\n\n\tif internalResponse, ok := obj.(*credentialproviderapi.CredentialProviderResponse); ok {\n\t\treturn internalResponse, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"unable to convert %T to *CredentialProviderResponse\", obj)\n}", "func NewUserFromProto(user *accounts_proto.User) *User {\n\treturn &User{User: *user}\n}", "func (*ListCredentialsResponse) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{23}\n}", "func (*CreateTokenResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_user_user_proto_rawDescGZIP(), []int{11}\n}", "func EncodeGRPCNewUserResponse(_ context.Context, r interface{}) (interface{}, error) {\n\tresp := r.(newUserResponse)\n\treturn &pb.NewUserResponse{\n\t\tId: resp.Id,\n\t\tErr: resp.Err,\n\t}, nil\n}", "func (*ValidateUserLoginResponse) Descriptor() ([]byte, []int) {\n\treturn file_pb_authentication_proto_rawDescGZIP(), []int{1}\n}", "func CreateResponse(resultCode uint32, internalCommand []byte) ([]byte, error) {\n\t// Response frame:\n\t// - uint32 (size of response)\n\t// - []byte (response)\n\t// - uint32 (code)\n\tvar buf bytes.Buffer\n\n\tif err := binary.Write(&buf, binary.BigEndian, uint32(len(internalCommand))); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif _, err := buf.Write(internalCommand); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := binary.Write(&buf, binary.BigEndian, resultCode); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func UnmarshalCreateAccountGroupResponse(m map[string]json.RawMessage, result interface{}) (err error) {\n\tobj := new(CreateAccountGroupResponse)\n\terr = core.UnmarshalPrimitive(m, \"account_group_id\", &obj.AccountGroupID)\n\tif err != nil {\n\t\treturn\n\t}\n\treflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj))\n\treturn\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_contact_proto_rawDescGZIP(), []int{7}\n}", "func (*AcceptCredentialResponse) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{33}\n}", "func NewGetCredentialsResponseCredential() *GetCredentialsResponseCredential {\n\tthis := GetCredentialsResponseCredential{}\n\treturn &this\n}", "func decodeSigninResponse(_ context.Context, reply interface{}) (interface{}, error) {\n\tr, found := reply.(*pb.SigninReply)\n\tif !found {\n\t\te := fmt.Errorf(\"pb CreateReply type assertion error\")\n\t\treturn &endpoint1.SigninResponse{\n\t\t\tE1: e,\n\t\t}, e\n\t}\n\treturn endpoint1.SigninResponse{S0: r.Token}, nil\n}", "func (*ChangePasswordResponse) Descriptor() ([]byte, []int) {\n\treturn file_pb_auth_proto_rawDescGZIP(), []int{3}\n}", "func (a *OidcApiService) CreateVerifiableCredential(ctx context.Context) ApiCreateVerifiableCredentialRequest {\n\treturn ApiCreateVerifiableCredentialRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (*MultiCreateCertificatesV1Response) Descriptor() ([]byte, []int) {\n\treturn file_api_ocp_certificate_api_ocp_certificate_api_proto_rawDescGZIP(), []int{1}\n}", "func userToProto(u *domain.User) *protouser.Response {\n\treturn &protouser.Response{\n\t\tApplication: proto.String(string(u.App)),\n\t\tUid: proto.String(u.Uid),\n\t\tIds: idsToStrings(u.Ids),\n\t\tCreatedTimestamp: timeToProto(u.Created),\n\t\tRoles: u.Roles,\n\t\tPasswordChangeTimestamp: timeToProto(u.PasswordChange),\n\t\tAccountExpirationDate: proto.String(string(u.AccountExpirationDate)),\n\t}\n}", "func FromProto(msg proto.Message) (*repb.Digest, error) {\n\tblob, err := proto.Marshal(msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn FromBlob(blob), nil\n}", "func CreateDescribePhoneTwiceTelVerifyResponse() (response *DescribePhoneTwiceTelVerifyResponse) {\n\tresponse = &DescribePhoneTwiceTelVerifyResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (*LoginResponse) Descriptor() ([]byte, []int) {\n\treturn file_pb_authentication_proto_rawDescGZIP(), []int{2}\n}", "func (*CancelTeamSubscriptionResponse) Descriptor() ([]byte, []int) {\n\treturn file_protos_participant_service_proto_rawDescGZIP(), []int{5}\n}", "func NewResponse(call *Call) *Response {\n\tresp := &Response{\n\t\tVersion: call.Version,\n\t\tID: call.ID,\n\t}\n\treturn resp\n}", "func (*SinglePasswordValidationResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{127}\n}", "func (*Room_CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_chat_chat_proto_rawDescGZIP(), []int{0, 1}\n}", "func (*CUserAccount_CreateFriendInviteToken_Response) Descriptor() ([]byte, []int) {\n\treturn file_steammessages_useraccount_steamclient_proto_rawDescGZIP(), []int{7}\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 (*CreateSubscriptionResponse) Descriptor() ([]byte, []int) {\n\treturn file_toit_api_data_proto_rawDescGZIP(), []int{3}\n}", "func (x *fastReflection_QueryAccountsResponse) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value {\n\tswitch fd.FullName() {\n\tcase \"cosmos.auth.v1beta1.QueryAccountsResponse.accounts\":\n\t\tlist := []*anypb.Any{}\n\t\treturn protoreflect.ValueOfList(&_QueryAccountsResponse_1_list{list: &list})\n\tcase \"cosmos.auth.v1beta1.QueryAccountsResponse.pagination\":\n\t\tm := new(v1beta1.PageResponse)\n\t\treturn protoreflect.ValueOfMessage(m.ProtoReflect())\n\tdefault:\n\t\tif fd.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: cosmos.auth.v1beta1.QueryAccountsResponse\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message cosmos.auth.v1beta1.QueryAccountsResponse does not contain field %s\", fd.FullName()))\n\t}\n}", "func decodeGRPCConcatResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.ConcatReply)\n\treturn endpoints.ConcatResponse{Rs: reply.Rs}, nil\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_versions_v1_versions_proto_rawDescGZIP(), []int{4}\n}", "func ParseCreateInstanceResponse(rsp *http.Response) (*CreateInstanceResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &CreateInstanceResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 200:\n\t\tvar dest Operation\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON200 = &dest\n\n\t}\n\n\treturn response, nil\n}", "func (*CreateUserResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_sample_proto_rawDescGZIP(), []int{3}\n}", "func FromProto(s *spb.Status) *Status {\n\treturn status.FromProto(s)\n}", "func FromProto(s *spb.Status) *Status {\n\treturn status.FromProto(s)\n}", "func (*CreateResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_engine_proto_rawDescGZIP(), []int{3}\n}", "func CreateCancelInstanceResponse() (response *CancelInstanceResponse) {\n\tresponse = &CancelInstanceResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (*CreateTokenResponse) Descriptor() ([]byte, []int) {\n\treturn file_service_proto_rawDescGZIP(), []int{2}\n}", "func (*CMsgDOTADestroyLobbyResponse) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{258}\n}", "func CreateFromResponse(u url.URL, r http.Response, b []byte) (Representor, error) {\n\n\tct := r.Header.Get(\"Content-Type\")\n\tif ct == \"\" {\n\t\treturn nil, errors.New(\"missing content-type\")\n\t}\n\n\t// TODO: Check the header for Link\n\n\treturn Create(u, ct, b)\n}", "func (o *Command) ValidateCredential(rw io.Writer, req io.Reader) command.Error {\n\trequest := &Credential{}\n\n\terr := json.NewDecoder(req).Decode(&request)\n\tif err != nil {\n\t\tlogutil.LogInfo(logger, CommandName, ValidateCredentialCommandMethod, \"request decode : \"+err.Error())\n\n\t\treturn command.NewValidationError(InvalidRequestErrorCode, fmt.Errorf(\"request decode : %w\", err))\n\t}\n\n\t// we are only validating the VerifiableCredential here, hence ignoring other return values\n\t_, err = verifiable.ParseCredential([]byte(request.VerifiableCredential),\n\t\tverifiable.WithPublicKeyFetcher(verifiable.NewVDRKeyResolver(o.ctx.VDRegistry()).PublicKeyFetcher()),\n\t\tverifiable.WithJSONLDDocumentLoader(o.documentLoader))\n\tif err != nil {\n\t\tlogutil.LogInfo(logger, CommandName, ValidateCredentialCommandMethod, \"validate vc : \"+err.Error())\n\n\t\treturn command.NewValidationError(ValidateCredentialErrorCode, fmt.Errorf(\"validate vc : %w\", err))\n\t}\n\n\tcommand.WriteNillableResponse(rw, nil, logger)\n\n\tlogutil.LogDebug(logger, CommandName, ValidateCredentialCommandMethod, \"success\")\n\n\treturn nil\n}", "func FromProto(s *spb.Status) *Status {\n\treturn &Status{s: proto.Clone(s).(*spb.Status)}\n}", "func (*GeneratedResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_auth_proto_rawDescGZIP(), []int{1}\n}", "func (*AuthResponse) Descriptor() ([]byte, []int) {\n\treturn file_toit_api_auth_proto_rawDescGZIP(), []int{2}\n}", "func (*CreateOrganizationResponse) Descriptor() ([]byte, []int) {\n\treturn file_toit_api_auth_proto_rawDescGZIP(), []int{7}\n}", "func NewCredentialsResponseElement(name string, type_ string, description string, owner string, ownerAccessOnly bool, ) *CredentialsResponseElement {\n\tthis := CredentialsResponseElement{}\n\tthis.Name = name\n\tthis.Type = type_\n\tthis.Description = description\n\tthis.Owner = owner\n\tthis.OwnerAccessOnly = ownerAccessOnly\n\treturn &this\n}", "func (*CreateCertificateV1Response) Descriptor() ([]byte, []int) {\n\treturn file_api_ocp_certificate_api_ocp_certificate_api_proto_rawDescGZIP(), []int{3}\n}", "func (cc *CredentialCreation) Validate() error {\n\tswitch {\n\tcase cc == nil:\n\t\treturn trace.BadParameter(\"credential creation required\")\n\tcase len(cc.Response.Challenge) == 0:\n\t\treturn trace.BadParameter(\"credential creation challenge required\")\n\tcase cc.Response.RelyingParty.ID == \"\":\n\t\treturn trace.BadParameter(\"credential creation relying party ID required\")\n\tcase len(cc.Response.RelyingParty.Name) == 0:\n\t\treturn trace.BadParameter(\"relying party name required\")\n\tcase len(cc.Response.User.Name) == 0:\n\t\treturn trace.BadParameter(\"user name required\")\n\tcase len(cc.Response.User.DisplayName) == 0:\n\t\treturn trace.BadParameter(\"user display name required\")\n\tcase len(cc.Response.User.ID) == 0:\n\t\treturn trace.BadParameter(\"user ID required\")\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (*InitializeResponse) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{52}\n}", "func NewFromGRPC(conn *grpc.ClientConn, log *zap.Logger, timeout time.Duration) (api.Peer, error) {\n\tl := log.Named(`NewFromGRPC`)\n\tp := &peer{conn: conn, log: log.Named(`peer`), timeout: timeout}\n\tif err := p.initEndorserClient(); err != nil {\n\t\tl.Error(`Failed to initialize endorser client`, zap.Error(err))\n\t\treturn nil, errors.Wrap(err, `failed to initialize EndorserClient`)\n\t}\n\treturn p, nil\n}", "func MakeMsgFromResult(result *graphql.Result, msg proto.Message) error {\n\tif err := mapstructure.Decode(result.Data, msg); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func DecodeCreatePDPContextResponse(b []byte) (*CreatePDPContextResponse, error) {\n\tlog.Println(\"DecodeCreatePDPContextResponse is deprecated. use ParseCreatePDPContextResponse instead\")\n\treturn ParseCreatePDPContextResponse(b)\n}", "func (*AuthenticationResponse) Descriptor() ([]byte, []int) {\n\treturn file_box_account_proto_rawDescGZIP(), []int{2}\n}", "func (*CreateUserResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_user_proto_rawDescGZIP(), []int{3}\n}", "func CreateModifyCallRatioResponse() (response *ModifyCallRatioResponse) {\n\tresponse = &ModifyCallRatioResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (*CreateUserResponse) Descriptor() ([]byte, []int) {\n\treturn file_buf_alpha_registry_v1alpha1_user_proto_rawDescGZIP(), []int{2}\n}", "func (*LoginCallbackResponse) Descriptor() ([]byte, []int) {\n\treturn file_pb_authentication_proto_rawDescGZIP(), []int{4}\n}", "func (a *OidcApiService) CreateVerifiableCredentialExecute(r ApiCreateVerifiableCredentialRequest) (*VerifiableCredentialResponse, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tformFiles []formFile\n\t\tlocalVarReturnValue *VerifiableCredentialResponse\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"OidcApiService.CreateVerifiableCredential\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/credentials\"\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\"}\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 = r.createVerifiableCredentialRequestBody\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\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\tlocalVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody))\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 == 400 {\n\t\t\tvar v VerifiableCredentialPrimingResponse\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\tvar v ErrorOAuth2\n\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\tif err != nil {\n\t\t\tnewErr.error = err.Error()\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tnewErr.model = v\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}" ]
[ "0.79458094", "0.76754075", "0.7466945", "0.7264637", "0.66078424", "0.6368274", "0.6345199", "0.633873", "0.6317732", "0.5856386", "0.57786655", "0.5684622", "0.5460006", "0.54394895", "0.5400118", "0.53531575", "0.531271", "0.5247152", "0.524472", "0.5205804", "0.5195482", "0.51779306", "0.5166182", "0.51628965", "0.516256", "0.51596177", "0.51593006", "0.5137958", "0.51320165", "0.5122554", "0.51088524", "0.508564", "0.508438", "0.5080847", "0.5079328", "0.50649154", "0.5052676", "0.50490975", "0.5039413", "0.5037255", "0.5006604", "0.49921644", "0.49734142", "0.49634615", "0.49591395", "0.49579784", "0.49453494", "0.4945206", "0.49159917", "0.4915652", "0.49136463", "0.49131867", "0.49127543", "0.491029", "0.49020386", "0.48835042", "0.48796108", "0.48793593", "0.48792744", "0.48748448", "0.48740092", "0.48734692", "0.48714396", "0.48545232", "0.48427075", "0.48412362", "0.48381045", "0.48322245", "0.48138845", "0.48029992", "0.48020038", "0.47965157", "0.47935605", "0.4793073", "0.47832164", "0.47804025", "0.47804025", "0.47764394", "0.47656634", "0.47655183", "0.47650084", "0.47641796", "0.47610638", "0.4760496", "0.4760422", "0.47575778", "0.47569475", "0.47563034", "0.4754726", "0.4753375", "0.47516158", "0.47462845", "0.47444558", "0.47422102", "0.47415915", "0.47369394", "0.47343937", "0.4734223", "0.47312814", "0.4729802" ]
0.88028467
0
Returns the default Template setter upper
func DefaultTemplateSetup(esClient *elasticsearch.Client, archiveTemplateModifier func(*Template)) TemplateSetup { archiveTemplateModifier(&TasquesArchiveTemplate) return &templateSetupImpl{ esClient: esClient, Templates: []Template{ TasquesQueuesTemplate, TasquesArchiveTemplate, TasquesLocksTemplate, TasquesRecurringTasksTemplate, }, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func templateFunctionGenerateDefault(def, value interface{}) interface{} {\n\tglog.V(log.LevelDebug).Infof(\"default: default '%v', value '%v'\", def, value)\n\n\tif value == nil {\n\t\tvalue = def\n\t}\n\n\tglog.V(log.LevelDebug).Infof(\"default: value '%v'\", value)\n\n\treturn value\n}", "func templateFunctionUpper(value string) string {\n\treturn strings.ToUpper(value)\n}", "func (vd *Verb_Delegate) GlobalsTemplate() *template.Template {\n\treturn delegate_method_template\n}", "func (r *AssetRendering) Template() {\n\tv := \"template\"\n\tr.Value = &v\n}", "func (e *Event) Template(key string) Template {\n\treturn e.Templates[strings.ToUpper(key)]\n}", "func (self *ScriptDef) makeDefault() error {\n if def, err := self.toInterfaceVal(self.DefaultStr); err != nil {\n return err\n } else {\n self.Default = def\n }\n return nil\n}", "func (EntityStateChanged) DefaultTemplates() (subject, html, text string) {\n\treturn entityStateChangedSubject, \"\", entityStateChangedText\n}", "func (t *TRoot) Template() *Template {\n\treturn t.Clone().template\n}", "func DefaultOrOverride(generator map[string]interface{}) func(configVar *providerconfig.GlobalSecretKeySelector, key string) (string, error) {\n\treturn func(configVar *providerconfig.GlobalSecretKeySelector, key string) (string, error) {\n\t\tif val, ok := generator[key]; ok {\n\t\t\tif err, ok := val.(error); ok {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\treturn val.(string), nil\n\t\t}\n\t\treturn key + \"-value\", nil\n\t}\n}", "func (o ApiOperationTemplateParameterOutput) DefaultValue() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApiOperationTemplateParameter) *string { return v.DefaultValue }).(pulumi.StringPtrOutput)\n}", "func NewCapitalizationWithDefaults() *Capitalization {\n this := Capitalization{}\n return &this\n}", "func Default(def string, value interface{}) string {\n\tif set, ok := template.IsTrue(value); ok && set {\n\t\treturn fmt.Sprint(value)\n\t}\n\treturn def\n}", "func NewTemplateDefault() *gomol.Template {\n\ttpl, _ := gomol.NewTemplate(\"[{{color}}{{ucase .LevelName}}{{reset}}] {{.Message}}\")\n\treturn tpl\n}", "func SetTemplate(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"URL PATH - %s!\", r.URL.Path[1:])\n}", "func T(name string) *template.Template {\n\treturn t(\"_base.html\", name)\n}", "func (f Base) Default() interface{} {\n\treturn f.defaultValue\n}", "func (p applicationPackager) defaultTemplate(templateName string, data map[string]interface{}) (template.HTML, error) {\n\n\tfmap := p.templateFMap()\n\treturn p.xmlTemplateWithFuncs(templateName, data, fmap)\n}", "func Default() render.HTMLRender {\n\treturn New(\"templates\", \"text/html; charset=utf-8\")\n}", "func UserTemplate(t *html5.Template) userOption {\n\treturn func(u *User) {\n\t\tu.template = t\n\t}\n}", "func (_m *ICreate) Template(language string, name string) {\n\t_m.Called(language, name)\n}", "func (p ByName) Setter() Setter { return p.setter }", "func SetTemplatePath(path string) {\n\tDefault.SetTemplatePath(path)\n}", "func Base_() HTML {\n return Base(nil)\n}", "func SetDefault(def Definition) {\n\tcrypt.SetDefault(def)\n}", "func (vd *Verb_Index) GlobalsTemplate() *template.Template {\n\treturn index_method_template\n}", "func (m *DirectorySetting) SetTemplateId(value *string)() {\n err := m.GetBackingStore().Set(\"templateId\", value)\n if err != nil {\n panic(err)\n }\n}", "func (rcv *impl) SetFormat(format string) Interface { rcv.TplText = format; return rcv }", "func setterName(typeName string) string {\n\treturn fmt.Sprintf(\"Set%s\", accessorName(typeName))\n}", "func (m *TemplateParameter) SetJsonDefaultValue(value *string)() {\n err := m.GetBackingStore().Set(\"jsonDefaultValue\", value)\n if err != nil {\n panic(err)\n }\n}", "func (r *K3sControlPlaneTemplate) Default() {\n\tinfrabootstrapv1.DefaultK3sConfigSpec(&r.Spec.Template.Spec.K3sConfigSpec)\n\n\tr.Spec.Template.Spec.RolloutStrategy = defaultRolloutStrategy(r.Spec.Template.Spec.RolloutStrategy)\n}", "func (rule *NamespacesTopicsSubscriptionsRule) defaultImpl() { rule.defaultAzureName() }", "func (c *Config) Template(src string) *Config {\n\tc.data = src\n\treturn c\n}", "func (subscription *NamespacesTopicsSubscription) defaultImpl() { subscription.defaultAzureName() }", "func (field Field) DefaultValue() string {\n\tresult, _ := field.TagGet(\"default\")\n\treturn result\n}", "func (*Prefix) Default() string { return defaultPrefix }", "func formatTemplate() template.FuncMap {\n\treplacer := strings.NewReplacer(\"-\", \"\", \"*\", \"\", \"/\", \"\", \":\", \"\")\n\treturn template.FuncMap{\n\n\t\t\"clean\": func(v string) string {\n\t\t\treturn replacer.Replace(v)\n\t\t},\n\n\t\t\"upper\": func(str string) string {\n\t\t\treturn strings.Title(str)\n\t\t},\n\t}\n}", "func (o ChangeSetOutput) TemplateBody() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ChangeSet) pulumi.StringPtrOutput { return v.TemplateBody }).(pulumi.StringPtrOutput)\n}", "func (UserRequested) TemplateName() string { return \"user_requested\" }", "func (UserRequested) TemplateName() string { return \"user_requested\" }", "func (m *TemplateParameter) GetJsonDefaultValue()(*string) {\n val, err := m.GetBackingStore().Get(\"jsonDefaultValue\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func defaultTemplateDir() string {\n return filepath.Join(\"contrib\", \"templates\", \"default\")\n}", "func (m *Store) SetDefaultLanguageTag(value *string)() {\n m.defaultLanguageTag = value\n}", "func (e Environment) Overridef(name string, format string, a ...interface{}) {\n\te[fmt.Sprintf(\"%s.override\", name)] = fmt.Sprintf(format, a...)\n}", "func (m pSortedDefault) Underlying() *models.Method {\n\treturn m.Method\n}", "func (loader riceTemplateLoader) Abs(base, name string) string {\n\t// TODO make sure we can ignore `base` argument\n\treturn name\n}", "func (UserRequested) DefaultTemplates() (subject, html, text string) {\n\treturn userRequestedSubject, \"\", userRequestedText\n}", "func (UserRequested) DefaultTemplates() (subject, html, text string) {\n\treturn userRequestedSubject, \"\", userRequestedText\n}", "func (store *ConfigurationStore) defaultImpl() { store.defaultAzureName() }", "func (rule *NamespacesEventhubsAuthorizationRule) defaultImpl() { rule.defaultAzureName() }", "func (e *Common) Default() string {\n\tif e.Def == nil {\n\t\treturn \"\"\n\t}\n\tif e.Def.Choice != \"\" {\n\t\treturn e.Def.Choice\n\t} else if e.Def.Type != \"\" {\n\t\t// Type is still used by the default element in collation.\n\t\treturn e.Def.Type\n\t}\n\treturn \"\"\n}", "func (m *TemplateParameter) GetBackingStore()(ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStore) {\n return m.backingStore\n}", "func (m *ManagementTemplateStep) SetManagementTemplate(value ManagementTemplateable)() {\n err := m.GetBackingStore().Set(\"managementTemplate\", value)\n if err != nil {\n panic(err)\n }\n}", "func (h HomepageView) Template() string {\n\treturn homepageTemplate\n}", "func (machine *VirtualMachine) defaultImpl() { machine.defaultAzureName() }", "func SetDefault(target interface{}) error {\n\tdecoder := &Decoder{\n\t\tTagName: \"default\",\n\t\tConverter: &Converter{\n\t\t\tTagName: \"default\",\n\t\t},\n\t\tProvider: &DefaultProvider{},\n\t}\n\n\treturn decoder.Decode(target)\n}", "func (record *PrivateDnsZonesSRVRecord) defaultImpl() { record.defaultAzureName() }", "func (rule *NamespacesEventhubsAuthorizationRule) Default() {\n\trule.defaultImpl()\n\tvar temp any = rule\n\tif runtimeDefaulter, ok := temp.(genruntime.Defaulter); ok {\n\t\truntimeDefaulter.CustomDefault()\n\t}\n}", "func (account *DatabaseAccount) defaultImpl() { account.defaultAzureName() }", "func (o TransformationOutput) Template() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Transformation) pulumi.StringPtrOutput { return v.Template }).(pulumi.StringPtrOutput)\n}", "func (database *SqlDatabase) defaultImpl() { database.defaultAzureName() }", "func SetDefault(i defInd) Asserter {\n\t// pkg lvl lock to allow only one pkg client call this at the time\n\tmu.Lock()\n\tdefer mu.Unlock()\n\n\t// to make this fully thread safe the def var should be atomic, BUT it\n\t// would be owerkill. We need only defaults to be set at once.\n\tdef = i\n\treturn defAsserter[i]\n}", "func (ruleset *DnsForwardingRuleset) defaultImpl() { ruleset.defaultAzureName() }", "func NewTemplateRepoInfoSetter(user *authclient.UserDataAttributes) TemplateRepoInfoSetter {\n\treturn func(config Config) Config {\n\t\tif user.FeatureLevel != nil && *user.FeatureLevel != \"internal\" {\n\t\t\treturn config\n\t\t}\n\t\tuserContext := user.ContextInformation\n\t\tif tc, found := userContext[\"tenantConfig\"]; found {\n\t\t\tif tenantConfig, ok := tc.(map[string]interface{}); ok {\n\t\t\t\tfind := func(key string) string {\n\t\t\t\t\tif rawValue, found := tenantConfig[key]; found {\n\t\t\t\t\t\tif value, ok := rawValue.(string); ok {\n\t\t\t\t\t\t\treturn value\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn \"\"\n\t\t\t\t}\n\t\t\t\tconfig.TemplatesRepo = find(\"templatesRepo\")\n\t\t\t\tconfig.TemplatesRepoBlob = find(\"templatesRepoBlob\")\n\t\t\t\tconfig.TemplatesRepoDir = find(\"templatesRepoDir\")\n\t\t\t}\n\t\t}\n\t\treturn config\n\t}\n}", "func (this *Group) Get(name string) *template.Template {\n\treturn this.t.Lookup(name)\n}", "func (me TxsdSpace) IsDefault() bool { return me.String() == \"default\" }", "func (trs *Transformations) Template() (trans *Transformation) {\n\ttrans = nil\n\n\tif trs != nil {\n\t\ttrans = &trs.Tmpl\n\t}\n\n\treturn trans\n}", "func (me TrestrictionType) IsDefault() bool { return me.String() == \"default\" }", "func StringFormatTemplate(value string) StringFormatAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"template\"] = value\n\t}\n}", "func TestDefaultTemplate(t *testing.T) {\n\ttmpl := Templates[\"default.html\"]\n\tif tmpl == nil {\n\t\tt.Errorf(\"Cannot find default template\")\n\t}\n}", "func (m pDefaultGet) Underlying() *models.Method {\n\treturn m.Method\n}", "func (p ByName) InitialValue() string { return p.initialValue }", "func (me *TGlyphOrientationVerticalValueType) Set(s string) { (*xsdt.String)(me).Set(s) }", "func (f *Funcs) alterDefault(s string) string {\n\tswitch f.driver {\n\tcase \"postgres\":\n\t\tif m := postgresDefaultCastRE.FindStringSubmatch(s); m != nil {\n\t\t\treturn m[1]\n\t\t}\n\tcase \"mysql\":\n\t\tif v := strings.ToUpper(s); v == \"CURRENT_TIMESTAMP()\" {\n\t\t\treturn \"CURRENT_TIMESTAMP\"\n\t\t}\n\tcase \"sqlite3\":\n\t\tif !sqliteDefaultNeedsParenRE.MatchString(s) {\n\t\t\treturn \"(\" + s + \")\"\n\t\t}\n\t}\n\treturn s\n}", "func (rule *NamespacesTopicsSubscriptionsRule) Default() {\n\trule.defaultImpl()\n\tvar temp any = rule\n\tif runtimeDefaulter, ok := temp.(genruntime.Defaulter); ok {\n\t\truntimeDefaulter.CustomDefault()\n\t}\n}", "func (conf blah) SetDef(key string, def string) {\n\tviper.SetDefault(key, def)\n}", "func (vl VerbLevel) Upper() string {\n\treturn strings.ToUpper(vl.Name())\n}", "func (i *Internationalization) Default() language.Tag { return i.fallback }", "func (t TextNode) Template() string {\n\treturn string(t)\n}", "func (tb *TriggerBinding) SetDefaults(ctx context.Context) {}", "func (uc *UserCreate) defaults() {\n\tif _, ok := uc.mutation.Name(); !ok {\n\t\tv := user.DefaultName\n\t\tuc.mutation.SetName(v)\n\t}\n}", "func lateTemplateMutator(mctx blueprint.TopDownMutatorContext) {\n\tmodule := mctx.Module()\n\n\tif e, ok := module.(enableable); ok {\n\t\tif isEnabled(e) {\n\t\t\tapplyLateTemplates(mctx)\n\t\t}\n\t}\n}", "func (u *User) Template(t string) (string, error) {\n\ttmpl := template.Must(template.New(\"\").Parse(t))\n\tvar b bytes.Buffer\n\tif err := tmpl.Execute(&b, u); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"tmpl execute\")\n\t}\n\treturn b.String(), nil\n}", "func (dt *Slick) HTMLTemplate() string {\n\treturn htmlTemplate\n}", "func GetTemplatePath() string {\n\treturn Default.GetTemplatePath()\n}", "func (pol *PolicyTestKind) SetTemplate(result *map[string]interface{}, spec *TestSpec) error {\n\tgetTemplate := func(tmpl string) (*bytes.Buffer, error) {\n\t\tt, err := template.New(\"\").Parse(tmpl)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcontent := new(bytes.Buffer)\n\t\terr = t.Execute(content, spec)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn content, nil\n\t}\n\n\tfor k, v := range pol.template {\n\t\t// If any key was already set we do not need to overwrite it.\n\t\t// This is in use on L7 when a port is always needed\n\t\tif _, ok := (*result)[k]; ok {\n\t\t\tcontinue\n\t\t}\n\t\ttmpl, err := getTemplate(v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar data interface{}\n\t\terr = json.Unmarshal(tmpl.Bytes(), &data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t(*result)[k] = data\n\t}\n\treturn nil\n}", "func (o *RenderTemplate) Identity() elemental.Identity {\n\n\treturn RenderTemplateIdentity\n}", "func (element String) DefaultValue() any {\n\treturn element.Default\n}", "func (p Property) Base() string {\n\tif p.Right != nil {\n\t\treturn p.Right.Name\n\t} else {\n\t\treturn p.Left.Name\n\t}\n}", "func (policy *StorageAccountsManagementPolicy) Default() {\n\tpolicy.defaultImpl()\n\tvar temp any = policy\n\tif runtimeDefaulter, ok := temp.(genruntime.Defaulter); ok {\n\t\truntimeDefaulter.CustomDefault()\n\t}\n}", "func (o ApiOperationResponseHeaderOutput) DefaultValue() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApiOperationResponseHeader) *string { return v.DefaultValue }).(pulumi.StringPtrOutput)\n}", "func (b *Builder) ToUpper() *Builder {\n\tb.p.RegisterTransformation(impl.ToUpper())\n\treturn b\n}", "func (policy *ServersConnectionPolicy) Default() {\n\tpolicy.defaultImpl()\n\tvar temp any = policy\n\tif runtimeDefaulter, ok := temp.(genruntime.Defaulter); ok {\n\t\truntimeDefaulter.CustomDefault()\n\t}\n}", "func DefaultSettigs() Settings {\n\treturn settings{\n\t\tflowFuncPostfix: \"Func\",\n\t\tlocalInterfaceVarname: \"service\",\n\t\timplFieldPostfix: \"FieldFunc\",\n\t\tnewImplFuncPrefix: \"New\",\n\t\timplPostfix: \"Impl\",\n\t\tinterfaceNamePostfix: \"Service\",\n\t}\n}", "func (setting *MongodbDatabaseCollectionThroughputSetting) Default() {\n\tsetting.defaultImpl()\n\tvar temp any = setting\n\tif runtimeDefaulter, ok := temp.(genruntime.Defaulter); ok {\n\t\truntimeDefaulter.CustomDefault()\n\t}\n}", "func (t *TRoot) Name() string {\n\treturn t.template.Name\n}", "func (m pDefaultGet) Extend(fnct func(m.UserSet) m.UserData) pDefaultGet {\n\treturn pDefaultGet{\n\t\tMethod: m.Method.Extend(fnct),\n\t}\n}", "func (EntityStateChanged) TemplateName() string { return \"entity_state_changed\" }", "func NewCapitalization() *Capitalization {\n this := Capitalization{}\n return &this\n}", "func (r *Unit) Default() {\n\tunitlog.Info(\"default\", \"name\", r.Name)\n\n\t// TODO(user): fill in your defaulting logic.\n\t// 这里可以加入一些Unit 结构体对象初始化之前的一些默认的逻辑,比如给一些字段填充默认值\n\n\t// default replicas set to 1\n\tunitlog.Info(\"default\", \"name\", r.Name)\n\n\tif r.Spec.Replicas == nil {\n\t\tdefaultReplicas := int32(1)\n\t\tr.Spec.Replicas = &defaultReplicas\n\t}\n\n\t// add default selector label\n\tlabelMap := make(map[string]string, 1)\n\tlabelMap[\"app\"] = r.Name\n\tr.Spec.Selector = &metav1.LabelSelector{\n\t\tMatchLabels: labelMap,\n\t}\n\n\t// add default template label\n\tr.Spec.Template.Labels = labelMap\n\n\tr.Status.LastUpdateTime = metav1.Now()\n\n\t// 当然,还可以根据需求加一些适合在初始化时做的逻辑,例如为pod注入sidecar\n\t// ...\n\n}", "func (vd *Verb_Iterate) GlobalsTemplate() *template.Template {\n\treturn iterate_method_template\n}" ]
[ "0.523974", "0.51359373", "0.5011097", "0.49829936", "0.49430534", "0.4891433", "0.484189", "0.478802", "0.47771356", "0.47767422", "0.47766063", "0.473133", "0.47030216", "0.4680616", "0.46647787", "0.46492925", "0.46391362", "0.4630544", "0.46262336", "0.46256065", "0.459022", "0.4578867", "0.4577664", "0.45356885", "0.45216367", "0.45141158", "0.45125723", "0.4509638", "0.45089823", "0.4500062", "0.44973025", "0.448074", "0.44737852", "0.44624373", "0.44577876", "0.44434035", "0.44323087", "0.44094867", "0.44094867", "0.44082063", "0.44065818", "0.44040745", "0.4403927", "0.44010103", "0.43955055", "0.4387352", "0.4387352", "0.43861613", "0.4383674", "0.43716925", "0.4362265", "0.4358731", "0.43583873", "0.43463418", "0.43361628", "0.43313473", "0.43278396", "0.43265384", "0.43253544", "0.43239745", "0.43212658", "0.4315825", "0.43137312", "0.4306455", "0.4281825", "0.42752582", "0.4264617", "0.42503655", "0.42488852", "0.42435348", "0.42389622", "0.42381993", "0.42313552", "0.42302483", "0.42263544", "0.4225627", "0.4220432", "0.4216895", "0.42161915", "0.42158097", "0.42126083", "0.42058575", "0.4205834", "0.41938463", "0.41853347", "0.41763726", "0.41699773", "0.4169765", "0.4166263", "0.41657352", "0.41582993", "0.41580978", "0.41576332", "0.4152813", "0.41514218", "0.41513094", "0.41507545", "0.4133782", "0.4133703", "0.41335434" ]
0.4633425
17
Name implements part of the Plugin interface.
func (p *ProtocGenGrpcNode) Name() string { return "grpc:grpc-node:protoc-gen-grpc-node" }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (Plugin) Name() string { return pluginName }", "func (p *Plugin) Name() string {\n\treturn p.PluginObj.Name\n}", "func (p *Plugin) Name() string {\n\treturn \"golang\"\n}", "func (p *GenericPlugin) Name() string {\n\n\tswitch p.state {\n\tcase stateNotLoaded:\n\t\treturn path.Base(p.filename)\n\tdefault:\n\t}\n\n\treturn p.name()\n}", "func (p *SimplePlugin) Name() string {\n\treturn p.name\n}", "func (s *Plugin) Name() string {\n\treturn \"simple\"\n}", "func (s *Plugin) Name() string {\n\treturn PluginName\n}", "func (p *JavaPlugin) Name() string {\n\treturn \"builtin:java\"\n}", "func (p Plugin) GetName() string {\n\treturn Name\n}", "func (r Plugin) GetName() string {\n\treturn Name\n}", "func (p *servicePlugin) Name() string { return \"protorpc\" }", "func (p *GogoPlugin) Name() string {\n\treturn \"gogo:protobuf:protoc-gen-\" + p.variant\n}", "func (p *Plugin) Name() string {\n\treturn \"gump\"\n}", "func (self *S3Plugin) Name() string {\n\treturn S3PluginName\n}", "func (plugin *NetworkPlugin) Name() string {\n\treturn DefaultPluginName\n}", "func (plugin *Auth) Name() string {\n\treturn plugin.name\n}", "func (p *ColorPlugin) Name() string {\n\treturn \"Color\"\n}", "func (p *IntelPlugin) Name() string {\n\treturn p.PluginName\n}", "func (*Plugin) Name() string {\n\treturn \"ds-cosmos\"\n}", "func (p *ProtocGenGoPlugin) Name() string {\n\treturn ProtocGenGoPluginName\n}", "func (p *CsharpPlugin) Name() string {\n\treturn \"builtin:csharp\"\n}", "func (g GeoIP) Name() string { return pluginName }", "func (p *ReminderPlugin) Name() string {\n\treturn \"Reminder\"\n}", "func (m KafkaPlugin) Name() string {\n\treturn \"plugin-kafka-publish\"\n}", "func (p *Plugin) GetName() string {\n\treturn p.Name\n}", "func (p Plugin) GetName() string {\n\treturn \"notify\"\n}", "func (eng *Engine) Name() string {\n\treturn \"JS-Plugin-Engine\"\n}", "func (pp *protocPlugin) Name() string {\n\treturn \"kitex-internal\"\n}", "func (p *QueryValidatePlugin) Name() string {\n\treturn \"atlas-query-validate\"\n}", "func (p *RangePlugin) Name() string {\n\treturn \"range\"\n}", "func (p *YouTubeJoinPlugin) Name() string {\n\treturn \"YouTubeJoin\"\n}", "func (*ConnectPlugin) Name() string {\n\treturn \"connect-to-list-plugin\"\n}", "func (d *RemovePodsViolatingInterPodAntiAffinity) Name() string {\n\treturn PluginName\n}", "func (plugin *recommended) Name() string {\n\treturn \"Recommended\"\n}", "func (*I2PGatePlugin) Name() string {\n\treturn \"fwd-i2pgate\"\n}", "func (n *piName) Name() string {\n\treturn n.name\n}", "func (a *ActionPlugin) GetName() string {\n\treturn a.Name\n}", "func (b backgroundPlugin) Name() string {\n\treturn \"auth\"\n}", "func (p *plug) Name() string { return \"dnsfilter\" }", "func (p *MongoPlugin) Name() string {\n\treturn \"bom\"\n}", "func (pp *PerfPlugin) Name() string { return \"perf\" }", "func (g *Guessit) Name() string {\n\treturn moduleName\n}", "func (p Packet) Name() (name string) {\n\t// todo: think of ways to make this not a compiled in hack\n\t// todo: collectd 4 uses different patterns for some plugins\n\t// https://collectd.org/wiki/index.php/V4_to_v5_migration_guide\n\tswitch p.Plugin {\n\tcase \"df\":\n\t\tname = fmt.Sprintf(\"df_%s_%s\", p.PluginInstance, p.TypeInstance)\n\tcase \"interface\":\n\t\tname = fmt.Sprintf(\"%s_%s\", p.Type, p.PluginInstance)\n\tcase \"load\":\n\t\tname = \"load\"\n\tcase \"memory\":\n\t\tname = fmt.Sprintf(\"memory_%s\", p.TypeInstance)\n\tdefault:\n\t\tname = fmt.Sprintf(\"%s_%s_%s_%s\", p.Plugin, p.PluginInstance, p.Type, p.TypeInstance)\n\t}\n\treturn name\n}", "func (e *EndComponent) Name() string {\n\treturn \"name\"\n}", "func (*unifinames) Name() string { return \"unifi-names\" }", "func (o ApplicationSpecSourcePluginEnvOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ApplicationSpecSourcePluginEnv) string { return v.Name }).(pulumi.StringOutput)\n}", "func (meta *MetaAI) Name() string {\n\treturn \"MetaAI\"\n}", "func (w *WebHook) Name() string {\n\treturn moduleName\n}", "func (ipecho) Name() string { return \"IPEcho\" }", "func (o ApplicationOperationSyncSourcePluginEnvOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ApplicationOperationSyncSourcePluginEnv) string { return v.Name }).(pulumi.StringOutput)\n}", "func (mg MessageHandler) Name() string {\n\treturn nameFromFunc(mg)\n}", "func (p ByName) Name() string { return p.name }", "func (o ApplicationStatusHistorySourcePluginEnvOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ApplicationStatusHistorySourcePluginEnv) string { return v.Name }).(pulumi.StringOutput)\n}", "func (dlmg RawMessageHandler) Name() string {\n\treturn nameFromFunc(dlmg)\n}", "func (w *Wechaty) Name() string {\n\tif len(w.Option.name) != 0 {\n\t\treturn w.Option.name\n\t}\n\treturn \"wechaty\"\n}", "func (p ProjectInit) Name() string {\n\treturn string(p)\n}", "func (o *PluginMount) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Name\n}", "func (i *Interface) Name() string {\n\treturn name\n}", "func (o *EditorPlugin) GetPluginName() gdnative.String {\n\t//log.Println(\"Calling EditorPlugin.GetPluginName()\")\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(\"EditorPlugin\", \"get_plugin_name\")\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 (p *PluginConfig) PluginName() string {\n\tif p == nil {\n\t\treturn \"\"\n\t}\n\tif p.Plugin != \"\" {\n\t\treturn p.Plugin\n\t}\n\tif p.Name != \"\" {\n\t\treturn p.Name\n\t}\n\tif p.Remote != \"\" {\n\t\treturn p.Remote\n\t}\n\treturn \"\"\n}", "func (o MixinOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v Mixin) *string { return v.Name }).(pulumi.StringPtrOutput)\n}", "func (p provider) Name() string {\n\treturn p.name\n}", "func (obj *script) Name() string {\n\treturn obj.name\n}", "func (g *generator) Name() string {\n\treturn g.typeName\n}", "func (n *CommandNode) Name() string { return n.name }", "func (fc *FooCommand) Name() string {\n\treturn \"foo\"\n}", "func (cmd *Command) Name() string {\n\treturn strings.SplitN(cmd.Names, \",\", 2)[0]\n}", "func (p *HelloWorld) Name() string {\n\treturn \"demo.HelloWorld\"\n}", "func(t *TargImp) Name() string {\n\treturn t.name\n}", "func (p *Provider) Name() string {\n\treturn p.name\n}", "func (g *GenerateKeySubcommand) Name() string {\n\treturn CmdGenerate\n}", "func (c Sub) Name() string {\n\treturn \"SUB\"\n}", "func Name() string {\n\treturn types.SubModuleName\n}", "func Name() string {\n\treturn types.SubModuleName\n}", "func Name() string {\n\treturn types.SubModuleName\n}", "func Name() string {\n\treturn types.SubModuleName\n}", "func (p *PublisherMunger) Name() string { return \"publisher\" }", "func (g Gossiper) Name() string {\n\treturn g.name\n}", "func (l *Loader) Name() string { return l.cfg.Name }", "func (cmd *CLI) Name() string {\n\tvar name string\n\tif cmd.parent != nil {\n\t\tname = strings.Join([]string{cmd.parent.Name(), cmd.name}, \" \")\n\t} else {\n\t\tname = cmd.name\n\t}\n\treturn name\n}", "func (o ApplicationStatusSyncComparedToSourcePluginEnvOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ApplicationStatusSyncComparedToSourcePluginEnv) string { return v.Name }).(pulumi.StringOutput)\n}", "func (n NamedComponents) Name() string {\n\treturn n.uniqueComponent\n}", "func (*visibilityExtension) Name() string {\n\treturn _extName\n}", "func (v *Plugin_Goodbye_Args) MethodName() string {\n\treturn \"goodbye\"\n}", "func (FranceTV) Name() string { return \"francetv\" }", "func (fp MockProvider) Name() string {\n\treturn fp.faux.Name()\n}", "func (ifce *Interface) Name() string {\n\treturn ifce.name\n}", "func (ifce *Interface) Name() string {\n\treturn ifce.name\n}", "func (o ApplicationStatusOperationStateOperationSyncSourcePluginEnvOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ApplicationStatusOperationStateOperationSyncSourcePluginEnv) string { return v.Name }).(pulumi.StringOutput)\n}", "func (p *Prometheus) PluginName() string {\n\treturn \"prometheus\"\n}", "func (fi *FeatureImpl) Name() string {\n\treturn fi.name\n}", "func (r *namespaceImpl) Name(p graphql.ResolveParams) (string, error) {\n\tnsp := p.Source.(*corev3.Namespace)\n\treturn nsp.Metadata.Name, nil\n}", "func (c *Command) Name() string {\n\tname := c.UsageLine\n\ti := strings.Index(name, \" \")\n\tif i >= 0 {\n\t\tname = name[:i]\n\t}\n\treturn name\n}", "func (c *Command) Name() string {\n\tname := c.UsageLine\n\ti := strings.Index(name, \" \")\n\tif i >= 0 {\n\t\tname = name[:i]\n\t}\n\treturn name\n}", "func (c *Command) Name() string {\n\tname := c.UsageLine\n\ti := strings.Index(name, \" \")\n\tif i >= 0 {\n\t\tname = name[:i]\n\t}\n\treturn name\n}", "func (f *FormatGeoFormat) Name() string {\n\treturn \"formatgeo\"\n}", "func (t *LogProviderHandler) Name() string {\n\treturn LogProvider\n}", "func (e *Exporter) Name() string {\n\treturn e.name\n}", "func (o RegistryTaskBaseImageTriggerOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RegistryTaskBaseImageTrigger) string { return v.Name }).(pulumi.StringOutput)\n}", "func (p *Provider) Name() string {\n\treturn p.internalName\n}", "func Name(v interface{}) string {\n\treturn New(v).Name()\n}" ]
[ "0.8802937", "0.8218319", "0.8196202", "0.8150867", "0.80918956", "0.7986361", "0.79730093", "0.7800767", "0.77767634", "0.7768216", "0.7708957", "0.76781195", "0.76700634", "0.76645356", "0.762978", "0.76037997", "0.7589927", "0.758337", "0.75551456", "0.75527585", "0.7532492", "0.75296223", "0.75231636", "0.74902964", "0.74890465", "0.74819434", "0.7432087", "0.74095154", "0.7373317", "0.72778165", "0.72102606", "0.7202173", "0.717849", "0.7086041", "0.7070266", "0.7055522", "0.7028784", "0.70132625", "0.69933563", "0.695655", "0.6900011", "0.68966544", "0.68813574", "0.687985", "0.6873878", "0.683888", "0.6811884", "0.67873657", "0.678617", "0.6776454", "0.6775421", "0.6772807", "0.67020404", "0.6692428", "0.6656472", "0.6652728", "0.66459084", "0.6634473", "0.6633387", "0.66162527", "0.6613623", "0.6609758", "0.660828", "0.660454", "0.6591793", "0.65888816", "0.6575704", "0.65685993", "0.6565315", "0.65586895", "0.6557295", "0.6554982", "0.6553673", "0.6553673", "0.6553673", "0.6553673", "0.65483904", "0.65480113", "0.65468925", "0.6546881", "0.65448606", "0.6544612", "0.65441924", "0.6540537", "0.65202534", "0.65200037", "0.6517329", "0.6517329", "0.65125287", "0.6511383", "0.6510284", "0.65000033", "0.6499929", "0.6499929", "0.6499929", "0.649885", "0.6498509", "0.6491848", "0.64909273", "0.6489901", "0.6486426" ]
0.0
-1
Configure implements part of the Plugin interface.
func (p *ProtocGenGrpcNode) Configure(ctx *protoc.PluginContext) *protoc.PluginConfiguration { if !protoc.HasServices(ctx.ProtoLibrary.Files()...) { return nil } return &protoc.PluginConfiguration{ Label: label.New("build_stack_rules_proto", "plugin/grpc/grpc-node", "protoc-gen-grpc-node"), Outputs: protoc.FlatMapFiles( grpcGeneratedFileName(ctx.Rel), protoc.HasService, ctx.ProtoLibrary.Files()..., ), Options: ctx.PluginConfig.GetOptions(), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Client) Configure(configuration map[string]interface{}) plugin.BasicError {\n\tvar response plugin.BasicError\n\terr := c.client.Call(\"Plugin.Configure\", configuration, &response)\n\tif err != nil {\n\t\tresponse = *plugin.NewBasicError(err)\n\t}\n\treturn response\n}", "func (s *Server) Configure(args map[string]interface{}, response *plugin.BasicError) error {\n\t*response = s.provider.Configure(args)\n\treturn nil\n}", "func (format *MetadataCopy) Configure(conf core.PluginConfigReader) {\n}", "func (format *Move) Configure(conf core.PluginConfigReader) {\n}", "func (cons *Proxy) Configure(conf core.PluginConfigReader) error {\n\tcons.SimpleConsumer.Configure(conf)\n\n\tcons.protocol, cons.address = tnet.ParseAddress(conf.GetString(\"Address\", \":5880\"), \"tcp\")\n\tif cons.protocol == \"udp\" {\n\t\tconf.Errors.Pushf(\"UDP is not supported\")\n\t}\n\n\tcons.delimiter = tstrings.Unescape(conf.GetString(\"Delimiter\", \"\\n\"))\n\tcons.offset = conf.GetInt(\"Offset\", 0)\n\tcons.flags = tio.BufferedReaderFlagEverything\n\n\tpartitioner := strings.ToLower(conf.GetString(\"Partitioner\", \"delimiter\"))\n\tswitch partitioner {\n\tcase \"binary_be\":\n\t\tcons.flags |= tio.BufferedReaderFlagBigEndian\n\t\tfallthrough\n\n\tcase \"binary\", \"binary_le\":\n\t\tswitch conf.GetInt(\"Size\", 4) {\n\t\tcase 1:\n\t\t\tcons.flags |= tio.BufferedReaderFlagMLE8\n\t\tcase 2:\n\t\t\tcons.flags |= tio.BufferedReaderFlagMLE16\n\t\tcase 4:\n\t\t\tcons.flags |= tio.BufferedReaderFlagMLE32\n\t\tcase 8:\n\t\t\tcons.flags |= tio.BufferedReaderFlagMLE64\n\t\tdefault:\n\t\t\tconf.Errors.Pushf(\"Size only supports the value 1,2,4 and 8\")\n\t\t}\n\n\tcase \"fixed\":\n\t\tcons.flags |= tio.BufferedReaderFlagMLEFixed\n\t\tcons.offset = conf.GetInt(\"Size\", 1)\n\n\tcase \"ascii\":\n\t\tcons.flags |= tio.BufferedReaderFlagMLE\n\n\tcase \"delimiter\":\n\t\t// Nothing to add\n\n\tdefault:\n\t\tconf.Errors.Pushf(\"Unknown partitioner: %s\", partitioner)\n\t}\n\n\treturn conf.Errors.OrNil()\n}", "func (co *Coordinator) Configure(conf *core.Config) {\n\t// Make sure the log is printed to stderr if we are stuck here\n\tlogFallback := time.AfterFunc(time.Duration(3)*time.Second, func() {\n\t\ttlog.SetWriter(os.Stderr)\n\t})\n\tdefer logFallback.Stop()\n\n\t// Initialize the plugins in the order of routers > producers > consumers\n\t// to match the order of reference between the different types.\n\n\tco.configureRouters(conf)\n\tco.configureProducers(conf)\n\tco.configureConsumers(conf)\n\n\t// As consumers might create new fallback router this is the first position\n\t// where we can add the wildcard producers to all streams. No new routers\n\t// created beyond this point must use StreamRegistry.AddWildcardProducersToRouter.\n\n\tcore.StreamRegistry.AddAllWildcardProducersToAllRouters()\n}", "func (cons *RedisSub) Configure(conf core.PluginConfig) error {\n\terr := cons.ConsumerBase.Configure(conf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcons.password = conf.GetString(\"Password\", \"\")\n\tcons.address, cons.protocol = shared.ParseAddress(conf.GetString(\"Address\", \":6379\"))\n\tcons.channel = conf.GetString(\"Channel\", \"defaultValue\")\n\tcons.sequence = new(uint64)\n\n\treturn nil\n}", "func (p *GogoPlugin) Configure(ctx *protoc.PluginContext) *protoc.PluginConfiguration {\n\tif !p.shouldApply(ctx.ProtoLibrary) {\n\t\treturn nil\n\t}\n\n\tgrpcOptions := p.grpcOptions(ctx.Rel, ctx.PluginConfig, ctx.ProtoLibrary)\n\treturn &protoc.PluginConfiguration{\n\t\tLabel: label.New(\"build_stack_rules_proto\", \"plugin/gogo/protobuf\", \"protoc-gen-\"+p.variant),\n\t\tOutputs: p.outputs(ctx.ProtoLibrary),\n\t\tOptions: append(grpcOptions, ctx.PluginConfig.GetOptions()...),\n\t}\n}", "func (cons *LogConsumer) Configure(conf PluginConfigReader) {\n\tcons.control = make(chan PluginControl, 1)\n\tcons.logRouter = StreamRegistry.GetRouter(LogInternalStreamID)\n\tcons.metric = conf.GetString(\"MetricKey\", \"\")\n\tcons.queue = NewMessageQueue(1024)\n\n\tif cons.metric != \"\" {\n\t\tcons.metricsRegistry = NewMetricsRegistry(cons.metric)\n\n\t\tcons.metricErrors = metrics.NewCounter()\n\t\tcons.metricWarning = metrics.NewCounter()\n\t\tcons.metricInfo = metrics.NewCounter()\n\t\tcons.metricDebug = metrics.NewCounter()\n\t\tcons.metricsRegistry.Register(\"errors\", cons.metricErrors)\n\t\tcons.metricsRegistry.Register(\"warnings\", cons.metricWarning)\n\t\tcons.metricsRegistry.Register(\"info\", cons.metricInfo)\n\t\tcons.metricsRegistry.Register(\"debug\", cons.metricDebug)\n\t}\n}", "func Configure(b *bootstrap.Bootstrapper) {\n\tNew(b)\n}", "func (p *PostProcessor) Configure(raws ...interface{}) error {\n\terr := config.Decode(&p.config, &config.DecodeOpts{\n\t\tPluginType: BuilderIdRegistry,\n\t\tInterpolate: true,\n\t\tInterpolateContext: &p.config.ctx,\n\t\tInterpolateFilter: &interpolate.RenderFilter{\n\t\t\tExclude: []string{},\n\t\t},\n\t}, raws...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif p.config.Tag == \"\" {\n\t\treturn fmt.Errorf(\"You must specify a valid tag for your Veertu Anka VM (e.g. 'latest')\")\n\t}\n\n\tif p.config.Local && p.config.RemoteVM != \"\" {\n\t\treturn fmt.Errorf(\"The 'local' and 'remote_vm' settings are mutually exclusive.\")\n\t}\n\n\tp.client = &client.AnkaClient{}\n\n\treturn nil\n}", "func (e *Implementation) Configure(config string) error {\n\tscope.Debugf(\"Applying configuration: \\n%s\\n\", config)\n\terr := kube.ApplyContents(e.ctx.Settings().KubeConfig, e.TestNamespace, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// TODO: Implement a mechanism for reliably waiting for the configuration to disseminate in the system.\n\t// We can use CtrlZ to expose the config state of Mixer and Pilot.\n\t// See https://github.com/istio/istio/issues/6169 and https://github.com/istio/istio/issues/6170.\n\ttime.Sleep(time.Second * 10)\n\n\treturn nil\n}", "func (MetaConfig) ConfigureMeta(Metaor) {\n}", "func Configure(s *startup.Startup) {\n\th := New(s)\n\ts.UseGlobal(h)\n}", "func (cc *Coordinator) Configure() {\n\tcc.Log.Info(\"configuring\")\n\n\tcc.modules = make(map[string]protocol.Module)\n\n\t// Create all configured cluster modules, add to list of clusters\n\tmodules := viper.GetStringMap(\"consumer\")\n\tfor name := range modules {\n\t\tconfigRoot := \"consumer.\" + name\n\t\tif !viper.IsSet(\"cluster.\" + viper.GetString(configRoot+\".cluster\")) {\n\t\t\tpanic(\"Consumer '\" + name + \"' references an unknown cluster '\" + viper.GetString(configRoot+\".cluster\") + \"'\")\n\t\t}\n\t\tmodule := getModuleForClass(cc.App, name, viper.GetString(configRoot+\".class-name\"))\n\t\tmodule.Configure(name, configRoot)\n\t\tcc.modules[name] = module\n\t}\n}", "func Configure(b *bootstrap.Bootstrapper) {\n\th := New(b)\n\tb.UseGlobal(h)\n}", "func (p *ProtocGenGoPlugin) Configure(ctx *protoc.PluginContext) *protoc.PluginConfiguration {\n\tif !p.shouldApply(ctx.ProtoLibrary) {\n\t\treturn nil\n\t}\n\tmappings, _ := GetImportMappings(ctx.PluginConfig.GetOptions())\n\n\t// record M associations now.\n\t//\n\t// TODO(pcj): where and when is the optimal time to do this? protoc-gen-go,\n\t// protoc-gen-gogo, and protoc-gen-go-grpc all use this. Perhaps they\n\t// should *all* perform it, just to be sure?\n\tfor k, v := range mappings {\n\t\t// \"option\" is used as the name since we cannot leave that part of the\n\t\t// label empty.\n\t\tprotoc.GlobalResolver().Provide(\"proto\", \"M\", k, label.New(\"\", v, \"option\")) // FIXME(pcj): should this not be config.RepoName?\n\t}\n\n\treturn &protoc.PluginConfiguration{\n\t\tLabel: label.New(\"build_stack_rules_proto\", \"plugin/golang/protobuf\", \"protoc-gen-go\"),\n\t\tOutputs: p.outputs(ctx.ProtoLibrary, mappings),\n\t\tOptions: ctx.PluginConfig.GetOptions(),\n\t}\n}", "func (c *Check) Configure(senderManager sender.SenderManager, integrationConfigDigest uint64, config, initConfig integration.Data, source string) error {\n\tif !ddConfig.Datadog.GetBool(\"container_lifecycle.enabled\") {\n\t\treturn errors.New(\"collection of container lifecycle events is disabled\")\n\t}\n\n\tvar err error\n\n\terr = c.CommonConfigure(senderManager, integrationConfigDigest, initConfig, config, source)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = c.instance.Parse(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsender, err := c.GetSender()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif c.instance.ChunkSize <= 0 || c.instance.ChunkSize > maxChunkSize {\n\t\tc.instance.ChunkSize = maxChunkSize\n\t}\n\n\tif c.instance.PollInterval <= 0 {\n\t\tc.instance.PollInterval = defaultPollInterval\n\t}\n\n\tc.processor = newProcessor(sender, c.instance.ChunkSize, c.workloadmetaStore)\n\n\treturn nil\n}", "func (m *Monitor) Configure(conf *Config) (err error) {\n\tm.logger = logger.WithField(\"monitorID\", conf.MonitorID)\n\tm.plugin = factory().(*telegrafPlugin.Statsd)\n\n\t// copy configurations to the plugin\n\tif err = deepcopier.Copy(conf).To(m.plugin); err != nil {\n\t\tm.logger.Error(\"unable to copy configurations to plugin\")\n\t\treturn err\n\t}\n\n\t// create the accumulator\n\tac := accumulator.NewAccumulator(baseemitter.NewEmitter(m.Output, m.logger))\n\n\t// create contexts for managing the plugin loop\n\tvar ctx context.Context\n\tctx, m.cancel = context.WithCancel(context.Background())\n\n\t// start the plugin\n\tif err = m.plugin.Start(ac); err != nil {\n\t\treturn err\n\t}\n\n\t// gather metrics on the specified interval\n\tutils.RunOnInterval(ctx, func() {\n\t\tif err := m.plugin.Gather(ac); err != nil {\n\t\t\tm.logger.WithError(err).Errorf(\"an error occurred while gathering metrics\")\n\t\t}\n\t}, time.Duration(conf.IntervalSeconds)*time.Second)\n\n\treturn err\n}", "func (format *Copy) Configure(conf core.PluginConfigReader) {\n\tmode := conf.GetString(\"Mode\", \"replace\")\n\tswitch strings.ToLower(mode) {\n\tcase \"replace\":\n\t\tformat.mode = metadataCopyModeReplace\n\tcase \"append\":\n\t\tformat.mode = metadataCopyModeAppend\n\tcase \"prepend\":\n\t\tformat.mode = metadataCopyModePrepend\n\tdefault:\n\t\tconf.Errors.Pushf(\"mode must be one of replace, append or prepend\")\n\t}\n}", "func Configure(config *Configuration) {\n\tglobalProbe.Configure(config)\n}", "func (cli *Client) Configure(proto string, host string, port int) error {\n\tcli.Endpoints.Health = fmt.Sprintf(\"%s://%s:%d/services/collector/health\", proto, host, port)\n\tcli.Endpoints.Event = fmt.Sprintf(\"%s://%s:%d/services/collector/event\", proto, host, port)\n\tcli.Endpoints.Raw = fmt.Sprintf(\"%s://%s:%d/services/collector/raw\", proto, host, port)\n\treturn nil\n}", "func Configure(conf interface{}) error {\n\treturn CommandLine.Configure(conf, os.Args[1:])\n}", "func (*GenericFramework) Configure(*Legion) error { return nil }", "func (l *LifeCycle) Configure(name string) error {\n\tl.log.Debug(\"Configuring...\")\n\n\tif err := l.EnureSNS(name); err != nil {\n\t\tl.log.Error(\"Could not ensure SNS Err: %s\", err.Error())\n\t\treturn err\n\t}\n\n\tif err := l.MakeSureSQS(name); err != nil {\n\t\tl.log.Error(\"Coud not ensure SQS Err: %s\", err.Error())\n\t\treturn err\n\t}\n\n\tif err := l.MakeSureSubscriptions(); err != nil {\n\t\tl.log.Error(\"Could not create subscription to SNS from SQS Err: %s\", err.Error())\n\t\treturn err\n\t}\n\n\tif err := l.AttachNotificationToAutoScaling(); err != nil {\n\t\tl.log.Error(\"Could not attach notification to autoscaling Err: %s\", err.Error())\n\t\treturn err\n\t}\n\n\t// output parameters, they are safe to be in logs\n\tl.log.New(\"queueURL\").Debug(*l.queueURL)\n\tl.log.New(\"queueARN\").Debug(*l.queueARN)\n\tl.log.New(\"topicARN\").Debug(*l.topicARN)\n\tl.log.New(\"subscriptionARN\").Debug(*l.subscriptionARN)\n\n\tl.log.Info(\"Lifecycle manager is ready\")\n\treturn nil\n}", "func (zc *Coordinator) Configure() {\n\tzc.Log.Info(\"configuring\")\n\n\t// if zookeeper.tls has been set, use the TLS connect function otherwise use default connect\n\tif zc.connectFunc == nil && viper.IsSet(\"zookeeper.tls\") {\n\t\tzc.connectFunc = helpers.ZookeeperConnectTLS\n\t} else if zc.connectFunc == nil {\n\t\tzc.connectFunc = helpers.ZookeeperConnect\n\t}\n\n\t// Set and check configs\n\tviper.SetDefault(\"zookeeper.timeout\", 6)\n\tviper.SetDefault(\"zookeeper.root-path\", \"/burrow\")\n\n\tzc.servers = viper.GetStringSlice(\"zookeeper.servers\")\n\tif len(zc.servers) == 0 {\n\t\tpanic(\"No Zookeeper servers specified\")\n\t} else if !helpers.ValidateHostList(zc.servers) {\n\t\tpanic(\"Failed to validate Zookeeper servers\")\n\t}\n\n\tzc.App.ZookeeperRoot = viper.GetString(\"zookeeper.root-path\")\n\tif !helpers.ValidateZookeeperPath(zc.App.ZookeeperRoot) {\n\t\tpanic(\"Zookeeper root path is not valid\")\n\t}\n\n\tzc.running = sync.WaitGroup{}\n}", "func (server *HostProtobufServer) Configure(ctx context.Context, in *protobuf.Configuration) (*protobuf.Confirmation, error) {\n\n\tvar errorMessage string\n\tvar completed bool\n\n\tconfig, err := server.mapProtobufToConfig(in)\n\n\tif err != nil {\n\t\terrorMessage = err.Error()\n\t\tcompleted = false\n\t\tlog.Printf(\"Error: %v\", err)\n\t} else {\n\t\tthis.Configuration = config\n\n\t\tlog.Printf(\"Successfully Configured Host Module\")\n\t\tcompleted = true\n\t}\n\n\treturn &protobuf.Confirmation{ Completed: completed, ErrorMessage: errorMessage }, nil\n}", "func (f *Frontend) Configure(cfg string) error {\n\terr := f.configure(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn f.Seed()\n}", "func (k *KubeASCheck) Configure(senderManager sender.SenderManager, integrationConfigDigest uint64, config, initConfig integration.Data, source string) error {\n\terr := k.CommonConfigure(senderManager, integrationConfigDigest, initConfig, config, source)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Check connectivity to the APIServer\n\terr = k.instance.parse(config)\n\tif err != nil {\n\t\tlog.Error(\"could not parse the config for the API server\")\n\t\treturn err\n\t}\n\tif k.instance.EventCollectionTimeoutMs == 0 {\n\t\tk.instance.EventCollectionTimeoutMs = defaultTimeoutEventCollection\n\t}\n\n\tif k.instance.MaxEventCollection == 0 {\n\t\tk.instance.MaxEventCollection = maxEventCardinality\n\t}\n\n\thostnameDetected, _ := hostname.Get(context.TODO())\n\tclusterName := clustername.GetRFC1123CompliantClusterName(context.TODO(), hostnameDetected)\n\n\tif k.instance.UnbundleEvents {\n\t\tk.eventCollection.Transformer = newUnbundledTransformer(clusterName, tagger.GetDefaultTagger(), k.instance.CollectedEventTypes)\n\t} else {\n\t\tk.eventCollection.Filter = convertFilters(k.instance.FilteredEventTypes)\n\t\tk.eventCollection.Transformer = newBundledTransformer(clusterName)\n\t}\n\n\treturn nil\n}", "func (m *Monitor) Configure(conf *Config) error {\n\treturn m.SetConfigurationAndRun(conf)\n}", "func (c *DirectClient) Configure(config *cconf.ConfigParams) {\n\tc.DependencyResolver.Configure(config)\n}", "func (format *Envelope) Configure(conf core.PluginConfig) error {\n\tplugin, err := core.NewPluginWithType(conf.GetString(\"EnvelopeFormatter\", \"format.Forward\"), conf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tformat.base = plugin.(core.Formatter)\n\tformat.prefix = shared.Unescape(conf.GetString(\"EnvelopePrefix\", \"\"))\n\tformat.postfix = shared.Unescape(conf.GetString(\"EnvelopePostfix\", \"\\n\"))\n\n\treturn nil\n}", "func Configure(a AdminInfo) {\n\ta = c\n}", "func Configure(active bool) {\n\tisActive = active\n}", "func Configure(appCfg *AppConfig, tmcfg *config.Config, initializing bool) {\n\tNoColorFormatting = viper.GetBool(\"no-colors\")\n\n\t// Set default version information\n\tappCfg.VersionInfo = &VersionInfo{}\n\n\t// Setup viper and app directories\n\tsetup(appCfg, tmcfg, initializing)\n\n\t// Tendermint config overwrites\n\tchainInfo := setupTendermintCfg(appCfg, tmcfg)\n\n\t// Setup logger\n\tsetupLogger(appCfg, tmcfg)\n\n\t// Add seed peers if .IgnoreSeeds is false\n\tif !appCfg.Node.IgnoreSeeds {\n\t\ttmcfg.P2P.PersistentPeers = appCfg.Node.PersistentPeers + \",\" + strings.Join(chainInfo.ChainSeedPeers, \",\")\n\t\tappCfg.DHT.BootstrapPeers = appCfg.DHT.BootstrapPeers + \",\" + strings.Join(chainInfo.DHTSeedPeers, \",\")\n\t}\n\n\tif appCfg.DHT.Address != \"\" && appCfg.DHT.Address[:1] == \":\" {\n\t\tappCfg.DHT.Address = \"0.0.0.0\" + appCfg.DHT.Address\n\t}\n\n\tif appCfg.RPC.User == \"\" && appCfg.RPC.Password == \"\" {\n\t\tappCfg.RPC.DisableAuth = true\n\t}\n\n\tif tmcfg.P2P.ListenAddress != \"\" && tmcfg.P2P.ListenAddress[:1] == \":\" {\n\t\ttmcfg.P2P.ListenAddress = \"0.0.0.0\" + tmcfg.P2P.ListenAddress\n\t}\n\n\tappCfg.G().Bus = emitter.New(10000)\n\tappCfg.G().TMConfig = tmcfg\n}", "func Configure(cfg *Config) error {\n\tif cfg.StatshubAddr == \"\" {\n\t\treturn fmt.Errorf(\"Must specify StatshubAddr if reporting stats\")\n\t}\n\treturn doConfigure(cfg, posterForDimGroupStats(cfg))\n}", "func (filter *SimpleFilter) Configure(conf PluginConfigReader) error {\n\tfilter.Logger = conf.GetSubLogger(\"Filter\")\n\t//filter.filteredStreamID = GetStreamID(conf.GetString(\"FilteredStream\", InvalidStream))\n\treturn nil\n}", "func Configure(verbswitch, activated bool, addrport, id string) {\n\taddress = addrport\n\tidentifier = id\n\tdemo = activated\n\tverbose = verbswitch\n}", "func (m *PyMonitor) Configure(conf *Config) error {\n\truntimeConf := subproc.DefaultPythonRuntimeConfig(\"sfxmonitor\")\n\tif conf.PythonBinary != \"\" {\n\t\truntimeConf.Binary = conf.PythonBinary\n\t\truntimeConf.Env = os.Environ()\n\t} else {\n\t\t// Pass down the default runtime binary to the Python script if it\n\t\t// needs it\n\t\tconf.PythonBinary = runtimeConf.Binary\n\t}\n\tif len(conf.PythonPath) > 0 {\n\t\truntimeConf.Env = append(runtimeConf.Env, \"PYTHONPATH=\"+strings.Join(conf.PythonPath, \":\"))\n\t}\n\n\thandler := &signalfx.JSONHandler{\n\t\tOutput: m.Output,\n\t\tLogger: m.Logger(),\n\t}\n\treturn m.MonitorCore.ConfigureInSubproc(conf, runtimeConf, handler)\n}", "func (b *S3ExporterBackend) Configure(\n\tconfigData map[string]interface{},\n) error {\n\tbackendConfig = new(S3Config)\n\tif err := mapstructure.Decode(configData, &backendConfig); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Configure(confPath string, data interface{}) {\n\tvar err error\n\tif enforcer, err = casbin.NewEnforcer(confPath, data); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (cons *Console) Configure(conf core.PluginConfigReader) {\n\tswitch strings.ToLower(cons.pipeName) {\n\tcase \"stdin\":\n\t\tcons.pipe = os.Stdin\n\t\tcons.pipeName = \"stdin\"\n\tdefault:\n\t\tcons.pipe = nil\n\t}\n}", "func (c *ContainerCheck) Configure(senderManager sender.SenderManager, integrationConfigDigest uint64, config, initConfig integration.Data, source string) error {\n\terr := c.CommonConfigure(senderManager, integrationConfigDigest, initConfig, config, source)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfilter, err := containers.GetSharedMetricFilter()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.processor = NewProcessor(metrics.GetProvider(), MetadataContainerAccessor{}, GenericMetricsAdapter{}, LegacyContainerFilter{OldFilter: filter})\n\treturn c.instance.Parse(config)\n}", "func (m *Monitor) Configure(conf ConfigInterface) error {\n\tif m.configureOnceSync(conf); m.configErr == nil {\n\t\tm.readSendCloseAsync(conf)\n\t}\n\treturn m.configErr\n}", "func (k *xyzProvider) Configure(_ context.Context, req *pulumirpc.ConfigureRequest) (*pulumirpc.ConfigureResponse, error) {\n\treturn &pulumirpc.ConfigureResponse{}, nil\n}", "func (p *Provider) Configure(opts ...RetrievalProviderOption) {\n\tfor _, opt := range opts {\n\t\topt(p)\n\t}\n}", "func (c *StdOutputConfig) Configure(details map[string]interface{}) error {\n\treturn nil\n}", "func (d *Driver) Configure(config Config) error {\n\tif d.IsImporting() {\n\t\treturn errors.New(\"importing\")\n\t}\n\t// write configration data\n\treturn d.write(newConfigureRequest(config))\n}", "func Configure() {\n\tenableLocalhopManagement = core.GetConfigBoolDefault(\"mgmt.allow_localhop\", false)\n}", "func (p *JavaPlugin) Configure(ctx *protoc.PluginContext) *protoc.PluginConfiguration {\n\tsrcjar := path.Join(ctx.Rel, ctx.ProtoLibrary.BaseName()+\".srcjar\")\n\treturn &protoc.PluginConfiguration{\n\t\tLabel: label.New(\"build_stack_rules_proto\", \"plugin/builtin\", \"java\"),\n\t\tOutputs: []string{srcjar},\n\t\tOut: srcjar,\n\t\tOptions: ctx.PluginConfig.GetOptions(),\n\t}\n}", "func Configure(c Client) {\n\tclient = c\n}", "func (p *PostProcessor) Configure(raws ...interface{}) error {\n\terr := config.Decode(&p.config, &config.DecodeOpts{\n\t\tInterpolate: true,\n\t\tInterpolateContext: &p.config.ctx,\n\t\tInterpolateFilter: &interpolate.RenderFilter{\n\t\t\tExclude: []string{},\n\t\t},\n\t}, raws...)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif p.config.AmiID == nil {\n\t\tp.config.AmiID = make(map[string][]string, 0)\n\t}\n\n\treturn nil\n}", "func (m *Monitor) Configure(conf *Config) error {\n\tm.logger = log.WithFields(log.Fields{\"monitorType\": monitorType, \"monitorID\": conf.MonitorID})\n\n\tplugin := telegrafInputs.Inputs[\"sqlserver\"]().(*telegrafPlugin.SQLServer)\n\n\tserver := fmt.Sprintf(\"Server=%s;Port=%d;\", conf.Host, conf.Port)\n\n\tif conf.UserID != \"\" {\n\t\tserver = fmt.Sprintf(\"%sUser Id=%s;\", server, conf.UserID)\n\t}\n\tif conf.Password != \"\" {\n\t\tserver = fmt.Sprintf(\"%sPassword=%s;\", server, conf.Password)\n\t}\n\tif conf.AppName != \"\" {\n\t\tserver = fmt.Sprintf(\"%sapp name=%s;\", server, conf.AppName)\n\t}\n\tserver = fmt.Sprintf(\"%slog=%d;\", server, conf.Log)\n\n\tplugin.Servers = []string{server}\n\tplugin.QueryVersion = conf.QueryVersion\n\tplugin.AzureDB = conf.AzureDB\n\tplugin.ExcludeQuery = conf.ExcludeQuery\n\n\t// create batch emitter\n\temit := baseemitter.NewEmitter(m.Output, m.logger)\n\n\t// Hard code the plugin name because the emitter will parse out the\n\t// configured measurement name as plugin and that is confusing.\n\temit.AddTag(\"plugin\", strings.Replace(monitorType, \"/\", \"-\", -1))\n\n\t// replacer sanitizes metrics according to our PCR reporter rules (ours have to come first).\n\treplacer := strings.NewReplacer(append([]string{\"%\", \"pct\", \"(s)\", \"_\"}, winperfcounters.MetricReplacements...)...)\n\n\temit.AddMetricNameTransformation(func(metric string) string {\n\t\treturn strings.Trim(replacer.Replace(strings.ToLower(metric)), \"_\")\n\t})\n\n\temit.AddMeasurementTransformation(\n\t\tfunc(ms telegraf.Metric) error {\n\t\t\t// if it's a sqlserver_performance metric\n\t\t\t// remap the counter and value to a field\n\t\t\tif ms.Name() == \"sqlserver_performance\" {\n\t\t\t\temitter.RenameFieldWithTag(ms, \"counter\", \"value\", replacer)\n\t\t\t}\n\n\t\t\t// if it's a sqlserver_memory_clerks metric remap clerk type to field\n\t\t\tif ms.Name() == \"sqlserver_memory_clerks\" {\n\t\t\t\tms.SetName(fmt.Sprintf(\"sqlserver_memory_clerks.size_kb\"))\n\t\t\t\temitter.RenameFieldWithTag(ms, \"clerk_type\", \"size_kb\", replacer)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\n\t// convert the metric name to lower case\n\temit.AddMetricNameTransformation(strings.ToLower)\n\n\t// create the accumulator\n\tac := accumulator.NewAccumulator(emit)\n\n\t// create contexts for managing the plugin loop\n\tvar ctx context.Context\n\tctx, m.cancel = context.WithCancel(context.Background())\n\n\t// gather metrics on the specified interval\n\tutils.RunOnInterval(ctx, func() {\n\t\tif err := plugin.Gather(ac); err != nil {\n\t\t\tm.logger.WithError(err).Errorf(\"an error occurred while gathering metrics from the plugin\")\n\t\t}\n\n\t}, time.Duration(conf.IntervalSeconds)*time.Second)\n\n\treturn nil\n}", "func Configure() *config.Config {\n\treturn config.CreateConfig()\n}", "func (ra *RenameAnalysis) Configure(facts map[string]interface{}) error {\n\tif l, exists := facts[core.ConfigLogger].(core.Logger); exists {\n\t\tra.l = l\n\t}\n\tif val, exists := facts[ConfigRenameAnalysisSimilarityThreshold].(int); exists {\n\t\tra.SimilarityThreshold = val\n\t}\n\tif val, exists := facts[ConfigRenameAnalysisTimeout].(int); exists {\n\t\tif val < 0 {\n\t\t\treturn fmt.Errorf(\"negative renames detection timeout is not allowed: %d\", val)\n\t\t}\n\t\tra.Timeout = time.Duration(val) * time.Millisecond\n\t}\n\treturn nil\n}", "func (n *mockAgent) configure(h hypervisor, id, sharePath string, config interface{}) error {\n\treturn nil\n}", "func (m *Monitor) Configure(conf *Config) error {\n\tm.logger = logrus.WithFields(logrus.Fields{\"monitorType\": monitorType, \"monitorID\": conf.MonitorID})\n\n\t// create contexts for managing the plugin loop\n\tvar ctx context.Context\n\tctx, m.cancel = context.WithCancel(context.Background())\n\n\t// save config to monitor for convenience\n\tm.conf = conf\n\n\t// initialize cpu times and per core cpu times so that we don't have to wait an entire reporting interval to report utilization\n\tm.initializeCPUTimes()\n\tm.initializePerCoreCPUTimes()\n\n\thasPerCPUMetric := utils.StringSliceToMap(m.Output.EnabledMetrics())[cpuUtilizationPerCore]\n\n\t// gather metrics on the specified interval\n\tutils.RunOnInterval(ctx, func() {\n\t\tdps := m.generateDatapoints()\n\t\tif hasPerCPUMetric || conf.ReportPerCPU {\n\t\t\t// NOTE: If this monitor ever fails to complete in a reporting interval\n\t\t\t// maybe run this on a separate go routine\n\t\t\tperCoreDPs := m.generatePerCoreDatapoints()\n\t\t\tdps = append(dps, perCoreDPs...)\n\t\t}\n\n\t\tm.Output.SendDatapoints(dps...)\n\t}, time.Duration(conf.IntervalSeconds)*time.Second)\n\n\treturn nil\n}", "func Configure(p *config.Provider) {\n\tp.AddResourceConfigurator(\"aws_grafana_workspace\", func(r *config.Resource) {\n\t\tr.Version = common.VersionV1Alpha2\n\t\tr.ExternalName = config.IdentifierFromProvider\n\t\tr.References = config.References{\n\t\t\t\"role_arn\": config.Reference{\n\t\t\t\tType: \"github.com/crossplane-contrib/provider-jet-aws/apis/iam/v1alpha2.Role\",\n\t\t\t\tExtractor: common.PathARNExtractor,\n\t\t\t},\n\t\t}\n\n\t})\n\n\tp.AddResourceConfigurator(\"aws_grafana_workspace_saml_configuration\", func(r *config.Resource) {\n\t\tr.Version = common.VersionV1Alpha2\n\t\tr.ExternalName = config.IdentifierFromProvider\n\t\tr.References = config.References{\n\t\t\t\"workspace_id\": config.Reference{\n\t\t\t\tType: \"Workspace\",\n\t\t\t},\n\t\t}\n\t})\n\n\tp.AddResourceConfigurator(\"aws_grafana_role_association\", func(r *config.Resource) {\n\t\tr.Version = common.VersionV1Alpha2\n\t\tr.ExternalName = config.IdentifierFromProvider\n\t\tr.References = config.References{\n\t\t\t\"workspace_id\": config.Reference{\n\t\t\t\tType: \"Workspace\",\n\t\t\t},\n\t\t}\n\t})\n}", "func (i *Ingester) Configure(config Config) error {\n\tvar err error\n\t// Configure generator\n\tif config.Source == \"json\" {\n\t\ti.generator = &generator.JSONGenerator{File: i.Stream}\n\t} else if config.Source == \"marc\" {\n\t\ti.generator = &generator.MarcGenerator{\n\t\t\tMarcfile: i.Stream,\n\t\t\tRulesfile: config.Rulesfile,\n\t\t}\n\t} else if config.Source == \"archives\" {\n\t\ti.generator = &generator.ArchivesGenerator{Archivefile: i.Stream}\n\t} else {\n\t\treturn errors.New(\"Unknown source data\")\n\t}\n\n\t// Configure consumer\n\tif config.Consumer == \"es\" {\n\t\t// This block relies on certain file naming conventions to work. Daily\n\t\t// updates to aleph have the string mit01_edsu1 in the filename. If that\n\t\t// string is present we will add the records to the current aleph index\n\t\t// instead of creating a new index.\n\t\tif config.Index == \"\" {\n\t\t\tif strings.Contains(config.Filename, \"mit01_edsu1\") {\n\t\t\t\tcurrent, err := i.Client.Current(config.Prefix)\n\t\t\t\tif err != nil || current == \"\" {\n\t\t\t\t\treturn errors.New(\"Could not determine current index\")\n\t\t\t\t}\n\t\t\t\tconfig.Index = current\n\t\t\t\tconfig.Promote = false\n\t\t\t} else {\n\t\t\t\tnow := time.Now().UTC()\n\t\t\t\tconfig.Index = fmt.Sprintf(\"%s-%s\", config.Prefix, now.Format(\"2006-01-02t15-04-05z\"))\n\t\t\t}\n\t\t}\n\n\t\terr = i.Client.Create(config.Index)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ti.consumer = &consumer.ESConsumer{\n\t\t\tIndex: config.Index,\n\t\t\tRType: \"Record\",\n\t\t\tClient: i.Client,\n\t\t}\n\t} else if config.Consumer == \"json\" {\n\t\ti.consumer = &consumer.JSONConsumer{Out: os.Stdout}\n\t} else if config.Consumer == \"title\" {\n\t\ti.consumer = &consumer.TitleConsumer{Out: os.Stdout}\n\t} else if config.Consumer == \"silent\" {\n\t\ti.consumer = &consumer.SilentConsumer{Out: os.Stdout}\n\t} else {\n\t\treturn errors.New(\"Unknown consumer\")\n\t}\n\n\ti.config = config\n\treturn nil\n}", "func (p *EnvironmentProvider) Configure(config map[string]interface{}) (err error) {\n\treturn\n}", "func (p *CsharpPlugin) Configure(ctx *protoc.PluginContext) *protoc.PluginConfiguration {\n\treturn &protoc.PluginConfiguration{\n\t\tLabel: label.New(\"build_stack_rules_proto\", \"plugin/builtin\", \"csharp\"),\n\t\tOutputs: protoc.FlatMapFiles(\n\t\t\tcsharpFileName(ctx.Rel, ctx.PluginConfig),\n\t\t\tprotoc.Always,\n\t\t\tctx.ProtoLibrary.Files()...,\n\t\t),\n\t\tOut: ctx.Rel,\n\t\tOptions: ctx.PluginConfig.GetOptions(),\n\t}\n}", "func (ch *chain) Configure(config *cb.Envelope, configSeq uint64) error {\n\n\tselect {\n\tcase ch.sendChan <- &message{\n\t\tconfigSeq: configSeq,\n\t\tconfigMsg: config,\n\t}:\n\t\treturn nil\n\tcase <-ch.exitChan:\n\t\treturn fmt.Errorf(\"Exiting\")\n\t}\n}", "func (postProcessor *PostProcessor) Configure(settings ...interface{}) (err error) {\n\tif len(settings) == 0 {\n\t\terr = fmt.Errorf(\"No settings\")\n\n\t\treturn\n\t}\n\n\t// Builder settings.\n\tpostProcessor.settings = &config.Settings{}\n\terr = confighelper.Decode(postProcessor.settings, &confighelper.DecodeOpts{\n\t\tInterpolate: true,\n\t\tInterpolateContext: &postProcessor.interpolationContext,\n\t}, settings...)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = postProcessor.settings.Validate()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpostProcessor.client = compute.NewClient(\n\t\tpostProcessor.settings.McpRegion,\n\t\tpostProcessor.settings.McpUser,\n\t\tpostProcessor.settings.McpPassword,\n\t)\n\tif os.Getenv(\"MCP_EXTENDED_LOGGING\") != \"\" {\n\t\tpostProcessor.client.EnableExtendedLogging()\n\t}\n\n\t// Configure post-processor execution logic.\n\tpostProcessor.runner = &multistep.BasicRunner{\n\t\tSteps: []multistep.Step{\n\t\t\t&steps.ResolveDatacenter{\n\t\t\t\tDatacenterID: postProcessor.settings.DatacenterID,\n\t\t\t\tAsTarget: true,\n\t\t\t},\n\t\t\t&steps.CheckTargetImage{\n\t\t\t\tTargetImage: postProcessor.settings.TargetImageName,\n\t\t\t},\n\t\t\t&steps.ConvertVMXToOVF{\n\t\t\t\tPackageName: postProcessor.settings.OVFPackagePrefix,\n\t\t\t\tOutputDir: \"\", // Create a new use new temporary directory\n\t\t\t\tCleanupOVF: true, // Delete once post-processor is done.\n\t\t\t\tDiskCompression: 5, // Hard-coded for now\n\t\t\t},\n\t\t\t&steps.UploadOVFPackage{},\n\t\t\t&steps.ImportCustomerImage{\n\t\t\t\tTargetImageName: postProcessor.settings.TargetImageName,\n\t\t\t\tDatacenterID: postProcessor.settings.DatacenterID,\n\t\t\t\tOVFPackagePrefix: postProcessor.settings.OVFPackagePrefix,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn nil\n}", "func (p *Provider) Configure(options ...StorageProviderOption) {\n\tfor _, option := range options {\n\t\toption(p)\n\t}\n}", "func (app *App) Configure() {\n\tapp.setConfigurationDefaults()\n\tapp.loadConfiguration()\n\tapp.configureStatsD()\n\tapp.configureJaeger()\n\tapp.connectDatabase()\n\tapp.configureApplication()\n\tapp.configureElasticsearch()\n\tapp.configureMongoDB()\n\tapp.initDispatcher()\n\tapp.initESWorker()\n\tapp.initMongoWorker()\n\tapp.configureGoWorkers()\n\tapp.configureCaches()\n}", "func (r *Router) Configure(opts ...RouterOption) {\n\tfor _, o := range opts {\n\t\to(r)\n\t}\n}", "func (p *Provider) Configure(c *terraform.ResourceConfig) error {\n\t// No configuration\n\tif p.ConfigureFunc == nil {\n\t\treturn nil\n\t}\n\n\tsm := schemaMap(p.Schema)\n\n\t// Get a ResourceData for this configuration. To do this, we actually\n\t// generate an intermediary \"diff\" although that is never exposed.\n\tdiff, err := sm.Diff(nil, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := sm.Data(nil, diff)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmeta, err := p.ConfigureFunc(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp.meta = meta\n\treturn nil\n}", "func (c *NTPCheck) Configure(data integration.Data, initConfig integration.Data) error {\n\tcfg := new(ntpConfig)\n\terr := cfg.parse(data, initConfig)\n\tif err != nil {\n\t\tlog.Criticalf(\"Error parsing configuration file: %s\", err)\n\t\treturn err\n\t}\n\n\tc.BuildID(data, initConfig)\n\tc.cfg = cfg\n\n\treturn nil\n}", "func (prod *InfluxDB) Configure(conf core.PluginConfigReader) {\n\tversion := conf.GetInt(\"Version\", 100)\n\tif conf.GetBool(\"UseVersion08\", false) {\n\t\tversion = 80\n\t}\n\n\tswitch {\n\tcase version < 90:\n\t\tprod.Logger.Debug(\"Using InfluxDB 0.8.x format\")\n\t\tprod.writer = new(influxDBWriter08)\n\tcase version == 90:\n\t\tprod.Logger.Debug(\"Using InfluxDB 0.9.0 format\")\n\t\tprod.writer = new(influxDBWriter09)\n\tdefault:\n\t\tprod.Logger.Debug(\"Using InfluxDB 0.9.1+ format\")\n\t\tprod.writer = new(influxDBWriter10)\n\t}\n\n\tif err := prod.writer.configure(conf, prod); conf.Errors.Push(err) {\n\t\treturn\n\t}\n\n\tprod.assembly = core.NewWriterAssembly(prod.writer, prod.TryFallback, prod)\n}", "func (service *Base) ConfigureConfig(filename string, config config.IConfiguration) *Base {\n\tservice.ConfigurationFilename = filename\n\tservice.Configuration = config\n\treturn service\n}", "func Configure() {\n\tlog = cfg.Logging.Logger\n\n\tcapturewriter.Configure()\n\n}", "func (IntegrationHandler) Configure(c dogma.IntegrationConfigurer) {\n\tc.Identity(\"<integration>\", \"099b5b8d-9e04-422f-bcc3-bb0d451158c7\")\n\n\tc.Routes(\n\t\tdogma.HandlesCommand[fixtures.MessageA](),\n\t\tdogma.HandlesCommand[fixtures.MessageB](),\n\t\tdogma.RecordsEvent[fixtures.MessageC](),\n\t\tdogma.RecordsEvent[fixtures.MessageD](),\n\t)\n}", "func (w *KMemCheck) Configure(senderManager sender.SenderManager, integrationConfigDigest uint64, data integration.Data, initConfig integration.Data, source string) error {\n\t// check to make sure the function is actually there, so we can fail gracefully\n\t// if it's not\n\tif err := modntdll.Load(); err != nil {\n\t\treturn err\n\t}\n\tif err := procNtQuerySystemInformation.Find(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := w.CommonConfigure(senderManager, integrationConfigDigest, initConfig, data, source); err != nil {\n\t\treturn err\n\t}\n\tcf := Config{\n\t\tTopNonPagedBytes: KMemDefaultTopNum,\n\t\tTopPagedBytes: KMemDefaultTopNum,\n\t\tTopPagedAllocsOutstanding: KMemDefaultTopNum,\n\t\tTopNonPagedAllocsOutstanding: KMemDefaultTopNum,\n\t}\n\terr := yaml.Unmarshal(initConfig, &cf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tw.config = cf\n\tlog.Infof(\"Winkmem config %v\", w.config)\n\treturn nil\n}", "func (n *Node) ConfigureRpc() {\n\t// TODO\n}", "func (p *PackageInfo) Configure() error {\n\n\t// The configure process consists in renaming the conffiles\n\t// unpacked at the previous step.\n\t//\n\t// We ignore some implementation concerns like checking if a conffile\n\t// has been updated using the last known checksum.\n\n\tfmt.Printf(\"Setting up %s (%s) ...\\n\", p.Name(), p.Version())\n\n\t// Rename conffiles\n\tfor _, conffile := range p.Conffiles {\n\t\tos.Rename(conffile+\".dpkg-new\", conffile)\n\t}\n\tp.SetStatus(\"half-configured\")\n\tp.Sync()\n\n\t// Run maintainer script\n\tif err := p.runMaintainerScript(\"postinst\"); err != nil {\n\t\treturn err\n\t}\n\tp.SetStatus(\"installed\")\n\tp.Sync()\n\n\treturn nil\n}", "func (tdb *TyposDatasetBuilder) Configure(facts map[string]interface{}) error {\n\tif l, exists := facts[core.ConfigLogger].(core.Logger); exists {\n\t\ttdb.l = l\n\t}\n\tif val, exists := facts[ConfigTyposDatasetMaximumAllowedDistance].(int); exists {\n\t\ttdb.MaximumAllowedDistance = val\n\t}\n\treturn nil\n}", "func (module *KafkaZkClient) Configure(name, configRoot string) {\n\tmodule.Log.Info(\"configuring\")\n\n\tmodule.name = name\n\tmodule.running = &sync.WaitGroup{}\n\tmodule.groupLock = &sync.RWMutex{}\n\tmodule.groupList = make(map[string]*topicList)\n\tmodule.connectFunc = helpers.ZookeeperConnect\n\n\tmodule.servers = viper.GetStringSlice(configRoot + \".servers\")\n\tif len(module.servers) == 0 {\n\t\tpanic(\"No Zookeeper servers specified for consumer \" + module.name)\n\t} else if !helpers.ValidateHostList(module.servers) {\n\t\tpanic(\"Consumer '\" + name + \"' has one or more improperly formatted servers (must be host:port)\")\n\t}\n\n\t// Set defaults for configs if needed, and get them\n\tviper.SetDefault(configRoot+\".zookeeper-timeout\", 30)\n\tmodule.zookeeperTimeout = viper.GetInt(configRoot + \".zookeeper-timeout\")\n\tmodule.zookeeperPath = viper.GetString(configRoot+\".zookeeper-path\") + \"/consumers\"\n\tmodule.cluster = viper.GetString(configRoot + \".cluster\")\n\n\tif !helpers.ValidateZookeeperPath(module.zookeeperPath) {\n\t\tpanic(\"Consumer '\" + name + \"' has a bad zookeeper path configuration\")\n\t}\n\n\t// Check for disallowed config values\n\tif viper.IsSet(configRoot+\".group-whitelist\") || viper.IsSet(configRoot+\".group-blacklist\") {\n\t\tmodule.Log.Panic(\"Please change configurations to allowlist and denylist\")\n\t\tpanic(\"Please change configurations to allowlist and denylist\")\n\t}\n\n\tallowlist := viper.GetString(configRoot + \".group-allowlist\")\n\tif allowlist != \"\" {\n\t\tre, err := regexp.Compile(allowlist)\n\t\tif err != nil {\n\t\t\tmodule.Log.Panic(\"Failed to compile group allowlist\")\n\t\t\tpanic(err)\n\t\t}\n\t\tmodule.groupAllowlist = re\n\t}\n\n\tdenylist := viper.GetString(configRoot + \".group-denylist\")\n\tif denylist != \"\" {\n\t\tre, err := regexp.Compile(denylist)\n\t\tif err != nil {\n\t\t\tmodule.Log.Panic(\"Failed to compile group denylist\")\n\t\t\tpanic(err)\n\t\t}\n\t\tmodule.groupDenylist = re\n\t}\n}", "func (c *BFTChain) Configure(config *cb.Envelope, configSeq uint64) error {\n\tif err := c.verifier.ConfigValidator.ValidateConfig(config); err != nil {\n\t\treturn err\n\t}\n\tseq := c.support.Sequence()\n\tif configSeq < seq {\n\t\tc.Logger.Warnf(\"Normal message was validated against %d, although current config seq has advanced (%d)\", configSeq, seq)\n\t\tif configEnv, _, err := c.support.ProcessConfigMsg(config); err != nil {\n\t\t\treturn errors.Errorf(\"bad normal message: %s\", err)\n\t\t} else {\n\t\t\treturn c.submit(configEnv, configSeq)\n\t\t}\n\t}\n\treturn c.submit(config, configSeq)\n}", "func Configure(url string, name string) {\n\tendpoint = url\n\tdbName = name\n}", "func (plugin *Plugin) Initialize(config *common.PluginConfig) error {\n\t// Initialize the base plugin.\n\tplugin.Plugin.Initialize(config)\n\n\t// Initialize the shared listener.\n\tif config.Listener == nil {\n\t\t// Fetch and parse the API server URL.\n\t\tu, err := url.Parse(plugin.getAPIServerURL())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Create the listener.\n\t\tlistener, err := common.NewListener(u)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Add generic protocol handlers.\n\t\tlistener.AddHandler(activatePath, plugin.activate)\n\n\t\t// Start the listener.\n\t\terr = listener.Start(config.ErrChan)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tconfig.Listener = listener\n\t}\n\n\tplugin.Listener = config.Listener\n\n\treturn nil\n}", "func (m *hostConfiguredContainer) Configure(paths []string) error {\n\tif len(paths) == 0 {\n\t\treturn nil\n\t}\n\n\treturn m.withForwardedRuntime(func() error {\n\t\treturn m.withConfigurationContainer(func() error {\n\t\t\treturn m.copyConfigFiles(paths)\n\t\t})\n\t})\n}", "func (m *Monitor) Configure(conf *Config) error {\n\n\tvar ctx context.Context\n\tctx, m.cancel = context.WithCancel(context.Background())\n\n\tclient := &http.Client{\n\t\tTimeout: 5 * time.Second,\n\t}\n\n\tutils.RunOnInterval(ctx, func() {\n\t\t// Derive the url each time since the AgentMeta data can change but\n\t\t// there is no notification system for it.\n\t\thost := conf.Host\n\t\tif host == \"\" {\n\t\t\thost = m.AgentMeta.InternalStatusHost\n\t\t}\n\n\t\tport := conf.Port\n\t\tif port == 0 {\n\t\t\tport = m.AgentMeta.InternalStatusPort\n\t\t}\n\n\t\turl := fmt.Sprintf(\"http://%s:%d%s\", host, port, conf.Path)\n\n\t\tlogger := log.WithFields(log.Fields{\n\t\t\t\"monitorType\": monitorType,\n\t\t\t\"url\": url,\n\t\t})\n\n\t\tresp, err := client.Get(url)\n\t\tif err != nil {\n\t\t\tlogger.WithError(err).Error(\"Could not connect to internal metric server\")\n\t\t\treturn\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\tdps := make([]*datapoint.Datapoint, 0)\n\t\terr = json.NewDecoder(resp.Body).Decode(&dps)\n\t\tif err != nil {\n\t\t\tlogger.WithError(err).Error(\"Could not parse metrics from internal metric server\")\n\t\t\treturn\n\t\t}\n\n\t\tfor _, dp := range dps {\n\t\t\tm.Output.SendDatapoint(dp)\n\t\t}\n\t}, time.Duration(conf.IntervalSeconds)*time.Second)\n\n\treturn nil\n}", "func (b *Bootstrapper) Configure(cs ...Configurator) {\n\tfor _, c := range cs {\n\t\tc(b)\n\t}\n}", "func (b *Bootstrapper) Configure(cs ...Configurator) {\n\tfor _, c := range cs {\n\t\tc(b)\n\t}\n}", "func (m *Monitor) Configure(conf *Config) error {\n\tm.logger = log.WithFields(log.Fields{\"monitorType\": monitorType, \"monitorID\": conf.MonitorID})\n\n\tvar ctx context.Context\n\tctx, m.cancel = context.WithCancel(context.Background())\n\n\t// save shallow copy of conf to monitor for quick reference\n\tconfCopy := *conf\n\tm.conf = &confCopy\n\n\t// configure filters\n\tvar err error\n\tif len(m.conf.FSTypes) > 0 {\n\t\tm.fsTypes, err = filter.NewOverridableStringFilter(m.conf.FSTypes)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// strip trailing / from HostFSPath so when we do string replacement later\n\t// we are left with a path starting at /\n\tm.hostFSPath = strings.TrimRight(m.conf.HostFSPath, \"/\")\n\n\t// configure filters\n\tif len(m.conf.MountPoints) > 0 {\n\t\tm.mountPoints, err = filter.NewOverridableStringFilter(m.conf.MountPoints)\n\t}\n\n\t// return an error if we can't set the filter\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm.sendModeDimension = m.conf.SendModeDimension\n\n\t// gather metrics on the specified interval\n\tutils.RunOnInterval(ctx, func() {\n\t\tm.emitDatapoints()\n\t}, time.Duration(m.conf.IntervalSeconds)*time.Second)\n\n\treturn nil\n}", "func Configure(b *bootstrap.Bootstrapper) {\n\t//superstarService := service.NewAdminService()\n\t//\n\t//index := mvc.New(b.Party(\"/\"))\n\t//index.Register(superstarService)\n\t//index.Handle(new(controller.IndexController))\n\n\tadminService := service.NewAdminService()\n\tadmin := mvc.New(b.Party(\"/admin\"))\n\t//admin.Router.Use(middleware.BasicAuth)\n\tadmin.Register(adminService)\n\tadmin.Handle(new(controller.AdminController))\n\n\t//b.Get(\"/follower/{id:long}\", GetFollowerHandler)\n\t//b.Get(\"/following/{id:long}\", GetFollowingHandler)\n\t//b.Get(\"/like/{id:long}\", GetLikeHandler)\n}", "func (m *SpanManager) Configure(trace_fraction float64, trace_debug bool,\n\tdefault_local_host *zipkin.Endpoint) {\n\tm.mtx.Lock()\n\tm.trace_fraction = trace_fraction\n\tm.trace_debug = trace_debug\n\tm.default_local_host = default_local_host\n\tm.mtx.Unlock()\n}", "func (p *Plugin) Exec() error {\n\tlogrus.Debug(\"running plugin with provided configuration\")\n\n\t// create kubectl configuration file for authentication\n\terr := p.Config.Write()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// output kubectl version for troubleshooting\n\terr = execCmd(versionCmd(p.Config))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// execute action specific configuration\n\tswitch p.Config.Action {\n\tcase applyAction:\n\t\t// execute apply action\n\t\treturn p.Apply.Exec(p.Config)\n\tcase patchAction:\n\t\t// execute patch action\n\t\treturn p.Patch.Exec(p.Config)\n\tcase statusAction:\n\t\t// execute status action\n\t\treturn p.Status.Exec(p.Config)\n\tdefault:\n\t\treturn fmt.Errorf(\n\t\t\t\"%w: %s (Valid actions: %s, %s, %s)\",\n\t\t\tErrInvalidAction,\n\t\t\tp.Config.Action,\n\t\t\tapplyAction,\n\t\t\tpatchAction,\n\t\t\tstatusAction,\n\t\t)\n\t}\n}", "func (prod *Firehose) Configure(conf core.PluginConfig) error {\n\terr := prod.ProducerBase.Configure(conf)\n\tif err != nil {\n\t\treturn err\n\t}\n\tprod.SetStopCallback(prod.close)\n\n\tprod.streamMap = conf.GetStreamMap(\"StreamMapping\", \"default\")\n\tprod.batch = core.NewMessageBatch(conf.GetInt(\"BatchMaxMessages\", 500))\n\tprod.recordMaxMessages = conf.GetInt(\"RecordMaxMessages\", 1)\n\tprod.delimiter = []byte(conf.GetString(\"RecordMessageDelimiter\", \"\\n\"))\n\tprod.flushFrequency = time.Duration(conf.GetInt(\"BatchTimeoutSec\", 3)) * time.Second\n\tprod.sendTimeLimit = time.Duration(conf.GetInt(\"SendTimeframeMs\", 1000)) * time.Millisecond\n\tprod.lastSendTime = time.Now()\n\tprod.counters = make(map[string]*int64)\n\tprod.lastMetricUpdate = time.Now()\n\n\tif prod.recordMaxMessages < 1 {\n\t\tprod.recordMaxMessages = 1\n\t\tLog.Warning.Print(\"RecordMaxMessages was < 1. Defaulting to 1.\")\n\t}\n\n\tif prod.recordMaxMessages > 1 && len(prod.delimiter) == 0 {\n\t\tprod.delimiter = []byte(\"\\n\")\n\t\tLog.Warning.Print(\"RecordMessageDelimiter was empty. Defaulting to \\\"\\\\n\\\".\")\n\t}\n\n\t// Config\n\tprod.config = aws.NewConfig()\n\tif endpoint := conf.GetString(\"Endpoint\", \"firehose.eu-west-1.amazonaws.com\"); endpoint != \"\" {\n\t\tprod.config.WithEndpoint(endpoint)\n\t}\n\n\tif region := conf.GetString(\"Region\", \"eu-west-1\"); region != \"\" {\n\t\tprod.config.WithRegion(region)\n\t}\n\n\t// Credentials\n\tcredentialType := strings.ToLower(conf.GetString(\"CredentialType\", firehoseCredentialNone))\n\tswitch credentialType {\n\tcase firehoseCredentialEnv:\n\t\tprod.config.WithCredentials(credentials.NewEnvCredentials())\n\n\tcase firehoseCredentialStatic:\n\t\tid := conf.GetString(\"CredentialId\", \"\")\n\t\ttoken := conf.GetString(\"CredentialToken\", \"\")\n\t\tsecret := conf.GetString(\"CredentialSecret\", \"\")\n\t\tprod.config.WithCredentials(credentials.NewStaticCredentials(id, secret, token))\n\n\tcase firehoseCredentialShared:\n\t\tfilename := conf.GetString(\"CredentialFile\", \"\")\n\t\tprofile := conf.GetString(\"CredentialProfile\", \"\")\n\t\tprod.config.WithCredentials(credentials.NewSharedCredentials(filename, profile))\n\n\tcase firehoseCredentialNone:\n\t\t// Nothing\n\n\tdefault:\n\t\treturn fmt.Errorf(\"Unknown CredentialType: %s\", credentialType)\n\t}\n\n\tfor _, streamName := range prod.streamMap {\n\t\tshared.Metric.New(firehoseMetricMessages + streamName)\n\t\tshared.Metric.New(firehoseMetricMessagesSec + streamName)\n\t\tprod.counters[streamName] = new(int64)\n\t}\n\n\treturn nil\n}", "func Configure(cfg *config.Config, logger log.Logger) {\n\tif cfg.Tracing.Enabled {\n\t\tswitch t := cfg.Tracing.Type; t {\n\t\tcase \"agent\":\n\t\t\tlogger.Error().\n\t\t\t\tStr(\"type\", t).\n\t\t\t\tMsg(\"Reva only supports the jaeger tracing backend\")\n\n\t\tcase \"jaeger\":\n\t\t\tlogger.Info().\n\t\t\t\tStr(\"type\", t).\n\t\t\t\tMsg(\"configuring storage to use the jaeger tracing backend\")\n\n\t\tcase \"zipkin\":\n\t\t\tlogger.Error().\n\t\t\t\tStr(\"type\", t).\n\t\t\t\tMsg(\"Reva only supports the jaeger tracing backend\")\n\n\t\tdefault:\n\t\t\tlogger.Warn().\n\t\t\t\tStr(\"type\", t).\n\t\t\t\tMsg(\"Unknown tracing backend\")\n\t\t}\n\n\t} else {\n\t\tlogger.Debug().\n\t\t\tMsg(\"Tracing is not enabled\")\n\t}\n}", "func (p *Plugin) Init(context *InitContext) {\n\tp.transport.SetInitHandler(func(out []byte, err error) error {\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Unable to get registration info from plugin. Error: %v\", err))\n\t\t}\n\n\t\tregInfo := registrationInfo{}\n\t\tif err := json.Unmarshal(out, &regInfo); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tp.processRegistrationInfo(context, regInfo)\n\t\treturn nil\n\t})\n\n\tlog.WithFields(logrus.Fields{\n\t\t\"plugin\": p,\n\t}).Debugln(\"request plugin to return configuration\")\n\tgo p.transport.RequestInit()\n}", "func providerConfigure(data *schema.ResourceData) (interface{}, error) {\n\tlog.Println(\"[INFO] Initializing Client\")\n\n\tconfig := Config{\n\t\tAPIKey: data.Get(\"api_key\").(string),\n\t\tAPIURL: data.Get(\"api_url\").(string),\n\t}\n\n\treturn config.Client()\n}", "func Configure(cfg BrokerConfig) error {\n\tb, err := NewBroker(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstd = b\n\treturn nil\n}", "func Configure(vi View) {\n\tviewInfo = vi\n}", "func (p *k8sPlugin) Setup(flagSet *pflag.FlagSet) {\n\tflagSet.StringVar(&p.ETCDTLSConfig.CAFile, \"kubernetes-etcd-ca-file\", \"\", \"CA certificate used by ETCD\")\n\tflagSet.StringVar(&p.ETCDTLSConfig.CertFile, \"kubernetes-etcd-cert-file\", \"\", \"Public key file used by ETCD\")\n\tflagSet.StringVar(&p.ETCDTLSConfig.KeyFile, \"kubernetes-etcd-key-file\", \"\", \"Private key file used by ETCD\")\n\tflagSet.StringVar(&p.KubeletTLSConfig.CAFile, \"kubelet-ca-file\", \"\", \"CA certificate used by Kubelet\")\n\tflagSet.StringVar(&p.KubeletTLSConfig.CertFile, \"kubelet-cert-file\", \"\", \"Public key file used by Kubelet\")\n\tflagSet.StringVar(&p.KubeletTLSConfig.KeyFile, \"kubelet-key-file\", \"\", \"Private key file used by Kubelet\")\n\tflagSet.StringVar(&p.LogLevel, \"kubernetes-log-level\", \"\", \"Log level of kubernetes plugin\")\n}", "func (plugin *ipamPlugin) Configure(stdinData []byte) (*cni.NetworkConfig, error) {\n\t// Parse network configuration from stdin.\n\tnwCfg, err := cni.ParseNetworkConfig(stdinData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Logger.Info(\"Read network configuration\",\n\t\tzap.Any(\"config\", nwCfg))\n\n\t// Apply IPAM configuration.\n\n\t// Set deployment environment.\n\tif nwCfg.IPAM.Environment == \"\" {\n\t\tnwCfg.IPAM.Environment = common.OptEnvironmentAzure\n\t}\n\tplugin.SetOption(common.OptEnvironment, nwCfg.IPAM.Environment)\n\n\t// Set query interval.\n\tif nwCfg.IPAM.QueryInterval != \"\" {\n\t\ti, _ := strconv.Atoi(nwCfg.IPAM.QueryInterval)\n\t\tplugin.SetOption(common.OptIpamQueryInterval, i)\n\t}\n\n\terr = plugin.am.StartSource(plugin.Options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Set default address space if not specified.\n\tif nwCfg.IPAM.AddrSpace == \"\" {\n\t\tnwCfg.IPAM.AddrSpace = ipam.LocalDefaultAddressSpaceId\n\t}\n\n\treturn nwCfg, nil\n}", "func Configure(configFlags *flags.CommonFlags) error {\n\t// pass in alternative location of g3 config file, if set.\n\tcfgm, err := cfg.NewConfigManager(configFlags.ConfigFile)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to load configuration\")\n\t}\n\n\taccount, err := cfgm.LoadIDPAccount(configFlags.IdpAccount)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to load idp account\")\n\t} else if account == nil {\n\t\taccount = cfg.NewIDPAccount()\n\t}\n\n\t// update username and hostname if supplied\n\tflags.ApplyFlagOverrides(configFlags, account)\n\n\t// do we need to prompt for values now?\n\tif !configFlags.SkipPrompt {\n\t\terr = g3.PromptForConfigurationDetails(account)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to input configuration\")\n\t\t}\n\n\t\tif credentials.SupportsStorage() {\n\t\t\tif err := storeCredentials(configFlags, account); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\terr = cfgm.SaveIDPAccount(account)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to save configuration\")\n\t}\n\n\tlog.Println(\"\")\n\tlog.Println(account)\n\tlog.Println(\"\")\n\tlog.Printf(\"Configuration saved for IDP account: %s\", account.Name)\n\n\treturn nil\n}", "func (b *AbstractBaseEntity) Configure(commands ...string) bool {\n\treturn b.node.Config(commands...)\n}", "func Configure(options *Options) {\n\n\tSetLogLevel(options.Level)\n\n\tvar f log15.Format\n\tswitch options.Format {\n\tcase \"term\":\n\t\tf = log15.TerminalFormat()\n\tcase \"json\":\n\t\tf = log15.JsonFormatEx(true, true)\n\tcase \"logfmt\":\n\t\tfallthrough\n\tdefault:\n\t\tf = log15.LogfmtFormat()\n\t}\n\n\tvar h log15.Handler\n\tif options.Stdout {\n\t\th = log15.StreamHandler(os.Stdout, f)\n\t} else {\n\t\th = log15.StreamHandler(os.Stderr, f)\n\t}\n\n\tif options.CallFunc {\n\t\th = log15.CallerFuncHandler(h)\n\t}\n\tif options.CallStack {\n\t\th = log15.CallerStackHandler(\"%+v\", h)\n\t}\n\n\tswitch options.Level {\n\tcase 0:\n\t\th = log15.DiscardHandler() // no output\n\tcase 1:\n\t\th = log15.LvlFilterHandler(log15.LvlCrit, h)\n\tcase 2:\n\t\th = log15.LvlFilterHandler(log15.LvlError, h)\n\tcase 3:\n\t\th = log15.LvlFilterHandler(log15.LvlWarn, h)\n\tcase 4:\n\t\th = log15.LvlFilterHandler(log15.LvlInfo, h)\n\tcase 5:\n\t\th = log15.LvlFilterHandler(log15.LvlDebug,\n\t\t\tverbosityFilterHandler(V(options.DebugV),\n\t\t\t\tmatchAnyFilterHandler(options.DebugMatchKeyValuePairs, h, !options.DebugMatchExclude)))\n\tdefault:\n\t\th = log15.LvlFilterHandler(log15.LvlInfo, h)\n\t}\n\tlog15.Root().SetHandler(h)\n\n\t// Necessary to stop glog from complaining / noisy logs\n\tflag.CommandLine.Parse([]string{})\n}", "func (i *interactor) Config(args ...string) error {\n\ti.logger.WithField(\"args\", args).Info(\"Configuring.\")\n\tif out, err := i.executor.Run(append([]string{\"config\"}, args...)...); err != nil {\n\t\treturn fmt.Errorf(\"error configuring %v: %w %v\", args, err, string(out))\n\t}\n\treturn nil\n}" ]
[ "0.738589", "0.7281108", "0.7218009", "0.72134584", "0.68088496", "0.67336166", "0.6719611", "0.6613242", "0.6582964", "0.657914", "0.6481576", "0.64588183", "0.6443354", "0.63777125", "0.6366098", "0.63492817", "0.6334886", "0.6314976", "0.6293726", "0.6278675", "0.6273871", "0.62692946", "0.61881274", "0.61843014", "0.61527133", "0.6118521", "0.611643", "0.6108595", "0.6105135", "0.6083917", "0.6074569", "0.6074004", "0.6044187", "0.60299796", "0.6002208", "0.5986307", "0.59842974", "0.5963919", "0.59466964", "0.5931547", "0.59277326", "0.5920197", "0.5919798", "0.59181005", "0.59092164", "0.5906769", "0.5903287", "0.58770686", "0.58650905", "0.5852448", "0.5851564", "0.58397084", "0.58296245", "0.5824623", "0.58213365", "0.58191836", "0.58044815", "0.5802033", "0.5786112", "0.57825327", "0.57658553", "0.5722744", "0.57212776", "0.5719821", "0.5697662", "0.56949896", "0.5689919", "0.56845164", "0.56624323", "0.56545365", "0.5638993", "0.5637232", "0.5626994", "0.5609895", "0.5609224", "0.5594644", "0.55872107", "0.5562169", "0.5551797", "0.55472356", "0.55462277", "0.55423546", "0.55417275", "0.55417275", "0.5540449", "0.55102116", "0.55067354", "0.55046415", "0.54806095", "0.54788935", "0.5476633", "0.5462142", "0.5458935", "0.54442996", "0.5434496", "0.54343724", "0.5432396", "0.54195493", "0.54189515", "0.54147744" ]
0.59749967
37
grpcGeneratedFileName is a utility function that returns a function that computes the name of a predicted generated file having the given extension(s) relative to the given dir.
func grpcGeneratedFileName(reldir string) func(f *protoc.File) []string { return func(f *protoc.File) []string { name := strings.ReplaceAll(f.Name, "-", "_") if reldir != "" { name = path.Join(reldir, name) } return []string{name + "_grpc_pb.js"} } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GenerateFileName(dir, name, issueNumber, format string) string {\n\treturn fmt.Sprintf(\"%s/%s-%s.%s\", dir, name, issueNumber, format)\n}", "func GenerateFileName(fileName, extension string) (string, error) {\n\tif fileName == \"\" {\n\t\treturn \"\", fmt.Errorf(\"%w missing filename\", errCannotGenerateFileName)\n\t}\n\tif extension == \"\" {\n\t\treturn \"\", fmt.Errorf(\"%w missing filename extension\", errCannotGenerateFileName)\n\t}\n\n\treg := regexp.MustCompile(`[\\w-]`)\n\tparsedFileName := reg.FindAllString(fileName, -1)\n\tparsedExtension := reg.FindAllString(extension, -1)\n\tfileName = strings.Join(parsedFileName, \"\") + \".\" + strings.Join(parsedExtension, \"\")\n\n\treturn strings.ToLower(fileName), nil\n}", "func GenerateFileName(directoryName string) (string, string) {\n\tpieces := strings.Split(directoryName, \"-\")\n\treturn pieces[0], pieces[1]\n}", "func RegenerableFileName(dir, suffix string) string {\n\treturn filepath.Join(dir, RegenerableFilePrefix+suffix)\n}", "func (d *Abstraction) getGeneratedName(s string, m string) string {\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(s)\n\tbuffer.WriteString(\".\")\n\tbuffer.WriteString(m)\n\treturn buffer.String()\n}", "func goFileName(d *descriptor.FileDescriptorProto) string {\n\tname := *d.Name\n\tif ext := path.Ext(name); ext == \".proto\" || ext == \".protodevel\" {\n\t\tname = name[:len(name)-len(ext)]\n\t}\n\tname += \".nrpc.go\"\n\n\t// Does the file have a \"go_package\" option?\n\t// If it does, it may override the filename.\n\tif impPath, _, ok := goPackageOption(d); ok && impPath != \"\" {\n\t\t// Replace the existing dirname with the declared import path.\n\t\t_, name = path.Split(name)\n\t\tname = path.Join(impPath, name)\n\t\treturn name\n\t}\n\n\treturn name\n}", "func RandFileName(ext string) string {\n\ts := rand.NewSource(time.Now().UTC().UnixNano())\n\tr := rand.New(s)\n\talphabet := \"abcdefghijklmnopqrstuvwxyz0123456789\"\n\tname := \"\"\n\tfor i := 0; i < 6; i++ {\n\t\tidx := r.Intn(len(alphabet))\n\t\tname += string(alphabet[idx])\n\t}\n\treturn filepath.Join(name + ext)\n}", "func (e *Automation) GetFileName() string {\n\treturn fmt.Sprintf(\n\t\t\"%s_v%d_%d.json\",\n\t\te.Name,\n\t\te.VersionNumber,\n\t\te.ID)\n}", "func genFileName(t *time.Time) string {\r\n\tfilename := \"2A-\" + t.Format(layout)\r\n\treturn filename + \".txt\"\r\n}", "func (gen *jsGenerator) getOutputFileName(pidl *idl.Idl, repl string, file string) string {\n\ts := strings.TrimSuffix(filepath.Base(pidl.Filename), \".babel\")\n\tif !strings.HasSuffix(strings.ToLower(s), strings.ToLower(repl)) {\n\t\ts += repl\n\t}\n\t//namespaceDirectories := gen.args.Options[\"output\"]\n\tpkgPath := \"\"\n\tpkgPath = filepath.Join(strings.Split(pidl.Namespaces[\"js\"], \".\")...)\n\t/*\n\t\tif (namespaceDirectories != \"\") {\n\t\t\tif (namespaceDirectories == \"ns-flat\") {\n\t\t\t\tpkgPath = pidl.Namespaces[\"js\"]\n\t\t\t} else if (namespaceDirectories == \"ns-nested\") {\n\n\t\t\t}\n\t\t}\n\t*/\n\treturn filepath.Join(gen.args.OutputDir, pkgPath, file)\n}", "func GetTSFileName(fileName string) string {\n\tbaseName := filepath.Base(fileName)\n\text := filepath.Ext(fileName)\n\tname := baseName[0 : len(baseName)-len(ext)]\n\treturn path.Join(filepath.Dir(fileName), name+\".pb.ts\")\n}", "func (c *Conn) GenerateRemoteFilename(file, backup string) string {\n\tif c.backupPathPrefix == \"\" {\n\t\treturn backupDir + \"/\" + backup + \"/\" + c.prefix + \"-\" + file + \"-\" + backup\n\t}\n\treturn c.backupPathPrefix + \"/\" + backupDir + \"/\" + backup + \"/\" + c.prefix + \"-\" + file + \"-\" + backup\n}", "func generateFilePath(currentAccount *int, fileName string) (string, error) {\n\tutcNow := time.Now().UTC()\n\tdatetimeValue := utcNow.Format(\"2006_01_02__15_04_05 \")\n\tbuff := make([]byte, 32)\n\t_, err := rand.Read(buff)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\thexString := fmt.Sprintf(\"%x\", buff)\n\tfileExtension := fileName[strings.LastIndex(fileName, \".\")+1 : len(fileName)]\n\treturn fmt.Sprintf(\"./file/image/%s__%d__%s.%s\", datetimeValue, currentAccount, hexString, fileExtension), nil\n}", "func (d *FileDescriptor) goFileName(pathType pathType) string {\n\tname := *d.Name\n\tif ext := path.Ext(name); ext == \".proto\" || ext == \".protodevel\" {\n\t\tname = name[:len(name)-len(ext)]\n\t}\n\tname += \".cobra.pb.go\"\n\n\tif pathType == pathTypeSourceRelative {\n\t\treturn name\n\t}\n\n\t// Does the file have a \"go_package\" option?\n\t// If it does, it may override the filename.\n\tif impPath, _, ok := d.goPackageOption(); ok && impPath != \"\" {\n\t\t// Replace the existing dirname with the declared import path.\n\t\t_, name = path.Split(name)\n\t\tname = path.Join(impPath, name)\n\t\treturn name\n\t}\n\n\treturn name\n}", "func determineOutputFilename(outputName string, renderType go_benchpress.RenderType) string {\n\tresult := outputName\n\n\t// If the file extension provided is different from that of the format, change the filename to use the correct\n\t// file extension.\n\text := filepath.Ext(result)\n\tformatExt := renderType.FileExtension()\n\tif ext != formatExt {\n\t\treplaceFrom := strings.LastIndex(result, ext)\n\t\tif replaceFrom != -1 {\n\t\t\tresult = result[:replaceFrom]\n\t\t}\n\t\tresult += formatExt\n\t}\n\n\treturn result\n}", "func GetFileName() string {\n\t_, sourcePath, _, _ := runtime.Caller(4)\n\trootDir, _ := os.Getwd()\n\n\tfilename := strings.TrimSuffix(strings.TrimPrefix(sourcePath, rootDir+\"/\"), \".go\")\n\n\treturn filename\n}", "func fileName(domain, instance, class, id string) string {\n\tvar fileName string\n\tinstance = strings.Replace(instance, \"\\\\\", \"__\", -1)\n\n\t// use it to build the file name\n\t// if prefix == \"\" {\n\t// \tfileName = fmt.Sprintf(\"%s_%s_%s.state\", instance, class, id)\n\t// } else {\n\tfileName = fmt.Sprintf(\"%s_%s_%s_%s.state\", domain, instance, class, id)\n\t//}\n\treturn fileName\n}", "func packageFilename(pwd, relativePath string) string {\n\tfullPath := filepath.Join(pwd, relativePath)\n\treturn strings.TrimPrefix(strings.TrimPrefix(fullPath, filepath.Join(gopath(), \"src\")), \"/\")\n}", "func (ts TestSuite) Filename() string {\n\tvar b strings.Builder\n\n\tif ts.Type == \"xpack\" {\n\t\tb.WriteString(\"xpack_\")\n\t}\n\n\tb.WriteString(strings.ToLower(strings.Replace(ts.Dir, \".\", \"_\", -1)))\n\tb.WriteString(\"__\")\n\n\tbname := reFilename.ReplaceAllString(filepath.Base(ts.Filepath), \"$1\")\n\tb.WriteString(strings.ToLower(bname))\n\n\treturn b.String()\n}", "func createUniqueFileName() string {\n\n\t// Get a timestamp\n\ttv := syscall.Timeval{}\n\tsyscall.Gettimeofday(&tv)\n\tleft := fmt.Sprintf(\"%d.%d\", tv.Sec, tv.Usec)\n\n\t// Just generate a random number for now\n\tb := make([]byte, 16)\n\trand.Read(b)\n\tmiddle := fmt.Sprintf(\"%x\", b)\n\n\t// The right dot should be the hostname\n\tright, _ := os.Hostname()\n\n\t// Put the pieces together\n\tcombined := []string{left, middle, right}\n\treturn strings.Join(combined, \".\")\n}", "func createDstFilepath(in string) (string, error) {\n\tdir, filename := path.Split(in)\n\n\t// Retrieve all files in the directory so we can diff the new filename against the existing filenames in the dir. We want to avoid naming collisions.\n\tfiles, err := getFiles(dir)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Create the initial version of the new filename. If this name is not already in the dir, it will become the name of the file. If this name already exists, we will append a number on the end to distinguish this file from others of the same name.\n\tout := fmt.Sprintf(\"enc_%s\", filename)\n\n\tif _, exists := files[out]; exists {\n\t\tfor count := 1; ; count++ {\n\t\t\tversion := fmt.Sprintf(\"(%d)\", count)\n\t\t\tbase := strings.Split(out, path.Ext(filename))[0]\n\t\t\tfilename = fmt.Sprintf(\"%s%s%s\", base, version, path.Ext(filename))\n\t\t\tif _, exists := files[filename]; !exists {\n\t\t\t\tout = filename\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tout = path.Join(dir, out)\n\treturn out, nil\n}", "func generateLocalName(filePath string, blobName string) string {\n\treturn fmt.Sprintf(\"%s%s\", filePath, filepath.FromSlash(blobName))\n}", "func dirName(filename string) string {\n\tif !strings.HasSuffix(filename, \"/\") {\n\t\tfilename += \"/\"\n\t}\n\treturn filename\n}", "func fileExt(path string) string {\n\tif strings.HasSuffix(path, \".tf\") {\n\t\treturn \".tf\"\n\t} else if strings.HasSuffix(path, \".tf.json\") {\n\t\treturn \".tf.json\"\n\t} else {\n\t\treturn \"\"\n\t}\n}", "func (cache *FileCache) GetFileName(key string) string {\n\tpath := filepath.Join(cache.dir, key)\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\treturn \"\"\n\t}\n\tif abs, err := filepath.Abs(path); err == nil {\n\t\treturn abs\n\t}\n\treturn \"\"\n}", "func getFilename(now *time.Time) string {\n\thour, _, _ := now.Clock()\n\tvar buf [2]byte\n\tbuf[1] = digits[hour%10]\n\thour /= 10\n\tbuf[0] = digits[hour]\n\treturn string(buf[:]) + \".log\"\n}", "func (b *Builder) Filename() string {\n\txOsExts := map[string]string{\n\t\t\"darwin\": \"\",\n\t\t\"linux\": \"\",\n\t\t\"windows\": \".exe\",\n\t}\n\tbinaryName := fmt.Sprintf(\"%s_%s_%s%s\",\n\t\tb.Cmd, b.OS, b.Arch, xOsExts[b.OS])\n\tif b.BinaryName != \"\" {\n\t\tbinaryName = fmt.Sprintf(\"%s%s\",\n\t\t\tb.BinaryName, xOsExts[b.OS])\n\t}\n\treturn filepath.Join(\n\t\t\"./dist/\",\n\t\tfmt.Sprintf(\"%s-%s-%s\",\n\t\t\tb.Cmd, b.OS, b.Arch),\n\t\tbinaryName,\n\t)\n}", "func legacyFileName(prefix, instance, class, id string) string {\n\tvar fileName string\n\tinstance = strings.Replace(instance, \"\\\\\", \"__\", -1)\n\n\t// use it to build the file name\n\tif prefix == \"\" {\n\t\tfileName = fmt.Sprintf(\"%s_%s_%s.status\", instance, class, id)\n\t} else {\n\t\tfileName = fmt.Sprintf(\"%s_%s_%s_%s.status\", prefix, instance, class, id)\n\t}\n\treturn fileName\n}", "func getOptFileName(filename string) string {\n\treturn genLib.SplitFilePath(filename, \"opt\").OutputNewExt\n}", "func GetStaticFileName(path string) (name string) {\r\n\tpathFormal := filepath.FromSlash(filepath.Clean(path))\r\n\tslashIdx := strings.LastIndex(pathFormal, \"\\\\\")\r\n\r\n\tif isStatic, _ := StaticSuffixDetermine(pathFormal[slashIdx+1:], \"\"); isStatic {\r\n\t\treturn pathFormal[slashIdx+1:]\r\n\t}\r\n\treturn \"\"\r\n}", "func NewFilename(id uint64, dir string) string {\n\treturn filepath.Join(dir, IDToFilename(id))\n}", "func (l *Logger) getFilename() (filename string) {\n\t// Get current unix timestamp\n\tnow := time.Now().UnixNano()\n\t// Create a filename by:\n\t//\t- Concatinate directory and name\n\t//\t- Append unix timestamp\n\t//\t- Append log extension\n\treturn fmt.Sprintf(\"%s.%d.log\", path.Join(l.dir, l.name), now)\n}", "func createFilename(filePath string, documentPath string) string {\n\t_, dcFn := filepath.Split(documentPath)\n\n\t// if no filePath is specified then use the documentpath\n\tif len(filePath) == 0 {\n\t\t// take document filename, strip suffix, then use that.\n\t\t// local directory in that case.\n\t\treturn strings.TrimSuffix(dcFn, filepath.Ext(documentPath))\n\t}\n\n\tfpDir, fpFn := filepath.Split(filePath)\n\n\tif IsDir(filePath) {\n\t\t// need to make sure fbFn is not a directory\n\t\tfpDir = filepath.Clean(filePath)\n\t\tfpFn = \"\"\n\t}\n\n\tif len(fpFn) == 0 {\n\t\t// filepath directory but not file\n\t\tfp := strings.TrimSuffix(dcFn, filepath.Ext(dcFn))\n\t\treturn filepath.Join(fpDir, fp)\n\t}\n\n\treturn strings.TrimSuffix(filePath, filepath.Ext(filePath))\n}", "func adjustFilename(in string, extension string) string {\n\tout := strings.Split(in, \".\")\n\treturn out[0] + extension\n}", "func Generate(req *plugin.CodeGeneratorRequest, p Plugin, filenameSuffix string) *plugin.CodeGeneratorResponse {\n\tg := New()\n\tg.Request = req\n\tif len(g.Request.FileToGenerate) == 0 {\n\t\tg.Fail(\"no files to generate\")\n\t}\n\n\tg.CommandLineParameters(g.Request.GetParameter())\n\n\tg.WrapTypes()\n\tg.SetPackageNames()\n\tg.BuildTypeNameMap()\n\tg.GeneratePlugin(p)\n\n\tfor i := 0; i < len(g.Response.File); i++ {\n\t\tg.Response.File[i].Name = proto.String(\n\t\t\tstrings.Replace(*g.Response.File[i].Name, \".pb.go\", filenameSuffix, -1),\n\t\t)\n\t}\n\tif err := FormatSource(g.Response); err != nil {\n\t\tg.Error(err)\n\t}\n\treturn g.Response\n}", "func programName(filename string) string {\n\tfilename = filepath.Base(filename)\n\text := filepath.Ext(filename)\n\treturn filename[:len(filename)-len(ext)]\n}", "func getFilename(src string) string {\n\trs := []rune(src)\n\ti := strings.LastIndex(src, \"\\\\\")\n\tif i == -1 {\n\t\ti = strings.LastIndex(src, \"/\")\n\t}\n\tres := string(rs[i+1:])\n\tres = strings.Split(res, \".bz2\")[0]\n\treturn res\n}", "func (p *Post) GetFileName() string {\n\ttimeStamp, _ := time.Parse(time.RubyDate, p.CreatedAt)\n\treturn fmt.Sprintf(\"%d-%s-%dx%d.%s\", timeStamp.Unix(), p.Id, p.Width, p.Height, getFileExt(p.FileURL))\n}", "func FileExtension() string {\n\treturn getRandValue([]string{\"file\", \"extension\"})\n}", "func getFullFilePath(objectDir string, extension string) string {\n\tprecompiledObjectName := filepath.Base(objectDir) //the base of the object's directory matches the name of the file\n\tfileName := strings.Join([]string{precompiledObjectName, extension}, \".\")\n\tfilePath := filepath.Join(objectDir, fileName)\n\treturn filePath\n}", "func GetFilePath(suffix string) string {\n\tid := core.GetID()\n\tyear := strconv.Itoa(time.Now().Year())\n\tmonth := time.Now().Format(\"01\")\n\tday := strconv.Itoa(time.Now().Day())\n\treturn filepath.Join(DataPath, year+month+day, id[0:1], id[2:3], id[4:5], id[6:7], id+\".\"+suffix)\n}", "func (t Test) BaseFilename() string {\n\tparts := strings.Split(t.Filepath, \"rest-api-spec/test\")\n\tif len(parts) < 1 {\n\t\tpanic(fmt.Sprintf(\"Unexpected parts for path [%s]: %s\", t.Filepath, parts))\n\t}\n\treturn strings.TrimPrefix(parts[1], string(filepath.Separator))\n}", "func MakeMigrationFilename(m Migration) string {\n\treturn MakeFilename(\n\t\tm.Version().String(),\n\t\tm.Indirection(),\n\t\tm.Label(),\n\t)\n}", "func (x ExportResult) Filename() (string) {\n _, filename := filepath.Split(x.Path)\n return filename\n}", "func generateServiceImplFile(pdArr []ProtoData, option string) error {\n\tdirPath := filepath.Join(appPath)\n\t_, fileErr := os.Stat(dirPath)\n\tif fileErr != nil {\n\t\tos.MkdirAll(dirPath, os.ModePerm)\n\t}\n\tfor _, pd := range pdArr {\n\t\tconnectorFile := filepath.Join(appPath, strings.Split(protoFileName, \".\")[0]+\".\"+pd.RegServiceName+\".\"+option+\".grpcservice.go\")\n\t\tf, err := os.Create(connectorFile)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"error: \", err)\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\tpd.Option = option\n\t\tif strings.Compare(option, \"server\") == 0 {\n\t\t\terr = registryServerTemplate.Execute(f, pd)\n\t\t} else {\n\t\t\terr = registryClientTemplate.Execute(f, pd)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func modify_filename(filename string) string{\n\tfilenameRaw := strings.Split(filename, \".\")\n\tnewFilename := filenameRaw[0] + \"1\" + \".\" + filenameRaw[1]\n\treturn newFilename\n\n}", "func FileNameExt(filename string) string {\n\treturn filepath.Ext(filename)\n}", "func commandName(filename string) string {\n\treturn filepath.Base(strings.ReplaceAll(filename, filepath.Ext(filename), \"\"))\n}", "func outputPath(filename string, testFile bool) string {\n\tfilename = filepath.Clean(filename)\n\tfilename = filename[len(filepath.VolumeName(filename)):]\n\tfilename = filepath.ToSlash(filename)\n\tfilename = strings.TrimSuffix(filename, filepath.Ext(filename)) + *suffixFlag\n\tif testFile {\n\t\tfilename += \"_test\"\n\t}\n\tfilename += \".go\"\n\treturn filename\n}", "func templatePathToActual(templFilePath, svcName string) string {\n\t// Switch \"NAME\" in path with svcName.\n\t// i.e. for svcName = addsvc; /NAME -> /addsvc-service/addsvc\n\tactual := strings.Replace(templFilePath, \"NAME\", strings.ToLower(svcName), -1)\n\n\tactual = strings.TrimSuffix(actual, \".tmpl\")\n\n\treturn actual\n}", "func (deb *DebPkg) GetFilename() string {\n\treturn fmt.Sprintf(\"%s-%s_%s.%s\",\n\t\tdeb.control.info.name,\n\t\tdeb.control.info.version.full,\n\t\tdeb.control.info.architecture,\n\t\tdebianFileExtension)\n}", "func getResultFilePath(outDir, name, subtype, suffix string) string {\n\treturn filepath.Join(outDir, fmt.Sprintf(\"%s_%s_%s\", name, subtype, suffix))\n}", "func filename() string {\n\tname := \"results b\" + string('0'+blanktone-38)\n\tif rhfinals {\n\t\tname += \" rhf\"\n\t}\n\treturn name + \".txt\"\n}", "func (l *line) fileName() string {\n\treturn l.file.path + dot + l.opts.Extension\n}", "func GetUniqueFilename(dir string, fname string) (string, error) {\r\n\tif _, err := os.Stat(path.Join(dir, fname)); os.IsNotExist(err) {\r\n\t\treturn fname, nil\r\n\t}\r\n\text := filepath.Ext(fname)\r\n\tattempt := 1\r\n\tfor attempt < 100 {\r\n\t\tnewname := FileBasename(fname) + \"_\" + strconv.Itoa(attempt) + ext\r\n\t\tif _, err := os.Stat(path.Join(dir, newname)); os.IsNotExist(err) {\r\n\t\t\treturn newname, nil\r\n\t\t}\r\n\t\tattempt++\r\n\t}\r\n\treturn \"\", errors.New(\"Please, rename file and try again\")\r\n}", "func (r RepoConfig) Filename(base string) string {\n\tif r.OutputFilename != \"\" {\n\t\treturn r.OutputFilename\n\t}\n\n\treturn path.Join(base, fmt.Sprintf(\"%s.json\", r.Name))\n}", "func fileNameWOExt(filePath string) string {\n\tfileName := filepath.Base(filePath)\n\treturn strings.TrimSuffix(fileName, filepath.Ext(fileName))\n}", "func (dp *Dumper) Filename(key registry.ServiceKey) string {\n\tdp.once.Do(func() {\n\t\terr := os.MkdirAll(dp.dir, 0755)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(\"os.MkdirAll(%s): %+v\", dp.dir, err)\n\t\t}\n\t})\n\n\treturn filepath.Join(dp.dir, key.ToString())\n}", "func getStatisticFilePath(outDir string, logPath string) (string, error) {\n\t_, logFile := path.Split(logPath)\n\tlogFileName := strings.Split(logFile, \".\")[0]\n\t//logFileBaseName := strings.Split(logFileName)\n\treturn path.Join(outDir, logFileName + \".json\"), nil\n}", "func fileName(name, version string) string {\n\treturn strings.ToLower(fmt.Sprintf(\"%s_v%s.html\", fileNamePrefix(name), version))\n}", "func (f *Function) GetCodeTemplateFileName() string {\n\tif f.Runtime == NodeRuntime {\n\t\tif f.Handler == HttpHandler {\n\t\t\treturn \"http.js\"\n\t\t}\n\t\treturn \"cron.js\"\n\t}\n\n\tif f.Handler == HttpHandler {\n\t\treturn \"http.go\"\n\t}\n\treturn \"cron.go\"\n}", "func Filename(in string) (name string) {\n\tname, _ = fileAndExt(in, fpb)\n\treturn\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 accountFilename(suffix, account, netdir string) string {\n\tif account == \"\" {\n\t\t// default account\n\t\treturn filepath.Join(netdir, suffix)\n\t}\n\n\t// non-default account\n\treturn filepath.Join(netdir, fmt.Sprintf(\"%v-%v\", account, suffix))\n}", "func makePkgManFileName(operatorName string) string {\n\treturn strings.ToLower(operatorName) + packageManifestFileExt\n}", "func (s *Store) idFile(ctx context.Context, name string) string {\n\tif s.crypto == nil {\n\t\treturn \"\"\n\t}\n\n\tfn := name\n\n\tvar cnt uint8\n\n\tfor {\n\t\tcnt++\n\t\tif cnt > 100 {\n\t\t\tbreak\n\t\t}\n\n\t\tif fn == \"\" || fn == Sep {\n\t\t\tbreak\n\t\t}\n\n\t\tgfn := filepath.Join(fn, s.crypto.IDFile())\n\t\tif s.storage.Exists(ctx, gfn) {\n\t\t\treturn gfn\n\t\t}\n\n\t\tfn = filepath.Dir(fn)\n\t}\n\n\treturn s.crypto.IDFile()\n}", "func (s Settings) DstFilename() string {\n\tif s.enumType == \"\" {\n\t\treturn \"\"\n\t}\n\tif s.dstDir == \"\" {\n\t\ts.dstDir, _ = os.Getwd()\n\t}\n\treturn filepath.Join(s.dstDir, naming.SnakeCase(s.enumType)+goFileExt)\n}", "func pkgFilePath(frame *runtime.Frame) string {\n\tpre := pkgPrefix(frame.Function)\n\tpost := pathSuffix(frame.File)\n\tif pre == \"\" {\n\t\treturn post\n\t}\n\treturn pre + \"/\" + post\n}", "func GenerateName() string {\n\ttestName := fmt.Sprintf(\"%s-%s\", NamePrefix, uuid.NewV4().String()[:8])\n\treturn testName\n}", "func generateName(c asserter, prefix string, maxLen int) string {\n\tname := c.CompactScenarioName() // don't want to just use test name here, because each test contains multiple scenarios with the declarative runner\n\n\ttextualPortion := fmt.Sprintf(\"%s-%s\", prefix, strings.ToLower(name))\n\t// GUIDs are less prone to overlap than times.\n\tguidSuffix := uuid.New().String()\n\tif maxLen > 0 {\n\t\tmaxTextLen := maxLen - len(guidSuffix)\n\t\tif maxTextLen < 1 {\n\t\t\tpanic(\"max len too short\")\n\t\t}\n\t\tif len(textualPortion) > maxTextLen {\n\t\t\ttextualPortion = textualPortion[:maxTextLen]\n\t\t}\n\t}\n\tname = textualPortion + guidSuffix\n\treturn name\n}", "func (b *BootstrapRepo) GenBSFile(extension string) (string, error) {\n\tbsAll, err := fakedata.BootstrapFakeData(b.domain)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfilename := fmt.Sprintf(\"%s.%s\", sharedConfig.NewID(), extension)\n\tjoined := filepath.Join(b.savePath, filename)\n\treturn b.sharedGenBS(bsAll, joined, extension)\n}", "func fileDir() string {\n\n\t_, filename, _, _ := runtime.Caller(0)\n\treturn path.Dir(filename)\n}", "func getFileName(url string, videoType string) string{\n\n\tfilename := url[:strings.Index(url, videoType)]\n\tfilename = filepath.Base(filename)\n\tfilename = filename + \".mp4\"\n\treturn filename\n\n}", "func GetFileName(file *multipart.FileHeader) (newFileName string, err error) {\n\treturn strconv.Itoa(int(time.Now().Unix())) + file.Filename, nil\n}", "func (artifact *Artifact) extension() string {\n\tconst unknown = \"\"\n\ti := strings.Index(artifact.File, \".\")\n\n\tif i != -1 {\n\t\ti = 1 + i\n\t\treturn artifact.File[i:]\n\t}\n\treturn unknown\n}", "func GetDownloadFilename(\n\tresponse *http.Response, nonStableDB bool, desiredVersion string,\n) (string, error) {\n\tfilename := fmt.Sprintf(\"cockroach-%s\", desiredVersion)\n\tif runtime.GOOS == \"windows\" {\n\t\tfilename += \".exe\"\n\t}\n\treturn filename, nil\n}", "func IntermediateFileName(\n\tjobName string, mapTaskIdx int, reduceTaskIdx int,\n) string {\n\tfileName := \"mrtmp.\" + jobName\n\tfileName += \"-mapper-\" + strconv.Itoa(mapTaskIdx)\n\tfileName += \"-output-for-reducer-\" + strconv.Itoa(reduceTaskIdx)\n\n\treturn fileName\n}", "func getFileExtensionBySdk(precompiledObjectPath string) (string, error) {\n\tsdk := strings.Split(precompiledObjectPath, string(os.PathSeparator))[0]\n\tvar extension string\n\tswitch sdk {\n\tcase pb.Sdk_SDK_JAVA.String():\n\t\textension = javaExtension\n\tcase pb.Sdk_SDK_PYTHON.String():\n\t\textension = pyExtension\n\tcase pb.Sdk_SDK_GO.String():\n\t\textension = goExtension\n\tcase pb.Sdk_SDK_SCIO.String():\n\t\textension = scioExtension\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"\")\n\t}\n\treturn extension, nil\n}", "func GetFileName(url string, videoType string) string{\n\n\tif videoType == \".m3u8\" {\n\t\tif strings.Contains(url, \"/d1.vnecdn.net/\"){\n\t\t\tvar re = regexp.MustCompile(`(?m)[a-z0-9\\-\\_]+\\-\\d{8,}`)\n\t\t\tmatch := re.FindString(url)\n\n\t\t\treturn match + \".mp4\"\n\t\t} else if strings.Contains(url, \"ss-hls.catscdn.vn\") {\n\t\t\tvar re = regexp.MustCompile(`(?m)[a-z0-9\\-\\_]+\\.mp4`)\n\t\t\tmatch := re.FindString(url)\n\n\t\t\treturn match + \".mp4\"\n\t\t}\n\t}\n\n\tfilename := url[:strings.Index(url, videoType)]\n\tfilename = filepath.Base(filename)\n\tfilename = filename + \".mp4\"\n\n\treturn filename\n}", "func GenerateName(group metav1.Object, jobIndex int) string {\n\treturn fmt.Sprintf(\"%s-%d\", group.GetName(), jobIndex+1)\n}", "func createFileName(address string) string {\n\tts := time.Now().UTC()\n\treturn fmt.Sprintf(\"UTC--%s--%s.json\", toISO8601(ts), address)\n}", "func (g *Generator) RecommendedFileName() string {\n\t//this is called after Build(), so we can assume that package name,\n\t//version, etc. were already validated\n\tpkg := g.Package\n\treturn fmt.Sprintf(\"%s-%s-%s.pkg.tar.xz\", pkg.Name, fullVersionString(pkg), archMap[pkg.Architecture])\n}", "func sourceFileDirectory() string {\n\t_, filename, _, _ := runtime.Caller(1)\n\treturn filepath.Dir(filename)\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 generateTitle(filename string) string {\n\tabsPath, err := filepath.Abs(filename)\n\tif err != nil {\n\t\treturn filepath.Base(filename)\n\t}\n\t// First try to find the relative path to the home directory\n\trelPath, err := filepath.Rel(os.Getenv(\"HOME\"), absPath)\n\tif err != nil {\n\t\t// If the relative directory to $HOME could not be found, then just use the base filename\n\t\treturn filepath.Base(filename)\n\t}\n\ttitle := filepath.Join(\"~\", relPath)\n\t// If the relative directory path is too long, just use the base filename\n\tif len(title) >= 30 {\n\t\ttitle = filepath.Base(filename)\n\t}\n\treturn title\n}", "func GenerateDerivedServiceName(serviceName string) string {\n\treturn fmt.Sprintf(\"%s-%s\", derivedServicePrefix, serviceName)\n}", "func (g *generator) customOpProtoName() string {\n\tf := g.descInfo.ParentFile[g.aux.customOp.message]\n\treturn fmt.Sprintf(\".%s.%s\", f.GetPackage(), g.aux.customOp.message.GetName())\n}", "func generateMetadataName(remote string) (newRemote string) {\n\treturn remote + metaFileExt\n}", "func GetBlobFilename(filename string, datetime time.Time) string {\n\treturn datetime.Format(filePrefixFormat) + filename\n}", "func (c *NodeGroup) generateName() string {\n\treturn fmt.Sprintf(\"%s-%s\", strings.ReplaceAll(c.Name, \" \", \"-\"), uuid.NewString()[:8])\n}", "func (id Id) Filename() string {\n\treturn strings.Replace(id.String(), \":\", \"-\", -1)\n}", "func getExt(p string) string {\n\treturn strings.ToLower(path.Ext(p))\n}", "func GetFileName(token string) (string, error) {\n\tsql := \"select name from files where autoName=?\"\n\tvar fileName string\n\trows := database.query(sql, fileName)\n\tif rows.Next() {\n\t\terr := rows.Scan(&fileName)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fileName, nil\n}", "func GetFrameFilename(filename string) string {\n\t_, file := filepath.Split(filename)\n\tfile = strings.TrimSuffix(file, filepath.Ext(file))\n\tframeFileName := path.Join(config.Opts.FrameDir, file+\".frame.jpg\")\n\treturn frameFileName\n}", "func (s *Store) idFile(ctx context.Context, name string) string {\n\tfn := name\n\tvar cnt uint8\n\tfor {\n\t\tcnt++\n\t\tif cnt > 100 {\n\t\t\tbreak\n\t\t}\n\t\tif fn == \"\" || fn == sep {\n\t\t\tbreak\n\t\t}\n\t\tgfn := filepath.Join(fn, s.crypto.IDFile())\n\t\tif s.store.Exists(ctx, gfn) {\n\t\t\treturn gfn\n\t\t}\n\t\tfn = filepath.Dir(fn)\n\t}\n\treturn s.crypto.IDFile()\n}", "func determineFileOutputPath(c *cli.Context) (outpath string) {\n\toutpath = c.String(\"out\")\n\n\tif strings.HasSuffix(outpath, \".go\") {\n\t\treturn outpath\n\t}\n\n\tif strings.ToLower(filepath.Base(outpath)) == \"migrations\" {\n\t\treturn filepath.Join(filepath.Dir(outpath), \"migrations.go\")\n\t}\n\n\treturn filepath.Join(outpath, \"migrations.go\")\n}", "func (f *factory) pageFileName(index int64) string {\n\treturn filepath.Join(f.path, fmt.Sprintf(\"%d.%s\", index, pageSuffix))\n}", "func getFilePath() string {\n\t_, filename, _, _ := runtime.Caller(1)\n\treturn path.Join(path.Dir(filename), \"/ratelimiter.lua\")\n}", "func IDToFilename(id uint64) string {\n\treturn fmt.Sprintf(\"%08x\", id) + fileSuffix\n}", "func GetFilePath(req *pb.Request) (string, error) {\n\text, err := getExtFromType(req.Type)\n\tif err != nil {\n\t\text, err = getExtFromUri(req.Uri)\n\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"could not parse ext from either type %s or uri %s\", req.Type.String(), req.Uri)\n\t\t}\n\t}\n\n\tcreatedTime := time.Unix(int64(req.Created), 0)\n\tcleanTitle := cleanTitle(req.Title)\n\n\treturn filepath.Join(req.Type.String(), createdTime.Format(\"2006/01/02\"), fmt.Sprintf(\"%s.%s\", cleanTitle, ext)), nil\n}" ]
[ "0.7159262", "0.7015586", "0.70049655", "0.64598197", "0.6322077", "0.6313036", "0.61655617", "0.60880876", "0.6077366", "0.59720206", "0.59513104", "0.59406734", "0.59303725", "0.58968973", "0.58964074", "0.5814274", "0.5774253", "0.57570577", "0.5718658", "0.5708201", "0.56948286", "0.56682867", "0.56381834", "0.56202304", "0.56140614", "0.561307", "0.5590354", "0.55823576", "0.557345", "0.55690044", "0.55583715", "0.55573976", "0.5542693", "0.5540137", "0.5521523", "0.5520234", "0.5512975", "0.5465833", "0.5456441", "0.5452264", "0.54444295", "0.5439873", "0.5436934", "0.5419241", "0.5415464", "0.5410029", "0.54076666", "0.54037344", "0.54036623", "0.5401045", "0.5400281", "0.53938806", "0.5392703", "0.53883827", "0.5386724", "0.5374138", "0.5366987", "0.53640354", "0.5346236", "0.5342408", "0.5342385", "0.5341135", "0.53257185", "0.5322287", "0.5306154", "0.530312", "0.53007066", "0.53004885", "0.52908796", "0.52893203", "0.52832776", "0.5281174", "0.5271781", "0.5270454", "0.526768", "0.5262182", "0.5257812", "0.5251746", "0.5250154", "0.5245377", "0.5239986", "0.52303314", "0.52275944", "0.5222505", "0.522078", "0.5218656", "0.52058566", "0.5204479", "0.5199866", "0.51986825", "0.51817757", "0.5180079", "0.51792306", "0.51697594", "0.5168553", "0.51684237", "0.5164635", "0.5157422", "0.51572365", "0.51531684" ]
0.80490637
0
Execute adds all child commands to the root command and sets flags appropriately. This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Execute() {\n\tif err := RootCmd.Execute(); err != nil {\n\t\tlog.Fatal(\"[FATAL] unable to add child commands to the root command\")\n\t}\n}", "func Execute() {\n\tif err := initSubCommands(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tif err := rootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}", "func Execute() {\n\tdefer func() {\n\t\t_ = gutils.Logger.Sync()\n\t}()\n\trand.Seed(time.Now().UnixNano())\n\n\tvar err error\n\tif err = gutils.Settings.BindPFlags(rootCmd.Flags()); err != nil {\n\t\tgutils.Logger.Panic(\"bind flags\", zap.Error(err))\n\t}\n\n\tif gutils.Settings.GetBool(\"debug\") {\n\t\tif err := gutils.Logger.ChangeLevel(gutils.LoggerLevelDebug); err != nil {\n\t\t\tgutils.Logger.Panic(\"change logger level to debug\", zap.Error(err))\n\t\t}\n\t}\n\n\tif err = rootCmd.Execute(); err != nil {\n\t\tgutils.Logger.Panic(\"parse command line arguments\", zap.Error(err))\n\t}\n}", "func (r *RootCmd) Execute() error {\n\treturn r.c.Execute()\n}", "func Execute() {\n\tinitRootCmdFlags()\n\n\tcleanupFunc := func() {\n\t\tvar wg = &sync.WaitGroup{}\n\t\tfor _, f := range cleanupFuncs {\n\t\t\twg.Add(1)\n\t\t\tgo f(wg)\n\t\t}\n\t\twg.Wait()\n\t}\n\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\tgo func() {\n\t\t<-c\n\t\tlog.Printf(\"Interrupted\")\n\t\tcleanupFunc()\n\t\tos.Exit(1)\n\t}()\n\n\terr := RootCmd.Execute()\n\tif err != nil {\n\t\tlog.Printf(\"Error: %s\", err)\n\t}\n\n\tcleanupFunc()\n\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n}", "func Execute() error { return rootCmd.Execute() }", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tlogrus.WithFields(logrus.Fields{\"reason\": err}).Fatal(\"unable execute rootCmd\")\n\t}\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\terrExit(err)\n\t}\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\teh.ExitOnError(err)\n\t}\n\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tlog.Error(err)\n\t}\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\texitWithError(err)\n\t}\n}", "func Execute(rootCmd fw.Command) {\n\terr := rootCmd.Execute()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tfmt.Println(Red(err))\n\t\tos.Exit(1)\n\t}\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n}", "func Execute() {\n\tflags := rootCmd.Flags()\n\tflags.SetInterspersed(false)\n\n\tpersistentFlags := rootCmd.PersistentFlags()\n\tpersistentFlags.BoolVarP(&debug, \"debug\", \"d\", false, \"print out debug information\")\n\n\tif err := rootCmd.Execute(); err != nil {\n\t\tos.Exit(1)\n\t}\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}", "func Execute() {\n\n\tif e := rootCmd.Execute(); e != nil {\n\t\tutils.Error().Err(e).Send()\n\t\tos.Exit(1)\n\t}\n}", "func Execute() {\r\n\tif err := rootCmd.Execute(); err != nil {\r\n\t\tfmt.Println(err)\r\n\t\tos.Exit(1)\r\n\t}\r\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n}", "func Execute() {\n\tif err := cmdInit(); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tif err := rootCmd.Execute(); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}", "func Execute() {\n\n\tif err := rootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tlog.Print(err)\n\t\tos.Exit(1)\n\t}\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tfmt.Print(err)\n\t\tos.Exit(1)\n\t}\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tlog.Fatal().Err(err).Send()\n\t}\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\n\t}\n\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tlog.Println(err)\n\t\tos.Exit(1)\n\t}\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tlog.Println(err)\n\t\tos.Exit(1)\n\t}\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() error {\n\treturn rootCmd.Execute()\n}", "func Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tlogrus.Error(err)\n\t\tos.Exit(1)\n\t}\n}" ]
[ "0.7883761", "0.7761668", "0.76657826", "0.76602453", "0.7636092", "0.75491834", "0.7535363", "0.7501637", "0.7483472", "0.74762964", "0.74595875", "0.7448777", "0.7448777", "0.7443535", "0.74403316", "0.7436203", "0.74361795", "0.74361795", "0.7432754", "0.74320066", "0.74320066", "0.74320066", "0.7430753", "0.74296516", "0.74262136", "0.74262136", "0.74262136", "0.74262136", "0.7425896", "0.7425896", "0.7423175", "0.7422824", "0.7422243", "0.741879", "0.7413358", "0.740839", "0.7406377", "0.7406377", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7405727", "0.7404137" ]
0.0
-1
expectFlag exits with an error if the flag value is empty.
func expectFlag(flag, value string) { if value == "" { exit.WithMessage(fmt.Sprintf("You must specify the %q flag", flag)) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TestExitOnUnknownFlag(t *testing.T) {\n\terr := joincap([]string{\"joincap\", \"--banana\"})\n\tif err == nil {\n\t\tt.Fatal(\"Shouldn't exited without an error\")\n\t}\n\tif !strings.Contains(err.Error(), \"unknown flag\") ||\n\t\t!strings.Contains(err.Error(), \"banana\") {\n\t\tt.FailNow()\n\t}\n}", "func verify(err error, str interface{}) {\n\tif err != nil {\n\t\tfmt.Printf(\"Error retrieving flag for %s \\n\", str)\n\t\tos.Exit(1)\n\t}\n}", "func TestEmptyInputs(t *testing.T) {\n\tc := &Command{Use: \"c\", Run: emptyRun}\n\n\tvar flagValue int\n\tc.Flags().IntVarP(&flagValue, \"intf\", \"i\", -1, \"\")\n\n\toutput, err := executeCommand(c, \"\", \"-i7\", \"\")\n\tif output != \"\" {\n\t\tt.Errorf(\"Unexpected output: %v\", output)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tif flagValue != 7 {\n\t\tt.Errorf(\"flagValue expected: %v, got %v\", 7, flagValue)\n\t}\n}", "func pflagFlagErrMsgFlag(errMsg string) string {\n\tflagText := strings.TrimPrefix(errMsg, \"no such flag \")\n\tflagText = strings.TrimPrefix(flagText, \"unknown flag: \")\n\tflagText = strings.TrimPrefix(flagText, \"bad flag syntax: \")\n\t// unknown shorthand flag: 'x' in -x\n\tflagText = strings.TrimPrefix(flagText, \"unknown shorthand flag: \")\n\n\tif flagText == errMsg {\n\t\treturn \"\"\n\t}\n\n\tshorthandSplit := strings.Split(flagText, \"' in \")\n\tif len(shorthandSplit) > 1 {\n\t\tflagText = shorthandSplit[1]\n\t}\n\n\treturn flagText\n}", "func ArgNonEmpty(option *Option) error {\n if option.HasArg && option.Arg != \"\" {\n return ARG_OK\n }\n return fmt.Errorf(\"Option '%v' requires a non-empty argument\", option)\n}", "func checkArgValue(v string, found bool, def cmdkit.Argument) error {\n\tif def.Variadic && def.SupportsStdin {\n\t\treturn nil\n\t}\n\n\tif !found && def.Required {\n\t\treturn fmt.Errorf(\"argument %q is required\", def.Name)\n\t}\n\n\treturn nil\n}", "func checkFlags() {\n\t// file flag is required\n\tif *filename == \"\" {\n\t\tlog.Fatalf(\"file is required\")\n\t}\n\n\tif *server == \"\" {\n\t\tlog.Fatalf(\"server is required\")\n\t}\n}", "func HasSingleFlagNonemptyArgument(flag string, params []string) bool {\n\tfound := filterFlags(params, flag)\n\tif len(found) != 1 {\n\t\treturn false\n\t}\n\n\t_, value := splitKV(found[0], \"=\")\n\tif value == \"\" {\n\t\treturn false\n\t}\n\treturn true\n}", "func verifyFlags(opt *options, fs *flag.FlagSet) {\n args := fs.Args()\n if len(args) > 0 {\n opt.Root = args[0]\n args = args[1:]\n }\n if len(args) > 0 {\n patterns := make([]string, len(args))\n for i := range args {\n patterns[i] = fmt.Sprintf(\"(%s)\", args[i])\n }\n opt.SpecPattern = strings.Join(patterns, \"|\")\n }\n}", "func CheckBenchmarkFlag(flag bool) {\n\t// If --benchmark flag is passed by user, this will be set to true.\n\tbenchmarkFlag = flag\n}", "func MatchFlag(full string, arg string) bool {\n\treturn Match(\"--\"+full, arg)\n}", "func checkFlag(fs *pflag.FlagSet, name string) (wasSet bool) {\n\tfs.Visit(func(f *pflag.Flag) {\n\t\tif f.Name == name {\n\t\t\twasSet = true\n\t\t}\n\t})\n\n\treturn\n}", "func checkFlag(f bool) error {\n\t// If the parameter is false return an appError.\n\tif !f {\n\t\treturn &appError{\n\t\t\terrors.New(\"App Error\"),\n\t\t\t\"App Error\",\n\t\t\t2,\n\t\t}\n\t}\n\n\t// Return a default error.\n\treturn errors.New(\"Normal error\")\n}", "func TestNilInt(t *testing.T) {\n\ty := GetIntFlag(\"example\").Value()\n\tassert.Nil(t, y)\n}", "func (errflag *ERR_FLAG) fail() {\n\t*errflag = 1\n}", "func isUnsupportedFlag(value string) bool {\n\n\t// a flag should be at least two characters log\n\tif len(value) >= 2 {\n\n\t\t// if short flag, it should start with `-` but not with `--`\n\t\tif len(value) == 2 {\n\t\t\treturn !strings.HasPrefix(value, \"-\") || strings.HasPrefix(value, \"--\")\n\t\t}\n\n\t\t// if long flag, it should start with `--` and not with `---`\n\t\treturn !strings.HasPrefix(value, \"--\") || strings.HasPrefix(value, \"---\")\n\t}\n\n\treturn false\n}", "func (p *common) expect(sym lss.Symbol, msg string, skip ...lss.Symbol) {\n\tassert.For(p.done, 20)\n\tif !p.await(sym, skip...) {\n\t\tp.mark(msg)\n\t}\n\tp.done = false\n}", "func assert(flag bool, s string) {\n\tif !flag {\n\t\tpanic(s)\n\t}\n}", "func (f *FakeOutput) ExpectNoEntry(t testing.TB, timeout time.Duration) {\n\tselect {\n\tcase <-f.Received:\n\t\trequire.FailNow(t, \"Should not have received entry\")\n\tcase <-time.After(timeout):\n\t\treturn\n\t}\n}", "func verifyOnFailureArg(err error, onFailure string) {\n\tif err != nil && (\n\t\tonFailure == cloudformation.OnFailureDelete ||\n\t\t\tonFailure == cloudformation.OnFailureRollback ||\n\t\t\tonFailure == cloudformation.OnFailureDoNothing) {\n\t\tfmt.Printf(\"onFailure provided with invalid flag with err: %s \\n\", err)\n\t\tos.Exit(1)\n\t}\n}", "func NFlag() int { return len(CommandLine.actual) }", "func (t *T) ExpectFalse(v bool) {\n\tif v {\n\t\tlog.Println(\"Expectation failed: boolean is not false\")\n\t\tt.Failed = true\n\t}\n}", "func ContainsFlag(flag string) bool {\n\tonce.Do(cmdLineOpener)\n\t_, present := Flag(flag)\n\treturn present\n}", "func HasSingleFlagArgument(flag string, argument string, params []string) bool {\n\tfound := filterFlags(params, flag)\n\tif len(found) != 1 {\n\t\treturn false\n\t}\n\n\t_, value := splitKV(found[0], \"=\")\n\tif value != argument {\n\t\treturn false\n\t}\n\treturn true\n}", "func HasSingleFlagValidTimeout(flag string, min int, max int, params []string) bool {\n\tfound := filterFlags(params, flag)\n\tif len(found) != 1 {\n\t\treturn false\n\t}\n\n\t_, value := splitKV(found[0], \"=\")\n\ttimeout, err := strconv.Atoi(value) // what about empty parameter?\n\tif err != nil {\n\t\treturn false\n\t}\n\tif timeout < min || timeout > max {\n\t\treturn false\n\t}\n\treturn true\n}", "func (mmIsStopped *mFlagMockIsStopped) Expect() *mFlagMockIsStopped {\n\tif mmIsStopped.mock.funcIsStopped != nil {\n\t\tmmIsStopped.mock.t.Fatalf(\"FlagMock.IsStopped mock is already set by Set\")\n\t}\n\n\tif mmIsStopped.defaultExpectation == nil {\n\t\tmmIsStopped.defaultExpectation = &FlagMockIsStoppedExpectation{}\n\t}\n\n\treturn mmIsStopped\n}", "func (f flagBool) HasArg() bool {\n\treturn false\n}", "func (s *BasePCREListener) ExitOption_flag(ctx *Option_flagContext) {}", "func checkEnvironmentFlag(cmd *cobra.Command) (err error) {\n\tfor i, env := range environment {\n\t\te := strings.Split(env, \"=\")\n\t\t// error on empty flag or env name\n\t\tif len(e) == 0 || e[0] == \"\" {\n\t\t\treturn fmt.Errorf(\"invalid env flag: '%s'\", env)\n\t\t}\n\t\t// if only name given, get from os.Env\n\t\tif len(e) == 1 {\n\t\t\tenvironment[i] = fmt.Sprintf(\"%s=%s\", e[0], os.Getenv(e[0]))\n\t\t}\n\t}\n\treturn\n}", "func multiFlagTester() bool {\n\tnumFlag := flag.NFlag()\n\tif numFlag > 1 {\n\t\treturn true\n\t}\n\treturn false\n}", "func (mmDone *mFlagMockDone) Expect(ctx context.Context, isDone func() bool) *mFlagMockDone {\n\tif mmDone.mock.funcDone != nil {\n\t\tmmDone.mock.t.Fatalf(\"FlagMock.Done mock is already set by Set\")\n\t}\n\n\tif mmDone.defaultExpectation == nil {\n\t\tmmDone.defaultExpectation = &FlagMockDoneExpectation{}\n\t}\n\n\tmmDone.defaultExpectation.params = &FlagMockDoneParams{ctx, isDone}\n\tfor _, e := range mmDone.expectations {\n\t\tif minimock.Equal(e.params, mmDone.defaultExpectation.params) {\n\t\t\tmmDone.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmDone.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmDone\n}", "func (f flagString) HasArg() bool {\n\treturn true\n}", "func (mmStop *mFlagMockStop) Expect(ctx context.Context) *mFlagMockStop {\n\tif mmStop.mock.funcStop != nil {\n\t\tmmStop.mock.t.Fatalf(\"FlagMock.Stop mock is already set by Set\")\n\t}\n\n\tif mmStop.defaultExpectation == nil {\n\t\tmmStop.defaultExpectation = &FlagMockStopExpectation{}\n\t}\n\n\tmmStop.defaultExpectation.params = &FlagMockStopParams{ctx}\n\tfor _, e := range mmStop.expectations {\n\t\tif minimock.Equal(e.params, mmStop.defaultExpectation.params) {\n\t\t\tmmStop.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmStop.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmStop\n}", "func Expect(msg string) error {\n\tif msg != \"\" {\n\t\treturn errors.New(msg)\n\t} else {\n\t\treturn nil\n\t}\n}", "func TestParseEnv(t *testing.T) {\n\n\tsyscall.Setenv(\"BOOL\", \"\")\n\tsyscall.Setenv(\"BOOL2\", \"true\")\n\tsyscall.Setenv(\"INT\", \"22\")\n\tsyscall.Setenv(\"INT64\", \"0x23\")\n\tsyscall.Setenv(\"UINT\", \"24\")\n\tsyscall.Setenv(\"UINT64\", \"25\")\n\tsyscall.Setenv(\"STRING\", \"hello\")\n\tsyscall.Setenv(\"FLOAT64\", \"2718e28\")\n\tsyscall.Setenv(\"DURATION\", \"2m\")\n\n\tf := NewFlagSet(os.Args[0], ContinueOnError)\n\n\tboolFlag := f.Bool(\"bool\", false, \"bool value\")\n\tbool2Flag := f.Bool(\"bool2\", false, \"bool2 value\")\n\tintFlag := f.Int(\"int\", 0, \"int value\")\n\tint64Flag := f.Int64(\"int64\", 0, \"int64 value\")\n\tuintFlag := f.Uint(\"uint\", 0, \"uint value\")\n\tuint64Flag := f.Uint64(\"uint64\", 0, \"uint64 value\")\n\tstringFlag := f.String(\"string\", \"0\", \"string value\")\n\tfloat64Flag := f.Float64(\"float64\", 0, \"float64 value\")\n\tdurationFlag := f.Duration(\"duration\", 5*time.Second, \"time.Duration value\")\n\n\terr := f.ParseEnv(os.Environ())\n\tif err != nil {\n\t\tt.Fatal(\"expected no error; got \", err)\n\t}\n\tif *boolFlag != true {\n\t\tt.Error(\"bool flag should be true, is \", *boolFlag)\n\t}\n\tif *bool2Flag != true {\n\t\tt.Error(\"bool2 flag should be true, is \", *bool2Flag)\n\t}\n\tif *intFlag != 22 {\n\t\tt.Error(\"int flag should be 22, is \", *intFlag)\n\t}\n\tif *int64Flag != 0x23 {\n\t\tt.Error(\"int64 flag should be 0x23, is \", *int64Flag)\n\t}\n\tif *uintFlag != 24 {\n\t\tt.Error(\"uint flag should be 24, is \", *uintFlag)\n\t}\n\tif *uint64Flag != 25 {\n\t\tt.Error(\"uint64 flag should be 25, is \", *uint64Flag)\n\t}\n\tif *stringFlag != \"hello\" {\n\t\tt.Error(\"string flag should be `hello`, is \", *stringFlag)\n\t}\n\tif *float64Flag != 2718e28 {\n\t\tt.Error(\"float64 flag should be 2718e28, is \", *float64Flag)\n\t}\n\tif *durationFlag != 2*time.Minute {\n\t\tt.Error(\"duration flag should be 2m, is \", *durationFlag)\n\t}\n}", "func (m *FlagMock) MinimockStopDone() bool {\n\tfor _, e := range m.StopMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.StopMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterStopCounter) < 1 {\n\t\treturn false\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcStop != nil && mm_atomic.LoadUint64(&m.afterStopCounter) < 1 {\n\t\treturn false\n\t}\n\treturn true\n}", "func expect(cond bool, msg string, args ...any) {\n\tif !cond {\n\t\tpanic(graphError{fmt.Sprintf(msg, args...)})\n\t}\n}", "func VerifyNoArgument(c *cli.Context) error {\n\ta := c.Args()\n\tif a.Present() {\n\t\treturn fmt.Errorf(`Syntax error, command takes no arguments`)\n\t}\n\n\treturn nil\n}", "func (m *FlagMock) MinimockWait(timeout mm_time.Duration) {\n\ttimeoutCh := mm_time.After(timeout)\n\tfor {\n\t\tif m.minimockDone() {\n\t\t\treturn\n\t\t}\n\t\tselect {\n\t\tcase <-timeoutCh:\n\t\t\tm.MinimockFinish()\n\t\t\treturn\n\t\tcase <-mm_time.After(10 * mm_time.Millisecond):\n\t\t}\n\t}\n}", "func ExpectBool(t *testing.T, field string, expected bool, found bool) {\n\tif expected != found {\n\t\tt.Errorf(\"%s [%v], found '%v'\", field, expected, found)\n\t}\n}", "func IsNormalFlag(s AbnormalFlag) bool {\n\treturn s == AbnormalFlagEmpty || s == AbnormalFlagNormal\n}", "func isZeroValue(flag *Flag, value string) bool {\n\t// Build a zero value of the flag's Value type, and see if the\n\t// result of calling its String method equals the value passed in.\n\t// This works unless the Value type is itself an interface type.\n\ttyp := reflect.TypeOf(flag.Value)\n\tvar z reflect.Value\n\tif typ.Kind() == reflect.Ptr {\n\t\tz = reflect.New(typ.Elem())\n\t} else {\n\t\tz = reflect.Zero(typ)\n\t}\n\treturn value == z.Interface().(Value).String()\n}", "func assertFlagsEqual(t *testing.T, expected, actual []Flag) {\n\tassert.Equal(t, len(expected), len(actual))\n\n\tfor k, v := range expected {\n\t\tassert.Equal(t, v, actual[k])\n\t}\n}", "func checkStringFlagReplaceWithUtilVersion(name string, arg string, compulsory bool) (exists bool) {\n\tvar hasArg bool\n\n\tif arg != \"\" {\n\t\texists = true\n\t}\n\n\t// Try to detect missing flag argument.\n\t// If an argument is another flag, argument has not been provided.\n\tif exists && !strings.HasPrefix(arg, \"-\") {\n\t\t// Option expecting an argument but has been followed by another flag.\n\t\thasArg = true\n\t}\n\t/*\n\t\twhere(fmt.Sprintf(\"-%s compulsory = %t\", name, compulsory))\n\t\twhere(fmt.Sprintf(\"-%s exists = %t\", name, exists))\n\t\twhere(fmt.Sprintf(\"-%s hasArg = %t\", name, hasArg))\n\t\twhere(fmt.Sprintf(\"-%s value = %s\", name, arg))\n\t*/\n\n\tif compulsory && !exists {\n\t\tfmt.Fprintf(os.Stderr, \"compulsory flag: -%s\\n\", name)\n\t\tprintUsage()\n\t\tos.Exit(2)\n\t}\n\n\tif exists && !hasArg {\n\t\tfmt.Fprintf(os.Stderr, \"flag -%s needs a valid argument (not: %s)\\n\", name, arg)\n\t\tprintUsage()\n\t\tos.Exit(3)\n\t}\n\n\treturn\n}", "func (t *T) ExpectTrue(v bool) {\n\tif !v {\n\t\tlog.Println(\"Expectation failed: boolean is not true\")\n\t\tt.Failed = true\n\t}\n}", "func Flag(flag string) (string, bool) {\n\tonce.Do(cmdLineOpener)\n\tcanonicalFlag := strings.Replace(flag, \"-\", \"_\", -1)\n\tvalue, present := procCmdLine.AsMap[canonicalFlag]\n\treturn value, present\n}", "func ResetFlagsForTesting() {\n\tflag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ContinueOnError)\n}", "func (flag *flag) TakesValue() bool {\n\treturn flag.FlagValue != nil && !flag.FlagValue.IsBoolFlag()\n}", "func (flags OptFlags) Test(mask OptFlags) bool {\n\treturn flags&mask != 0\n}", "func CheckVerboseFlag(flag bool) {\n\t// If --verbose flag is passed by user, this will be set to true.\n\tverboseFlag = flag\n}", "func (p *parser) expect(tok token.Type) {\n\tif p.tok != tok {\n\t\tp.error(p.off, \"'\"+tok.String()+\"' expected\")\n\t}\n}", "func (m *MockFlag) EXPECT() *MockFlagMockRecorder {\n\treturn m.recorder\n}", "func ValidateFlags(args ...string) error {\n\tfor _, arg := range args {\n\t\tif arg == \"\" {\n\t\t\treturn errors.New(\"Missing flag\")\n\t\t}\n\t}\n\treturn nil\n}", "func (checker *CheckerType) NeedsExpectedValue() bool {\n return true\n}", "func isFlagPassed(name string) bool {\n\tfound := false\n\tflag.Visit(func(f *flag.Flag) {\n\t\tif f.Name == name {\n\t\t\tfound = true\n\t\t}\n\t})\n\treturn found\n}", "func TestMultipleOperationFlags(t *testing.T) {\n\t// Test all combinations\n\topFlags := []string{\"-init\", \"-info\", \"-passwd\", \"-fsck\"}\n\tfor _, flag1 := range opFlags {\n\t\tvar flag2 string\n\t\tfor _, flag2 = range opFlags {\n\t\t\tif flag1 == flag2 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\targs := []string{flag1, flag2, \"/tmp\"}\n\t\t\t//t.Logf(\"testing %v\", args)\n\t\t\tcmd := exec.Command(test_helpers.GocryptfsBinary, args...)\n\t\t\terr := cmd.Run()\n\t\t\texitCode := test_helpers.ExtractCmdExitCode(err)\n\t\t\tif exitCode != exitcodes.Usage {\n\t\t\t\tt.Fatalf(\"this should have failed with code %d, but returned %d\",\n\t\t\t\t\texitcodes.Usage, exitCode)\n\t\t\t}\n\t\t}\n\t}\n}", "func TestConfig_1Flag_1FlagMatch_1BoolFlag_Cmd_1Flag_2Arg_2FlagArrayMatch(context *testing.T) {\n\tinput := \"gomu -include test1 -include test2 -name-only sync -b JIRA-Ticket mod-common simply -i hatchify vroomy\"\n\tos.Args = strings.Split(input, \" \")\n\n\tcommand, err := configureCommand()\n\n\ttest := simply.Target(err, context, \"Error should not exist\")\n\tresult := test.Assert().Equals(nil)\n\ttest.Validate(result)\n\n\ttest = simply.Target(command, context, \"Command should exist\")\n\tresult = test.Assert().DoesNotEqual(nil)\n\ttest.Validate(result)\n\n\ttest = simply.Target(command.Action, context, \"Action should be <sync>\")\n\tresult = test.Equals(\"sync\")\n\ttest.Validate(result)\n\n\ttest = simply.Target(len(command.Arguments), context, \"Arguments should have 2 elements\")\n\tresult = test.Equals(2)\n\ttest.Validate(result)\n\n\ttest = simply.Target(command.Arguments[0].Name, context, \"Argument[0] should be mod-common\")\n\tresult = test.Equals(\"mod-common\")\n\ttest.Validate(result)\n\n\ttest = simply.Target(command.Arguments[1].Name, context, \"Argument[1] should be simply\")\n\tresult = test.Equals(\"simply\")\n\ttest.Validate(result)\n\n\ttest = simply.Target(len(command.Flags), context, \"Flags should have 3 elements\")\n\tresult = test.Equals(3)\n\ttest.Validate(result)\n\n\tincludes, _ := command.Flags[\"-include\"].Value.([]string)\n\ttest = simply.Target(includes[0], context, \"-i[0] should be test1\")\n\tresult = test.Equals(\"test1\")\n\ttest.Validate(result)\n\ttest = simply.Target(includes[1], context, \"-i[1] should be test2\")\n\tresult = test.Equals(\"test2\")\n\ttest.Validate(result)\n\ttest = simply.Target(includes[2], context, \"-i[2] should be hatchify\")\n\tresult = test.Equals(\"hatchify\")\n\ttest.Validate(result)\n\ttest = simply.Target(includes[3], context, \"-i[3] should be vroomy\")\n\tresult = test.Equals(\"vroomy\")\n\ttest.Validate(result)\n\n\tbranch, _ := command.Flags[\"-branch\"].Value.(string)\n\ttest = simply.Target(branch, context, \"-b should be JIRA-Ticket\")\n\tresult = test.Equals(\"JIRA-Ticket\")\n\ttest.Validate(result)\n\n\tnameOnly, _ := command.Flags[\"-name-only\"].Value.(bool)\n\ttest = simply.Target(nameOnly, context, \"-name-only should be true\")\n\tresult = test.Equals(true)\n\ttest.Validate(result)\n}", "func (m *FlagMock) MinimockDoneInspect() {\n\tfor _, e := range m.DoneMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\tm.t.Errorf(\"Expected call to FlagMock.Done with params: %#v\", *e.params)\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.DoneMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterDoneCounter) < 1 {\n\t\tif m.DoneMock.defaultExpectation.params == nil {\n\t\t\tm.t.Error(\"Expected call to FlagMock.Done\")\n\t\t} else {\n\t\t\tm.t.Errorf(\"Expected call to FlagMock.Done with params: %#v\", *m.DoneMock.defaultExpectation.params)\n\t\t}\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcDone != nil && mm_atomic.LoadUint64(&m.afterDoneCounter) < 1 {\n\t\tm.t.Error(\"Expected call to FlagMock.Done\")\n\t}\n}", "func earlyExit(flag bool) {\n\tif flag {\n\t\tos.Exit(0)\n\t\treturn\n\t}\n}", "func OkNotEmptyString(label, a string, t *testing.T) {\n\tif a != \"\" {\n\t\tt.Logf(\"ok - %s: string is not empty as expected\\n\", label)\n\t} else {\n\t\tt.Logf(\"not ok - %s: String is empty\", label)\n\t\tt.Fail()\n\t}\n}", "func isFlagPassed(set *flag.FlagSet, name string) bool {\n\tif set == nil {\n\t\treturn false\n\t}\n\n\tfound := false\n\tset.Visit(func(f *flag.Flag) {\n\t\tif f.Name == name {\n\t\t\tfound = true\n\t\t}\n\t})\n\n\treturn found\n}", "func validateFlags() error {\n\t// if username == \"\" {\n\t// \treturn fmt.Errorf(\"username is required\")\n\t// }\n\n\tif host == \"\" {\n\t\treturn fmt.Errorf(\"host is required\")\n\t}\n\n\treturn nil\n}", "func parseSingleFlag(flag string) (rune, string, error) {\n\tif flag == \"\" {\n\t\treturn utf8.RuneError, \"\", errors.New(\"cannot use empty flag string\")\n\t}\n\n\tvar firstRune rune\n\tvar bufIndex, runeCount int\n\n\t// Ensure all bytes are valid runes\n\tbuf := []byte(flag)\n\n\tfor bufIndex < len(buf) {\n\t\tthisRune, runeSize := utf8.DecodeRune(buf[bufIndex:])\n\t\tif thisRune == utf8.RuneError {\n\t\t\treturn thisRune, \"\", fmt.Errorf(\"cannot use flag with invalid rune: %q\", flag)\n\t\t}\n\t\tif runeCount == 0 {\n\t\t\tif thisRune == '-' {\n\t\t\t\treturn thisRune, \"\", fmt.Errorf(\"cannot use flag that starts with a hyphen: %q\", flag)\n\t\t\t}\n\t\t\tfirstRune = thisRune\n\t\t}\n\t\truneCount++\n\t\tbufIndex += runeSize\n\t}\n\n\tif runeCount == 1 {\n\t\treturn firstRune, \"\", redefinition(firstRune, \"\")\n\t}\n\treturn utf8.RuneError, flag, redefinition(utf8.RuneError, flag)\n}", "func itValidatesLocketFlags(args ...string) {\n\tContext(\"Locket Flag Validation\", func() {\n\t\tIt(\"exits with status 3 when no locket flags are specified\", func() {\n\t\t\tcmd := exec.Command(cfdotPath, args...)\n\n\t\t\tsess, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess.Exited).Should(BeClosed())\n\n\t\t\tExpect(sess.ExitCode()).To(Equal(3))\n\t\t})\n\t})\n}", "func (a *Arg) parse() {\n\tif len(a.Text) == 0 {\n\t\treturn\n\t}\n\n\t// A pure value, no flag.\n\tif a.Text[0] != '-' {\n\t\ta.Value = a.Text\n\t\ta.HasValue = true\n\t\treturn\n\t}\n\n\t// Seprate the dashes from the flag name.\n\tdahsI := 1\n\tif len(a.Text) > 1 && a.Text[1] == '-' {\n\t\tdahsI = 2\n\t}\n\ta.Dashes = a.Text[:dahsI]\n\ta.HasFlag = true\n\ta.Flag = a.Text[dahsI:]\n\n\t// Empty flag\n\tif a.Flag == \"\" {\n\t\treturn\n\t}\n\t// Third dash or empty flag with equal is forbidden.\n\tif a.Flag[0] == '-' || a.Flag[0] == '=' {\n\t\ta.Parsed = Parsed{}\n\t\treturn\n\t}\n\t// The flag is valid.\n\n\t// Check if flag has a value.\n\tif equal := strings.IndexRune(a.Flag, '='); equal != -1 {\n\t\ta.Flag, a.Value = a.Flag[:equal], a.Flag[equal+1:]\n\t\ta.HasValue = true\n\t\treturn\n\t}\n\n}", "func TestGetInt8VarInvalidValue(t *testing.T) {\n\tfor _, v := range getInt8VarFlagTestsInvalid {\n\t\tt.Run(v, func(t *testing.T) {\n\t\t\tos.Clearenv()\n\t\t\tif err := os.Setenv(variableName, v); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\n\t\t\tv, err := GetInt8Var(variableName, 0)\n\n\t\t\tif err == nil {\n\t\t\t\tt.Error(\"Must be error\")\n\t\t\t}\n\n\t\t\tif v != 0 {\n\t\t\t\tt.Error(\"Variable must contain 0\")\n\t\t\t}\n\t\t})\n\t}\n}", "func (m *ModbusPDUGetComEventLogResponse) ErrorFlag() bool {\n\treturn false\n}", "func isZeroValue(f *flag.Flag, value string) bool {\n\t// Build a zero value of the flag's Value type, and see if the\n\t// result of calling its String method equals the value passed in.\n\t// This works unless the Value type is itself an interface type.\n\ttyp := reflect.TypeOf(f.Value)\n\tvar z reflect.Value\n\tif typ.Kind() == reflect.Ptr {\n\t\tz = reflect.New(typ.Elem())\n\t} else {\n\t\tz = reflect.Zero(typ)\n\t}\n\tif value == z.Interface().(flag.Value).String() {\n\t\treturn true\n\t}\n\n\tswitch value {\n\tcase \"false\":\n\t\treturn true\n\tcase \"\":\n\t\treturn true\n\tcase \"0\":\n\t\treturn true\n\t}\n\treturn false\n}", "func TestMissingOArg(t *testing.T) {\n\tcmd := exec.Command(test_helpers.GocryptfsBinary, \"foo\", \"bar\", \"-o\")\n\terr := cmd.Run()\n\texitCode := test_helpers.ExtractCmdExitCode(err)\n\tif exitCode != exitcodes.Usage {\n\t\tt.Fatalf(\"this should have failed with code %d, but returned %d\",\n\t\t\texitcodes.Usage, exitCode)\n\t}\n}", "func (o *GetMessagesAllOf) GetFlagsOk() (*[]string, bool) {\n\tif o == nil || o.Flags == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Flags, true\n}", "func RequiredWithDefaultEnvVar(flag *string, envVarName, errMsg string) *string {\n\tif *flag != \"\" {\n\t\treturn flag\n\t}\n\tnewFlag := os.Getenv(envVarName)\n\tif newFlag != \"\" {\n\t\treturn &newFlag\n\t}\n\tFatal(CLI_INPUT_ERROR, errMsg)\n\treturn flag // won't ever happen, here just to make intellij happy\n}", "func (c *Command) addFlag(flag *Flag) {\n\n\tif _, exists := c.innerFlagsLong[flag.Long]; exists {\n\t\tpanic(fmt.Errorf(\"Flag '%s' already exists \", flag.Long))\n\t}\n\tif _, exists := c.innerFlagsShort[flag.Short]; exists {\n\t\tpanic(fmt.Errorf(\"Flag '%s' already exists \", flag.Short))\n\t}\n\tc.innerFlagsLong[flag.Long] = flag\n\tc.orderedFlags = append(c.orderedFlags, flag)\n\tif flag.Short != \"\" {\n\t\tc.innerFlagsShort[flag.Short] = flag\n\t}\n\n}", "func ArgUnknown(option *Option) error {\n if ambiguous, ok := option.Value.([]string); ok && len(ambiguous) == 2 {\n return fmt.Errorf(\"Ambiguous abbreviation '%v'. Candiates: --%v, --%v\", option, ambiguous[0], ambiguous[1])\n }\n return fmt.Errorf(\"Unknown option '%v'\", option)\n}", "func (m *FlagMock) MinimockFinish() {\n\tif !m.minimockDone() {\n\t\tm.MinimockDoneInspect()\n\n\t\tm.MinimockIsStoppedInspect()\n\n\t\tm.MinimockStopInspect()\n\t\tm.t.FailNow()\n\t}\n}", "func isZeroValue(f *flag.Flag, value string) bool {\n\t// Build a zero value of the flag's Value type, and see if the\n\t// result of calling its String method equals the value passed in.\n\t// This works unless the Value type is itself an interface type.\n\ttyp := reflect.TypeOf(f.Value)\n\tvar z reflect.Value\n\tif typ.Kind() == reflect.Ptr {\n\t\tz = reflect.New(typ.Elem())\n\t} else {\n\t\tz = reflect.Zero(typ)\n\t}\n\treturn value == z.Interface().(flag.Value).String()\n}", "func (s *BasePCREListener) EnterOption_flag(ctx *Option_flagContext) {}", "func (f *FakeOutput) ExpectEntry(t testing.TB, expected *entry.Entry) {\n\tselect {\n\tcase e := <-f.Received:\n\t\trequire.Equal(t, expected, e)\n\tcase <-time.After(time.Second):\n\t\trequire.FailNow(t, \"Timed out waiting for entry\")\n\t}\n}", "func isZeroValue(f *flag.Flag, value string) bool {\n\t// for the \"false\" bool value, return false\n\tif value == \"false\" {\n\t\treturn false\n\t}\n\n\t// Build a zero value of the flag's Value type, and see if the\n\t// result of calling its String method equals the value passed in.\n\t// This works unless the Value type is itself an interface type.\n\ttyp := reflect.TypeOf(f.Value)\n\tvar z reflect.Value\n\tif typ.Kind() == reflect.Ptr {\n\t\tz = reflect.New(typ.Elem())\n\t} else {\n\t\tz = reflect.Zero(typ)\n\t}\n\tif value == z.Interface().(flag.Value).String() {\n\t\treturn true\n\t}\n\n\tswitch value {\n\tcase \"false\":\n\t\treturn true\n\tcase \"\":\n\t\treturn true\n\tcase \"0\":\n\t\treturn true\n\t}\n\treturn false\n}", "func (_ZKOnacci *ZKOnacciTransactor) CaptureTheFlag(opts *bind.TransactOpts, proofA [2]*big.Int, proofB [2][2]*big.Int, proofC [2]*big.Int, nextRoot *big.Int) (*types.Transaction, error) {\n\treturn _ZKOnacci.contract.Transact(opts, \"captureTheFlag\", proofA, proofB, proofC, nextRoot)\n}", "func Ok(t *testing.T, b bool) {\n\tif b == false {\n\t\tt.Fatal(\"not ok\")\n\t}\n}", "func (m *FlagMock) MinimockDoneDone() bool {\n\tfor _, e := range m.DoneMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.DoneMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterDoneCounter) < 1 {\n\t\treturn false\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcDone != nil && mm_atomic.LoadUint64(&m.afterDoneCounter) < 1 {\n\t\treturn false\n\t}\n\treturn true\n}", "func ErrMissingFlag(f string) *FlagError {\n\treturn &FlagError{\n\t\tFlag: f,\n\t\tMessage: \"is a required flag\",\n\t}\n}", "func (b FormatOption) Has(flag FormatOption) bool { return b&flag != 0 }", "func itValidatesBBSFlags(args ...string) {\n\tContext(\"BBS Flag Validation\", func() {\n\t\tIt(\"exits with status 3 when no bbs flags are specified\", func() {\n\t\t\tcmd := exec.Command(cfdotPath, args...)\n\n\t\t\tsess, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess.Exited).Should(BeClosed())\n\n\t\t\tExpect(sess.ExitCode()).To(Equal(3))\n\t\t})\n\t})\n}", "func isFlagSet(cflags uint32, c cflag) (bool) {\n if (cflags & uint32(c)) != 0 {\n return true\n }\n return false\n}", "func Assert(t *testing.T, value bool, format string, args ...interface{}) {\n\tif !value {\n\t\tt.Errorf(format, args...)\n\t}\n}", "func isFlag(value string) bool {\n\treturn len(value) >= 2 && strings.HasPrefix(value, \"-\")\n}", "func (f *flag) validate() error {\n\tif f.Type != \"string\" || len(f.Enum) == 0 {\n\t\treturn nil\n\t}\n\tval := f.cobraFlag.Value.String()\n\tfor _, validVal := range f.Enum {\n\t\tif val == validVal {\n\t\t\treturn nil\n\t\t}\n\t}\n\toptions := fmt.Sprintf(\"[%v]\", strings.Join(f.Enum, \", \"))\n\terrMsg := fmt.Sprintf(\"Invalid \\\"%s\\\" flag option: %s\\nAvailable options are: %s\\n\", f.Long, val, options)\n\treturn errors.New(errMsg)\n\t// ===== Sample Output =====\n\t// Invalid \"environment\" flag option: testing\n\t// Available options are: [development, staging, production]\n}", "func ArgOptional(option *Option) error {\n if option.HasArg {\n if option.ArgAttached {\n return ARG_OK\n } else {\n return ARG_NONE{fmt.Errorf(\"Option %v only accepts attached arguments\", option.Name)}\n }\n }\n return ARG_NONE{fmt.Errorf(\"No argument given (but that's ok, it's optional)\")}\n}", "func (_Rootchain *RootchainCaller) ClearFlag(opts *bind.CallOpts, _value *big.Int) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Rootchain.contract.Call(opts, out, \"clearFlag\", _value)\n\treturn *ret0, err\n}", "func fail(err error) {\n\tfmt.Println(\"match:\", err)\n\tos.Exit(1)\n}", "func (d *flagDef) flagValue() interface{} {\n\tswitch d.paramtype {\n\tcase stringType:\n\t\treturn *d.value.(*string)\n\n\tcase boolType:\n\t\treturn *d.value.(*bool)\n\tcase intType:\n\t\treturn *d.value.(*int)\n\tcase uintType:\n\t\treturn *d.value.(*uint)\n\tcase floatType:\n\t\treturn *d.value.(*float64)\n\tcase durationType:\n\t\treturn *d.value.(*time.Duration)\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"can't %v\", d.paramtype))\n\t}\n}", "func argIsFlag(commandFlags []Flag, arg string) bool {\n\tif arg == \"-\" || arg == \"--\" {\n\t\t// `-` is never a flag\n\t\t// `--` is an option-value when following a flag, and a delimiter indicating the end of options in other cases.\n\t\treturn false\n\t}\n\t// flags always start with a -\n\tif !strings.HasPrefix(arg, \"-\") {\n\t\treturn false\n\t}\n\t// this line turns `--flag` into `flag`\n\tif strings.HasPrefix(arg, \"--\") {\n\t\targ = strings.Replace(arg, \"-\", \"\", 2)\n\t}\n\t// this line turns `-flag` into `flag`\n\tif strings.HasPrefix(arg, \"-\") {\n\t\targ = strings.Replace(arg, \"-\", \"\", 1)\n\t}\n\t// this line turns `flag=value` into `flag`\n\targ = strings.Split(arg, \"=\")[0]\n\t// look through all the flags, to see if the `arg` is one of our flags\n\tfor _, flag := range commandFlags {\n\t\tfor _, key := range strings.Split(flag.GetName(), \",\") {\n\t\t\tkey := strings.TrimSpace(key)\n\t\t\tif key == arg {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\t// return false if this arg was not one of our flags\n\treturn false\n}", "func checkCmdDoesNotFinish(prereqs []*cmd) bool {\n\treturn !testCmdDone(prereqs, 3*time.Millisecond)\n}", "func Flag(discord *discordgo.Session, message *discordgo.MessageCreate) {\r\n\tif message.ChannelID == channelid {\r\n\t\tif message.Content == (commandPrefix + \"flag\") {\r\n\t\t\t_, err := discord.ChannelMessageSend(message.ChannelID, \"Support Turned back On\")\r\n\t\t\tif err != nil {\r\n\t\t\t\ttools.Log.WithField(\"Error\", err).Warn(\"Unusual Error\")\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\t\t\tflag = 0\r\n\t\t}\r\n\t}\r\n}", "func main() {\n\tflag.Parse()\n\tfmt.Println(\"ip var use address\", ip)\n\tfmt.Println(\"IP has value\", *ip)\n\n\tif !*criterion {\n\t\tfmt.Println(\"use *criterion to log value and ! as a negative note \\n and also printt out testIP\", *ip)\n\t}\n\n\tfmt.Println(\"flagname is :\", flagvar)\n\n}", "func main() {\n\t// Call the checkFlag function to simulate an error of the\n\t// concrete type.\n\terr := checkFlag(false)\n\n\t// Check the concrete type and handle appropriately.\n\tswitch e := err.(type) {\n\t// Apply the case for the existence of the Temporary behavior.\n\t// Log the error and write a second message only if the\n\t// error is not temporary.\n\tcase temporary:\n\t\tif !e.Temporary() {\n\t\t\tfmt.Println(e)\n\t\t}\n\t// Apply the default case and just log the error.\n\tdefault:\n\t\tfmt.Println(err)\n\n\t}\n}", "func Must(f Flag, err error) Flag {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn f\n}", "func (f *FlagSet) NFlag() int { return len(f.actual) }", "func (h *Header) parseFlag(flag uint16) {\n\th.Response = flag&(1<<15) > 0\n\n\topCodeValue := flag & (0b1111 << 11) >> 11 // get just the four at elenth position\n\th.OpCode = OpCode(opCodeValue)\n\n\th.AuthoritativeAnswer = flag&(1<<10) > 0\n\th.Truncation = flag&(1<<9) > 0\n\th.RecursionDesired = flag&(1<<8) > 0\n\th.RecursionAvailable = flag&(1<<7) > 0\n\n\tresponseCodeValue := flag & (0b1111) // get just the four\n\th.ResponseCode = ResponseCode(responseCodeValue)\n\n}" ]
[ "0.6079569", "0.58692366", "0.57598114", "0.57287717", "0.5551134", "0.5460788", "0.5388357", "0.5382268", "0.53631026", "0.5357898", "0.5328667", "0.5325936", "0.53098136", "0.5273933", "0.5264968", "0.52546215", "0.52443177", "0.523296", "0.52326876", "0.52184695", "0.52027696", "0.5153301", "0.513347", "0.512982", "0.5127879", "0.51167494", "0.5113649", "0.5110278", "0.5108425", "0.5103537", "0.503883", "0.5032234", "0.50250757", "0.50246453", "0.50209457", "0.49886274", "0.49851543", "0.49738988", "0.49710637", "0.4967404", "0.49669003", "0.4963463", "0.49480653", "0.49381125", "0.4935954", "0.4930909", "0.49295923", "0.4895265", "0.48835784", "0.48723385", "0.48662585", "0.48616695", "0.48604298", "0.4859275", "0.4853801", "0.48530203", "0.48473847", "0.48416466", "0.48393917", "0.48383287", "0.48296407", "0.48292565", "0.48233616", "0.4809046", "0.48020977", "0.47965133", "0.47896993", "0.47822806", "0.4779052", "0.47729567", "0.4765083", "0.47566992", "0.4747759", "0.4745326", "0.47446856", "0.4736493", "0.4726024", "0.47195855", "0.47158897", "0.47152674", "0.4713604", "0.4708831", "0.46997985", "0.46968246", "0.46857816", "0.46801236", "0.46800408", "0.46752107", "0.467495", "0.467038", "0.46632305", "0.4659927", "0.4659271", "0.46591964", "0.46578598", "0.4642411", "0.4641941", "0.46370047", "0.46347988", "0.463409" ]
0.8324694
0
checkNoArguments checks that there are no arguments.
func checkNoArguments(_ *cobra.Command, args []string) error { if len(args) > 0 { return errors.New("this command doesn't support any arguments") } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func VerifyNoArgument(c *cli.Context) error {\n\ta := c.Args()\n\tif a.Present() {\n\t\treturn fmt.Errorf(`Syntax error, command takes no arguments`)\n\t}\n\n\treturn nil\n}", "func validateArguments(args ...string) error {\n\tif args == nil {\n\t\treturn errors.New(\"No command line args were specified\")\n\t}\n\tfor _, arg := range args {\n\t\tif arg == \"\" {\n\t\t\treturn errors.New(\"Unspecified required command line args\")\n\t\t}\n\t}\n\treturn nil\n}", "func checkArgs() error {\n\tnargs := len(os.Args)\n\tpiped := isPiped()\n\tswitch {\n\tcase (2 != nargs) && piped:\n\t\treturn PipeArgErr\n\tcase (3 != nargs) && !piped:\n\t\treturn FileArgErr\n\t}\n\treturn nil\n}", "func ArgNonEmpty(option *Option) error {\n if option.HasArg && option.Arg != \"\" {\n return ARG_OK\n }\n return fmt.Errorf(\"Option '%v' requires a non-empty argument\", option)\n}", "func (s service) checkArgs() error {\n\tif len(s.args) < 1 {\n\t\treturn errors.New(\"no file added as a command line argument\")\n\t}\n\n\tif s.args[0] == \"\" {\n\t\treturn errors.New(\"filename cannot be empty\")\n\t}\n\n\treturn nil\n}", "func checkNumberOfArgs(name string, nargs, nresults, min, max int) error {\n\tif min == max {\n\t\tif nargs != max {\n\t\t\treturn ExceptionNewf(TypeError, \"%s() takes exactly %d arguments (%d given)\", name, max, nargs)\n\t\t}\n\t} else {\n\t\tif nargs > max {\n\t\t\treturn ExceptionNewf(TypeError, \"%s() takes at most %d arguments (%d given)\", name, max, nargs)\n\t\t}\n\t\tif nargs < min {\n\t\t\treturn ExceptionNewf(TypeError, \"%s() takes at least %d arguments (%d given)\", name, min, nargs)\n\t\t}\n\t}\n\n\tif nargs > nresults {\n\t\treturn ExceptionNewf(TypeError, \"Internal error: not enough arguments supplied to Unpack*/Parse*\")\n\t}\n\treturn nil\n}", "func CheckArguments(arguments []Argument, min int, max int, fname string, usage string) (int, ErrorValue) {\n\targLen := len(arguments)\n\tif argLen < min || argLen > max {\n\t\treturn argLen, NewErrorValue(fmt.Sprintf(\"Invalid call to %s. Usage: %s %s\", fname, fname, usage))\n\t}\n\treturn argLen, nil\n}", "func checkNilPermission(argTypeName string, emptyPermissionList []string) error {\n\n\tfor _, permittedArgTypeName := range(emptyPermissionList) {\n\t\tif permittedArgTypeName == argTypeName {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"%v's input value is empty!\", argTypeName)\n}", "func NoArgs(cmd *cobra.Command, args []string) error {\n\tif len(args) > 0 {\n\t\treturn errors.Errorf(\n\t\t\t\"%q accepts no arguments\\n\\nUsage: %s\",\n\t\t\tcmd.CommandPath(),\n\t\t\tcmd.UseLine(),\n\t\t)\n\t}\n\treturn nil\n}", "func NoArgs(cmd *Command, args []string) error {\n\tif len(args) > 0 {\n\t\treturn fmt.Errorf(\"unknown command %q for %q\", args[0], cmd.CommandPath())\n\t}\n\treturn nil\n}", "func checkAtLeastArgs(nargs int, errMsg string) func(cmd *cobra.Command, args []string) error {\n\treturn func(cmd *cobra.Command, args []string) error {\n\t\tif len(args) < nargs {\n\t\t\treturn errors.Errorf(errMsg)\n\t\t}\n\t\treturn nil\n\t}\n}", "func checkArgs(nargs int, errMsg string) func(cmd *cobra.Command, args []string) error {\n\treturn func(cmd *cobra.Command, args []string) error {\n\t\tif len(args) != nargs {\n\t\t\treturn errors.Errorf(errMsg)\n\t\t}\n\t\treturn nil\n\t}\n}", "func (cmd *Command) checkArgs(args []string) {\n\tif len(args) < cmd.MinArgs {\n\t\tsyntaxError()\n\t\tfmt.Fprintf(os.Stderr, \"Command %s needs %d arguments mininum\\n\", cmd.Name, cmd.MinArgs)\n\t\tos.Exit(1)\n\t} else if len(args) > cmd.MaxArgs {\n\t\tsyntaxError()\n\t\tfmt.Fprintf(os.Stderr, \"Command %s needs %d arguments maximum\\n\", cmd.Name, cmd.MaxArgs)\n\t\tos.Exit(1)\n\t}\n}", "func CheckNumArgs(num int, args []string, usage string) error {\n\tif len(os.Args) != num {\n\t\tvar errString string\n\t\tif len(os.Args) >= 1 {\n\t\t\terrString = fmt.Sprintf(\"Incorrect usage should do: %s %s\", args[0], usage)\n\t\t} else {\n\t\t\terrString = fmt.Sprintf(\"Incorrect usage should do: scriptname %s\", usage)\n\t\t}\n\t\treturn errors.New(errString)\n\t}\n\treturn nil\n}", "func (p RProc) IsNoArg() bool { return (C._mrb_rproc_flags(p.p) & C.MRB_PROC_NOARG) != 0 }", "func NoArgs(cmd *cobra.Command, args []string) error {\n\terrorMessage := fmt.Sprintf(\n\t\t\"%s does not take any arguments. See `stripe %s --help` for supported flags and usage\",\n\t\tcmd.Name(),\n\t\tcmd.Name(),\n\t)\n\n\tif len(args) > 0 {\n\t\treturn errors.New(errorMessage)\n\t}\n\n\treturn nil\n}", "func checkArguments(hash string, privateKey string) bool {\n\t// easy check\n\t// if len(hash) != 46 || len(privateKey) != 64 {\n\t// \treturn false\n\t// }\n\n\treturn true\n}", "func check_args(parsed_query []string, num_expected int) bool {\n\treturn (len(parsed_query) >= num_expected)\n}", "func nilParseArguments(args interface{}) (interface{}, error) {\n\tif args == nil {\n\t\treturn nil, nil\n\t}\n\tif args, ok := args.(map[string]interface{}); !ok || len(args) != 0 {\n\t\treturn nil, fmt.Errorf(\"unexpected args\")\n\t}\n\treturn nil, nil\n}", "func (o Args) IsNil() bool { return false }", "func CheckArgsLength(args []string, expectedLength int) error {\r\n\tif len(args) != expectedLength {\r\n\t\treturn fmt.Errorf(\"invalid number of arguments. Expected %v, got %v\", expectedLength, len(args))\r\n\t}\r\n\treturn nil\r\n}", "func (o Args) Empty() bool { return o.Len() == 0 }", "func validateProgramArgs() {\n\tif *version {\n\t\tshowVersion()\n\t}\n\n\tif *helpUsage {\n\t\tusage(0)\n\t}\n\n\tif *helpFull {\n\t\tshowHelp(0)\n\t}\n\n\tif *LocalFolderPath == \"\" ||\n\t\t(*dpUsername != \"\" && *dpRestURL == \"\" && *dpSomaURL == \"\") {\n\t\tusage(1)\n\t}\n\n}", "func checkArguments(url, dir string) {\n\tif !httputil.IsURL(url) {\n\t\tprintErrorAndExit(\"Url %s doesn't look like valid url\", url)\n\t}\n\n\tif !fsutil.IsExist(dir) {\n\t\tprintErrorAndExit(\"Directory %s does not exist\", dir)\n\t}\n\n\tif !fsutil.IsDir(dir) {\n\t\tprintErrorAndExit(\"Target %s is not a directory\", dir)\n\t}\n\n\tif !fsutil.IsReadable(dir) {\n\t\tprintErrorAndExit(\"Directory %s is not readable\", dir)\n\t}\n\n\tif !fsutil.IsExecutable(dir) {\n\t\tprintErrorAndExit(\"Directory %s is not executable\", dir)\n\t}\n}", "func TestHelloWithEmptyValidArg(t *testing.T) {\n\n\t//test for validy argument\n\tresult := hello(\"Mike\")\n\n\tif result != \"Hello Mike!\" {\n\t\tt.Errorf(\"Hello(\\\"\\\") failed, expected %v, got %v\", \"Hello Dude!\", result)\n\t} else {\n\t\tt.Logf(\"Hello(\\\"\\\") success, expected %v, got %v\", \"Hello Dude!\", result)\n\t}\n}", "func HasSingleFlagNonemptyArgument(flag string, params []string) bool {\n\tfound := filterFlags(params, flag)\n\tif len(found) != 1 {\n\t\treturn false\n\t}\n\n\t_, value := splitKV(found[0], \"=\")\n\tif value == \"\" {\n\t\treturn false\n\t}\n\treturn true\n}", "func (args *CliArgs) checkArgs() {\n\t// print all filed of the object\n\tif !(args.startPage > 0 && args.endPage > 0 && args.endPage-args.startPage >= 0) {\n\t\tfmt.Fprintf(os.Stderr, \"start page and end page should be positive and endpage should be bigger than startpage\")\n\t\tos.Exit(1)\n\t}\n\n\tif args.isFtype {\n\t\tif args.lineNumPerPage != specialNum {\n\t\t\tfmt.Fprintln(os.Stderr, \"Fatal: setting -f and -l simultaneously is not allowed\")\n\t\t\tos.Exit(1)\n\t\t}\n\t} else {\n\t\tif args.lineNumPerPage == specialNum {\n\t\t\targs.lineNumPerPage = defaultLineNum\n\t\t} else if args.lineNumPerPage < 0 {\n\t\t\tfmt.Fprintln(os.Stderr, \"Fatal: the linenum should be positive\")\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\t// set default number of linenumber\n\tif pflag.NArg() != 0 {\n\t\targs.inFilename = pflag.Args()[0]\n\t}\n\n\tfmt.Printf(\"%+v\", args)\n}", "func (Interface *LineInterface) ValidateArguments() {\n\tif len(os.Args) < 2 {\n\t\tInterface.PrintUsage()\n\t\truntime.Goexit()\n\t}\n}", "func TestCmd_Validate_MissingArgs(t *testing.T) {\n\tlog.SetOutput(io.Discard)\n\tdefer log.SetOutput(os.Stdout)\n\tv := ValidateSpec{}\n\tresult := v.Execute([]string{})\n\tassert.Error(t, result)\n\n\tresult = v.Execute([]string{\"nowhere.json\"})\n\tassert.Error(t, result)\n}", "func (args *ModuleArgs) Check() *constant.YiError {\n\tif args.Downloader == nil {\n\t\treturn constant.NewYiErrorf(constant.ERR_SCHEDULER_ARGS, \"Nil downloader.\")\n\t}\n\tif args.Analyzer == nil {\n\t\treturn constant.NewYiErrorf(constant.ERR_SCHEDULER_ARGS, \"Nil analyzer.\")\n\t}\n\tif args.Pipeline == nil {\n\t\treturn constant.NewYiErrorf(constant.ERR_SCHEDULER_ARGS, \"Nil pipeline.\")\n\t}\n\treturn nil\n}", "func (c *Compiler) checkBuiltinArgs() {\n\tfor _, m := range c.Modules {\n\t\tfor _, r := range m.Rules {\n\t\t\tfor _, expr := range r.Body {\n\t\t\t\tif ts, ok := expr.Terms.([]*Term); ok {\n\t\t\t\t\tif bi, ok := BuiltinMap[ts[0].Value.(Var)]; ok {\n\t\t\t\t\t\tif bi.NumArgs != len(ts[1:]) {\n\t\t\t\t\t\t\tc.err(expr.Location.Errorf(\"%v: wrong number of arguments (expression %s must specify %d arguments to built-in function %v)\", r.Name, expr.Location.Text, bi.NumArgs, ts[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}\n\t}\n}", "func checkArguments() {\n\tif len(dockerRegistryUrl) == 0 {\n\t\tlog.Fatalln(\"Environment Variable 'DOCKER_REGISTRY_URL' not set\")\n\t}\n\n\tif len(replaceRegistryUrl) == 0 {\n\t\tlog.Fatalln(\"Environment Variable 'REPLACE_REGISTRY_URL' not set\")\n\t}\n\n\t_, err := strconv.ParseBool(replaceRegistryUrl)\n\tif err != nil {\n\t\tlog.Fatalln(\"Invalid Value in Environment Variable 'REPLACE_REGISTRY_URL'\")\n\t}\n}", "func doAnyParametersExist(args ...string) bool {\n\tif args == nil {\n\t\treturn false\n\t}\n\tfor _, arg := range args {\n\t\tif arg != \"\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func validateArgs() {\n\tif *optionsEndpoint == \"\" {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\tif *inputEndpoint == \"\" {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\tif *outputEndpoint == \"\" {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n}", "func CheckArgs(argsLength, argIndex int) error {\n\tif argsLength == (argIndex + 1) {\n\t\treturn errors.New(\"Not specified key value.\")\n\t}\n\treturn nil\n}", "func VerifyRequiredArgs(c *Command, required []string) *Result {\n for _, arg := range required {\n _, r := getArgument(c, arg)\n if r != nil { return r }\n }\n return nil\n}", "func validateArgs() {\n\tif *inputEndpoint == \"\" {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n}", "func IsValidArgsLength(args []string, n int) bool {\n\tif args == nil && n == 0 {\n\t\treturn true\n\t}\n\tif args == nil {\n\t\treturn false\n\t}\n\n\tif n < 0 {\n\t\treturn false\n\t}\n\n\targsNr := len(args)\n\tif argsNr < n || argsNr > n {\n\t\treturn false\n\t}\n\treturn true\n}", "func ArgNone(option *Option) error {\n return ARG_NONE_Err(option.Name)\n}", "func NotEmpty(t *testing.T, target interface{}) {\n\tif IsEmpty(target) {\n\t\tt.Errorf(\"%v Empty: %v\", line(), target)\n\t}\n}", "func checkArgValue(v string, found bool, def cmdkit.Argument) error {\n\tif def.Variadic && def.SupportsStdin {\n\t\treturn nil\n\t}\n\n\tif !found && def.Required {\n\t\treturn fmt.Errorf(\"argument %q is required\", def.Name)\n\t}\n\n\treturn nil\n}", "func (s *PodStorage) checkPodArgument(pod *types.Pod) error {\n\tif pod == nil {\n\t\treturn errors.New(store.ErrStructArgIsNil)\n\t}\n\n\tif pod.Meta.Name == \"\" {\n\t\treturn errors.New(store.ErrStructArgIsInvalid)\n\t}\n\n\treturn nil\n}", "func (c *requiredIDRemainingArgsCatcher) verifyRequiredIDAndNoRemainingArgs() error {\n\tif c.ID == \"\" {\n\t\tif len(c.RemainingArgs.Rest) != 1 {\n\t\t\treturn fmt.Errorf(\"expected --id flag or a single identifier argument\")\n\t\t}\n\t\tc.ID = c.remainingArg(0)\n\t\treturn nil\n\t}\n\treturn c.verifyNoRemainingArgs()\n}", "func (args *Args) isEmpty() bool {\n\treturn len(args.items) == 0\n}", "func checkFlags() {\n\t// file flag is required\n\tif *filename == \"\" {\n\t\tlog.Fatalf(\"file is required\")\n\t}\n\n\tif *server == \"\" {\n\t\tlog.Fatalf(\"server is required\")\n\t}\n}", "func (c *optionalIDRemainingArgsCatcher) verifyOptionalIDAndNoRemainingArgs() error {\n\tif c.ID == \"\" {\n\t\tif len(c.RemainingArgs.Rest) > 0 {\n\t\t\tif err := c.verifyNRemainingArgs(1); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tc.ID = c.remainingArg(0)\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn c.verifyNoRemainingArgs()\n}", "func (args *DataArgs) Check() *constant.YiError {\n\tif args.ReqBufferCap == 0 {\n\t\treturn constant.NewYiErrorf(constant.ERR_ARGS, \"Zero request buffer capacity.\")\n\t}\n\tif args.ReqMaxBufferNumber == 0 {\n\t\treturn constant.NewYiErrorf(constant.ERR_ARGS, \"Zero max request buffer number.\")\n\t}\n\tif args.RespBufferCap == 0 {\n\t\treturn constant.NewYiErrorf(constant.ERR_ARGS, \"Zero response buffer capacity.\")\n\t}\n\tif args.RespMaxBufferNumber == 0 {\n\t\treturn constant.NewYiErrorf(constant.ERR_ARGS, \"Zero max response buffer capacity.\")\n\t}\n\tif args.ItemBufferCap == 0 {\n\t\treturn constant.NewYiErrorf(constant.ERR_ARGS, \"Zero item buffer capacity.\")\n\t}\n\tif args.ItemMaxBufferNumber == 0 {\n\t\treturn constant.NewYiErrorf(constant.ERR_ARGS, \"Zero max item buffer capatity.\")\n\t}\n\tif args.ErrorBufferCap == 0 {\n\t\treturn constant.NewYiErrorf(constant.ERR_ARGS, \"Zero error buffer capacity.\")\n\t}\n\tif args.ErrorMaxBufferNumber == 0 {\n\t\treturn constant.NewYiErrorf(constant.ERR_ARGS, \"Zero max error buffer number.\")\n\t}\n\treturn nil\n}", "func validateArgs(linkIndex int, fn reflect.Type, args []Argument) error {\n\tif !fn.IsVariadic() && (fn.NumIn() != len(args)) {\n\t\treturn argumentMismatchError(linkIndex, len(args), fn.NumIn())\n\t}\n\n\treturn nil\n}", "func noArgs(c *cli.Context) error {\r\n\t// Print app usage\r\n\tcli.ShowAppHelp(c)\r\n\r\n\t// It's possible to change the return status code and error here\r\n\t// cli.NewExitError creates a a new error and the return status code for\r\n\t// the application.\r\n\treturn cli.NewExitError(\"no commands provided\", 2)\r\n}", "func TestHelloWithEmptyArg(t *testing.T) {\n\n\t//test for empty argument\n\temptyResult := hello(\"\")\n\n\tif emptyResult != \"Hello Dude!\" {\n\t\tt.Errorf(\"Hello(\\\"\\\") failed, expected %v, got %v\", \"Hello Dude!\", emptyResult)\n\t} else {\n\t\tt.Logf(\"Hello(\\\"\\\") success, expected %v, got %v\", \"Hello Dude!\", emptyResult)\n\t}\n}", "func checkEmpty(t *testing.T, q *availableUnits) {\n\tassert.Zero(t, q.Len())\n}", "func (c *MigrationsCmd) CheckArgs(cmd *cobra.Command, args []string) error {\n\treturn nil\n}", "func checkArgs() {\n\tif TemplatesPath == \"\" {\n\t\texitErr(\"-t is required\")\n\t}\n\n\tif PackagePath == \"\" {\n\t\texitErr(\"-p is required\")\n\t}\n\n\tif LeftDelim == \"\" {\n\t\tLeftDelim = \"{{\"\n\t}\n\n\tif RightDelim == \"\" {\n\t\tRightDelim = \"}}\"\n\t}\n\n\tif OutputFormat == \"\" {\n\t\tOutputFormat = \"plain\"\n\t}\n\tif OutputFormat != \"json\" && OutputFormat != \"plain\" {\n\t\texitErr(`unsupported output format: \"` + OutputFormat + `\"`)\n\t}\n}", "func CheckArgsNotMultiColumnRow(args ...Expression) error {\n\ttrace_util_0.Count(_util_00000, 151)\n\tfor _, arg := range args {\n\t\ttrace_util_0.Count(_util_00000, 153)\n\t\tif GetRowLen(arg) != 1 {\n\t\t\ttrace_util_0.Count(_util_00000, 154)\n\t\t\treturn ErrOperandColumns.GenWithStackByArgs(1)\n\t\t}\n\t}\n\ttrace_util_0.Count(_util_00000, 152)\n\treturn nil\n}", "func checkForArgErrors(token string, platform string) error {\n\tif token == \"\" {\n\t\treturn errors.New(\"Token needs to be a device token\")\n\t} else if platform != PlatformIos && platform != PlatformAndroid {\n\t\treturn errors.New(\"Platform must be either PlatformIos or PlatformAndroid\")\n\t}\n\treturn nil\n}", "func (s *ServiceStorage) checkServiceArgument(service *types.Service) error {\n\n\tif service == nil {\n\t\treturn errors.New(store.ErrStructArgIsNil)\n\t}\n\n\tif service.Meta.Name == \"\" {\n\t\treturn errors.New(store.ErrStructArgIsInvalid)\n\t}\n\n\treturn nil\n}", "func MsgArgsNotNil() predicate.Step {\n\treturn predicate.Step(func(s *sql.Selector) {\n\t\ts.Where(sql.NotNull(s.C(FieldMsgArgs)))\n\t})\n}", "func CheckNoMutatesFromActions(t *testing.T, actions rtesting.Actions) {\n\tif len(actions.Creates)+len(actions.Deletes)+len(actions.Updates)+len(actions.DeleteCollections)+len(actions.Patches) > 0 {\n\t\tt.Fatalf(\"Wanted no mutating actions. Got [%+v]\", actions)\n\t}\n}", "func ValidateNonDefault(args []string) error {\n\n\tif len(args) == 0 {\n\t\treturn errors.New(missingArguments)\n\t}\n\n\tif err := validateMethod(args[0]); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateURL(args[1]); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateExtension(args[2]); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func HasArgs(instr ssa.Instruction, typ types.Type) bool {\n\tcall, ok := instr.(ssa.CallInstruction)\n\tif !ok {\n\t\treturn false\n\t}\n\n\tssaCall := call.Value()\n\tif ssaCall == nil {\n\t\treturn false\n\t}\n\n\tfor _, arg := range ssaCall.Call.Args {\n\t\tif types.Identical(arg.Type(), typ) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func checkArgs(ctxt context.Context, s string, args ...interface{}) {\n\tc := 0\n\tfor _, f := range []string{\"%s\", \"%d\", \"%v\", \"%#v\", \"%t\", \"%p\"} {\n\t\tc += strings.Count(s, f)\n\t}\n\tl := len(args)\n\tif c != l {\n\t\tWarningf(ctxt, \"Wrong number of args for format string, [%d != %d]\", l, c)\n\t}\n}", "func (o Args) Truthy() bool { return !o.Empty() }", "func NotEmpty(obj string, a ...any) {\n\tif obj == \"\" {\n\t\tdefMsg := assertionMsg + \": string shouldn't be empty\"\n\t\tDefault().reportAssertionFault(defMsg, a...)\n\t}\n}", "func OnlyValidArgs(cmd *Command, args []string) error {\n\tif len(cmd.ValidArgs) > 0 {\n\t\t// Remove any description that may be included in ValidArgs.\n\t\t// A description is following a tab character.\n\t\tvar validArgs []string\n\t\tfor _, v := range cmd.ValidArgs {\n\t\t\tvalidArgs = append(validArgs, strings.Split(v, \"\\t\")[0])\n\t\t}\n\t\tfor _, v := range args {\n\t\t\tif !stringInSlice(v, validArgs) {\n\t\t\t\treturn fmt.Errorf(\"invalid argument %q for %q%s\", v, cmd.CommandPath(), cmd.findSuggestions(args[0]))\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func NotEmpty(object interface{}) error {\n\tif object == nil {\n\t\treturn xerrors.New(fmt.Sprintf(`%s should be not empty`, PrintValue(object)))\n\t}\n\tv := misc.GetValue(object)\n\tswitch v.Kind() {\n\tcase reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String:\n\t\tif v.Len() == 0 {\n\t\t\treturn xerrors.New(fmt.Sprintf(`%s should be not empty`, PrintValue(object)))\n\t\t}\n\t\treturn nil\n\tdefault:\n\t\treturn xerrors.New(fmt.Sprintf(\"called Len() on %s\", PrintValue(object)))\n\t}\n}", "func verifyArgs() (bool, string) {\n\tvar errMsg string\n\tvar webhookURL string\n\n\tif *auth == \"\" {\n\t\terrMsg = \"Invalid authentication! It must not be empty.\\n\"\n\t\treturn false, errMsg\n\t}\n\n\tif *address == \"\" {\n\t\terrMsg = \"Invalid URL! It must not be empty.\\n\"\n\t\treturn false, errMsg\n\t}\n\n\tif *port < 1025 || *port > 65535 {\n\t\terrMsg = \"Invalid port! Please, check it is between 1025 and 65535.\\n\"\n\t\treturn false, errMsg\n\t}\n\n\tif *prefix != \"\" {\n\t\t*prefix = strings.Trim(*prefix, \"/\")\n\t}\n\n\twebhookURL = fmt.Sprintf(\"%s:%d\", *address, *port)\n\n\treturn true, webhookURL\n}", "func SkipArgs() Option { return Option{skipArgs: true} }", "func CheckArgs() map[string]*string {\n\n\targs := make(map[string]*string)\n\n\tparser := argparse.NewParser(\"print\", \"Prints provided string to stdout\")\n\n\targs[\"git_path\"] = parser.String(\"p\", \"git_path\", &argparse.Options{Required: true, Help: \"Path to git repository\"})\n\targs[\"word_list\"] = parser.String(\"w\", \"word_list\", &argparse.Options{Required: true, Help: \"Path to word list. HTTPS/HTTP/FS\"})\n\n\terr := parser.Parse(os.Args)\n\tif err != nil {\n\t\tfmt.Print(parser.Usage(err))\n\t}\n\n\treturn args\n}", "func HitArgsNotNil() predicate.Step {\n\treturn predicate.Step(func(s *sql.Selector) {\n\t\ts.Where(sql.NotNull(s.C(FieldHitArgs)))\n\t})\n}", "func Check(args ...interface{}) {\n\n\tlast := args[len(args)-1]\n\n\tif last == nil {\n\t\treturn\n\t}\n\n\terr, ok := last.(error)\n\tif ok {\n\t\tThrow(err)\n\t}\n\n}", "func ValidateArgCount(expectedArgNo, argNo int) error {\n\tswitch {\n\tcase expectedArgNo < argNo:\n\t\treturn ErrUnexpectedArgs\n\tcase expectedArgNo > argNo:\n\t\treturn ErrNotEnoughArgs\n\tcase expectedArgNo == argNo:\n\t}\n\n\treturn nil\n}", "func (c *UsersGetPresenceCall) ValidateArgs() error {\n\tif len(c.user) <= 0 {\n\t\treturn errors.New(`required field user not initialized`)\n\t}\n\treturn nil\n}", "func checkArgs() (string, error) {\n\t//Fetch the command line arguments.\n\targs := os.Args\n\n\t//Check the length of the arugments, return failure if they are too\n\t//long or too short.\n\tif len(args) > 2 {\n\t\treturn \"\", errors.New(\"Invalid number of arguments. \\n\" +\n\t\t\t\" Please provide the file name with relative path\" +\n\t\t\t\" of the csv data input file!\\n\")\n\t}\n\tfile_path := args[1]\n\t//On success, return the file_path and isSort value\n\treturn file_path, nil\n}", "func ValidateIfNotEmpty(fields ...int) bool {\n\tfor _, field := range fields {\n\t\tif field == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func CheckRequired(required []string) {\n\tseen := make(map[string]bool)\n\tflag.Visit(func(f *flag.Flag) { seen[f.Name] = true })\n\tfor _, req := range required {\n\t\tif !seen[req] {\n\t\t\tfmt.Fprintf(os.Stderr, \"missing required -%s argument\\n\", req)\n\t\t\tos.Exit(2)\n\t\t}\n\t}\n}", "func (h *FuncHandler) CheckArgs(check func(cmd *cobra.Command, args []string) error) func(cmd *cobra.Command, args []string) error {\n\treturn func(cmd *cobra.Command, args []string) error {\n\t\treturn check(cmd, args)\n\t}\n}", "func (o *Options) validate(args []string) error {\n\tif len(args) != 0 {\n\t\treturn errors.New(\"arguments are not supported\")\n\t}\n\treturn nil\n}", "func checkFilterArgs(name string, args []sexp) ([]Filter, error) {\n\tif len(args) < 1 {\n\t\treturn nil, fmt.Errorf(\"%v got [%v]: %w\", name, args, ErrWrongArgCount)\n\t}\n\tfilters := []Filter{}\n\tfor i, a := range args {\n\t\tf, err := compileSexp(a)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"compiling %v filter, arg %d [%v]: %w\", name, i+1, a, err)\n\t\t}\n\t\tfilters = append(filters, f)\n\t}\n\treturn filters, nil\n}", "func (s *RouteStorage) checkRouteArgument(route *types.Route) error {\n\n\tif route == nil {\n\t\treturn errors.New(store.ErrStructArgIsNil)\n\t}\n\n\tif route.Meta.Name == \"\" {\n\t\treturn errors.New(store.ErrStructArgIsInvalid)\n\t}\n\n\treturn nil\n}", "func TestMissingOArg(t *testing.T) {\n\tcmd := exec.Command(test_helpers.GocryptfsBinary, \"foo\", \"bar\", \"-o\")\n\terr := cmd.Run()\n\texitCode := test_helpers.ExtractCmdExitCode(err)\n\tif exitCode != exitcodes.Usage {\n\t\tt.Fatalf(\"this should have failed with code %d, but returned %d\",\n\t\t\texitcodes.Usage, exitCode)\n\t}\n}", "func MsgArgsIsNil() predicate.Step {\n\treturn predicate.Step(func(s *sql.Selector) {\n\t\ts.Where(sql.IsNull(s.C(FieldMsgArgs)))\n\t})\n}", "func sanitize_arguments(strs []string) error {\n\tfor i, val := range strs {\n\t\tif len(val) <= 0 {\n\t\t\treturn errors.New(\"Argument \" + strconv.Itoa(i) + \" must be a non-empty string\")\n\t\t}\n\t\t// if len(val) > 32 {\n\t\t// \treturn errors.New(\"Argument \" + strconv.Itoa(i) + \" must be <= 32 characters\")\n\t\t// }\n\t}\n\treturn nil\n}", "func newEmptyFormulaArg() formulaArg {\n\treturn formulaArg{Type: ArgEmpty}\n}", "func ValidateFlags(args ...string) error {\n\tfor _, arg := range args {\n\t\tif arg == \"\" {\n\t\t\treturn errors.New(\"Missing flag\")\n\t\t}\n\t}\n\treturn nil\n}", "func analysisArgs() bool {\n\t//没有选项的情况显示帮助信息\n\tif len(os.Args) <= 1 {\n\t\tfor _, v := range gCommandItems {\n\t\t\tlog(v.mBuilder.getCommandDesc())\n\t\t}\n\t\treturn false\n\t}\n\n\t//解析指令\n\targs := os.Args[1:]\n\tvar pItem *sCommandItem = nil\n\tfor i := 0; i < len(args); i++ {\n\t\tparm := args[i]\n\t\tif parm[0] == '-' {\n\t\t\tpItem = findCommandItem(parm)\n\t\t\tif pItem == nil {\n\t\t\t\tlogErr(\"illegal command:\" + parm)\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tpItem.mCanExecute = true\n\t\t} else {\n\t\t\tif pItem == nil {\n\t\t\t\tlogErr(\"illegal command:\" + parm)\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tpItem.mParm = append(pItem.mParm, parm)\n\t\t}\n\t}\n\n\treturn true\n}", "func (v *ExecuteCommandParams) IsNil() bool { return v == nil }", "func CheckCreateArgs(cmd *cobra.Command, args []string) (err error) {\n\tname := cmdutil.ArgDefault(args, 0, \"default\")\n\thas, err := wallet.NewDefault().KeyExists(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif has {\n\t\treturn fmt.Errorf(\"%q wallet already exists\", name)\n\t}\n\treturn nil\n}", "func requireZeroParams(parse func() (Command, error)) Parser {\n\treturn requireNParams(0, func(tokens []string) (Command, error) { return parse() })\n}", "func checkArgs() (string, bool, error) {\n\t//Fetch the command line arguments.\n\targs := os.Args\n\n\t//Check the length of the arugments, return failure if they are too\n\t//long or too short.\n\tif (len(args) < 2) || (len(args) > 3) {\n\t\treturn \"\", false, errors.New(\"Invalid number of arguments. \\n\" +\n\t\t\t\" Please provide sort option (-s) and the file name with relative path\" +\n\t\t\t\" of the csv data input file!\\n\")\n\t}\n\tfile_path := args[1]\n\tvar isSort bool\n\tif len(args) == 3 {\n\t\tif args[1] != \"-s\" {\n\t\t\treturn \"\", false, errors.New(\"Invalid number of arguments. \\n\" +\n\t\t\t\t\" Please provide sort option (-s) and the file name with relative path\" +\n\t\t\t\t\" of the csv data input file!\\n\")\n\t\t}\n\t\tisSort = true\n\t\tfile_path = args[2]\n\t}\n\t//On success, return the file_path and isSort value\n\treturn file_path, isSort, nil\n}", "func (f Function) Check(i Instruction) error {\n\tif f.NeedsVariable && len(i.Variable) == 0 {\n\t\treturn fmt.Errorf(\"missing variable in %s\", i.Function)\n\t}\n\tif len(i.Arguments) < f.NumArgsMin {\n\t\treturn fmt.Errorf(\"missing argument(s) in %s for %s, wanted: %d, got: %d\", i.Function, i.Variable, f.NumArgsMin, len(i.Arguments))\n\t}\n\tif len(i.Arguments) > f.NumArgsMax {\n\t\treturn fmt.Errorf(\"too many arguments in %s for %s, wanted: %d, got: %d\", i.Function, i.Variable, f.NumArgsMax, len(i.Arguments))\n\t}\n\treturn nil\n}", "func (c *CommandContext) RequireExactlyNArgs(n int) {\n\tif len(c.Args) != n {\n\t\tc.UsageExit()\n\t}\n}", "func (h NLBHealthCheckArgs) validate() error {\n\tif h.isEmpty() {\n\t\treturn nil\n\t}\n\treturn nil\n}", "func NotEmpty(t testing.TB, object interface{}, msgAndArgs ...interface{}) bool {\n\tif IsObjectEmpty(object) {\n\t\treturn failTest(t, 1, fmt.Sprintf(\"NotEmpty: expected not to be empty value, actual `%#v`\", object), msgAndArgs...)\n\t}\n\n\treturn true\n}", "func checkIfRequiredFloatParameterIsSupplied(propName, optionName, in string, parsedBody interface{}, varValue float64) error {\n\tif in == \"body\" {\n\t\tcontains := doesBodyContainParameter(parsedBody, propName)\n\t\tif !contains && varValue == 0.0 {\n\t\t\treturn fmt.Errorf(\"required parameter '%s' in body (or command line option '%s') is not specified\", propName, optionName)\n\t\t}\n\t\treturn nil\n\t}\n\n\tif varValue == 0.0 {\n\t\treturn fmt.Errorf(\"required parameter '%s' is not specified\", optionName)\n\t}\n\treturn nil\n}", "func checkSetParameter(param interface{}) bool {\n\tswitch param.(type) {\n\tcase string:\n\t\tif param.(string) == \"\" {\n\t\t\treturn false\n\t\t}\n\tcase int:\n\t\tif param.(int) == 0 {\n\t\t\treturn false\n\t\t}\n\tcase uint:\n\t\tif param.(uint) == 0 {\n\t\t\treturn false\n\t\t}\n\tcase float64:\n\t\tif param.(float64) == 0 {\n\t\t\treturn false\n\t\t}\n\tcase []Namespace:\n\t\tif param.([]Namespace) == nil {\n\t\t\treturn false\n\t\t}\n\tdefault:\n\t\treturn false\n\t}\n\treturn true\n}", "func (o *arg) check(argument string) (int, error) {\n\trez := o.checkLongName(argument)\n\tif rez > 0 {\n\t\treturn rez, nil\n\t}\n\n\treturn o.checkShortName(argument)\n}", "func (m *MongoStore) validateParams(args ...interface{}) bool {\n\tfor _, v := range args {\n\t\tval, ok := v.(string)\n\t\tif ok {\n\t\t\tif val == \"\" {\n\t\t\t\treturn false\n\t\t\t}\n\t\t} else {\n\t\t\tif v == nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func RequiredArgs(reqArgs ...string) cobra.PositionalArgs {\n\treturn func(cmd *cobra.Command, args []string) error {\n\t\tn := len(reqArgs)\n\t\tif len(args) >= n {\n\t\t\treturn nil\n\t\t}\n\n\t\tmissing := reqArgs[len(args):]\n\n\t\ta := fmt.Sprintf(\"arguments <%s>\", strings.Join(missing, \", \"))\n\t\tif len(missing) == 1 {\n\t\t\ta = fmt.Sprintf(\"argument <%s>\", missing[0])\n\t\t}\n\n\t\treturn fmt.Errorf(\"missing %s \\n\\n%s\", a, cmd.UsageString())\n\t}\n}", "func VerifySingleArgument(c *cli.Context) error {\n\ta := c.Args()\n\tif !a.Present() {\n\t\treturn fmt.Errorf(`Syntax error, command requires argument`)\n\t}\n\n\tif len(a.Tail()) != 0 {\n\t\treturn fmt.Errorf(\n\t\t\t\"Syntax error, too many arguments (expected: 1, received %d)\",\n\t\t\tlen(a.Tail())+1,\n\t\t)\n\t}\n\treturn nil\n}", "func none(cmd *cobra.Command, args []string) {}" ]
[ "0.6990896", "0.6740155", "0.6736732", "0.6645205", "0.65820414", "0.64653146", "0.6459614", "0.64470625", "0.64260644", "0.64201087", "0.6372319", "0.63715017", "0.63523114", "0.6348488", "0.6329301", "0.632766", "0.6326579", "0.6272477", "0.61495304", "0.6096113", "0.6079046", "0.6078105", "0.606206", "0.60595566", "0.60294896", "0.5934809", "0.59210396", "0.5900359", "0.5896893", "0.5884976", "0.58434826", "0.5828388", "0.58128357", "0.5811175", "0.5781037", "0.5780134", "0.5777377", "0.5770583", "0.57694894", "0.5769486", "0.57668495", "0.5713008", "0.57053876", "0.57046276", "0.56942445", "0.56874055", "0.5685342", "0.5683829", "0.5626207", "0.5602637", "0.5596428", "0.5584025", "0.55838245", "0.5558986", "0.55298245", "0.55248654", "0.55245787", "0.55072427", "0.54963106", "0.5496301", "0.548398", "0.54616183", "0.54488224", "0.544183", "0.5423555", "0.53360444", "0.5331912", "0.53315616", "0.53177166", "0.53097045", "0.52998555", "0.5285393", "0.52728075", "0.52668315", "0.52661705", "0.5253814", "0.52357507", "0.52190053", "0.52128464", "0.5191042", "0.51898724", "0.5187675", "0.5179907", "0.5179695", "0.51685244", "0.51656353", "0.51636505", "0.5152754", "0.5148442", "0.5138828", "0.51380455", "0.5136415", "0.5134278", "0.5133083", "0.51289755", "0.5128105", "0.5121194", "0.5116808", "0.5097508", "0.50963885" ]
0.81754017
0
GetItems returns the items for the given hunt
func GetItems(huntID int) ([]*models.Item, *response.Error) { itemDBs, e := db.GetItemsWithHuntID(huntID) if itemDBs == nil { return nil, e } items := make([]*models.Item, 0, len(itemDBs)) for _, itemDB := range itemDBs { item := models.Item{ItemDB: *itemDB} items = append(items, &item) } return items, e }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetItemsForHunt(huntID int) ([]*models.Item, *response.Error) {\n\titemDBs, e := db.GetItemsWithHuntID(huntID)\n\tif itemDBs == nil {\n\t\treturn nil, e\n\t}\n\n\titems := make([]*models.Item, 0, len(itemDBs))\n\n\tfor _, v := range itemDBs {\n\t\titem := models.Item{ItemDB: *v}\n\t\titems = append(items, &item)\n\t}\n\n\treturn items, e\n}", "func getItems(ctx context.Context, request events.APIGatewayProxyRequest,\n\tih *item.Handler) (events.APIGatewayProxyResponse, error) {\n\n\tvar list *item.List\n\n\tlist, err := ih.List(ctx, request.PathParameters[PathParamCategoryID])\n\tif err != nil {\n\t\treturn web.GetResponse(ctx, err.Error(), http.StatusInternalServerError)\n\t}\n\n\treturn web.GetResponse(ctx, list, http.StatusOK)\n}", "func (b *OGame) GetItems(celestialID ogame.CelestialID) ([]ogame.Item, error) {\n\treturn b.WithPriority(taskRunner.Normal).GetItems(celestialID)\n}", "func getItems(w http.ResponseWriter, r *http.Request) {\n\titems, err := supermart.GetItems(r.Context(), r)\n\tif err != nil {\n\t\tutils.WriteErrorResponse(http.StatusInternalServerError, err, w)\n\t\treturn\n\t}\n\tutils.WriteResponse(http.StatusOK, items, w)\n}", "func (api *API) ItemsGet(params Params) (res Items, err error) {\n\tif _, present := params[\"output\"]; !present {\n\t\tparams[\"output\"] = \"extend\"\n\t}\n\tresponse, err := api.CallWithError(\"item.get\", params)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treflector.MapsToStructs2(response.Result.([]interface{}), &res, reflector.Strconv, \"json\")\n\treturn\n}", "func GetItems(c *gin.Context) {\n\tvar items []model.ItemJson\n\terr := util.DB.Table(\"items\").Find(&items).Error\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t} else {\n\t\tc.JSON(http.StatusOK, util.SuccessResponse(http.StatusOK, \"Success\", items))\n\t}\n}", "func (c *Client) GetItems(ctx context.Context, owner string) (Items, error) {\n\tresponse, err := c.sendRequest(ctx, owner, http.MethodGet, fmt.Sprintf(\"%s/%s\", c.storeBaseURL, c.bucket), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif response.Code != http.StatusOK {\n\t\tlevel.Error(c.getLogger(ctx)).Log(xlog.MessageKey(), \"Argus responded with non-200 response for GetItems request\",\n\t\t\t\"code\", response.Code, \"ErrorHeader\", response.ArgusErrorHeader)\n\t\treturn nil, fmt.Errorf(errStatusCodeFmt, response.Code, translateNonSuccessStatusCode(response.Code))\n\t}\n\n\tvar items Items\n\n\terr = json.Unmarshal(response.Body, &items)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"GetItems: %w: %s\", errJSONUnmarshal, err.Error())\n\t}\n\n\treturn items, nil\n}", "func GetItems(da DataAccess, username string) (*ItemList, error) {\n\t// find the user and verify they exist\n\tuser, err := FindUserByName(da, username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// try to get their items\n\titems, err := da.GetItemsByUser(context.Background(), user.Id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// calculate net worth, asset total, liability total\n\tvar net, asset, liability int64\n\tfor i := range *items {\n\t\tif (*items)[i].Type == ItemTypeAsset {\n\t\t\tnet += (*items)[i].Value\n\t\t\tasset += (*items)[i].Value\n\t\t} else if (*items)[i].Type == ItemTypeLiability {\n\t\t\tnet -= (*items)[i].Value\n\t\t\tliability += (*items)[i].Value\n\t\t}\n\t}\n\n\treturn &ItemList{Username: username, Items: items, NetWorth: net, AssetTotal: asset, LiabilityTotal: liability}, nil\n}", "func (m *Drive) GetItems()([]DriveItemable) {\n return m.items\n}", "func GetItems(c *gin.Context) {\n\tvar items []models.Item\n\tif err := models.DB.Order(\"name\").Find(&items).Error; err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": \"Could not find items\"})\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"items\": items})\n}", "func (c *Client) GetItems(id int) (Item, error) {\n\tc.defaultify()\n\tvar item Item\n\tresp, err := http.Get(fmt.Sprintf(\"%s/item/%d.json\", c.apiBase, id))\n\tif err != nil {\n\t\treturn item, err\n\t}\n\tdefer resp.Body.Close()\n\tdec := json.NewDecoder(resp.Body)\n\terr = dec.Decode(&item)\n\tif err != nil {\n\t\treturn item, err\n\t}\n\treturn item, nil\n}", "func (_CraftingI *CraftingICallerSession) Items(arg0 *big.Int) (struct {\n\tBaseType uint8\n\tItemType uint8\n\tCrafted uint32\n\tCrafter *big.Int\n}, error) {\n\treturn _CraftingI.Contract.Items(&_CraftingI.CallOpts, arg0)\n}", "func (_CraftingI *CraftingISession) Items(arg0 *big.Int) (struct {\n\tBaseType uint8\n\tItemType uint8\n\tCrafted uint32\n\tCrafter *big.Int\n}, error) {\n\treturn _CraftingI.Contract.Items(&_CraftingI.CallOpts, arg0)\n}", "func GetItems(ctx *fasthttp.RequestCtx) {\n\tenc := json.NewEncoder(ctx)\n\titems := ReadItems()\n\tenc.Encode(&items)\n\tctx.SetStatusCode(fasthttp.StatusOK)\n}", "func (self *SearchJob) GetItems() (items []Item) {\n\tself.Mutex.Lock()\n\titems = self.Items\n\t//update last access time\n\tself.LastRead = time.Now()\n\t//write to the writer\n\tself.Items = make([]Item, 0)\n\tself.Mutex.Unlock()\n\tlog.Println(\"items:\",len(items))\n\treturn items\n}", "func (c *Controller) GetItems() http.Handler {\n\treturn http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) {\n\t\tu := utility.New(writer, req)\n\t\tsession := c.store.DB.Copy()\n\t\tdefer session.Close()\n\n\t\tvar items []Item\n\t\tcollection := session.DB(c.databaseName).C(ItemsCollection)\n\t\terr := collection.\n\t\t\tFind(nil).\n\t\t\tSelect(bson.M{\"_id\": 1, \"color\": 1, \"code\": 1, \"description\": 1, \"category\": 1}).\n\t\t\tSort(\"description\").\n\t\t\tAll(&items)\n\t\tif err != nil {\n\t\t\tc.logger.Error(err)\n\t\t\tu.WriteJSONError(\"verification failed\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tu.WriteJSON(items)\n\t})\n}", "func GetAllItems(w http.ResponseWriter, r *http.Request) {\r\n\r\n\t// get the bearer token\r\n\tbearerHeader := r.Header.Get(\"Authorization\")\r\n\r\n\t// validate token, it will return a User{UserID, Name}\r\n\t_, err := ValidateToken(bearerHeader)\r\n\r\n\tcheckErr(err)\r\n\r\n\t// create the db connection\r\n\tdb := getDBConn()\r\n\r\n\t// close the db connection\r\n\tdefer db.Close()\r\n\r\n\t// query\r\n\trows, err := db.Query(\"SELECT * FROM items\")\r\n\r\n\tcheckErr(err)\r\n\r\n\t// create an array of item type to store all the items\r\n\tvar items []item\r\n\r\n\t// iterate over rows to format item in item type\r\n\tfor rows.Next() {\r\n\t\tvar params item\r\n\r\n\t\terr = rows.Scan(&params.ItemID, &params.MerchantID, &params.Name)\r\n\r\n\t\titems = append(items, params)\r\n\t}\r\n\r\n\t// return the order array in json format\r\n\tjson.NewEncoder(w).Encode(items)\r\n}", "func GetItemsHandler(db *sqlx.DB) gin.HandlerFunc {\n\treturn func (ctx *gin.Context) {\n\t\tcreatedBy, createdByExists := GetUserID(ctx)\n\t\tif !createdByExists {\n\t\t\tctx.String(http.StatusUnauthorized, \"User id not found in authorization token.\")\n\t\t\treturn\n\t\t}\n\n\t\tvar searchQuery ItemsGetQuery\n\t\tif err := ctx.ShouldBindQuery(&searchQuery); err != nil {\n\t\t\tctx.String(http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tquery := sq.Select(\"items.public_id, name, price, unit, created_at, updated_at\").From(\"items\")\n\n\t\tif createdBy != \"\" {\n\t\t\tquery = query.Join(\"users ON users.id = items.created_by\").Where(sq.Eq{\"users.public_id\": createdBy})\n\t\t}\n\n\t\tif searchQuery.Name != \"\" {\n\t\t\tquery = query.Where(\"items.name LIKE ?\", fmt.Sprint(\"%\", searchQuery.Name, \"%\"))\n\t\t}\n\n\t\tqueryString, queryStringArgs, err := query.ToSql()\n\t\tif err != nil {\n\t\t\tctx.String(http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\titems := []Item{}\n\t\tif err := db.Select(&items, queryString, queryStringArgs...); err != nil {\n\t\t\tlog.Fatalln(err.Error())\n\t\t}\n\n\t\tctx.JSON(http.StatusOK, items)\n\t}\n}", "func GetItemsByMerchant(w http.ResponseWriter, r *http.Request) {\r\n\r\n\t// get the bearer token\r\n\tbearerHeader := r.Header.Get(\"Authorization\")\r\n\r\n\t// validate token, it will return a User{UserID, Name}\r\n\tuser, err := ValidateToken(bearerHeader)\r\n\r\n\tcheckErr(err)\r\n\r\n\t// create the db connection\r\n\tdb := getDBConn()\r\n\r\n\t// close db connection\r\n\tdefer db.Close()\r\n\r\n\t// prepare query\r\n\tstmtOut, err := db.Prepare(\"SELECT * FROM items WHERE merchantID = ?\")\r\n\r\n\t// close stmtOut request\r\n\tdefer stmtOut.Close()\r\n\r\n\tcheckErr(err)\r\n\r\n\t// filter orders by merchantID\r\n\trows, err := stmtOut.Query(user.UserID)\r\n\r\n\tcheckErr(err)\r\n\r\n\t// create an array of item type to store all the items\r\n\tvar items []item\r\n\r\n\t// iterate over rows to format item in item type\r\n\tfor rows.Next() {\r\n\r\n\t\tvar item item\r\n\r\n\t\terr = rows.Scan(&item.ItemID, &item.MerchantID, &item.Name)\r\n\r\n\t\titems = append(items, item)\r\n\t}\r\n\r\n\t// return the item array in json format\r\n\tjson.NewEncoder(w).Encode(items)\r\n\r\n}", "func (c *container) Items(prefix, cursor string, count int) ([]stow.Item, string, error) {\n\tvar entries []entry\n\tentries, cursor, err := c.getFolderItems([]entry{}, prefix, \"\", filepath.Join(c.location.config.basePath, c.name), cursor, count, false)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\t// Convert entries to []stow.Item\n\tsItems := make([]stow.Item, len(entries))\n\tfor i := range entries {\n\t\tsItems[i] = entries[i].item\n\t}\n\n\treturn sItems, cursor, nil\n}", "func (c HourlyCommand) Items(arg, data string) (items []alfred.Item, err error) {\n\tdlog.Printf(\"Running HourlyCommand\")\n\n\tvar cfg hourlyConfig\n\tif data != \"\" {\n\t\tif err := json.Unmarshal([]byte(data), &cfg); err != nil {\n\t\t\tdlog.Printf(\"Invalid hourly config\")\n\t\t}\n\t}\n\n\tvar weather Weather\n\tvar loc Location\n\tif loc, weather, err = getWeather(arg); err != nil {\n\t\treturn\n\t}\n\n\tvar startTime time.Time\n\tif cfg.Start != nil {\n\t\tstartTime = *cfg.Start\n\t} else if len(weather.Hourly) > 0 {\n\t\tstartTime = weather.Hourly[0].Time\n\t}\n\n\theading := alfred.Item{\n\t\tTitle: \"Weather for \" + loc.Name,\n\t\tSubtitle: alfred.Line,\n\t\tArg: &alfred.ItemArg{\n\t\t\tKeyword: \"daily\",\n\t\t},\n\t}\n\n\tif weather.URL != \"\" {\n\t\theading.AddMod(alfred.ModCmd, alfred.ItemMod{\n\t\t\tSubtitle: \"Open this forecast in a browser\",\n\t\t\tArg: &alfred.ItemArg{\n\t\t\t\tKeyword: \"daily\",\n\t\t\t\tMode: alfred.ModeDo,\n\t\t\t\tData: alfred.Stringify(&dailyCfg{ToOpen: weather.URL}),\n\t\t\t},\n\t\t})\n\t}\n\n\titems = append(items, heading)\n\n\tdeg := \"F\"\n\tif config.Units == unitsMetric {\n\t\tdeg = \"C\"\n\t}\n\n\taddAlertItems(&weather, &items)\n\n\tfor _, entry := range weather.Hourly {\n\t\tif entry.Time.Before(startTime) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconditions := entry.Summary\n\t\ticon := entry.Icon\n\n\t\titem := alfred.Item{\n\t\t\tTitle: entry.Time.Format(\"Mon \"+config.TimeFormat) + \": \" + conditions,\n\t\t\tSubtitle: fmt.Sprintf(\"%d°%s (%d°%s) ☂ %d%%\", entry.Temp.Int64(), deg, entry.ApparentTemp.Int64(), deg, entry.Precip),\n\t\t\tIcon: getIconFile(icon),\n\t\t}\n\n\t\titems = append(items, item)\n\t}\n\n\treturn\n}", "func GetItem(w http.ResponseWriter, r *http.Request) {\r\n\r\n\t// get the bearer token\r\n\tbearerHeader := r.Header.Get(\"Authorization\")\r\n\r\n\t// validate token, it will return a User{UserID, Name}\r\n\t_, err := ValidateToken(bearerHeader)\r\n\r\n\tcheckErr(err)\r\n\r\n\t// get all the params from the request\r\n\tvars := mux.Vars(r)\r\n\r\n\t// create the db connection\r\n\tdb := getDBConn()\r\n\r\n\t// close db connection\r\n\tdefer db.Close()\r\n\r\n\t// prepare query\r\n\tstmtOut, err := db.Prepare(\"SELECT * FROM items WHERE itemID=?\")\r\n\r\n\t// close stmtOut request\r\n\tdefer stmtOut.Close()\r\n\r\n\tcheckErr(err)\r\n\r\n\tvar item item\r\n\r\n\terr = stmtOut.QueryRow(vars[\"itemID\"]).Scan(&item.ItemID, &item.MerchantID, &item.Name)\r\n\r\n\tcheckErr(err)\r\n\r\n\t// return the order in json format\r\n\tjson.NewEncoder(w).Encode(item)\r\n}", "func (out Outlooky) GetItems(folder *ole.IDispatch) *ole.IDispatch {\n\titems, err := out.CallMethod(folder, \"Items\")\n\tutil.Catch(err, \"Failed retrieving items.\")\n\n\treturn items.ToIDispatch()\n}", "func (c *Container) Items(prefix string, cursor string, count int) ([]stow.Item, string, error) {\n\tquery := &storage.Query{Prefix: prefix}\n\tcall := c.Bucket().Objects(c.ctx, query)\n\n\tp := iterator.NewPager(call, count, cursor)\n\tvar results []*storage.ObjectAttrs\n\tnextPageToken, err := p.NextPage(&results)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tvar items []stow.Item\n\tfor _, item := range results {\n\t\ti, err := c.convertToStowItem(item)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\n\t\titems = append(items, i)\n\t}\n\n\treturn items, nextPageToken, nil\n}", "func (_CraftingI *CraftingICaller) Items(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tBaseType uint8\n\tItemType uint8\n\tCrafted uint32\n\tCrafter *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _CraftingI.contract.Call(opts, &out, \"items\", arg0)\n\n\toutstruct := new(struct {\n\t\tBaseType uint8\n\t\tItemType uint8\n\t\tCrafted uint32\n\t\tCrafter *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.BaseType = *abi.ConvertType(out[0], new(uint8)).(*uint8)\n\toutstruct.ItemType = *abi.ConvertType(out[1], new(uint8)).(*uint8)\n\toutstruct.Crafted = *abi.ConvertType(out[2], new(uint32)).(*uint32)\n\toutstruct.Crafter = *abi.ConvertType(out[3], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func GetItemNames(c *gin.Context) {\n\ttype ItemName struct {\n\t\tName string\n\t\tID uint\n\t}\n\n\tvar items []ItemName\n\tif err := models.DB.Model(&models.Item{}).Order(\"name\").Find(&items).Error; err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"Couldn't retrieve items\"})\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"items\": items})\n}", "func GetItems() (items []Item, err error) {\n\tdir, err := os.Open(rootPath)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfi, err := dir.Stat()\n\tif !fi.Mode().IsDir() {\n\t\tpanic(\"need directory\")\n\t}\n\n\tnames, err := dir.Readdirnames(0)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, name := range names {\n\t\titem, err := NewItem(name)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\titems = append(items, item)\n\t}\n\n\tsort.Sort(sort.Reverse(byCreatedAt(items)))\n\n\treturn items, nil\n}", "func GetAllItems(c *gin.Context) {\n\tdb := PostSQLConfig()\n\ts := c.Request.URL.Query().Get(\"user\")\n\trows, err := db.Query(\"select * from menu where userinfo = '\" + s + \"';\")\n\tif err != nil {\n\t\tfmt.Println(\"ERROR IS1\", err)\n\t\tcreateUserTable()\n\t}\n\tdefer rows.Close()\n\trepos := model_menu.MenuItems{}\n\tvar childUnit []uint8\n\tfor rows.Next() {\n\t\tp := model_menu.Menu{}\n\t\terr = rows.Scan(&p.ID, &p.Name, &p.Url, &p.Sysname, &p.UserInfo, &childUnit)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\ts := string(childUnit)\n\n\t\terr := json.Unmarshal([]byte(s), &p.Child)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"error:\", err)\n\t\t}\n\n\t\trepos = append(repos, p)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tc.JSON(200, gin.H{\n\t\t\"menu\": &repos,\n\t})\n\tdefer db.Close()\n}", "func GetItem(itemName string, marketplace string) ([]Item, error) {\n\t// TODO query an item from db\n\n\t// item0, err0 := flipkart.GetItem(itemName)\n\t// item1, err1 := amazon.GetItem(itemName)\n\n\tvar OneItem []Item\n\n\t// err0 = json.Unmarshal([]byte(item0), Items[0])\n\t// err1 = json.Unmarshal([]byte(item1), Items[1])\n\n\tswitch marketplace {\n\tcase \"flipkart\":\n\t\t{\n\t\t\titem, err := flipkart.GetItem(itemName)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tjson.Unmarshal([]byte(item), &OneItem)\n\n\t\t\treturn OneItem, nil\n\t\t}\n\n\tcase \"amazon\":\n\t\t{\n\t\t\titem, err := amazon.GetItem(itemName)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\terr = json.Unmarshal([]byte(item), &OneItem)\n\t\t\tfmt.Println(\"from app domain\", OneItem, err)\n\t\t\treturn OneItem, nil\n\t\t}\n\n\tdefault:\n\t\t{\n\t\t\treturn nil, errors.New(\"marketplace not available\")\n\t\t}\n\t}\n}", "func (m *ExternalConnection) GetItems()([]ExternalItemable) {\n return m.items\n}", "func GetItemsHandler(rep repository.Repository) func(w http.ResponseWriter, r *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tif err := r.ParseForm(); err != nil {\n\t\t\trespond(w, http.StatusBadRequest, data.ErrorResponse{Error: \"malformed form input\"})\n\t\t\treturn\n\t\t}\n\n\t\tsearch := r.FormValue(\"search\")\n\t\tif len(search) < 3 {\n\t\t\trespond(w, http.StatusBadRequest, data.ErrorResponse{Error: \"search should be at least 3 characters\"})\n\t\t\treturn\n\t\t}\n\n\t\titems, err := rep.GetItems(search)\n\t\tif err != nil {\n\t\t\trespond(w, http.StatusInternalServerError, data.ErrorResponse{Error: \"server has failed to fetch items\"})\n\t\t}\n\n\t\trespond(w, http.StatusOK, data.Response{Items: items})\n\t}\n}", "func (ris *rssItems) getItems() []RssItem {\n\tris.RLock()\n\tdefer ris.RUnlock()\n\treturn ris.items\n}", "func (db Database) GetItems() (*models.ItemList, error) {\n\tlist := &models.ItemList{}\n\n\trows, err := db.Conn.Query(\"SELECT * FROM items ORDER BY created_at desc;\")\n\tif err != nil {\n\t\treturn list, err\n\t}\n\n\tfor rows.Next() {\n\t\tvar item models.Item\n\n\t\tif err = rows.Scan(\n\t\t\t&item.ID,\n\t\t\t&item.Name,\n\t\t\t&item.Description,\n\t\t\t&item.Creation,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tlist.Items = append(list.Items, item)\n\t}\n\n\treturn list, nil\n}", "func getItems(repoIndex *index.Index, url string) []FileInfo {\n\tvar items []FileInfo\n\n\tfor _, os := range repoIndex.Data.Keys() {\n\t\tfor _, arch := range repoIndex.Data[os].Keys() {\n\t\t\tfor _, category := range repoIndex.Data[os][arch].Keys() {\n\t\t\t\tfor _, version := range repoIndex.Data[os][arch][category] {\n\t\t\t\t\titems = append(items, FileInfo{\n\t\t\t\t\t\tFile: version.File,\n\t\t\t\t\t\tURL: url + \"/\" + version.Path + \"/\" + version.File,\n\t\t\t\t\t\tOS: os,\n\t\t\t\t\t\tArch: arch,\n\t\t\t\t\t\tSize: version.Size,\n\t\t\t\t\t})\n\n\t\t\t\t\tif len(version.Variations) != 0 {\n\t\t\t\t\t\tfor _, subVersion := range version.Variations {\n\t\t\t\t\t\t\titems = append(items, FileInfo{\n\t\t\t\t\t\t\t\tFile: subVersion.File,\n\t\t\t\t\t\t\t\tURL: url + \"/\" + subVersion.Path + \"/\" + subVersion.File,\n\t\t\t\t\t\t\t\tOS: os,\n\t\t\t\t\t\t\t\tArch: arch,\n\t\t\t\t\t\t\t\tSize: subVersion.Size,\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\treturn items\n}", "func (c GroupCommand) Items(arg, data string) (items []alfred.Item, err error) {\n\tif err = checkRefresh(); err != nil {\n\t\treturn\n\t}\n\n\tvar cfg groupConfig\n\n\tif data != \"\" {\n\t\tif err = json.Unmarshal([]byte(data), &cfg); err != nil {\n\t\t\tdlog.Printf(\"Error unmarshalling group config: %v\", err)\n\t\t}\n\t}\n\n\tif cfg.Group != \"\" {\n\t} else {\n\t\tfor _, group := range cache.Groups {\n\t\t\tif alfred.FuzzyMatches(group.Name, arg) {\n\t\t\t\tlights, _ := getLightNamesFromIDs(group.Lights)\n\n\t\t\t\titems = append(items, alfred.Item{\n\t\t\t\t\tTitle: group.Name,\n\t\t\t\t\tSubtitle: strings.Join(lights, \", \"),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}", "func GetBoughtItem(c *gin.Context) {\n\tuserID, ok := c.MustGet(\"user_id\").(int64)\n\tif !ok {\n\t\tlog.Printf(\"invalid userid in token, userid: %v\", c.MustGet(\"user_id\"))\n\t\tc.JSON(http.StatusForbidden, &model.ErrResp{Error: \"Invalid token\"})\n\t\treturn\n\t}\n\n\tuserRole, ok := c.MustGet(\"role\").(string)\n\tif !ok {\n\t\tlog.Printf(\"invalid userole in token, userid: %v\", c.MustGet(\"role\"))\n\t\tc.JSON(http.StatusForbidden, &model.ErrResp{Error: \"Invalid token\"})\n\t\treturn\n\t}\n\n\tparamUserID, err := strconv.ParseInt(c.Param(\"user_id\"), 10, 64)\n\tif err != nil {\n\t\tlog.Printf(\"path parm user_id err: %v\", err)\n\t\tc.JSON(http.StatusBadRequest, &model.ErrResp{Error: \"Invalid path param\", Fields: &[]string{\"user_id\"}})\n\t\treturn\n\t}\n\n\tif userID != paramUserID && userRole != constAdminRole {\n\t\tc.JSON(http.StatusMethodNotAllowed, &model.ErrResp{Error: \"Not allowed please check token\"})\n\t\treturn\n\t}\n\n\tboughtItemList, err := (&model.BoughtItem{}).Get(\"user_id=$1\", paramUserID)\n\tif err != nil {\n\t\tlog.Printf(\"db fetching bought item error: %v\", err)\n\t\tc.JSON(http.StatusInternalServerError, &model.ErrResp{Error: \"Server error\"})\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, boughtItemList)\n}", "func (s *GORMStore) GetItems() interface{} {\n\treturn s.items\n}", "func (api *API) ItemsGetByApplicationID(id string) (res Items, err error) {\n\treturn api.ItemsGet(Params{\"applicationids\": id})\n}", "func getGitHubRepoItems(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\titemType := vars[\"itemType\"]\n\n\tif itemType == \"branch\" || itemType == \"commit\" {\n\t\towner := vars[\"owner\"]\n\t\trepo := vars[\"repo\"]\n\t\ttoken, err := parseTokenFromCookie(r)\n\t\thelpers.HandleError(err)\n\n\t\tvar res interface{}\n\n\t\tif itemType == \"branch\" {\n\t\t\tres, err = github.GetBranches(token, owner, repo)\n\t\t\thelpers.HandleError(err)\n\t\t} else {\n\t\t\tfrom, err := time.Parse(dtParamLayout, r.URL.Query().Get(\"from\"))\n\t\t\tif err != nil {\n\t\t\t\tfrom = time.Now().AddDate(0, 0, -7)\n\t\t\t}\n\t\t\tto, err := time.Parse(dtParamLayout, r.URL.Query().Get(\"to\"))\n\t\t\tif err != nil {\n\t\t\t\tto = time.Now()\n\t\t\t}\n\n\t\t\tres, err = github.GetCommits(token, owner, repo, from, to)\n\t\t\thelpers.HandleError(err)\n\t\t}\n\n\t\tapiResponse(map[string]interface{}{\"data\": res}, w)\n\t} else {\n\t\thelpers.HandleError(errors.New(\"Invalid itemType param\"))\n\t}\n}", "func (op Client) GetItem(vault VaultName, item ItemName) (ItemMap, error) {\n\tvaultArg := getArg(\"vault\", string(vault))\n\tres, err := op.runCmd(\"get\", \"item\", string(item), vaultArg)\n\tif err != nil {\n\t\treturn make(ItemMap), fmt.Errorf(\"error getting item: %s\", err)\n\t}\n\tim, err := parseItemResponse(res)\n\tif err != nil {\n\t\treturn im, fmt.Errorf(\"error parsing response: %s\", err)\n\t}\n\treturn im, nil\n}", "func GetAllItemsInBasket(w http.ResponseWriter, r *http.Request) {\r\n\trouteParams := mux.Vars(r)\r\n\tbasketID, err := strconv.Atoi(routeParams[\"basketId\"])\r\n\r\n\tif err != nil {\r\n\t\trespondWithError(w, http.StatusBadRequest, \"Invalid basket ID\")\r\n\t}\r\n\r\n\tbasketItems, err := models.GetItemsInBasket(basketID)\r\n\r\n\tif err != nil {\r\n\t\trespondWithError(w, http.StatusNotFound, \"Items not found for this basket\")\r\n\t\treturn\r\n\t}\r\n\r\n\trespondWithJSON(w, http.StatusOK, basketItems)\r\n}", "func (o IopingSpecVolumeVolumeSourceSecretOutput) Items() IopingSpecVolumeVolumeSourceSecretItemsArrayOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceSecret) []IopingSpecVolumeVolumeSourceSecretItems { return v.Items }).(IopingSpecVolumeVolumeSourceSecretItemsArrayOutput)\n}", "func getStories(ids []int, numstories int) []item {\n\tvar client hn.Client\n\tvar stories []item\n\tfor i, id := range ids { // Look up the cache first\n\t\tif it, found := cach.find(id); found {\n\t\t\tstories = append(stories, it)\n\t\t\tif len(stories) >= numstories {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\thnItem, err := client.GetItem(id) // not found in cache, send a request\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\titem := parseHNItem(hnItem, i)\n\t\tif isStoryLink(item) {\n\t\t\tstories = append(stories, item)\n\t\t\tif len(stories) >= numstories {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn stories\n}", "func (is *ItemServices) Items(ctx context.Context, limit, offset int) ([]entity.Item, []error) {\n\titms, errs := is.itemRepo.Items(ctx, limit, offset)\n\tif len(errs) > 0 {\n\t\treturn nil, errs\n\t}\n\treturn itms, errs\n}", "func (d *Database) GetItems(\n\treq GetItemsRequest) (*GetItemsResponse, error) {\n\tvar err error\n\tresp := GetItemsResponse{\n\t\tItems: []*structs.Item{}}\n\n\tif !req.Unread && req.ReadAfter == nil && req.ReadBefore == nil {\n\t\tlog.Info(\"GetItems() called with empty request\")\n\t\treturn &resp, nil\n\t}\n\n\tif len(req.FeedIDs) != 0 && req.CategoryID != nil {\n\t\treturn nil, errors.New(\"Can't call GetItems for both feeds and a category\")\n\t}\n\n\tif req.Unread && len(req.FeedIDs) == 0 {\n\t\treturn nil, errors.New(\"Can't request unread except by feeds\")\n\t}\n\n\tif (req.ReadAfter != nil) && (req.ReadBefore != nil) {\n\t\treturn nil, errors.New(\"Must not specify both ReadBefore and ReadAfter\")\n\t}\n\n\tif req.ReadAfter != nil {\n\t\t*req.ReadAfter = req.ReadAfter.UTC().Truncate(time.Second)\n\t}\n\n\tif req.ReadBefore != nil {\n\t\t*req.ReadBefore = req.ReadBefore.UTC().Truncate(time.Second)\n\t}\n\n\td.lock.RLock()\n\tdefer d.lock.RUnlock()\n\n\tif err := d.checkClosed(); err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tif !req.IncludeFeeds {\n\t\tresp.Items, err = getItemsFor(d.db, req)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn &resp, nil\n\t}\n\n\ttx, err := d.db.Begin()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\tdefer tx.Rollback()\n\n\tresp.Items, err = getItemsFor(tx, req)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tif req.IncludeFeeds && req.FeedIDs != nil {\n\t\tresp.Feeds, err = getFeeds(tx, req.FeedIDs)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\ttx.Rollback()\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}", "func (m *List) GetItems()([]ListItemable) {\n return m.items\n}", "func (c *Cache) GetItems() map[string]*Item {\n\treturn c.items\n}", "func (d *Discovery) Get() []string {\n d.Lock()\n defer d.Unlock()\n\n items := make([]string, len(d.items))\n for i, item := range d.items {\n items[i] = item\n }\n\n return items\n}", "func GetSelfItems() ([]Item, error) {\n\treq, _ := http.NewRequest(\"GET\", \"https://qiita.com/api/v2/authenticated_user/items\", nil)\n\tresbyte, err := DoRequest(req)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to DoRequest\")\n\t}\n\n\tvar items []Item\n\tif err := json.Unmarshal(resbyte, &items); err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to unmarshal\")\n\t}\n\treturn items, nil\n}", "func (m *Drive) GetBundles()([]DriveItemable) {\n return m.bundles\n}", "func (b *Bag) Items() []Item {\n\treturn b.items\n}", "func GetItems(filter interface{}) (GetItemResult, error) {\n\t// create connection to database\n\tctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)\n\tdefer cancel()\n\tc := newConnection(ctx)\n\tdefer c.clt.Disconnect(ctx)\n\n\tcursor, err := c.collection(itemCollection).Find(context.Background(), filter)\n\tif err == mongo.ErrNoDocuments {\n\t\treturn GetItemResult{\n\t\t\tGotItemCount: 0,\n\t\t\tData: nil,\n\t\t}, nil\n\t} else if err != nil {\n\t\treturn GetItemResult{}, err\n\t}\n\n\tvar res []bson.M\n\tif err = cursor.All(context.Background(), &res); err != nil {\n\t\treturn GetItemResult{}, err\n\t}\n\treturn GetItemResult{\n\t\tGotItemCount: int64(len(res)),\n\t\tData: res,\n\t}, nil\n}", "func GetItemInfoByIDs(w http.ResponseWriter, r *http.Request) {\n\thelpers.EnableCors(w)\n\tparams := mux.Vars(r)\n\tk := strings.Replace(params[\"ids\"], \" \", \"\", -1)\n\ts := strings.Split(k, \",\")\n\n\tvar itemInfos []models.ItemInfo\n\tdb, err := helpers.CreateDatabase()\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t}\n\n\tfor _, element := range s {\n\t\titemID, err := strconv.Atoi(element)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t}\n\t\terr = helpers.CheckID(&itemID)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t}\n\n\t\titemInfo := GetByID(itemID, db)\n\t\titemInfos = append(itemInfos, itemInfo[0])\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(itemInfos)\n}", "func (c *pricedCart) GetItems() []Item {\n\titems := make([]Item, len(c.items))\n\ti := 0\n\tfor _, item := range c.items {\n\t\titems[i] = *item\n\t\ti++\n\t}\n\treturn items\n}", "func (m *MGOStore) GetItems() interface{} {\n\treturn m.items\n}", "func (l *GatewayResponseList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func getItemList(r *http.Request, pb transactionPb.TransactionService) (proto.Message, error) {\n\tpbRequest := &transactionPb.ItemListReq{}\n\tpbResponse, err := pb.GetItemList(context.Background(), pbRequest)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pbResponse, nil\n}", "func (i *Inventory) Items() []*ItemStack {\n\treturn i.items\n}", "func GetItems(root string, dir string, ignore IgnoreHandler) ([]Item, error) {\r\n\tfiles, err := ioutil.ReadDir(dir)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\titems := []Item{}\r\n\tfor _, file := range files {\r\n\t\tname := file.Name()\r\n\t\tpath := filepath.Join(dir, name)\r\n\t\tevt, err := newEvent(root, path, fsnotify.Write)\r\n\t\tif err != nil {\r\n\t\t\treturn nil, err\r\n\t\t}\r\n\t\tif ignore(evt) == false {\r\n\t\t\tif evt.Dir {\r\n\t\t\t\tchildren, err := GetItems(root, path, ignore)\r\n\t\t\t\tif err != nil {\r\n\t\t\t\t\treturn nil, err\r\n\t\t\t\t}\r\n\t\t\t\titems = append(items, children...)\r\n\t\t\t} else {\r\n\t\t\t\tchecksum, err := GetChecksum(path)\r\n\t\t\t\tif err != nil {\r\n\t\t\t\t\treturn nil, err\r\n\t\t\t\t}\r\n\t\t\t\titems = append(items, Item{\r\n\t\t\t\t\tRelPath: evt.RelPath,\r\n\t\t\t\t\tChecksum: checksum,\r\n\t\t\t\t\tModTime: file.ModTime().UnixNano(),\r\n\t\t\t\t})\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn items, err\r\n}", "func (items *items) getUntil(checker func(item interface{}) bool) []interface{} {\n\tlength := len(*items)\n\tif length == 0 {\n\t\treturn []interface{}{}\n\t}\n\n\treturnItems := make([]interface{}, 0, length)\n\tindex := 0\n\tfor i, item := range *items {\n\t\tif !checker(item) {\n\t\t\tbreak\n\t\t}\n\n\t\treturnItems = append(returnItems, item)\n\t\tindex = i\n\t}\n\n\t*items = (*items)[index:]\n\treturn returnItems\n}", "func GetVaults(c *gin.Context) {\n\tdbmap := c.MustGet(\"DBmap\").(*gorp.DbMap)\n\tverbose := c.MustGet(\"Verbose\").(bool)\n\tquery := \"SELECT * FROM vault\"\n\n\t// Parse query string\n\tq := c.Request.URL.Query()\n\ts, o, l := ParseQuery(q)\n\tvar count int64\n\tif s != \"\" {\n\t\tcount, _ = dbmap.SelectInt(\"SELECT COUNT(*) FROM vault WHERE \" + s)\n\t\tquery = query + \" WHERE \" + s\n\t} else {\n\t\tcount, _ = dbmap.SelectInt(\"SELECT COUNT(*) FROM vault\")\n\t}\n\tif o != \"\" {\n\t\tquery = query + o\n\t}\n\tif l != \"\" {\n\t\tquery = query + l\n\t}\n\n\tif verbose == true {\n\t\tfmt.Println(q)\n\t\tfmt.Println(\" -- \" + query)\n\t}\n\n\tvar vaults []Vault\n\t_, err := dbmap.Select(&vaults, query)\n\n\tif err == nil {\n\t\tc.Header(\"X-Total-Count\", strconv.FormatInt(count, 10)) // float64 to string\n\t\tc.JSON(200, vaults)\n\t} else {\n\t\tc.JSON(404, gin.H{\"error\": \"no vault(s) into the table\"})\n\t}\n\n\t// curl -i http://localhost:8080/api/v1/vaults\n}", "func (m *SiteItemRequestBuilder) Items()(*ItemItemsRequestBuilder) {\n return NewItemItemsRequestBuilderInternal(m.pathParameters, m.requestAdapter)\n}", "func (o TagsResponseOutput) Items() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v TagsResponse) []string { return v.Items }).(pulumi.StringArrayOutput)\n}", "func (l *IntegrationResponseList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func GetItem(c *gin.Context) {\n\tvar item model.ItemJson\n\tid := c.Param(\"id\")\n\tif err := util.DB.Table(\"items\").Where(\"id = ?\", id).First(&item).Error; err != nil {\n\t\tc.JSON(http.StatusNotFound, util.FailResponse(http.StatusNotFound, \"Item not found\"))\n\t} else {\n\t\tc.JSON(http.StatusOK, util.SuccessResponse(http.StatusOK, \"Success\", item))\n\t}\n}", "func (c Client) Get(team string) ([]ActionItem, error) {\n\tresp, err := http.Get(c.url + \"/retros/\" + team)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode >= 400 {\n\t\treturn nil, fmt.Errorf(\"unexpected HTTP status: %d\", resp.StatusCode)\n\t}\n\n\treturn readResponse(resp.Body)\n}", "func (s Service) GetSecrets(items []Item, ses Session) (map[dbus.ObjectPath]Secret, error) {\n\t// spec: GetSecrets(IN Array<ObjectPath> items, IN ObjectPath session, OUT Dict<ObjectPath,Secret> secrets);\n\targ := make([]dbus.ObjectPath, len(items))\n\tfor i, o := range items {\n\t\targ[i] = o.Path()\n\t}\n\tcall := s.Call(_ServiceGetSecrets, 0, arg, ses.Path())\n\tif call.Err != nil {\n\t\treturn map[dbus.ObjectPath]Secret{}, call.Err\n\t}\n\tret := make(map[dbus.ObjectPath]Secret)\n\terr := call.Store(&ret)\n\treturn ret, err\n}", "func (v *Vault) LookupItems(pred ItemPredicate) ([]Item, error) {\n\tvar items []Item\n\n\terr := transact(v.db, func(tx *sql.Tx) (e error) {\n\t\trows, e := tx.Query(\n\t\t\t\"SELECT id, category_uuid, key_data, overview_data\" +\n\t\t\t\" FROM items\" +\n\t\t\t\" WHERE profile_id = ? AND trashed = 0\",\n\t\t\tv.profileId)\n\t\tif e != nil {\n\t\t\treturn\n\t\t}\n\t\tdefer rows.Close()\n\n\t\t// Figure out matches\n\t\tfor rows.Next() {\n\t\t\tvar itemId int\n\t\t\tvar catUuid string\n\t\t\tvar itemKeyBlob, opdata []byte\n\t\t\te = rows.Scan(&itemId, &catUuid, &itemKeyBlob, &opdata)\n\t\t\tif e != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Decrypt the overview\n\t\t\tvar overview []byte\n\t\t\toverview, e = crypto.DecryptOPData01(opdata, v.overviewKP)\n\t\t\tif e != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvar item Item\n\t\t\te = json.Unmarshal(overview, &item)\n\t\t\tif e != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\titem.Category = Category{catUuid, v.categories[catUuid]}\n\n\t\t\t// Decrypt the item key\n\t\t\tvar kp *crypto.KeyPair\n\t\t\tkp, e = crypto.DecryptItemKey(itemKeyBlob, v.masterKP)\n\t\t\tif e != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Decrypt the item details\n\t\t\tdetRow := tx.QueryRow(\n\t\t\t\t\"SELECT data FROM item_details\" +\n\t\t\t\t\" WHERE item_id = ?\", itemId)\n\t\t\tvar detailsCT []byte\n\t\t\te = detRow.Scan(&detailsCT)\n\t\t\tif e != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvar details []byte\n\t\t\tdetails, e = crypto.DecryptOPData01(detailsCT, kp)\n\t\t\tif e != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\titem.Details = details\n\n\t\t\tif pred(&item) {\n\t\t\t\titems = append(items, item)\n\t\t\t}\n\t\t}\n\n\t\treturn rows.Err()\n\t})\n\n\tif err != nil {\n\t\titems = nil\n\t}\n\n\treturn items, err\n}", "func (s *InventoryApiService) ListItems(w http.ResponseWriter) error {\n\tctx := context.Background()\n\tl, err := s.db.ListItems(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn EncodeJSONResponse(l, nil, w)\n}", "func GetItemsByOwner(params items.GetItemsByOwnerParams) model.Items {\n\tdb := dbpkg.Connect()\n\tdefer db.Close()\n\n\tvar items model.Items\n\n\tdb.Select(\"*\").Table(\"items\").Where(\"user_id=?\", params.ID).Scan(&items)\n\tfor _, item := range items {\n\t\titem.Descriptions = getItemsDescriptionByID(item.ID)\n\t}\n\n\treturn items\n\n}", "func (m *Drive) GetSpecial()([]DriveItemable) {\n return m.special\n}", "func (o TagsOutput) Items() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v Tags) []string { return v.Items }).(pulumi.StringArrayOutput)\n}", "func (rw *RankedWeapon) Items(skills []decode.CharSkill, cfg npcdefs.NPCCfg) []InvItem {\n\tw := defs.Weapons[rw.WeaponID]\n\tif !w.Reusable {\n\t\treturn rw.oneUseWeapons(rw.Rank, cfg)\n\t}\n\n\tvar items []InvItem\n\n\titems = append(items, InvItem{\n\t\tItemID: w.ItemID,\n\t\tCount: 1,\n\t})\n\n\tif w.ClipItemID != defs.ItemIDNone {\n\t\tcount := util.RandRange(cfg.WeaponClipsMin, cfg.WeaponClipsMax)\n\t\titems = append(items, InvItem{\n\t\t\tItemID: w.ClipItemID,\n\t\t\tCount: count,\n\t\t})\n\t}\n\n\treturn items\n}", "func (l *IntegrationList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func Get(reddit string) ([]Item, error) {\n\tc := new(redditClient)\n\turl := fmt.Sprintf(\"http://reddit.com/r/%s.json\", reddit)\n\tresp, err := c.get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, errors.New(resp.Status)\n\t}\n\tr := new(response)\n\tif err = json.NewDecoder(resp.Body).Decode(r); err != nil {\n\t\treturn nil, err\n\t}\n\titems := make([]Item, len(r.Data.Children))\n\tfor i, child := range r.Data.Children {\n\t\titems[i] = child.Data\n\t}\n\treturn items, nil\n}", "func (c StatusFilter) Items(arg, data string) (items []alfred.Item, err error) {\n\tdlog.Printf(\"status items with arg=%s, data=%s\", arg, data)\n\n\tif err = refresh(); err != nil {\n\t\titems = append(items, alfred.Item{\n\t\t\tTitle: \"Error syncing with toggl.com\",\n\t\t\tSubtitle: fmt.Sprintf(\"%v\", err),\n\t\t})\n\t\treturn\n\t}\n\n\tif entry, found := getRunningTimer(); found {\n\t\tstartTime := entry.StartTime().Local()\n\t\tseconds := round(time.Now().Sub(startTime).Seconds())\n\t\tduration := float64(seconds) / float64(60*60)\n\t\tdate := toHumanDateString(startTime)\n\t\ttime := startTime.Format(\"15:04:05\")\n\t\tsubtitle := fmt.Sprintf(\"%s, started %s at %s\",\n\t\t\tformatDuration(round(duration*100.0)), date, time)\n\n\t\tif project, _, ok := getProjectByID(entry.Pid); ok {\n\t\t\tsubtitle = \"[\" + project.Name + \"] \" + subtitle\n\t\t}\n\n\t\titem := alfred.Item{\n\t\t\tTitle: entry.Description,\n\t\t\tSubtitle: subtitle,\n\t\t\tArg: &alfred.ItemArg{\n\t\t\t\tKeyword: \"timers\",\n\t\t\t\tData: alfred.Stringify(timerCfg{Timer: &entry.ID}),\n\t\t\t},\n\t\t}\n\n\t\titem.AddMod(alfred.ModCmd, alfred.ItemMod{\n\t\t\tSubtitle: \"Stop this timer\",\n\t\t\tArg: &alfred.ItemArg{\n\t\t\t\tKeyword: \"timers\",\n\t\t\t\tMode: alfred.ModeDo,\n\t\t\t\tData: alfred.Stringify(timerCfg{ToToggle: &toggleCfg{entry.ID, config.DurationOnly}}),\n\t\t\t},\n\t\t})\n\n\t\titems = append(items, item)\n\t} else {\n\t\titems = append(items, alfred.Item{\n\t\t\tTitle: \"No timers currently running\",\n\t\t\tIcon: \"off.png\",\n\t\t})\n\t}\n\n\tspan, _ := getSpan(\"today\")\n\tvar report *summaryReport\n\treport, err = generateReport(span.Start, span.End, -1, \"\")\n\tfor _, date := range report.dates {\n\t\titems = append(items, alfred.Item{\n\t\t\tTitle: fmt.Sprintf(\"Total time for today: %s\", formatDuration(date.total)),\n\t\t})\n\t\tbreak\n\t}\n\n\treturn\n}", "func (c Caretaker) Items() []string {\n\tvar items []string\n\tfor k, _ := range c.o.data {\n\t\titems = append(items, k)\n\t}\n\n\treturn items\n}", "func GetItem(params items.GetItemParams) model.Item {\n\tdb := dbpkg.Connect()\n\tdefer db.Close()\n\tvar item model.Item\n\n\t//This Gets everything BUT descriptions\n\tdb.Select(\"*\").Where(\"id = ?\", params.ID).Find(&item)\n\n\t// Gets Descriptions\n\titem.Descriptions = getItemsDescriptionByID(params.ID)\n\n\treturn item\n\n}", "func (o IopingSpecVolumeVolumeSourceSecretPtrOutput) Items() IopingSpecVolumeVolumeSourceSecretItemsArrayOutput {\n\treturn o.ApplyT(func(v *IopingSpecVolumeVolumeSourceSecret) []IopingSpecVolumeVolumeSourceSecretItems {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Items\n\t}).(IopingSpecVolumeVolumeSourceSecretItemsArrayOutput)\n}", "func (l *DeploymentList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (us *ItemsUseCase) GetItems() ([]model.Item, *model.Error) {\n\treturn us.csvservice.GetItemsFromCSV()\n}", "func (api *apiConfig) GetItem(cName, cSlug, cID, iName, iID string) ([]byte, error) {\n\t// If an override was configured, use it instead.\n\tif api.getItem != nil {\n\t\treturn api.getItem(cName, cSlug, cID, iName, iID)\n\t}\n\n\tvar items [][]byte\n\tvar err error\n\n\t// Just quietly return nothing since a collection name & slug & ID were not provided.\n\tif cName == \"\" && cSlug == \"\" && cID == \"\" {\n\t\treturn nil, nil\n\t}\n\n\t// Just quietly return nothing since neither an item name nor an ID was provided.\n\tif iName == \"\" && iID == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tif cName != \"\" {\n\t\titems, err = api.GetAllItemsInCollectionByName(cName, 10)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to get all items in collection by collection name; error: %+v\", err)\n\t\t}\n\t} else if cSlug != \"\" {\n\t\titems, err = api.GetAllItemsInCollectionBySlug(cSlug, 10)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to get all items in collection by collection slug; error: %+v\", err)\n\t\t}\n\t} else {\n\t\titems, err = api.GetAllItemsInCollectionByID(cID, 10)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to get all items in collection by collection ID; error: %+v\", err)\n\t\t}\n\t}\n\n\tfor _, rawItem := range items {\n\t\titem := &CollectionItem{}\n\t\tif err2 := json.Unmarshal(rawItem, item); err2 != nil {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"GetItem() did not receive the proper collection item type: %+v\",\n\t\t\t\terr2,\n\t\t\t)\n\t\t}\n\n\t\tif iName != \"\" && item.Name != iName {\n\t\t\tcontinue\n\t\t}\n\n\t\tif iID != \"\" && item.ID != iID {\n\t\t\tcontinue\n\t\t}\n\n\t\treturn rawItem, nil\n\t}\n\n\treturn nil, nil\n}", "func (l *StageList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (c *CfgSvc) GetItems(lastExecution time.Time) (items []*configservice.ConfigurationItem, err error) {\n\tres, err := c.GetDiscoveredResources()\n\tif err != nil {\n\t\tlog.Fatalf(\"Error getting discovered resources: %v\\n\", err)\n\t\treturn nil, err\n\t}\n\n\tfor _, r := range res {\n\t\tvar results []*configservice.ConfigurationItem\n\n\t\tinput := &configservice.GetResourceConfigHistoryInput{\n\t\t\tResourceType: r.ResourceType,\n\t\t\tResourceId: r.ResourceId,\n\t\t\tEarlierTime: aws.Time(lastExecution.Add(time.Minute * time.Duration(-window))),\n\t\t\tLaterTime: aws.Time(lastExecution.Add(time.Minute * time.Duration(window))),\n\t\t}\n\t\terr := c.Client.GetResourceConfigHistoryPages(input,\n\t\t\tfunc(page *configservice.GetResourceConfigHistoryOutput, lastPage bool) bool {\n\t\t\t\tresults = append(results, page.ConfigurationItems...)\n\t\t\t\treturn !lastPage\n\t\t\t})\n\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"error getting resource config history (Input: %v):\\n%v\\n\", input, err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\titems = append(items, results...)\n\t}\n\n\tsortItemSlices(items)\n\n\treturn items, nil\n}", "func (l *AuthorizerList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (b *Bag) QueryItems() *BagItemQuery {\n\treturn (&BagClient{config: b.config}).QueryItems(b)\n}", "func (l *APIKeyList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (s *Server) getPopular(request *restful.Request, response *restful.Response) {\n\t// Authorize\n\tif !s.auth(request, response) {\n\t\treturn\n\t}\n\tbase.Logger().Debug(\"get popular items\")\n\ts.getList(cache.PopularItems, \"\", request, response)\n}", "func (s *Server) getPopular(request *restful.Request, response *restful.Response) {\n\t// Authorize\n\tif !s.auth(request, response) {\n\t\treturn\n\t}\n\tbase.Logger().Debug(\"get popular items\")\n\ts.getList(cache.PopularItems, \"\", request, response)\n}", "func ShardItems(items []*Item, threshold int64) []*ItemBundle {\n\tvar (\n\t\tbundles []*ItemBundle\n\t\tbundle *ItemBundle\n\t)\n\n\tfor len(items) > 0 {\n\t\tbundle, items = oneBundle(items, threshold)\n\t\tbundles = append(bundles, bundle)\n\t}\n\treturn bundles\n}", "func GetBurgers() Burgers {\n\treturn burgerList\n}", "func (l *RestAPIList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (o FioSpecVolumeVolumeSourceSecretOutput) Items() FioSpecVolumeVolumeSourceSecretItemsArrayOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceSecret) []FioSpecVolumeVolumeSourceSecretItems { return v.Items }).(FioSpecVolumeVolumeSourceSecretItemsArrayOutput)\n}", "func (l *UsagePlanKeyList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func getNewsItems() []string {\n\turl := baseURL + \"/newstories.json\"\n\tbody := fmtRes(url)\n\tstoryIds := strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(string(body)), \"[\"), \"]\")\n\tidSlice := strings.Split(storyIds, \",\")\n\treturn idSlice\n}", "func (res ItemsResource) List(w http.ResponseWriter, r *http.Request) {\n\trender.JSON(w, r, items)\n}", "func (r *Roster) Get() []RosterItem {\n\treturn <-r.get\n}", "func GetIngredients() (ingredients []Ingredient, err error) {\n\tvar httpClient = &http.Client{}\n\tr, err := httpClient.Get(\"http://ingredients:8080/ingredients\")\n\tif err != nil || r.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"%d StatusCode from ingredients\", r.StatusCode)\n\t}\n\tdefer r.Body.Close()\n\tjson.NewDecoder(r.Body).Decode(&ingredients)\n\treturn\n}", "func GetInventory(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n}", "func (o IopingSpecVolumeVolumeSourceDownwardAPIOutput) Items() IopingSpecVolumeVolumeSourceDownwardAPIItemsArrayOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceDownwardAPI) []IopingSpecVolumeVolumeSourceDownwardAPIItems {\n\t\treturn v.Items\n\t}).(IopingSpecVolumeVolumeSourceDownwardAPIItemsArrayOutput)\n}" ]
[ "0.7557881", "0.64705104", "0.6452308", "0.64334404", "0.64011496", "0.63178134", "0.6234697", "0.6177612", "0.6156206", "0.61173177", "0.6100953", "0.59985477", "0.5981244", "0.5923877", "0.59163713", "0.58571386", "0.583082", "0.5816483", "0.5781093", "0.5710015", "0.5638911", "0.5624284", "0.5524923", "0.5516475", "0.54620314", "0.5426602", "0.5407449", "0.5399733", "0.53856146", "0.5384633", "0.5378321", "0.53573054", "0.5328851", "0.5328212", "0.5289667", "0.5282124", "0.52765447", "0.52580404", "0.5249817", "0.52410686", "0.52406347", "0.5216338", "0.5215414", "0.5211318", "0.52084446", "0.5208104", "0.52020794", "0.5202066", "0.5190375", "0.5176805", "0.5175918", "0.5175567", "0.51533794", "0.514307", "0.5124102", "0.5104243", "0.5101512", "0.50964785", "0.50860816", "0.5081031", "0.50319564", "0.5025193", "0.50250435", "0.50246286", "0.5023072", "0.5013647", "0.5011263", "0.50015676", "0.4971189", "0.49688882", "0.49385157", "0.49323222", "0.49282497", "0.49280953", "0.49248666", "0.4924095", "0.49129733", "0.49086583", "0.4901174", "0.48999998", "0.48952493", "0.48832214", "0.48765734", "0.48661318", "0.48654014", "0.48580498", "0.48401064", "0.4836185", "0.4836185", "0.48176885", "0.48131672", "0.48111862", "0.48034322", "0.48008835", "0.47964674", "0.47959894", "0.4786007", "0.4782449", "0.47612172", "0.47585902" ]
0.73712164
1
GetItemsForHunt returns all the items for the hunt with the given id
func GetItemsForHunt(huntID int) ([]*models.Item, *response.Error) { itemDBs, e := db.GetItemsWithHuntID(huntID) if itemDBs == nil { return nil, e } items := make([]*models.Item, 0, len(itemDBs)) for _, v := range itemDBs { item := models.Item{ItemDB: *v} items = append(items, &item) } return items, e }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetItems(huntID int) ([]*models.Item, *response.Error) {\n\titemDBs, e := db.GetItemsWithHuntID(huntID)\n\tif itemDBs == nil {\n\t\treturn nil, e\n\t}\n\n\titems := make([]*models.Item, 0, len(itemDBs))\n\tfor _, itemDB := range itemDBs {\n\t\titem := models.Item{ItemDB: *itemDB}\n\t\titems = append(items, &item)\n\t}\n\n\treturn items, e\n}", "func (c *Client) GetItems(id int) (Item, error) {\n\tc.defaultify()\n\tvar item Item\n\tresp, err := http.Get(fmt.Sprintf(\"%s/item/%d.json\", c.apiBase, id))\n\tif err != nil {\n\t\treturn item, err\n\t}\n\tdefer resp.Body.Close()\n\tdec := json.NewDecoder(resp.Body)\n\terr = dec.Decode(&item)\n\tif err != nil {\n\t\treturn item, err\n\t}\n\treturn item, nil\n}", "func (api *API) ItemsGetByApplicationID(id string) (res Items, err error) {\n\treturn api.ItemsGet(Params{\"applicationids\": id})\n}", "func (b *OGame) GetItems(celestialID ogame.CelestialID) ([]ogame.Item, error) {\n\treturn b.WithPriority(taskRunner.Normal).GetItems(celestialID)\n}", "func getItems(ctx context.Context, request events.APIGatewayProxyRequest,\n\tih *item.Handler) (events.APIGatewayProxyResponse, error) {\n\n\tvar list *item.List\n\n\tlist, err := ih.List(ctx, request.PathParameters[PathParamCategoryID])\n\tif err != nil {\n\t\treturn web.GetResponse(ctx, err.Error(), http.StatusInternalServerError)\n\t}\n\n\treturn web.GetResponse(ctx, list, http.StatusOK)\n}", "func getItems(w http.ResponseWriter, r *http.Request) {\n\titems, err := supermart.GetItems(r.Context(), r)\n\tif err != nil {\n\t\tutils.WriteErrorResponse(http.StatusInternalServerError, err, w)\n\t\treturn\n\t}\n\tutils.WriteResponse(http.StatusOK, items, w)\n}", "func GetItemsHandler(db *sqlx.DB) gin.HandlerFunc {\n\treturn func (ctx *gin.Context) {\n\t\tcreatedBy, createdByExists := GetUserID(ctx)\n\t\tif !createdByExists {\n\t\t\tctx.String(http.StatusUnauthorized, \"User id not found in authorization token.\")\n\t\t\treturn\n\t\t}\n\n\t\tvar searchQuery ItemsGetQuery\n\t\tif err := ctx.ShouldBindQuery(&searchQuery); err != nil {\n\t\t\tctx.String(http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tquery := sq.Select(\"items.public_id, name, price, unit, created_at, updated_at\").From(\"items\")\n\n\t\tif createdBy != \"\" {\n\t\t\tquery = query.Join(\"users ON users.id = items.created_by\").Where(sq.Eq{\"users.public_id\": createdBy})\n\t\t}\n\n\t\tif searchQuery.Name != \"\" {\n\t\t\tquery = query.Where(\"items.name LIKE ?\", fmt.Sprint(\"%\", searchQuery.Name, \"%\"))\n\t\t}\n\n\t\tqueryString, queryStringArgs, err := query.ToSql()\n\t\tif err != nil {\n\t\t\tctx.String(http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\titems := []Item{}\n\t\tif err := db.Select(&items, queryString, queryStringArgs...); err != nil {\n\t\t\tlog.Fatalln(err.Error())\n\t\t}\n\n\t\tctx.JSON(http.StatusOK, items)\n\t}\n}", "func GetItems(c *gin.Context) {\n\tvar items []model.ItemJson\n\terr := util.DB.Table(\"items\").Find(&items).Error\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t} else {\n\t\tc.JSON(http.StatusOK, util.SuccessResponse(http.StatusOK, \"Success\", items))\n\t}\n}", "func GetItemsByMerchant(w http.ResponseWriter, r *http.Request) {\r\n\r\n\t// get the bearer token\r\n\tbearerHeader := r.Header.Get(\"Authorization\")\r\n\r\n\t// validate token, it will return a User{UserID, Name}\r\n\tuser, err := ValidateToken(bearerHeader)\r\n\r\n\tcheckErr(err)\r\n\r\n\t// create the db connection\r\n\tdb := getDBConn()\r\n\r\n\t// close db connection\r\n\tdefer db.Close()\r\n\r\n\t// prepare query\r\n\tstmtOut, err := db.Prepare(\"SELECT * FROM items WHERE merchantID = ?\")\r\n\r\n\t// close stmtOut request\r\n\tdefer stmtOut.Close()\r\n\r\n\tcheckErr(err)\r\n\r\n\t// filter orders by merchantID\r\n\trows, err := stmtOut.Query(user.UserID)\r\n\r\n\tcheckErr(err)\r\n\r\n\t// create an array of item type to store all the items\r\n\tvar items []item\r\n\r\n\t// iterate over rows to format item in item type\r\n\tfor rows.Next() {\r\n\r\n\t\tvar item item\r\n\r\n\t\terr = rows.Scan(&item.ItemID, &item.MerchantID, &item.Name)\r\n\r\n\t\titems = append(items, item)\r\n\t}\r\n\r\n\t// return the item array in json format\r\n\tjson.NewEncoder(w).Encode(items)\r\n\r\n}", "func (m *SiteItemRequestBuilder) ItemsById(id string)(*ItemItemsBaseItemItemRequestBuilder) {\n urlTplParams := make(map[string]string)\n for idx, item := range m.pathParameters {\n urlTplParams[idx] = item\n }\n if id != \"\" {\n urlTplParams[\"baseItem%2Did\"] = id\n }\n return NewItemItemsBaseItemItemRequestBuilderInternal(urlTplParams, m.requestAdapter)\n}", "func GetItemInfoByIDs(w http.ResponseWriter, r *http.Request) {\n\thelpers.EnableCors(w)\n\tparams := mux.Vars(r)\n\tk := strings.Replace(params[\"ids\"], \" \", \"\", -1)\n\ts := strings.Split(k, \",\")\n\n\tvar itemInfos []models.ItemInfo\n\tdb, err := helpers.CreateDatabase()\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t}\n\n\tfor _, element := range s {\n\t\titemID, err := strconv.Atoi(element)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t}\n\t\terr = helpers.CheckID(&itemID)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t}\n\n\t\titemInfo := GetByID(itemID, db)\n\t\titemInfos = append(itemInfos, itemInfo[0])\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(itemInfos)\n}", "func (_CraftingI *CraftingICallerSession) Items(arg0 *big.Int) (struct {\n\tBaseType uint8\n\tItemType uint8\n\tCrafted uint32\n\tCrafter *big.Int\n}, error) {\n\treturn _CraftingI.Contract.Items(&_CraftingI.CallOpts, arg0)\n}", "func (_CraftingI *CraftingISession) Items(arg0 *big.Int) (struct {\n\tBaseType uint8\n\tItemType uint8\n\tCrafted uint32\n\tCrafter *big.Int\n}, error) {\n\treturn _CraftingI.Contract.Items(&_CraftingI.CallOpts, arg0)\n}", "func GetItems(c *gin.Context) {\n\tvar items []models.Item\n\tif err := models.DB.Order(\"name\").Find(&items).Error; err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": \"Could not find items\"})\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"items\": items})\n}", "func GetAllItemsInBasket(w http.ResponseWriter, r *http.Request) {\r\n\trouteParams := mux.Vars(r)\r\n\tbasketID, err := strconv.Atoi(routeParams[\"basketId\"])\r\n\r\n\tif err != nil {\r\n\t\trespondWithError(w, http.StatusBadRequest, \"Invalid basket ID\")\r\n\t}\r\n\r\n\tbasketItems, err := models.GetItemsInBasket(basketID)\r\n\r\n\tif err != nil {\r\n\t\trespondWithError(w, http.StatusNotFound, \"Items not found for this basket\")\r\n\t\treturn\r\n\t}\r\n\r\n\trespondWithJSON(w, http.StatusOK, basketItems)\r\n}", "func (m *Drive) GetItems()([]DriveItemable) {\n return m.items\n}", "func (c *Client) GetItems(ctx context.Context, owner string) (Items, error) {\n\tresponse, err := c.sendRequest(ctx, owner, http.MethodGet, fmt.Sprintf(\"%s/%s\", c.storeBaseURL, c.bucket), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif response.Code != http.StatusOK {\n\t\tlevel.Error(c.getLogger(ctx)).Log(xlog.MessageKey(), \"Argus responded with non-200 response for GetItems request\",\n\t\t\t\"code\", response.Code, \"ErrorHeader\", response.ArgusErrorHeader)\n\t\treturn nil, fmt.Errorf(errStatusCodeFmt, response.Code, translateNonSuccessStatusCode(response.Code))\n\t}\n\n\tvar items Items\n\n\terr = json.Unmarshal(response.Body, &items)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"GetItems: %w: %s\", errJSONUnmarshal, err.Error())\n\t}\n\n\treturn items, nil\n}", "func GetItems(da DataAccess, username string) (*ItemList, error) {\n\t// find the user and verify they exist\n\tuser, err := FindUserByName(da, username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// try to get their items\n\titems, err := da.GetItemsByUser(context.Background(), user.Id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// calculate net worth, asset total, liability total\n\tvar net, asset, liability int64\n\tfor i := range *items {\n\t\tif (*items)[i].Type == ItemTypeAsset {\n\t\t\tnet += (*items)[i].Value\n\t\t\tasset += (*items)[i].Value\n\t\t} else if (*items)[i].Type == ItemTypeLiability {\n\t\t\tnet -= (*items)[i].Value\n\t\t\tliability += (*items)[i].Value\n\t\t}\n\t}\n\n\treturn &ItemList{Username: username, Items: items, NetWorth: net, AssetTotal: asset, LiabilityTotal: liability}, nil\n}", "func (api *API) ItemsGet(params Params) (res Items, err error) {\n\tif _, present := params[\"output\"]; !present {\n\t\tparams[\"output\"] = \"extend\"\n\t}\n\tresponse, err := api.CallWithError(\"item.get\", params)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treflector.MapsToStructs2(response.Result.([]interface{}), &res, reflector.Strconv, \"json\")\n\treturn\n}", "func GetAllItems(w http.ResponseWriter, r *http.Request) {\r\n\r\n\t// get the bearer token\r\n\tbearerHeader := r.Header.Get(\"Authorization\")\r\n\r\n\t// validate token, it will return a User{UserID, Name}\r\n\t_, err := ValidateToken(bearerHeader)\r\n\r\n\tcheckErr(err)\r\n\r\n\t// create the db connection\r\n\tdb := getDBConn()\r\n\r\n\t// close the db connection\r\n\tdefer db.Close()\r\n\r\n\t// query\r\n\trows, err := db.Query(\"SELECT * FROM items\")\r\n\r\n\tcheckErr(err)\r\n\r\n\t// create an array of item type to store all the items\r\n\tvar items []item\r\n\r\n\t// iterate over rows to format item in item type\r\n\tfor rows.Next() {\r\n\t\tvar params item\r\n\r\n\t\terr = rows.Scan(&params.ItemID, &params.MerchantID, &params.Name)\r\n\r\n\t\titems = append(items, params)\r\n\t}\r\n\r\n\t// return the order array in json format\r\n\tjson.NewEncoder(w).Encode(items)\r\n}", "func (c HourlyCommand) Items(arg, data string) (items []alfred.Item, err error) {\n\tdlog.Printf(\"Running HourlyCommand\")\n\n\tvar cfg hourlyConfig\n\tif data != \"\" {\n\t\tif err := json.Unmarshal([]byte(data), &cfg); err != nil {\n\t\t\tdlog.Printf(\"Invalid hourly config\")\n\t\t}\n\t}\n\n\tvar weather Weather\n\tvar loc Location\n\tif loc, weather, err = getWeather(arg); err != nil {\n\t\treturn\n\t}\n\n\tvar startTime time.Time\n\tif cfg.Start != nil {\n\t\tstartTime = *cfg.Start\n\t} else if len(weather.Hourly) > 0 {\n\t\tstartTime = weather.Hourly[0].Time\n\t}\n\n\theading := alfred.Item{\n\t\tTitle: \"Weather for \" + loc.Name,\n\t\tSubtitle: alfred.Line,\n\t\tArg: &alfred.ItemArg{\n\t\t\tKeyword: \"daily\",\n\t\t},\n\t}\n\n\tif weather.URL != \"\" {\n\t\theading.AddMod(alfred.ModCmd, alfred.ItemMod{\n\t\t\tSubtitle: \"Open this forecast in a browser\",\n\t\t\tArg: &alfred.ItemArg{\n\t\t\t\tKeyword: \"daily\",\n\t\t\t\tMode: alfred.ModeDo,\n\t\t\t\tData: alfred.Stringify(&dailyCfg{ToOpen: weather.URL}),\n\t\t\t},\n\t\t})\n\t}\n\n\titems = append(items, heading)\n\n\tdeg := \"F\"\n\tif config.Units == unitsMetric {\n\t\tdeg = \"C\"\n\t}\n\n\taddAlertItems(&weather, &items)\n\n\tfor _, entry := range weather.Hourly {\n\t\tif entry.Time.Before(startTime) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconditions := entry.Summary\n\t\ticon := entry.Icon\n\n\t\titem := alfred.Item{\n\t\t\tTitle: entry.Time.Format(\"Mon \"+config.TimeFormat) + \": \" + conditions,\n\t\t\tSubtitle: fmt.Sprintf(\"%d°%s (%d°%s) ☂ %d%%\", entry.Temp.Int64(), deg, entry.ApparentTemp.Int64(), deg, entry.Precip),\n\t\t\tIcon: getIconFile(icon),\n\t\t}\n\n\t\titems = append(items, item)\n\t}\n\n\treturn\n}", "func (db Database) GetItems() (*models.ItemList, error) {\n\tlist := &models.ItemList{}\n\n\trows, err := db.Conn.Query(\"SELECT * FROM items ORDER BY created_at desc;\")\n\tif err != nil {\n\t\treturn list, err\n\t}\n\n\tfor rows.Next() {\n\t\tvar item models.Item\n\n\t\tif err = rows.Scan(\n\t\t\t&item.ID,\n\t\t\t&item.Name,\n\t\t\t&item.Description,\n\t\t\t&item.Creation,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tlist.Items = append(list.Items, item)\n\t}\n\n\treturn list, nil\n}", "func (v *Vault) findPendingItems(id string) ([]*Item, error) {\n\tpath := dstore.Path(\"push\")\n\tentries, err := v.store.List(&ListOptions{Prefix: path})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\titems := []*Item{}\n\tfor _, entry := range entries {\n\t\tpc := dstore.PathComponents(entry.Path)\n\t\tif pc[2] != \"item\" || pc[3] != id {\n\t\t\tcontinue\n\t\t}\n\t\titem, err := decryptItem(entry.Data, v.mk, id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif item.ID == id {\n\t\t\titems = append(items, item)\n\t\t}\n\t}\n\treturn items, nil\n}", "func getStories(ids []int, numstories int) []item {\n\tvar client hn.Client\n\tvar stories []item\n\tfor i, id := range ids { // Look up the cache first\n\t\tif it, found := cach.find(id); found {\n\t\t\tstories = append(stories, it)\n\t\t\tif len(stories) >= numstories {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\thnItem, err := client.GetItem(id) // not found in cache, send a request\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\titem := parseHNItem(hnItem, i)\n\t\tif isStoryLink(item) {\n\t\t\tstories = append(stories, item)\n\t\t\tif len(stories) >= numstories {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn stories\n}", "func (c *APIClient) ListHunts(ctx context.Context, fn func(h *hunt.Hunt) error) (int64, error) {\n\treturn hunt.ListHunts(ctx, c.conn, fn)\n}", "func GetBoughtItem(c *gin.Context) {\n\tuserID, ok := c.MustGet(\"user_id\").(int64)\n\tif !ok {\n\t\tlog.Printf(\"invalid userid in token, userid: %v\", c.MustGet(\"user_id\"))\n\t\tc.JSON(http.StatusForbidden, &model.ErrResp{Error: \"Invalid token\"})\n\t\treturn\n\t}\n\n\tuserRole, ok := c.MustGet(\"role\").(string)\n\tif !ok {\n\t\tlog.Printf(\"invalid userole in token, userid: %v\", c.MustGet(\"role\"))\n\t\tc.JSON(http.StatusForbidden, &model.ErrResp{Error: \"Invalid token\"})\n\t\treturn\n\t}\n\n\tparamUserID, err := strconv.ParseInt(c.Param(\"user_id\"), 10, 64)\n\tif err != nil {\n\t\tlog.Printf(\"path parm user_id err: %v\", err)\n\t\tc.JSON(http.StatusBadRequest, &model.ErrResp{Error: \"Invalid path param\", Fields: &[]string{\"user_id\"}})\n\t\treturn\n\t}\n\n\tif userID != paramUserID && userRole != constAdminRole {\n\t\tc.JSON(http.StatusMethodNotAllowed, &model.ErrResp{Error: \"Not allowed please check token\"})\n\t\treturn\n\t}\n\n\tboughtItemList, err := (&model.BoughtItem{}).Get(\"user_id=$1\", paramUserID)\n\tif err != nil {\n\t\tlog.Printf(\"db fetching bought item error: %v\", err)\n\t\tc.JSON(http.StatusInternalServerError, &model.ErrResp{Error: \"Server error\"})\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, boughtItemList)\n}", "func (c *APIClient) Hunt(id string) *hunt.Hunt {\n\treturn hunt.NewHunt(id, c.conn, nil)\n}", "func GetSelfItems() ([]Item, error) {\n\treq, _ := http.NewRequest(\"GET\", \"https://qiita.com/api/v2/authenticated_user/items\", nil)\n\tresbyte, err := DoRequest(req)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to DoRequest\")\n\t}\n\n\tvar items []Item\n\tif err := json.Unmarshal(resbyte, &items); err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to unmarshal\")\n\t}\n\treturn items, nil\n}", "func (_CraftingI *CraftingICaller) Items(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tBaseType uint8\n\tItemType uint8\n\tCrafted uint32\n\tCrafter *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _CraftingI.contract.Call(opts, &out, \"items\", arg0)\n\n\toutstruct := new(struct {\n\t\tBaseType uint8\n\t\tItemType uint8\n\t\tCrafted uint32\n\t\tCrafter *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.BaseType = *abi.ConvertType(out[0], new(uint8)).(*uint8)\n\toutstruct.ItemType = *abi.ConvertType(out[1], new(uint8)).(*uint8)\n\toutstruct.Crafted = *abi.ConvertType(out[2], new(uint32)).(*uint32)\n\toutstruct.Crafter = *abi.ConvertType(out[3], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func GetEntliehen(id int) (borroweds []Borrowed, err error) {\n\t//Abfragen für Array Entliehen\n\trows, err := Db.Query(\"select equipment.ID, equipment.name, equipment.description, equipment.Image, borrow.returnUntil, borrow.borrowedOn from equipment, borrow where borrow.clientID=$1 and borrow.equipmentID=equipment.ID\", id)\n\tif err != nil {\tfmt.Println(err)}\n\n\tfor rows.Next() {\n\t\tequipment := Equipment{}\n\t\tborrow := Borrow{}\n\t\terr = rows.Scan(&equipment.ID, &equipment.Name, &equipment.Description, &equipment.Image, &borrow.ReturnUntil, &borrow.BorrowedOn)\n\n\t\tif err != nil {\n\t\t\tlog.Println(\"Fehler Nr. 2 in model.GetAllEquipment\")\n\t\t\treturn\n\t\t}\n\n\t\tborrowed := Borrowed{Name:equipment.Name, ID:equipment.ID, Description:equipment.Description, Image:equipment.Image, BorrowedOn:borrow.BorrowedOn, ReturnUntil:borrow.ReturnUntil}\n\t\tfmt.Print(\"borrowed: \")\n\t\tfmt.Print(borrowed)\n\t\tborroweds = append(borroweds, borrowed)\n\t}\n\trows.Close()\n\treturn\n}", "func (c Client) GetUserShelves(id string) (shelves Shelf_shelves, err error) {\n\tvar response Shelf_GoodreadsResponse\n\n\turl := apiRoot + fmt.Sprintf(\"shelf/list.xml?key=%s&user_id=%s\", c.consumerKey, id)\n\n\t// Build the request\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tlog.Println(\"NewRequest: \", err)\n\t\treturn\n\t}\n\n\tclient, err := c.GetHttpClient()\n\tif err != nil {\n\t\tlog.Println(\"Do: \", err)\n\t\treturn\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Println(\"Do: \", err)\n\t\treturn\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\terr = errors.New(resp.Status)\n\t\treturn\n\t}\n\n\tif err = xml.NewDecoder(resp.Body).Decode(&response); err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\treturn response.Shelf_shelves, nil\n}", "func (c *Controller) GetItems() http.Handler {\n\treturn http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) {\n\t\tu := utility.New(writer, req)\n\t\tsession := c.store.DB.Copy()\n\t\tdefer session.Close()\n\n\t\tvar items []Item\n\t\tcollection := session.DB(c.databaseName).C(ItemsCollection)\n\t\terr := collection.\n\t\t\tFind(nil).\n\t\t\tSelect(bson.M{\"_id\": 1, \"color\": 1, \"code\": 1, \"description\": 1, \"category\": 1}).\n\t\t\tSort(\"description\").\n\t\t\tAll(&items)\n\t\tif err != nil {\n\t\t\tc.logger.Error(err)\n\t\t\tu.WriteJSONError(\"verification failed\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tu.WriteJSON(items)\n\t})\n}", "func GetItems(ctx *fasthttp.RequestCtx) {\n\tenc := json.NewEncoder(ctx)\n\titems := ReadItems()\n\tenc.Encode(&items)\n\tctx.SetStatusCode(fasthttp.StatusOK)\n}", "func GetItem(w http.ResponseWriter, r *http.Request) {\r\n\r\n\t// get the bearer token\r\n\tbearerHeader := r.Header.Get(\"Authorization\")\r\n\r\n\t// validate token, it will return a User{UserID, Name}\r\n\t_, err := ValidateToken(bearerHeader)\r\n\r\n\tcheckErr(err)\r\n\r\n\t// get all the params from the request\r\n\tvars := mux.Vars(r)\r\n\r\n\t// create the db connection\r\n\tdb := getDBConn()\r\n\r\n\t// close db connection\r\n\tdefer db.Close()\r\n\r\n\t// prepare query\r\n\tstmtOut, err := db.Prepare(\"SELECT * FROM items WHERE itemID=?\")\r\n\r\n\t// close stmtOut request\r\n\tdefer stmtOut.Close()\r\n\r\n\tcheckErr(err)\r\n\r\n\tvar item item\r\n\r\n\terr = stmtOut.QueryRow(vars[\"itemID\"]).Scan(&item.ItemID, &item.MerchantID, &item.Name)\r\n\r\n\tcheckErr(err)\r\n\r\n\t// return the order in json format\r\n\tjson.NewEncoder(w).Encode(item)\r\n}", "func (c *Client) GetFiltered(qp map[string]string) ([]Task, error) {\n\tresp, err := c.DoGetRequest(\"tasks\", qp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttasks := Tasks{}\n\terr = json.NewDecoder(resp.Body).Decode(&tasks)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn tasks.Items, nil\n}", "func (self *SearchJob) GetItems() (items []Item) {\n\tself.Mutex.Lock()\n\titems = self.Items\n\t//update last access time\n\tself.LastRead = time.Now()\n\t//write to the writer\n\tself.Items = make([]Item, 0)\n\tself.Mutex.Unlock()\n\tlog.Println(\"items:\",len(items))\n\treturn items\n}", "func (s *InventoryApiService) GetItem(id string, w http.ResponseWriter) error {\n\tctx := context.Background()\n\tr, err := s.db.GetItem(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn EncodeJSONResponse(r, nil, w)\n}", "func (v *Vault) ItemHistory(id string) ([]*Item, error) {\n\tpath := dstore.Path(\"pull\")\n\tds, err := v.store.List(&ListOptions{Prefix: path, NoData: true})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpaths := []string{}\n\tfor _, doc := range ds {\n\t\tif strings.HasPrefix(dstore.PathFrom(doc.Path, 2), dstore.Path(\"item\", id)) {\n\t\t\tpaths = append(paths, doc.Path)\n\t\t}\n\t}\n\n\titems := make([]*Item, 0, len(paths))\n\tfor _, p := range paths {\n\t\tb, err := v.store.Get(p)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif b == nil {\n\t\t\tcontinue\n\t\t}\n\t\tvar event events.Event\n\t\tif err := msgpack.Unmarshal(b, &event); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tid := dstore.PathLast(p)\n\t\titem, err := decryptItem(event.Data, v.mk, id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, item)\n\t}\n\n\tpending, err := v.findPendingItems(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\titems = append(items, pending...)\n\n\treturn items, nil\n}", "func getIds() []string {\n\tclient := &http.Client{}\n\tvar ids []string\n\tsongRequest, err := http.NewRequest(\"GET\", \"https://api.spotify.com/v1/me/tracks?limit=50&offset=0\", nil)\n\tsongRequest.Header.Add(\"Authorization\", key)\n\tresponse, err := client.Do(songRequest)\n\tif err != nil {\n\t\tfmt.Println(\"Request failed with error:\", err)\n\t} else {\n\t\tdata, _ := ioutil.ReadAll(response.Body)\n\t\titems := gjson.Get(string(data), \"items\")\n\t\tfor i := 0; i < len(items.Array()); i++ {\n\t\t\ttrack := gjson.Get(items.Array()[i].String(), \"track\")\n\t\t\tid := gjson.Get(track.String(), \"id\")\n\t\t\tids = append(ids, id.String())\n\t\t}\n\t}\n\tids = append(ids, getPlaylistIds()...) // Calls to get song IDs from user playlists\n\treturn fixIds(ids)\n}", "func (is *ItemServices) Items(ctx context.Context, limit, offset int) ([]entity.Item, []error) {\n\titms, errs := is.itemRepo.Items(ctx, limit, offset)\n\tif len(errs) > 0 {\n\t\treturn nil, errs\n\t}\n\treturn itms, errs\n}", "func (o IopingSpecVolumeVolumeSourceSecretOutput) Items() IopingSpecVolumeVolumeSourceSecretItemsArrayOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceSecret) []IopingSpecVolumeVolumeSourceSecretItems { return v.Items }).(IopingSpecVolumeVolumeSourceSecretItemsArrayOutput)\n}", "func GetItemNames(c *gin.Context) {\n\ttype ItemName struct {\n\t\tName string\n\t\tID uint\n\t}\n\n\tvar items []ItemName\n\tif err := models.DB.Model(&models.Item{}).Order(\"name\").Find(&items).Error; err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"Couldn't retrieve items\"})\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"items\": items})\n}", "func (i *Inventory) Items() []*ItemStack {\n\treturn i.items\n}", "func GetItems(root string, dir string, ignore IgnoreHandler) ([]Item, error) {\r\n\tfiles, err := ioutil.ReadDir(dir)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\titems := []Item{}\r\n\tfor _, file := range files {\r\n\t\tname := file.Name()\r\n\t\tpath := filepath.Join(dir, name)\r\n\t\tevt, err := newEvent(root, path, fsnotify.Write)\r\n\t\tif err != nil {\r\n\t\t\treturn nil, err\r\n\t\t}\r\n\t\tif ignore(evt) == false {\r\n\t\t\tif evt.Dir {\r\n\t\t\t\tchildren, err := GetItems(root, path, ignore)\r\n\t\t\t\tif err != nil {\r\n\t\t\t\t\treturn nil, err\r\n\t\t\t\t}\r\n\t\t\t\titems = append(items, children...)\r\n\t\t\t} else {\r\n\t\t\t\tchecksum, err := GetChecksum(path)\r\n\t\t\t\tif err != nil {\r\n\t\t\t\t\treturn nil, err\r\n\t\t\t\t}\r\n\t\t\t\titems = append(items, Item{\r\n\t\t\t\t\tRelPath: evt.RelPath,\r\n\t\t\t\t\tChecksum: checksum,\r\n\t\t\t\t\tModTime: file.ModTime().UnixNano(),\r\n\t\t\t\t})\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn items, err\r\n}", "func GetItems() (items []Item, err error) {\n\tdir, err := os.Open(rootPath)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfi, err := dir.Stat()\n\tif !fi.Mode().IsDir() {\n\t\tpanic(\"need directory\")\n\t}\n\n\tnames, err := dir.Readdirnames(0)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, name := range names {\n\t\titem, err := NewItem(name)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\titems = append(items, item)\n\t}\n\n\tsort.Sort(sort.Reverse(byCreatedAt(items)))\n\n\treturn items, nil\n}", "func (o IopingSpecVolumeVolumeSourceSecretPtrOutput) Items() IopingSpecVolumeVolumeSourceSecretItemsArrayOutput {\n\treturn o.ApplyT(func(v *IopingSpecVolumeVolumeSourceSecret) []IopingSpecVolumeVolumeSourceSecretItems {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Items\n\t}).(IopingSpecVolumeVolumeSourceSecretItemsArrayOutput)\n}", "func GetAllItems(c *gin.Context) {\n\tdb := PostSQLConfig()\n\ts := c.Request.URL.Query().Get(\"user\")\n\trows, err := db.Query(\"select * from menu where userinfo = '\" + s + \"';\")\n\tif err != nil {\n\t\tfmt.Println(\"ERROR IS1\", err)\n\t\tcreateUserTable()\n\t}\n\tdefer rows.Close()\n\trepos := model_menu.MenuItems{}\n\tvar childUnit []uint8\n\tfor rows.Next() {\n\t\tp := model_menu.Menu{}\n\t\terr = rows.Scan(&p.ID, &p.Name, &p.Url, &p.Sysname, &p.UserInfo, &childUnit)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\ts := string(childUnit)\n\n\t\terr := json.Unmarshal([]byte(s), &p.Child)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"error:\", err)\n\t\t}\n\n\t\trepos = append(repos, p)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tc.JSON(200, gin.H{\n\t\t\"menu\": &repos,\n\t})\n\tdefer db.Close()\n}", "func (i Inventory) GetItemById(id int) (Item, *ErrHandler) {\n var item Item\n err := i.Db.GetItemById(id,&item)\n return item, err\n}", "func (c *Client) GetTopItemsID() ([]int, error) {\n\tc.defaultify()\n\tresp, err := http.Get(fmt.Sprintf(\"%s/topstories.json\", c.apiBase))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tvar IDs []int\n\tdec := json.NewDecoder(resp.Body)\n\terr = dec.Decode(&IDs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn IDs, nil\n}", "func (ris *rssItems) getItems() []RssItem {\n\tris.RLock()\n\tdefer ris.RUnlock()\n\treturn ris.items\n}", "func (api *apiConfig) GetAllItemsInCollectionByID(id string, maxPages int) ([][]byte, error) {\n\t// If an override was configured, use it instead.\n\tif api.getAllItemsInCollectionByID != nil {\n\t\treturn api.getAllItemsInCollectionByID(id, maxPages)\n\t}\n\n\toffset := 0\n\titems := [][]byte{}\n\n\tfor {\n\t\tqueryParams := map[string]string{\n\t\t\t\"offset\": strconv.Itoa(offset),\n\t\t\t\"limit\": \"100\",\n\t\t}\n\n\t\tcollectionItems := &CollectionItems{}\n\t\terr := api.MethodGet(fmt.Sprintf(listCollectionItemsURL, id), queryParams, collectionItems)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Iteratae over all the collection's items.\n\t\tjsonItems := gjson.Parse(string(collectionItems.Items))\n\t\tjsonItems.ForEach(func(key, value gjson.Result) bool {\n\t\t\t// Add each json item to the slice.\n\t\t\titems = append(items, []byte(value.Raw))\n\t\t\t// Keep iterating.\n\t\t\treturn true\n\t\t})\n\n\t\toffset = collectionItems.Offset + collectionItems.Count\n\n\t\t// Webflow API should report when the last set of items has been requested. Once this has happened, this loop should\n\t\t// be broken.\n\t\tif offset >= collectionItems.Total {\n\t\t\tbreak\n\t\t}\n\n\t\t// Safety feature to keep the code from infinite looping or asking the API for far too many items.\n\t\tif maxPages--; maxPages < 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn items, nil\n}", "func (s *InventoryApiService) ListItems(w http.ResponseWriter) error {\n\tctx := context.Background()\n\tl, err := s.db.ListItems(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn EncodeJSONResponse(l, nil, w)\n}", "func GetItem(c *gin.Context) {\n\tvar item model.ItemJson\n\tid := c.Param(\"id\")\n\tif err := util.DB.Table(\"items\").Where(\"id = ?\", id).First(&item).Error; err != nil {\n\t\tc.JSON(http.StatusNotFound, util.FailResponse(http.StatusNotFound, \"Item not found\"))\n\t} else {\n\t\tc.JSON(http.StatusOK, util.SuccessResponse(http.StatusOK, \"Success\", item))\n\t}\n}", "func GetItemsByOwner(params items.GetItemsByOwnerParams) model.Items {\n\tdb := dbpkg.Connect()\n\tdefer db.Close()\n\n\tvar items model.Items\n\n\tdb.Select(\"*\").Table(\"items\").Where(\"user_id=?\", params.ID).Scan(&items)\n\tfor _, item := range items {\n\t\titem.Descriptions = getItemsDescriptionByID(item.ID)\n\t}\n\n\treturn items\n\n}", "func (c *Container) Items(prefix string, cursor string, count int) ([]stow.Item, string, error) {\n\tquery := &storage.Query{Prefix: prefix}\n\tcall := c.Bucket().Objects(c.ctx, query)\n\n\tp := iterator.NewPager(call, count, cursor)\n\tvar results []*storage.ObjectAttrs\n\tnextPageToken, err := p.NextPage(&results)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tvar items []stow.Item\n\tfor _, item := range results {\n\t\ti, err := c.convertToStowItem(item)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\n\t\titems = append(items, i)\n\t}\n\n\treturn items, nextPageToken, nil\n}", "func (c *container) Items(prefix, cursor string, count int) ([]stow.Item, string, error) {\n\tvar entries []entry\n\tentries, cursor, err := c.getFolderItems([]entry{}, prefix, \"\", filepath.Join(c.location.config.basePath, c.name), cursor, count, false)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\t// Convert entries to []stow.Item\n\tsItems := make([]stow.Item, len(entries))\n\tfor i := range entries {\n\t\tsItems[i] = entries[i].item\n\t}\n\n\treturn sItems, cursor, nil\n}", "func Get(reddit string) ([]Item, error) {\n\tc := new(redditClient)\n\turl := fmt.Sprintf(\"http://reddit.com/r/%s.json\", reddit)\n\tresp, err := c.get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, errors.New(resp.Status)\n\t}\n\tr := new(response)\n\tif err = json.NewDecoder(resp.Body).Decode(r); err != nil {\n\t\treturn nil, err\n\t}\n\titems := make([]Item, len(r.Data.Children))\n\tfor i, child := range r.Data.Children {\n\t\titems[i] = child.Data\n\t}\n\treturn items, nil\n}", "func getStoriesWithWaitGroup(idx int, ids []int) []item {\n\tstories := make([]item, len(ids))\n\tvar p []int\n\tn := 0\n\tfor _, id := range ids { // Look up the cache first\n\t\tit, found := cach.find(id)\n\t\tif found {\n\t\t\tstories[n] = it\n\t\t\tn++\n\t\t\tif n >= len(ids) {\n\t\t\t\treturn stories\n\t\t\t}\n\t\t\tcontinue\n\t\t} else {\n\t\t\tif n+len(p) >= len(ids) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tp = append(p, id)\n\t\t}\n\t}\n\n\tvar wg sync.WaitGroup\n\ttemp := make([]item, len(p)) // use a temporary array to avoid data races\n\tfor i, id := range p { // not found in cache, send a request\n\t\twg.Add(1)\n\t\tgo func(i, id int) {\n\t\t\tvar client hn.Client\n\t\t\thnItem, err := client.GetItem(id)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t\titem := parseHNItem(hnItem, i+idx)\n\t\t\ttemp[i] = item\n\t\t\twg.Done()\n\t\t}(i, id)\n\t}\n\twg.Wait()\n\n\tfor _, it := range temp { // add the temp to the stories if it is a story\n\t\tif isStoryLink(it) {\n\t\t\tstories[n] = it\n\t\t\tn++\n\t\t}\n\t}\n\treturn stories\n}", "func (b *Bag) Items() []Item {\n\treturn b.items\n}", "func (s *sqlService) Items() (items []definitions.ItemDefinition) {\n\ts.Lock()\n\tdefer s.Unlock()\n\ts.context = context.Background()\n\tdb := s.connect(s.context)\n\t// defer db.Close()\n\trows, err := db.QueryContext(s.context, \"SELECT id, name, description, command, base_price, stackable, special, members FROM items ORDER BY id\")\n\tif err != nil {\n\t\tlog.Warn(\"Couldn't load entity definitions from sqlService:\", err)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tnextDef := definitions.ItemDefinition{}\n\t\trows.Scan(&nextDef.ID, &nextDef.Name, &nextDef.Description, &nextDef.Command, &nextDef.BasePrice, &nextDef.Stackable, &nextDef.Quest, &nextDef.Members)\n\t\titems = append(items, nextDef)\n\t}\n\trows.Close()\n\n\trows, err = db.QueryContext(s.context, \"SELECT id, skillIndex, level FROM item_wieldable_requirements\")\n\tif err != nil {\n\t\tlog.Error.Println(\"Couldn't load entity information from sql database:\", err)\n\t\treturn\n\t}\n\tvar id, skill, level int\n\tfor rows.Next() {\n\t\trows.Scan(&id, &skill, &level)\n\t\tif items[id].Requirements == nil {\n\t\t\titems[id].Requirements = make(map[int]int)\n\t\t}\n\t\titems[id].Requirements[skill] = level\n\t}\n\trows.Close()\n\n\trows, err = db.QueryContext(s.context, \"SELECT id, sprite, type, armour_points, magic_points, prayer_points, range_points, weapon_aim_points, weapon_power_points, pos, femaleOnly FROM item_wieldable\")\n\tif err != nil {\n\t\tlog.Error.Println(\"Couldn't load entity information from sql database:\", err)\n\t\treturn\n\t}\n\t// TODO: Integrate into ItemDefinition\n\tfor rows.Next() {\n\t\tnextDef := definitions.EquipmentDefinition{}\n\t\trows.Scan(&nextDef.ID, &nextDef.Sprite, &nextDef.Type, &nextDef.Armour, &nextDef.Magic, &nextDef.Prayer, &nextDef.Ranged, &nextDef.Aim, &nextDef.Power, &nextDef.Position, &nextDef.Female)\n\t\tdefinitions.Equipment = append(definitions.Equipment, nextDef)\n\t}\n\n\treturn\n}", "func GetItem(ctx Context) {\n\tid, err := strconv.Atoi(ctx.Param(\"id\"))\n\tif err != nil {\n\t\tctx.JSON(http.StatusInternalServerError, nil)\n\t\treturn\n\t}\n\titem, err := db.SelectItem(int64(id))\n\tif err != nil {\n\t\tctx.JSON(http.StatusInternalServerError, nil)\n\t\treturn\n\t}\n\tctx.JSON(http.StatusOK, item)\n}", "func GetBidsByItemController(rw http.ResponseWriter, req *http.Request){\n\tlogrus.Info(\"GetBidsByItemController Started\")\n\tsuccessResp := responses.Response{}\n\trequest := requests.GetBidByItem{}\n\tid := req.URL.Query()[\"product_id\"][0]\n\terr := request.PopulateGetBidByItem(id)\n\tif err != nil{\n\t\tlogrus.WithError(err).Error(\"Error while PopulateGetBidByItem()\")\n\t\tresponses.HandleError(rw, err)\n\t\treturn\n\t}\n\terr = request.ValidateGetBidByItem()\n\tif err != nil{\n\t\tlogrus.WithError(err).Error(\"Error while ValidateGetBidByItem()\")\n\t\tresponses.HandleError(rw, err)\n\t\treturn\n\t}\n\tbidService := dm.BidServiceDependencyManager(dm.BIDINGSERVICE)\n\tresp, err := bidService.GetBidsByItemservice(req.Context(),id)\n\tif err != nil{\n\t\tlogrus.WithError(err).Error(\"Error while GetBidsByItemController()\")\n\t\tresponses.HandleError(rw, err)\n\t\treturn\n\t}\n\tsuccessResp.GetBidByItemResponse(resp)\n\tsuccessResp.SendResponse(rw, http.StatusOK)\n\tlogrus.Info(\"GetBidsByItemController done\")\n\treturn\n\n}", "func (c *Client) GetItemRelatedItems(itemID, categoryID, categoryPath, itemName string) ([]ItemDetails, error) {\n\t// Fetch the item page.\n\tresp, err := c.client.Get(ItemRecommendations(itemID, categoryID, categoryPath, itemName))\n\tif err != nil {\n\t\t// Return the HTTPError.\n\t\treturn nil, err\n\t}\n\n\t// Read the HTML body.\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, api.NewAPIError(resp, \"failed to read response body\", \"io_error\", err)\n\t}\n\n\tjsonStr := string(body)\n\n\ttype queryType struct {\n\t\tStatusCode int // should be \"200\"\n\t\tModules []struct {\n\t\t\tName string\n\t\t\tConfigs map[string]struct {\n\t\t\t\tTitle string\n\t\t\t\tProducts []struct {\n\t\t\t\t\tID struct {\n\t\t\t\t\t\tProductID string `json:\"productId\"`\n\t\t\t\t\t}\n\t\t\t\t\tPrice struct {\n\t\t\t\t\t\tCurrentPrice float32\n\t\t\t\t\t}\n\t\t\t\t\tProductName string\n\t\t\t\t\tProductURL string `json:\"productUrl\"`\n\t\t\t\t\tCategory string\n\t\t\t\t\tAvailabilityStatus string\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Decode the JSON value into the struct.\n\tquery := queryType{}\n\terr = json.NewDecoder(strings.NewReader(jsonStr)).Decode(&query)\n\tif err != nil {\n\t\treturn nil, api.NewAPIError(resp, \"failed to decode item json payload\", \"deserialization_error\", err)\n\t}\n\n\tif query.StatusCode != 200 {\n\t\treturn nil, api.NewAPIError(resp, \"API returned non-200 status code\", \"server_error\", nil)\n\t}\n\n\titems := map[string]ItemDetails{}\n\n\tfor _, module := range query.Modules {\n\t\tfor _, config := range module.Configs {\n\t\t\tfor _, product := range config.Products {\n\t\t\t\tif product.ID.ProductID == \"\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tslug := SlugRegex.FindStringSubmatch(product.ProductURL)[1]\n\n\t\t\t\titems[product.ID.ProductID] = ItemDetails{\n\t\t\t\t\tID: product.ID.ProductID,\n\t\t\t\t\tSlug: slug,\n\t\t\t\t\tName: product.ProductName,\n\t\t\t\t\tCategory: product.Category,\n\t\t\t\t\tCategoryID: \"\",\n\t\t\t\t\tPrice: product.Price.CurrentPrice,\n\t\t\t\t\tAvailabilityStatus: product.AvailabilityStatus,\n\t\t\t\t\tInStock: product.AvailabilityStatus == \"IN_STOCK\",\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\titemsArray := []ItemDetails{}\n\tfor _, item := range items {\n\t\titemsArray = append(itemsArray, item)\n\t}\n\n\treturn itemsArray, nil\n}", "func getStoriesWithChannel(idx int, ids []int) []item {\n\tvar stories []item\n\tc := make(chan item)\n\tn := 0\n\tfor i, id := range ids { // Look up the cache first\n\t\tif it, found := cach.find(id); found {\n\t\t\tstories = append(stories, it)\n\t\t\tif len(stories) >= len(ids) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tn++\n\t\tgo func(i, id int) {\n\t\t\tvar client hn.Client\n\t\t\thnItem, err := client.GetItem(id)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t\titm := parseHNItem(hnItem, i+idx)\n\t\t\tif !isStoryLink(itm) {\n\t\t\t\titm.id = -1\n\t\t\t}\n\t\t\tc <- itm\n\t\t}(i, id)\n\t}\n\tfor i := 0; i < n; i++ { // we need to know the exact number of items in the blocking channel\n\t\titm := <-c\n\t\tif itm.ID != -1 {\n\t\t\tstories = append(stories, itm)\n\t\t}\n\t}\n\treturn stories\n}", "func (pg *PostgresqlDb)GetItemById(id int, item *domain.Item) *domain.ErrHandler {\n if pg.conn == nil {\n return &domain.ErrHandler{7, \"func (pg PostgresqlDb)\", \"getItem(inventory *domain.Inventory)\", \"\"}\n }\n recordset := pg.conn.QueryRow(\"SELECT id, name, quantity FROM inventory WHERE id=$1;\", id)\n var err domain.ErrHandler\n switch err := recordset.Scan(&item.Id, &item.Name, &item.Quantity); err {\n case sql.ErrNoRows:\n return &domain.ErrHandler{13, \"func (pg PostgresqlDb)\", \"getItem(inventory *domain.Inventory)\", \"\"}\n case nil:\n return nil\n }\n return &domain.ErrHandler{1, \"func (pg PostgresqlDb)\", \"getItem(inventory *domain.Inventory)\", err.Error()}\n}", "func GetIngridientsOfPizza(pizzaID int) ([]types.IngredientSimple, error) {\n\tlog.Printf(\"Get all ingridients for pizza %d\\n\", pizzaID)\n\tvar ingredients []types.IngredientSimple\n\tvar ingredient types.IngredientSimple\n\tvar rows *sql.Rows\n\n\tquerySQL := `SELECT i.id, i.name, i.image_url, i.price\n FROM used_ingredient n\n LEFT JOIN ingredient i ON i.id=n.ingredient_id\n WHERE n.pizza_id=$1 ;`\n\n\trows = database.query(querySQL, pizzaID)\n\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tingredient = types.IngredientSimple{}\n\n\t\terr = rows.Scan(&ingredient.ID, &ingredient.Name, &ingredient.ImgURL, &ingredient.Price)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\n\t\tingredients = append(ingredients, ingredient)\n\t}\n\n\treturn ingredients, nil\n}", "func GetItems(filter interface{}) (GetItemResult, error) {\n\t// create connection to database\n\tctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)\n\tdefer cancel()\n\tc := newConnection(ctx)\n\tdefer c.clt.Disconnect(ctx)\n\n\tcursor, err := c.collection(itemCollection).Find(context.Background(), filter)\n\tif err == mongo.ErrNoDocuments {\n\t\treturn GetItemResult{\n\t\t\tGotItemCount: 0,\n\t\t\tData: nil,\n\t\t}, nil\n\t} else if err != nil {\n\t\treturn GetItemResult{}, err\n\t}\n\n\tvar res []bson.M\n\tif err = cursor.All(context.Background(), &res); err != nil {\n\t\treturn GetItemResult{}, err\n\t}\n\treturn GetItemResult{\n\t\tGotItemCount: int64(len(res)),\n\t\tData: res,\n\t}, nil\n}", "func (v *Vault) LookupItems(pred ItemPredicate) ([]Item, error) {\n\tvar items []Item\n\n\terr := transact(v.db, func(tx *sql.Tx) (e error) {\n\t\trows, e := tx.Query(\n\t\t\t\"SELECT id, category_uuid, key_data, overview_data\" +\n\t\t\t\" FROM items\" +\n\t\t\t\" WHERE profile_id = ? AND trashed = 0\",\n\t\t\tv.profileId)\n\t\tif e != nil {\n\t\t\treturn\n\t\t}\n\t\tdefer rows.Close()\n\n\t\t// Figure out matches\n\t\tfor rows.Next() {\n\t\t\tvar itemId int\n\t\t\tvar catUuid string\n\t\t\tvar itemKeyBlob, opdata []byte\n\t\t\te = rows.Scan(&itemId, &catUuid, &itemKeyBlob, &opdata)\n\t\t\tif e != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Decrypt the overview\n\t\t\tvar overview []byte\n\t\t\toverview, e = crypto.DecryptOPData01(opdata, v.overviewKP)\n\t\t\tif e != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvar item Item\n\t\t\te = json.Unmarshal(overview, &item)\n\t\t\tif e != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\titem.Category = Category{catUuid, v.categories[catUuid]}\n\n\t\t\t// Decrypt the item key\n\t\t\tvar kp *crypto.KeyPair\n\t\t\tkp, e = crypto.DecryptItemKey(itemKeyBlob, v.masterKP)\n\t\t\tif e != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Decrypt the item details\n\t\t\tdetRow := tx.QueryRow(\n\t\t\t\t\"SELECT data FROM item_details\" +\n\t\t\t\t\" WHERE item_id = ?\", itemId)\n\t\t\tvar detailsCT []byte\n\t\t\te = detRow.Scan(&detailsCT)\n\t\t\tif e != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvar details []byte\n\t\t\tdetails, e = crypto.DecryptOPData01(detailsCT, kp)\n\t\t\tif e != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\titem.Details = details\n\n\t\t\tif pred(&item) {\n\t\t\t\titems = append(items, item)\n\t\t\t}\n\t\t}\n\n\t\treturn rows.Err()\n\t})\n\n\tif err != nil {\n\t\titems = nil\n\t}\n\n\treturn items, err\n}", "func (m *List) GetItems()([]ListItemable) {\n return m.items\n}", "func getStocks() []stock {\n\tst := []stock{}\n\trows, _ := DB.Query(`\n\t\tSELECT s.id, sku, w.id, amount\n\t\tFROM stock s\n\t\tINNER JOIN items i\n\t\tON s.item_sku = i.sku\n\t\tINNER JOIN warehouses w\n\t\tON s.warehouse_id = w.id;\n\t`)\n\n\tfor rows.Next() {\n\t\trow := stock{}\n\t\trows.Scan(&row.ID, &row.SKU, &row.Warehouse, &row.Amount)\n\t\tst = append(st, row)\n\t}\n\n\treturn st\n}", "func GetItemsHandler(rep repository.Repository) func(w http.ResponseWriter, r *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tif err := r.ParseForm(); err != nil {\n\t\t\trespond(w, http.StatusBadRequest, data.ErrorResponse{Error: \"malformed form input\"})\n\t\t\treturn\n\t\t}\n\n\t\tsearch := r.FormValue(\"search\")\n\t\tif len(search) < 3 {\n\t\t\trespond(w, http.StatusBadRequest, data.ErrorResponse{Error: \"search should be at least 3 characters\"})\n\t\t\treturn\n\t\t}\n\n\t\titems, err := rep.GetItems(search)\n\t\tif err != nil {\n\t\t\trespond(w, http.StatusInternalServerError, data.ErrorResponse{Error: \"server has failed to fetch items\"})\n\t\t}\n\n\t\trespond(w, http.StatusOK, data.Response{Items: items})\n\t}\n}", "func (c *ClientWithResponses) GetSoundSetitemsWithResponse(ctx context.Context, params *GetSoundSetitemsParams) (*GetSoundSetitemsResponse, error) {\n\trsp, err := c.GetSoundSetitems(ctx, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseGetSoundSetitemsResponse(rsp)\n}", "func (out Outlooky) GetItems(folder *ole.IDispatch) *ole.IDispatch {\n\titems, err := out.CallMethod(folder, \"Items\")\n\tutil.Catch(err, \"Failed retrieving items.\")\n\n\treturn items.ToIDispatch()\n}", "func getPlaylistIds() []string {\n\tclient := &http.Client{}\n\n\tvar ids []string\n\turl := \"https://api.spotify.com/v1/users/\" + userId + \"/playlists?limit=50\"\n\tplaylistRequest, err := http.NewRequest(\"GET\", url, nil)\n\n\tplaylistRequest.Header.Add(\"Authorization\", key)\n\tresponse, err := client.Do(playlistRequest)\n\tif err != nil {\n\t\tfmt.Println(\"Request failed with error:\", err)\n\t} else {\n\t\tdata, _ := ioutil.ReadAll(response.Body)\n\t\titems := gjson.Get(string(data), \"items\")\n\t\tfor i := 0; i < len(items.Array()); i++ {\n\t\t\tid := gjson.Get(items.Array()[i].String(), \"id\")\n\t\t\tids = append(ids, id.String())\n\t\t}\n\t}\n\treturn getPlaylistSongIds(ids)\n}", "func (c StatusFilter) Items(arg, data string) (items []alfred.Item, err error) {\n\tdlog.Printf(\"status items with arg=%s, data=%s\", arg, data)\n\n\tif err = refresh(); err != nil {\n\t\titems = append(items, alfred.Item{\n\t\t\tTitle: \"Error syncing with toggl.com\",\n\t\t\tSubtitle: fmt.Sprintf(\"%v\", err),\n\t\t})\n\t\treturn\n\t}\n\n\tif entry, found := getRunningTimer(); found {\n\t\tstartTime := entry.StartTime().Local()\n\t\tseconds := round(time.Now().Sub(startTime).Seconds())\n\t\tduration := float64(seconds) / float64(60*60)\n\t\tdate := toHumanDateString(startTime)\n\t\ttime := startTime.Format(\"15:04:05\")\n\t\tsubtitle := fmt.Sprintf(\"%s, started %s at %s\",\n\t\t\tformatDuration(round(duration*100.0)), date, time)\n\n\t\tif project, _, ok := getProjectByID(entry.Pid); ok {\n\t\t\tsubtitle = \"[\" + project.Name + \"] \" + subtitle\n\t\t}\n\n\t\titem := alfred.Item{\n\t\t\tTitle: entry.Description,\n\t\t\tSubtitle: subtitle,\n\t\t\tArg: &alfred.ItemArg{\n\t\t\t\tKeyword: \"timers\",\n\t\t\t\tData: alfred.Stringify(timerCfg{Timer: &entry.ID}),\n\t\t\t},\n\t\t}\n\n\t\titem.AddMod(alfred.ModCmd, alfred.ItemMod{\n\t\t\tSubtitle: \"Stop this timer\",\n\t\t\tArg: &alfred.ItemArg{\n\t\t\t\tKeyword: \"timers\",\n\t\t\t\tMode: alfred.ModeDo,\n\t\t\t\tData: alfred.Stringify(timerCfg{ToToggle: &toggleCfg{entry.ID, config.DurationOnly}}),\n\t\t\t},\n\t\t})\n\n\t\titems = append(items, item)\n\t} else {\n\t\titems = append(items, alfred.Item{\n\t\t\tTitle: \"No timers currently running\",\n\t\t\tIcon: \"off.png\",\n\t\t})\n\t}\n\n\tspan, _ := getSpan(\"today\")\n\tvar report *summaryReport\n\treport, err = generateReport(span.Start, span.End, -1, \"\")\n\tfor _, date := range report.dates {\n\t\titems = append(items, alfred.Item{\n\t\t\tTitle: fmt.Sprintf(\"Total time for today: %s\", formatDuration(date.total)),\n\t\t})\n\t\tbreak\n\t}\n\n\treturn\n}", "func (rw *RankedWeapon) Items(skills []decode.CharSkill, cfg npcdefs.NPCCfg) []InvItem {\n\tw := defs.Weapons[rw.WeaponID]\n\tif !w.Reusable {\n\t\treturn rw.oneUseWeapons(rw.Rank, cfg)\n\t}\n\n\tvar items []InvItem\n\n\titems = append(items, InvItem{\n\t\tItemID: w.ItemID,\n\t\tCount: 1,\n\t})\n\n\tif w.ClipItemID != defs.ItemIDNone {\n\t\tcount := util.RandRange(cfg.WeaponClipsMin, cfg.WeaponClipsMax)\n\t\titems = append(items, InvItem{\n\t\t\tItemID: w.ClipItemID,\n\t\t\tCount: count,\n\t\t})\n\t}\n\n\treturn items\n}", "func (e Endpoints) GetChildes(ctx context.Context, id string) (t []io.Todo, error error) {\n\trequest := GetChildesRequest{Id: id}\n\tresponse, err := e.GetChildesEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn response.(GetChildesResponse).T, response.(GetChildesResponse).Error\n}", "func (b *Bag) QueryItems() *BagItemQuery {\n\treturn (&BagClient{config: b.config}).QueryItems(b)\n}", "func (c GroupCommand) Items(arg, data string) (items []alfred.Item, err error) {\n\tif err = checkRefresh(); err != nil {\n\t\treturn\n\t}\n\n\tvar cfg groupConfig\n\n\tif data != \"\" {\n\t\tif err = json.Unmarshal([]byte(data), &cfg); err != nil {\n\t\t\tdlog.Printf(\"Error unmarshalling group config: %v\", err)\n\t\t}\n\t}\n\n\tif cfg.Group != \"\" {\n\t} else {\n\t\tfor _, group := range cache.Groups {\n\t\t\tif alfred.FuzzyMatches(group.Name, arg) {\n\t\t\t\tlights, _ := getLightNamesFromIDs(group.Lights)\n\n\t\t\t\titems = append(items, alfred.Item{\n\t\t\t\t\tTitle: group.Name,\n\t\t\t\t\tSubtitle: strings.Join(lights, \", \"),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}", "func RequestQiitaItems(w http.ResponseWriter, r *http.Request) {\r\n\tif r.URL.Path != \"/qiita/items/request\" {\r\n\t\thttp.NotFound(w, r)\r\n\t\treturn\r\n\t}\r\n\r\n\tctx := appengine.NewContext(r)\r\n\tclient := urlfetch.Client(ctx)\r\n\tresp, err := client.Get(\"https://qiita.com/api/v2/users/kik4/items?per_page=100\")\r\n\tif err != nil || resp.StatusCode != http.StatusOK {\r\n\t\tInternalServerError(ctx, w, err)\r\n\t\treturn\r\n\t}\r\n\r\n\te := domain.QiitaItemsEntity{}\r\n\terr = json.NewDecoder(resp.Body).Decode(&e.Value)\r\n\tif err != nil {\r\n\t\tInternalServerError(ctx, w, err)\r\n\t\treturn\r\n\t}\r\n\te.UpdatedAt = time.Now()\r\n\r\n\tfmt.Fprintf(w, \"%#v\", e)\r\n\r\n\tkey := datastore.NewKey(ctx, \"qiita\", \"kik4\", 0, nil)\r\n\tkey, err = datastore.Put(ctx, key, &e)\r\n\tif err != nil {\r\n\t\tInternalServerError(ctx, w, err)\r\n\t\treturn\r\n\t}\r\n\tfmt.Fprintln(w, key)\r\n}", "func (c *pricedCart) GetItems() []Item {\n\titems := make([]Item, len(c.items))\n\ti := 0\n\tfor _, item := range c.items {\n\t\titems[i] = *item\n\t\ti++\n\t}\n\treturn items\n}", "func ShardItems(items []*Item, threshold int64) []*ItemBundle {\n\tvar (\n\t\tbundles []*ItemBundle\n\t\tbundle *ItemBundle\n\t)\n\n\tfor len(items) > 0 {\n\t\tbundle, items = oneBundle(items, threshold)\n\t\tbundles = append(bundles, bundle)\n\t}\n\treturn bundles\n}", "func (s Service) GetSecrets(items []Item, ses Session) (map[dbus.ObjectPath]Secret, error) {\n\t// spec: GetSecrets(IN Array<ObjectPath> items, IN ObjectPath session, OUT Dict<ObjectPath,Secret> secrets);\n\targ := make([]dbus.ObjectPath, len(items))\n\tfor i, o := range items {\n\t\targ[i] = o.Path()\n\t}\n\tcall := s.Call(_ServiceGetSecrets, 0, arg, ses.Path())\n\tif call.Err != nil {\n\t\treturn map[dbus.ObjectPath]Secret{}, call.Err\n\t}\n\tret := make(map[dbus.ObjectPath]Secret)\n\terr := call.Store(&ret)\n\treturn ret, err\n}", "func (s *InventoryItemServiceOp) Get(id int64, options interface{}) (*InventoryItem, error) {\n\tpath := fmt.Sprintf(\"%s/%d.json\", inventoryItemsBasePath, id)\n\tresource := new(InventoryItemResource)\n\terr := s.client.Get(path, resource, options)\n\treturn resource.InventoryItem, err\n}", "func (items *items) getUntil(checker func(item interface{}) bool) []interface{} {\n\tlength := len(*items)\n\tif length == 0 {\n\t\treturn []interface{}{}\n\t}\n\n\treturnItems := make([]interface{}, 0, length)\n\tindex := 0\n\tfor i, item := range *items {\n\t\tif !checker(item) {\n\t\t\tbreak\n\t\t}\n\n\t\treturnItems = append(returnItems, item)\n\t\tindex = i\n\t}\n\n\t*items = (*items)[index:]\n\treturn returnItems\n}", "func (m *Drive) GetBundles()([]DriveItemable) {\n return m.bundles\n}", "func (d *Database) GetItems(\n\treq GetItemsRequest) (*GetItemsResponse, error) {\n\tvar err error\n\tresp := GetItemsResponse{\n\t\tItems: []*structs.Item{}}\n\n\tif !req.Unread && req.ReadAfter == nil && req.ReadBefore == nil {\n\t\tlog.Info(\"GetItems() called with empty request\")\n\t\treturn &resp, nil\n\t}\n\n\tif len(req.FeedIDs) != 0 && req.CategoryID != nil {\n\t\treturn nil, errors.New(\"Can't call GetItems for both feeds and a category\")\n\t}\n\n\tif req.Unread && len(req.FeedIDs) == 0 {\n\t\treturn nil, errors.New(\"Can't request unread except by feeds\")\n\t}\n\n\tif (req.ReadAfter != nil) && (req.ReadBefore != nil) {\n\t\treturn nil, errors.New(\"Must not specify both ReadBefore and ReadAfter\")\n\t}\n\n\tif req.ReadAfter != nil {\n\t\t*req.ReadAfter = req.ReadAfter.UTC().Truncate(time.Second)\n\t}\n\n\tif req.ReadBefore != nil {\n\t\t*req.ReadBefore = req.ReadBefore.UTC().Truncate(time.Second)\n\t}\n\n\td.lock.RLock()\n\tdefer d.lock.RUnlock()\n\n\tif err := d.checkClosed(); err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tif !req.IncludeFeeds {\n\t\tresp.Items, err = getItemsFor(d.db, req)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn &resp, nil\n\t}\n\n\ttx, err := d.db.Begin()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\tdefer tx.Rollback()\n\n\tresp.Items, err = getItemsFor(tx, req)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tif req.IncludeFeeds && req.FeedIDs != nil {\n\t\tresp.Feeds, err = getFeeds(tx, req.FeedIDs)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\ttx.Rollback()\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}", "func (b BladeStorage) GetAllByDisksID(offset string, limit string, serials []string) (count int, blades []model.Blade, err error) {\n\tif offset != \"\" && limit != \"\" {\n\t\tif err = b.db.Limit(limit).Offset(offset).Joins(\"INNER JOIN disk ON disk.blade_serial = blade.serial\").Where(\"disk.serial in (?)\", serials).Find(&blades).Error; err != nil {\n\t\t\treturn count, blades, err\n\t\t}\n\t\tb.db.Model(&model.Blade{}).Joins(\"INNER JOIN disk ON disk.blade_serial = blade.serial\").Where(\"disk.serial in (?)\", serials).Count(&count)\n\t} else {\n\t\tif err = b.db.Joins(\"INNER JOIN disk ON disk.blade_serial = blade.serial\").Where(\"disk.serial in (?)\", serials).Find(&blades).Error; err != nil {\n\t\t\treturn count, blades, err\n\t\t}\n\t}\n\treturn count, blades, err\n}", "func (s *GORMStore) GetItems() interface{} {\n\treturn s.items\n}", "func (r *FinancialItemRepository) GetUserItems(tx *sql.Tx, userID int64) ([]models.FinancialItem, error) {\n\trows, err := tx.Query(\"SELECT * FROM items WHERE user_id=$1;\", userID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer rows.Close()\n\n\titems := make([]models.FinancialItem, 0)\n\tfor rows.Next() {\n\t\titem := models.FinancialItem{}\n\t\terr := rows.Scan(&item.ID,\n\t\t\t&item.PlaidItemID, &item.PlaidAccessToken, &item.UserID, &item.PlaidInstitutionID,\n\t\t\t&item.InstitutionName, &item.InstitutionColor, &item.InstitutionLogo,\n\t\t\t&item.ErrorCode, &item.ErrorDevMessage, &item.ErrorUserMessage)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, item)\n\t}\n\n\treturn items, nil\n}", "func (m *ExternalConnection) GetItems()([]ExternalItemable) {\n return m.items\n}", "func getNewsItems() []string {\n\turl := baseURL + \"/newstories.json\"\n\tbody := fmtRes(url)\n\tstoryIds := strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(string(body)), \"[\"), \"]\")\n\tidSlice := strings.Split(storyIds, \",\")\n\treturn idSlice\n}", "func (b BladeStorage) GetAllByChassisID(offset string, limit string, serials []string) (count int, blades []model.Blade, err error) {\n\tif offset != \"\" && limit != \"\" {\n\t\tif err = b.db.Limit(limit).Offset(offset).Where(\"chassis_serial in (?)\", serials).Preload(\"Nics\").Find(&blades).Error; err != nil {\n\t\t\treturn count, blades, err\n\t\t}\n\t\tb.db.Model(&model.Blade{}).Where(\"chassis_serial in (?)\", serials).Count(&count)\n\t} else {\n\t\tif err = b.db.Where(\"chassis_serial in (?)\", serials).Find(&blades).Error; err != nil {\n\t\t\treturn count, blades, err\n\t\t}\n\t}\n\treturn count, blades, err\n}", "func ListItemByOrderID(db *sql.DB, query string, orderid uint32) ([]*Item, error) {\n\tvar (\n\t\tProductID uint32\n\t\tOrderID uint32\n\t\tCount uint32\n\t\tPrice uint32\n\t\tDiscount uint32\n\n\t\titems []*Item\n\t)\n\n\trows, err := db.Query(query, orderid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tif err := rows.Scan(&ProductID, &OrderID, &Count, &Price, &Discount); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\titem := &Item{\n\t\t\tProductID: ProductID,\n\t\t\tOrderID: OrderID,\n\t\t\tCount: Count,\n\t\t\tPrice: Price,\n\t\t\tDiscount: Discount,\n\t\t}\n\n\t\titems = append(items, item)\n\t}\n\n\treturn items, nil\n}", "func (c *Client) HeroItems(account string, heroID int) (*response.HeroItems, error) {\n\tvar data *d3.HeroItems\n\n\tep := endpointDetailedHeroItems(c.region, account, heroID)\n\n\tq, err := c.get(ep, &data)\n\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\n\treturn &response.HeroItems{\n\t\tData: data,\n\t\tEndpoint: ep,\n\t\tQuota: q,\n\t\tRegion: c.region,\n\t}, nil\n}", "func GetItem(c Context) {\n\tidentifer, err := strconv.Atoi(c.Param(\"id\"))\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tres, err := db.SelectItem(int64(identifer))\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, res)\n}", "func GetIngredientsByIDs(ingrdIDs []int) ([]types.Ingredient, error) {\n\tlog.Println(\"All getting categories\")\n\tvar ingredients []types.Ingredient\n\tvar ingredient types.Ingredient\n\tvar rows *sql.Rows\n\n\tquerySQL := `SELECT i.id, i.name, i.price\n FROM ingredient i\n WHERE id in `\n\n\tqueryIDs := strings.Trim(strings.Replace(fmt.Sprint(ingrdIDs), \" \", \",\", -1), \"[]\")\n\tquerySQL += \"(\" + queryIDs + \");\"\n\n\trows = database.query(querySQL)\n\n\tif err != nil {\n\t\tlog.Println(\"Failed to get all categories from db\")\n\t}\n\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tingredient = types.Ingredient{}\n\n\t\terr = rows.Scan(\n\t\t\t&ingredient.ID, &ingredient.Name, &ingredient.Price)\n\n\t\tingredients = append(ingredients, ingredient)\n\t}\n\treturn ingredients, nil\n}", "func (o IopingSpecVolumeVolumeSourceDownwardAPIOutput) Items() IopingSpecVolumeVolumeSourceDownwardAPIItemsArrayOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceDownwardAPI) []IopingSpecVolumeVolumeSourceDownwardAPIItems {\n\t\treturn v.Items\n\t}).(IopingSpecVolumeVolumeSourceDownwardAPIItemsArrayOutput)\n}", "func getGitHubRepoItems(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\titemType := vars[\"itemType\"]\n\n\tif itemType == \"branch\" || itemType == \"commit\" {\n\t\towner := vars[\"owner\"]\n\t\trepo := vars[\"repo\"]\n\t\ttoken, err := parseTokenFromCookie(r)\n\t\thelpers.HandleError(err)\n\n\t\tvar res interface{}\n\n\t\tif itemType == \"branch\" {\n\t\t\tres, err = github.GetBranches(token, owner, repo)\n\t\t\thelpers.HandleError(err)\n\t\t} else {\n\t\t\tfrom, err := time.Parse(dtParamLayout, r.URL.Query().Get(\"from\"))\n\t\t\tif err != nil {\n\t\t\t\tfrom = time.Now().AddDate(0, 0, -7)\n\t\t\t}\n\t\t\tto, err := time.Parse(dtParamLayout, r.URL.Query().Get(\"to\"))\n\t\t\tif err != nil {\n\t\t\t\tto = time.Now()\n\t\t\t}\n\n\t\t\tres, err = github.GetCommits(token, owner, repo, from, to)\n\t\t\thelpers.HandleError(err)\n\t\t}\n\n\t\tapiResponse(map[string]interface{}{\"data\": res}, w)\n\t} else {\n\t\thelpers.HandleError(errors.New(\"Invalid itemType param\"))\n\t}\n}", "func world_itemByID(id int32, meta int16) (world.Item, bool)" ]
[ "0.70549184", "0.6203212", "0.57432526", "0.561227", "0.55682933", "0.537858", "0.5327069", "0.5295185", "0.5257403", "0.52491146", "0.51914525", "0.51633185", "0.51590073", "0.51384294", "0.5119515", "0.5101776", "0.50942695", "0.50225264", "0.5011956", "0.5010836", "0.49795574", "0.49130875", "0.49086317", "0.49065328", "0.4880542", "0.4845152", "0.48393917", "0.48225915", "0.48059955", "0.47745785", "0.47531", "0.47491267", "0.4738573", "0.47277948", "0.47031575", "0.469516", "0.46708056", "0.466335", "0.46095386", "0.46049973", "0.46025988", "0.46000552", "0.45972186", "0.45926106", "0.45904413", "0.4585476", "0.45654985", "0.45600635", "0.45565885", "0.45461783", "0.45362428", "0.4505603", "0.450095", "0.44860163", "0.44786924", "0.44753656", "0.44685093", "0.44547448", "0.44526073", "0.4448777", "0.44063675", "0.43971702", "0.43944556", "0.4393019", "0.43911684", "0.4387902", "0.43784046", "0.43773448", "0.4376168", "0.4369881", "0.4365857", "0.43646786", "0.43566003", "0.4351755", "0.4331862", "0.43254718", "0.43133911", "0.43062323", "0.43019423", "0.42937875", "0.42901513", "0.4289804", "0.4264651", "0.42498717", "0.42436486", "0.42350933", "0.42342445", "0.42321688", "0.422508", "0.42212024", "0.42210346", "0.42204025", "0.42184177", "0.42169946", "0.42121804", "0.42114973", "0.42092305", "0.4208053", "0.41993776", "0.41960192" ]
0.7852285
0
InsertItem inserts an Item into the db
func InsertItem(item *models.Item) *response.Error { return item.Insert() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (repo *MySQLRepository) InsertItem(item item.Item) error {\n\ttx, err := repo.db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\titemQuery := `INSERT INTO item (\n\t\t\tid, \n\t\t\tname, \n\t\t\tdescription, \n\t\t\tcreated_at, \n\t\t\tcreated_by, \n\t\t\tmodified_at, \n\t\t\tmodified_by,\n\t\t\tversion\n\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = tx.Exec(itemQuery,\n\t\titem.ID,\n\t\titem.Name,\n\t\titem.Description,\n\t\titem.CreatedAt,\n\t\titem.CreatedBy,\n\t\titem.ModifiedAt,\n\t\titem.ModifiedBy,\n\t\titem.Version,\n\t)\n\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\ttagQuery := \"INSERT INTO item_tag (item_id, tag) VALUES (?, ?)\"\n\n\tfor _, tag := range item.Tags {\n\t\t_, err = tx.Exec(tagQuery, item.ID, tag)\n\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\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (r Item) Insert() error {\n\tr.ID = bson.NewObjectId()\n\terr := db.C(\"item\").Insert(&r)\n\treturn err\n}", "func (r *Repository) InsertOrderItem(data *OrderItem) (err error) {\n\n\terr = r.db.Create(data).Error\n\n\treturn\n}", "func InsertItem(s *mgo.Session, i Item) bool {\n if s == nil {\n log.Println(\"FATAL: Can not access MongoDB! Application Closing!\")\n os.Exit(1)\n }\n\n collName := i.Category\n defer s.Close()\n\n s.SetMode(mgo.Monotonic, true)\n\n c := s.DB(\"nebula\").C(collName)\n\n mID := bson.NewObjectId()\n i.ID = mID \n\n err := c.Insert(i)\n\n res := false\n if err != nil {\n log.Println(\"ERROR: Failed to delete item from MongoDB\")\n res = true\n return res\n }\n\n c = s.DB(\"users\").C(i.Seller)\n err = c.Insert(i)\n\n res = false\n if err != nil {\n res = true\n }\n\n return res\n}", "func (so *SQLOrderItemStore) Insert(oi *model.OrderItem) (*model.OrderItem, error) {\n\toi.OrderItemID = uuid.NewV4().String()\n\toi.CreatedAt = time.Now().UnixNano()\n\toi.UpdatedAt = oi.CreatedAt\n\terr := so.SQLStore.Tx.Insert(oi)\n\treturn oi, err\n}", "func Insert(Items Item) error {\n\terr := db.C(\"unit\").Insert(&Items)\n\treturn err\n}", "func (c *Conn) Insert(ctx context.Context, i Item) (err error) {\n\t_, err = c.db.Exec(ctx, \"INSERT INTO jobs (url) VALUES ($1)\", i.URL)\n\treturn\n}", "func (db *JSONLite) Insert(item Item) (string, error) {\n\tuids, err := db.InsertBatch([]Item{item})\n\treturn uids[0], err\n}", "func SaveItem(db *sql.DB, items []StoreItem) {\n\taddItem, err := db.Prepare(`INSERT OR REPLACE INTO items(\n\t\tRegion,\n\t\tKategorie,\n\t\tAngebot,\n\t\tLaden) values(?, ?, ?, ?)`)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer addItem.Close()\n\n\tfor _, item := range items {\n\t\taddItem.Exec(item.Region, item.Kategorie, item.Angebot, item.Laden)\n\t}\n}", "func CreateItem(w http.ResponseWriter, r *http.Request) {\r\n\r\n\t// get the bearer token\r\n\tbearerHeader := r.Header.Get(\"Authorization\")\r\n\r\n\t// validate token, it will return a User{UserID, Name}\r\n\tuser, err := ValidateToken(bearerHeader)\r\n\r\n\tcheckErr(err)\r\n\r\n\t// get the db connection\r\n\tdb := getDBConn()\r\n\r\n\t// close db connection\r\n\tdefer db.Close()\r\n\r\n\tvar params item\r\n\r\n\t// decode the request parameters to item type\r\n\terr = json.NewDecoder(r.Body).Decode(&params)\r\n\r\n\tcheckErr(err)\r\n\r\n\t// insert into the items db\r\n\tstmt, err := db.Prepare(\"INSERT INTO items SET itemID=?,merchantID=?,name=?\")\r\n\r\n\t// close the stmt request\r\n\tdefer stmt.Close()\r\n\r\n\tcheckErr(err)\r\n\r\n\t// execute the insert statement\r\n\tres, err := stmt.Exec(params.ItemID, user.UserID, params.Name)\r\n\r\n\tcheckErr(err)\r\n\r\n\tid, err := res.LastInsertId()\r\n\r\n\tcheckErr(err)\r\n\r\n\tfmt.Println(id)\r\n\r\n\t// return the order created msg in json format\r\n\tjson.NewEncoder(w).Encode(\"Item Created!\")\r\n}", "func AddItem(c *gin.Context) {\n\tvar item model.Item\n\terr := c.ShouldBindJSON(&item)\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"Error\": err.Error()})\n\t\treturn\n\t}\n\tutil.DB.Create(&item)\n\tc.JSON(http.StatusOK, util.SuccessResponse(http.StatusOK, \"Success add item\", item))\n}", "func (insert *ItemTable) Create(c *gin.Context, db *gorm.DB) error {\n\ttype Body struct {\n\t\tItemID string `json:\"item_id\" binding:\"required\"`\n\t\tName string `json:\"name\" binding:\"required\"`\n\t\tDate string `json:\"date\" binding:\"required\"`\n\t\tAgeLimit uint `json:\"age_limit\" binding:\"required\"`\n\t\tCost uint `json:\"cost\" binding:\"required\"`\n\t\tLocation string `json:\"location\" binding:\"required\"`\n\t\tState ItemState `json:\"state\" binding:\"required\"`\n\t\tNote string `json:\"note\" binding:\"required\"`\n\t}\n\tvar body Body\n\terr := c.ShouldBindJSON(&body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tselectField := []string{\n\t\t\"item_id\",\n\t\t\"name\",\n\t\t\"date\",\n\t\t\"age_limit\",\n\t\t\"cost\",\n\t\t\"location\",\n\t\t\"state\",\n\t\t\"note\",\n\t}\n\n\tinsert.ItemID = body.ItemID\n\tinsert.Name = body.Name\n\tinsert.Date = body.Date\n\tinsert.AgeLimit = body.AgeLimit\n\tinsert.Cost = body.Cost\n\tinsert.Location = body.Location\n\tinsert.State = body.State\n\tinsert.Note = body.Note\n\n\treturn db.Select(\n\t\tselectField[0], selectField[1:],\n\t).Create(&insert).Error\n}", "func (r *FinancialItemRepository) AddItem(tx *sql.Tx, item *models.FinancialItem) error {\n\tvar itemID int64\n\terr := tx.QueryRow(\"INSERT INTO items (PLAID_ITEM_ID, PLAID_ACCESS_TOKEN, USER_ID, PLAID_INSTITUTION_ID, INSTITUTION_NAME, INSTITUTION_COLOR, INSTITUTION_LOGO, ERROR_CODE, ERROR_DEV_MSG, ERROR_USER_MSG) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING id\",\n\t\titem.PlaidItemID, item.PlaidAccessToken, item.UserID, item.PlaidInstitutionID,\n\t\titem.InstitutionName, item.InstitutionColor, item.InstitutionLogo,\n\t\titem.ErrorCode, item.ErrorDevMessage, item.ErrorUserMessage).Scan(&itemID)\n\tif err != nil {\n\t\treturn err\n\t}\n\titem.ID = itemID\n\treturn nil\n}", "func (i Inventory) AddItem(item Item) (string, *ErrHandler) {\n if item.Id == 0 {\n return \"\", &ErrHandler{10, \"func (Inventory)\", \"AddItem\", \"\"}\n }\n if item.Name == \"\" {\n return \"\", &ErrHandler{11, \"func (Inventory)\", \"AddItem\", \"\"}\n }\n if item.Quantity == 0 {\n return \"\", &ErrHandler{12, \"func (Inventory)\", \"AddItem\", \"\"}\n }\n err := i.Db.AddItem(item)\n if err != nil {\n return \"\", err\n }\n return \"item added\", nil\n}", "func (o *Item) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no items provided for insertion\")\n\t}\n\n\tvar err error\n\n\tnzDefaults := queries.NonZeroDefaultSet(itemColumnsWithDefault, o)\n\n\tkey := makeCacheKey(columns, nzDefaults)\n\titemInsertCacheMut.RLock()\n\tcache, cached := itemInsertCache[key]\n\titemInsertCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl, returnColumns := columns.InsertColumnSet(\n\t\t\titemAllColumns,\n\t\t\titemColumnsWithDefault,\n\t\t\titemColumnsWithoutDefault,\n\t\t\tnzDefaults,\n\t\t)\n\n\t\tcache.valueMapping, err = queries.BindMapping(itemType, itemMapping, wl)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcache.retMapping, err = queries.BindMapping(itemType, itemMapping, returnColumns)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(wl) != 0 {\n\t\t\tcache.query = fmt.Sprintf(\"INSERT INTO \\\"items\\\" (\\\"%s\\\") %%sVALUES (%s)%%s\", strings.Join(wl, \"\\\",\\\"\"), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1))\n\t\t} else {\n\t\t\tcache.query = \"INSERT INTO \\\"items\\\" %sDEFAULT VALUES%s\"\n\t\t}\n\n\t\tvar queryOutput, queryReturning string\n\n\t\tif len(cache.retMapping) != 0 {\n\t\t\tcache.retQuery = fmt.Sprintf(\"SELECT \\\"%s\\\" FROM \\\"items\\\" WHERE %s\", strings.Join(returnColumns, \"\\\",\\\"\"), strmangle.WhereClause(\"\\\"\", \"\\\"\", 0, itemPrimaryKeyColumns))\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning)\n\t}\n\n\tvalue := reflect.Indirect(reflect.ValueOf(o))\n\tvals := queries.ValuesFromMapping(value, cache.valueMapping)\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.query)\n\t\tfmt.Fprintln(writer, vals)\n\t}\n\t_, err = exec.ExecContext(ctx, cache.query, vals...)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to insert into items\")\n\t}\n\n\tvar identifierCols []interface{}\n\n\tif len(cache.retMapping) == 0 {\n\t\tgoto CacheNoHooks\n\t}\n\n\tidentifierCols = []interface{}{\n\t\to.ID,\n\t}\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.retQuery)\n\t\tfmt.Fprintln(writer, identifierCols...)\n\t}\n\terr = exec.QueryRowContext(ctx, cache.retQuery, identifierCols...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to populate default values for items\")\n\t}\n\nCacheNoHooks:\n\tif !cached {\n\t\titemInsertCacheMut.Lock()\n\t\titemInsertCache[key] = cache\n\t\titemInsertCacheMut.Unlock()\n\t}\n\n\treturn nil\n}", "func StoreItem(document interface{}) (StoreItemResult, error) {\n\t// create connection to database\n\tctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)\n\tdefer cancel()\n\tc := newConnection(ctx)\n\tdefer c.clt.Disconnect(ctx)\n\n\t_, err := c.collection(itemCollection).InsertOne(context.Background(), document)\n\tif err != nil {\n\t\treturn StoreItemResult{}, err\n\t}\n\treturn StoreItemResult{\n\t\tStoredItemCount: 1,\n\t}, nil\n}", "func (s Storage) StoreItem(item core.Item) (int, error) {\n\tns, err := uuid.FromString(\"6ba7b810-9dad-11d1-80b4-00c04fd430c8\") // TODO: namespace\n\tif err != nil {\n\t\tlog.Printf(\"can't generate namespace %e\", err)\n\t}\n\tkey := \"salt:\" + item.Filename\n\tu5 := uuid.NewV5(ns, key)\n\tif err != nil {\n\t\tlog.Printf(\"can't generate UUID %e\", err)\n\t}\n\n\tdir := s.dir + u5.String() + \"/\"\n\tpath := dir + item.Filename\n\n\terr = os.MkdirAll(dir, os.ModePerm)\n\tif err != nil {\n\t\tlog.Printf(\"can't create directory %s %e\", dir, err)\n\t}\n\terr = os.Rename(item.SourceName, path)\n\tif err != nil {\n\t\tlog.Printf(\"can't rename file %s to %s %e\", item.SourceName, path, err)\n\t}\n\n\tfi, err := os.Stat(path)\n\tsize := int64(-1)\n\tif err == nil {\n\t\tsize = fi.Size()\n\t}\n\n\tmutex.Lock()\n\tdefer mutex.Unlock()\n\n\tsql := \"INSERT INTO items(name, filename, path, size, category, available) VALUES(?, ?, ?, ?, ?, ?)\"\n\tstmt, err := s.connection.Prepare(sql)\n\tif err != nil {\n\t\tlog.Fatal(\"prepared statement for table items \", err)\n\t}\n\tdefer stmt.Close()\n\n\tres, err := stmt.Exec(\"\", item.Filename, path, size, item.Category, true)\n\tif err != nil {\n\t\tlog.Printf(\"can't insert item into db %e\", err)\n\t\treturn 0, err\n\t}\n\n\tif item.IsNew() {\n\t\tid, err := res.LastInsertId()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error get last inserted id for item %e\", err)\n\t\t}\n\t\titem.ID = int(id)\n\t}\n\treturn item.ID, err\n}", "func Insert(db *sql.DB, order Order, orderTable, itemTable string, items []Item, closedIntercal int) (uint32, error) {\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tdefer func() {\n\t\tif err != nil {\n\t\t\terr = tx.Rollback()\n\t\t} else {\n\t\t\terr = tx.Commit()\n\t\t}\n\t}()\n\n\torder.Closed = order.Created.Add(time.Duration(closedIntercal * int(time.Hour)))\n\n\tsql := fmt.Sprintf(orderSQLString[orderInsert], orderTable)\n\n\tresult, err := db.Exec(sql, order.OrderCode, order.UserID, order.AddressID, order.TotalPrice, order.Promotion, order.Freight, order.Closed)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif affected, _ := result.RowsAffected(); affected == 0 {\n\t\treturn 0, errOrderInsert\n\t}\n\n\tID, err := result.LastInsertId()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\torder.ID = uint32(ID)\n\n\tfor _, x := range items {\n\t\tsql := fmt.Sprintf(orderSQLString[itemInsert], itemTable)\n\n\t\tresult, err := db.Exec(sql, x.ProductID, order.ID, x.Count, x.Price, x.Discount)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tif affected, _ := result.RowsAffected(); affected == 0 {\n\t\t\treturn 0, errItemInsert\n\t\t}\n\t}\n\n\treturn order.ID, nil\n}", "func InsertContentItem(item models.Content) (bson.M, error) {\n\titem.SetCreationDate(time.Now())\n\titem.SetUpdateDate(time.Now())\n\tresult, err := db.Collection(contentCollection).InsertOne(context.Background(), item)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn nil, err\n\t}\n\tnewID := result.InsertedID\n\tid := string(newID.(primitive.ObjectID).Hex())\n\treturn GetContentItem(id)\n}", "func (s *Server) insertItems(request *restful.Request, response *restful.Response) {\n\t// Authorize\n\tif !s.auth(request, response) {\n\t\treturn\n\t}\n\t// Add ratings\n\titems := make([]data.Item, 0)\n\tif err := request.ReadEntity(&items); err != nil {\n\t\tbadRequest(response, err)\n\t\treturn\n\t}\n\t// Insert items\n\tvar count int\n\tfor _, item := range items {\n\t\terr := s.dataStore.InsertItem(data.Item{ItemId: item.ItemId, Timestamp: item.Timestamp, Labels: item.Labels})\n\t\tcount++\n\t\tif err != nil {\n\t\t\tinternalServerError(response, err)\n\t\t\treturn\n\t\t}\n\t}\n\tok(response, Success{RowAffected: count})\n}", "func (ctx *TestContext) addItem(fields map[string]string) {\n\tdbFields := make(map[string]interface{})\n\tfor key, value := range fields {\n\t\tif key == \"item\" {\n\t\t\tkey = \"id\"\n\t\t}\n\n\t\tswitch {\n\t\tcase strings.HasSuffix(key, \"id\"):\n\t\t\tdbFields[key] = ctx.getReference(value)\n\t\tcase value[0] == ReferencePrefix:\n\t\t\tdbFields[key] = value[1:]\n\t\tdefault:\n\t\t\tdbFields[key] = value\n\t\t}\n\t}\n\n\titemKey := strconv.FormatInt(dbFields[\"id\"].(int64), 10)\n\n\tif oldFields, ok := ctx.dbTables[\"items\"][itemKey]; ok {\n\t\tdbFields = mergeFields(oldFields, dbFields)\n\t}\n\n\tif _, ok := dbFields[\"type\"]; !ok {\n\t\tdbFields[\"type\"] = \"Task\"\n\t}\n\tif _, ok := dbFields[\"default_language_tag\"]; !ok {\n\t\tdbFields[\"default_language_tag\"] = \"en\"\n\t}\n\tif _, ok := dbFields[\"text_id\"]; !ok && fields[\"item\"][0] == ReferencePrefix {\n\t\tdbFields[\"text_id\"] = fields[\"item\"][1:]\n\t}\n\n\tctx.addInDatabase(\"items\", itemKey, dbFields)\n}", "func (s *Server) insertItems(request *restful.Request, response *restful.Response) {\n\t// Authorize\n\tif !s.auth(request, response) {\n\t\treturn\n\t}\n\t// Add ratings\n\titems := make([]data.Item, 0)\n\tif err := request.ReadEntity(&items); err != nil {\n\t\tbadRequest(response, err)\n\t\treturn\n\t}\n\t// Insert items\n\tvar count int\n\tfor _, item := range items {\n\t\terr := s.DataStore.InsertItem(data.Item{ItemId: item.ItemId, Timestamp: item.Timestamp, Labels: item.Labels})\n\t\tcount++\n\t\tif err != nil {\n\t\t\tinternalServerError(response, err)\n\t\t\treturn\n\t\t}\n\t}\n\tok(response, Success{RowAffected: count})\n}", "func CreateItem(c *gin.Context) {\n\t// Validate input\n\tvar input CreateItemInput\n\tif err := c.ShouldBindJSON(&input); err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\t// Create item\n\titem := models.Item{\n\t\tName: input.Name,\n\t\tType: input.Type,\n\t\tRarity: input.Rarity,\n\t\tCost: input.Cost}\n\tmodels.DB.Create(&item)\n\n\tc.JSON(http.StatusOK, gin.H{\"data\": item})\n}", "func (d *Database) InsertItems(items []*structs.Item) error {\n\tif len(items) == 0 {\n\t\tlog.Trace(\"InsertItems() called with empty list\")\n\t\treturn nil\n\t}\n\n\td.lock.Lock()\n\tdefer d.lock.Unlock()\n\n\tif err := d.checkClosed(); err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\n\tinsertColumns := structs.ItemInsertColumns\n\tinsertPlaceholders := structs.ItemInsertPlaceholders\n\n\tif d.conf.Dedupe {\n\t\t// Allow duplicates within the same feed\n\t\t// The unhandled corner case is where multiple feeds have 'legitimate'\n\t\t// duplicates, but I don't think it's worth the effort to handle.\n\t\tinsertColumns += \", read\"\n\t\tinsertPlaceholders += `,\n\t\t\t\t(SELECT EXISTS (SELECT url FROM items WHERE url = ? AND feedid != ?))`\n\t}\n\n\tsql := insertSQL(\"items\", insertColumns, insertPlaceholders)\n\tbinds := []interface{}{}\n\n\tfor _, i := range items {\n\t\t// TODO -- ON CONFLICT UPDATE if we want to handle updates\n\t\tlog.Tracef(\"Attempting to insert [%s]\", i)\n\t\tinsertValues := i.InsertValues()\n\t\tif d.conf.Dedupe {\n\t\t\tinsertValues = append(insertValues, i.URL(), i.FeedID())\n\t\t}\n\n\t\tbinds = append(binds, insertValues...)\n\t}\n\n\tlog.Debugf(\"Inserting %d potentially new items\", len(items))\n\n\ttx, err := d.db.Begin()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\tdefer tx.Rollback()\n\n\t_, err = tx.Exec(strings.Repeat(sql, len(items)), binds...)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func insertRepoItem(repoItems *[]models.RepoItem, timeEntryId uint) {\n\tdbConn := ConnectDB()\n\tquery := `call sp_time_repoitem_insert($1, $2, $3, $4, $5, $6, $7)`\n\n\t// Loop through the linked repository items to the database with a link to this\n\t// new time entry, using the sp_time_repoitem_insert stored procedure\n\tfor _, r := range *repoItems {\n\t\tif r.Id == 0 {\n\t\t\tdbConn.Exec(query, timeEntryId, r.Created, r.ItemIdSource, r.ItemType, r.Source, r.RepoName, r.Description)\n\t\t}\n\t}\n}", "func (db Database) NewItem(item *models.Item) error {\n\tvar id string\n\tvar createdAt time.Time\n\n\tquery := `INSERT INTO items (name, description) VALUES ($1, $2) RETURNING id, created_at;`\n\n\tif err := db.Conn.QueryRow(query, item.Name, item.Description).Scan(&id, &createdAt); err != nil {\n\t\treturn nil\n\t}\n\n\titem.ID = id\n\titem.Creation = createdAt\n\n\treturn nil\n}", "func Insert(collection string, item interface{}) error {\n\tsession, db, err := GetGlobalSessionFactory().GetSession()\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\tdefer session.Close()\n\n\treturn db.C(collection).Insert(item)\n}", "func (s *ExtractLogItemDao) SaveItem(item domain.ExtractLogItem) error {\n\tuuid := uuid.New()\n\titem.ID = uuid.String()\n\titem.DateInserted = time.Now().Format(\"20060102 15:04:05\")\n\n\tdbSession := session.Must(session.NewSession())\n\tclient := dynamodb.New(dbSession, aws.NewConfig().WithEndpoint(s.endpoint).WithRegion(s.region))\n\n\tav, err := dynamodbattribute.MarshalMap(item)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tinput := &dynamodb.PutItemInput{\n\t\tItem: av,\n\t\tTableName: aws.String(\"ExtractLogItems\"),\n\t}\n\n\t_, err = client.PutItem(input)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (i *Item) Create() error {\n\tif len(i.UserUUID) < MinIDLength {\n\t\treturn validationError{fmt.Errorf(\"user_uuid too short\")}\n\t}\n\n\tif i.UUID == \"\" {\n\t\tid := uuid.New()\n\t\ti.UUID = uuid.Must(id, nil).String()\n\t}\n\ti.CreatedAt = time.Now().UTC()\n\ti.UpdatedAt = time.Now().UTC()\n\tlogger.LogIfDebug(\"Create:\", i.UUID)\n\treturn db.Query(\n\t\tstrings.TrimSpace(`\n\t\tINSERT INTO items (\n\t\t\tuuid, user_uuid, content, content_type, enc_item_key, auth_hash, deleted, created_at, updated_at\n\t\t) VALUES(?,?,?,?,?,?,?,?,?)`),\n\t\ti.UUID, i.UserUUID, i.Content, i.ContentType, i.EncItemKey, i.AuthHash, i.Deleted, i.CreatedAt, i.UpdatedAt,\n\t)\n}", "func CreateItem(dbc *sqlx.DB, r Item) (Item, error) {\n\tr.Created = time.Now()\n\tr.Modified = time.Now()\n\n\tif _, err := list.SelectList(dbc, r.ListID); errors.Cause(err) == sql.ErrNoRows {\n\t\treturn Item{}, sql.ErrNoRows\n\t}\n\n\tstmt, err := dbc.Prepare(insert)\n\tif err != nil {\n\t\treturn Item{}, errors.Wrap(err, \"insert new item row\")\n\t}\n\n\tdefer func() {\n\t\tif err := stmt.Close(); err != nil {\n\t\t\tlogrus.WithError(errors.Wrap(err, \"close psql statement\")).Info(\"create item\")\n\t\t}\n\t}()\n\n\trow := stmt.QueryRow(r.ListID, r.Name, r.Quantity, r.Created, r.Modified)\n\n\tif err = row.Scan(&r.ID); err != nil {\n\t\treturn Item{}, errors.Wrap(err, \"get inserted row id\")\n\t}\n\n\treturn r, nil\n}", "func (r *ItemsRepository) save(i *Item) error {\n\tif query := r.databaseHandler.DB().Create(&i); query.Error != nil {\n\t\treturn query.Error\n\t}\n\treturn nil\n}", "func AddOrderItem(db *sqlx.DB) gin.HandlerFunc {\n\n\treturn func(c *gin.Context) {\n\t\tvar newItem OrderItem\n\n\t\terr := c.Bind(&newItem)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tc.JSON(422, gin.H{\"error\": \"Data provided in wrong format, unable to complete request.\"})\n\t\t\treturn\n\t\t}\n\n\t\tif ok := auth.MustUser(c, newItem.UserName); !ok {\n\t\t\tc.AbortWithError(401, errors.NewAPIError(401, \"tried to add order item to another user's order\", \"internal server error\", c))\n\t\t\treturn\n\t\t}\n\n\t\tnewItem.UpdatedAt = time.Now()\n\n\t\t// check to make sure sale is still open\n\t\tsaleOpen, err := CheckOrderOpen(newItem.OrderId, db)\n\t\tif err != nil {\n\t\t\tc.AbortWithError(503, errors.NewAPIError(503, fmt.Sprintf(\"CheckOpenOrder returned an error : %s\", err), \"Internal Server Error\", c))\n\t\t\treturn\n\t\t}\n\t\tif !saleOpen {\n\t\t\tc.AbortWithError(409, errors.NewAPIError(409, \"sale not open\", \"Cannot fufill request because the associated sale is not open.\", c))\n\t\t\treturn\n\t\t}\n\n\t\tvar returnID int\n\t\tdbErr := db.Get(&returnID, `INSERT INTO gaea.orderitem\n\t\t\t(orderitem_id, order_id, inventory_id, qty, updated_at, user_name)\n\t\t\tVALUES (DEFAULT, $1, $2, $3, $4, $5) RETURNING orderitem_id`, newItem.OrderId, newItem.InventoryId, newItem.Qty, newItem.UpdatedAt, newItem.UserName)\n\t\tif dbErr != nil {\n\t\t\tfmt.Println(\"error on db entry\")\n\t\t\tfmt.Println(dbErr)\n\t\t\tc.AbortWithError(503, errors.NewAPIError(503, \"failed on inserting order items\", \"internal server error\", c))\n\t\t\treturn\n\t\t}\n\t\tnewItem.OrderitemId = returnID\n\t\tc.JSON(200, newItem)\n\t}\n}", "func (c *Controller) CreateItem() http.Handler {\n\treturn http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) {\n\t\tu := utility.New(writer, req)\n\n\t\titem := &Item{}\n\t\terr := u.UnmarshalWithValidation(item)\n\t\tif err != nil {\n\t\t\tc.logger.Warn(err)\n\t\t\tu.WriteJSONError(err, http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tsession := c.store.DB.Copy()\n\t\tdefer session.Close()\n\n\t\tcollection := session.DB(c.databaseName).C(ItemsCollection)\n\t\tcount, err := collection.Find(bson.M{\"code\": item.Code}).Count()\n\t\tif err != nil {\n\t\t\tc.logger.Error(err)\n\t\t\tu.WriteJSONError(\"Something Wrong, Please try again later\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tif count != 0 {\n\t\t\tu.WriteJSONError(\"code exist\", http.StatusConflict)\n\t\t\treturn\n\t\t}\n\n\t\titem.ID = bson.NewObjectId()\n\t\ttimeNow := time.Now()\n\t\titem.CreatedDate = &timeNow\n\t\titem.CreatedBy = \"todo\"\n\t\terr = collection.Insert(item)\n\n\t\tif err != nil {\n\t\t\tc.logger.Error(err)\n\t\t\tu.WriteJSONError(\"code exist\", http.StatusInternalServerError)\n\t\t\tpanic(err)\n\t\t}\n\n\t\tu.WriteJSON(item.ID, http.StatusCreated)\n\t})\n}", "func (db *MongoDatabase) Insert(collection_name string, item interface{}) error {\n\tcurrent_session := db.GetSession()\n\tdefer current_session.Close()\n\n\tcollection := current_session.DB(db.name).C(collection_name)\n\n\terr := collection.Insert(item)\n\n\treturn convertMgoError(err)\n}", "func (o *CMFSlideItem) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no cmf_slide_item provided for insertion\")\n\t}\n\n\tvar err error\n\n\tif err := o.doBeforeInsertHooks(ctx, exec); err != nil {\n\t\treturn err\n\t}\n\n\tnzDefaults := queries.NonZeroDefaultSet(cmfSlideItemColumnsWithDefault, o)\n\n\tkey := makeCacheKey(columns, nzDefaults)\n\tcmfSlideItemInsertCacheMut.RLock()\n\tcache, cached := cmfSlideItemInsertCache[key]\n\tcmfSlideItemInsertCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl, returnColumns := columns.InsertColumnSet(\n\t\t\tcmfSlideItemAllColumns,\n\t\t\tcmfSlideItemColumnsWithDefault,\n\t\t\tcmfSlideItemColumnsWithoutDefault,\n\t\t\tnzDefaults,\n\t\t)\n\n\t\tcache.valueMapping, err = queries.BindMapping(cmfSlideItemType, cmfSlideItemMapping, wl)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcache.retMapping, err = queries.BindMapping(cmfSlideItemType, cmfSlideItemMapping, returnColumns)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(wl) != 0 {\n\t\t\tcache.query = fmt.Sprintf(\"INSERT INTO `cmf_slide_item` (`%s`) %%sVALUES (%s)%%s\", strings.Join(wl, \"`,`\"), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1))\n\t\t} else {\n\t\t\tcache.query = \"INSERT INTO `cmf_slide_item` () VALUES ()%s%s\"\n\t\t}\n\n\t\tvar queryOutput, queryReturning string\n\n\t\tif len(cache.retMapping) != 0 {\n\t\t\tcache.retQuery = fmt.Sprintf(\"SELECT `%s` FROM `cmf_slide_item` WHERE %s\", strings.Join(returnColumns, \"`,`\"), strmangle.WhereClause(\"`\", \"`\", 0, cmfSlideItemPrimaryKeyColumns))\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning)\n\t}\n\n\tvalue := reflect.Indirect(reflect.ValueOf(o))\n\tvals := queries.ValuesFromMapping(value, cache.valueMapping)\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.query)\n\t\tfmt.Fprintln(writer, vals)\n\t}\n\tresult, err := exec.ExecContext(ctx, cache.query, vals...)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to insert into cmf_slide_item\")\n\t}\n\n\tvar lastID int64\n\tvar identifierCols []interface{}\n\n\tif len(cache.retMapping) == 0 {\n\t\tgoto CacheNoHooks\n\t}\n\n\tlastID, err = result.LastInsertId()\n\tif err != nil {\n\t\treturn ErrSyncFail\n\t}\n\n\to.ID = uint(lastID)\n\tif lastID != 0 && len(cache.retMapping) == 1 && cache.retMapping[0] == cmfSlideItemMapping[\"id\"] {\n\t\tgoto CacheNoHooks\n\t}\n\n\tidentifierCols = []interface{}{\n\t\to.ID,\n\t}\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.retQuery)\n\t\tfmt.Fprintln(writer, identifierCols...)\n\t}\n\terr = exec.QueryRowContext(ctx, cache.retQuery, identifierCols...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to populate default values for cmf_slide_item\")\n\t}\n\nCacheNoHooks:\n\tif !cached {\n\t\tcmfSlideItemInsertCacheMut.Lock()\n\t\tcmfSlideItemInsertCache[key] = cache\n\t\tcmfSlideItemInsertCacheMut.Unlock()\n\t}\n\n\treturn o.doAfterInsertHooks(ctx, exec)\n}", "func (ctx *TestContext) addItemItem(parentItem, childItem string) {\n\tparentItemID := ctx.getReference(parentItem)\n\tchildItemID := ctx.getReference(childItem)\n\n\tctx.addInDatabase(\n\t\t\"items_items\",\n\t\tstrconv.FormatInt(parentItemID, 10)+\",\"+strconv.FormatInt(childItemID, 10),\n\t\tmap[string]interface{}{\n\t\t\t\"parent_item_id\": parentItemID,\n\t\t\t\"child_item_id\": childItemID,\n\t\t\t\"child_order\": rand.Int31n(1000),\n\t\t},\n\t)\n}", "func insertItem(r *http.Request, svc *mirror.Service) string {\n\tc := appengine.NewContext(r)\n\tc.Infof(\"Inserting Timeline Item\")\n\n\tbody := mirror.TimelineItem{\n\t\tNotification: &mirror.NotificationConfig{Level: \"AUDIO_ONLY\"},\n\t}\n\tif r.FormValue(\"html\") == \"on\" {\n\t\tbody.Html = r.FormValue(\"message\")\n\t} else {\n\t\tbody.Text = r.FormValue(\"message\")\n\t}\n\n\tvar media io.Reader = nil\n\tmediaLink := r.FormValue(\"imageUrl\")\n\tif mediaLink != \"\" {\n\t\tif strings.HasPrefix(mediaLink, \"/\") {\n\t\t\tmediaLink = fullURL(r.Host, mediaLink)\n\t\t}\n\t\tc.Infof(\"Downloading media from: %s\", mediaLink)\n\t\tclient := urlfetch.Client(c)\n\t\tif resp, err := client.Get(mediaLink); err != nil {\n\t\t\tc.Errorf(\"Unable to retrieve media: %s\", err)\n\t\t} else {\n\t\t\tdefer resp.Body.Close()\n\t\t\tmedia = resp.Body\n\t\t}\n\t}\n\n\tif _, err := svc.Timeline.Insert(&body).Media(media).Do(); err != nil {\n\t\treturn fmt.Sprintf(\"Unable to insert timeline item: %s\", err)\n\t}\n\treturn \"A timeline item has been inserted.\"\n}", "func (d DB) PutItem(ctx context.Context) error {\n\titem := item{\n\t\tPK: uuid.NewString(),\n\t\tValue: uuid.NewString(),\n\t}\n\tav, err := attributevalue.MarshalMap(item)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = d.client.PutItem(ctx, &dynamodb.PutItemInput{\n\t\tItem: av,\n\t\tTableName: aws.String(d.tableName),\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *Storage) Create(item interface{}) error {\n\tses := s.GetDBSession()\n\tdefer ses.Close()\n\terr := ses.DB(s.database).C(s.table).Insert(item)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func insertObject(object *remember.DataObject, connection *sql.DB) error {\n\tstatement, err := connection.Prepare(CREATE)\n\tif nil != err {\n\t\treturn err\n\t}\n\tdefer statement.Close()\n\n\tobject.CreatedAt = time.Now()\n\tobject.UpdatedAt = time.Now()\n\n\tresponse, err := statement.Exec(\n\t\tobject.Title,\n\t\tobject.GroupId,\n\t\tobject.Payload,\n\t\tobject.CreatedAt.Unix(),\n\t\tobject.UpdatedAt.Unix(),\n\t)\n\tif nil != err {\n\t\treturn err\n\t}\n\n\tobject.ID, err = response.LastInsertId()\n\treturn err\n}", "func (m *SnippetModel) Insert(title, content, expires string) (int, error) {\n\t// Start a transaction\n\t// Each action that is done is atomic in nature:\n\t// All statements are executed successfully or no statement is executed\n\ttx, err := m.DB.Begin()\n\tif err != nil {\n\t\treturn 0, nil\n\t}\n\n\t// Statement to insert data to the database\n\tstmt := `INSERT INTO snippets (title, content, created, expires)\n\tVALUES(?, ?, UTC_TIMESTAMP(), DATE_ADD(UTC_TIMESTAMP(), INTERVAL ? DAY))`\n\t// Pass in the placeholder parameters aka the ? in the stmt\n\tresult, err := tx.Exec(stmt, title, content, expires)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn 0, err\n\t}\n\t// Return the id of the inserted record in the snippets table\n\tid, err := result.LastInsertId()\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn 0, err\n\t}\n\n\t// id is an int64 to convert it to a int\n\terr = tx.Commit()\n\treturn int(id), err\n\n}", "func (sq *SQ3Driver) Insert(key string, obj *DBObj, force bool) error {\n\t// For now, just insert the key (and make sure the key matches the obj.Key\n\tif key != obj.Key {\n\t\treturn fmt.Errorf(\"Error: key does not match obj.key:\\n key: %v\\nobj.Key:%v\", key, obj.Key)\n\t}\n\n\t// If force is NOT set, check for a duplicate\n\tfound, err := sq.queryExists(fmt.Sprintf(\"SELECT key FROM %v WHERE key=$1\", dbTable), key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\taction := \"INSERT\"\n\n\t// If we have one, either error out, or delete\n\tif found {\n\t\tif force {\n\t\t\t// We could also update, but, I'm lazy\n\t\t\terr = sq.Delete(key)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\taction = \"UPDATE\"\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"Error: can not insert: item already exists\")\n\t\t}\n\t}\n\n\t// And, do our insert\n\t_, err = sq.DB.Exec(fmt.Sprintf(\"INSERT INTO %v(key, lc_key) VALUES (?, ?)\", dbTable), key, strings.ToLower(key))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"%v: %v\\n\", action, key)\n\treturn nil\n}", "func (s *Store) Put(item storage.Item) error {\n\tvalue, err := item.Marshal()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed serializing: %w\", err)\n\t}\n\n\treturn s.db.Put(key(item), value, nil)\n}", "func (cartData *CartData) CreateCartItem(CartID, UserID uint64) error {\n\tconn, err := db.MySQLConnect()\n\t// defer conn.Close()\n\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tconn.Close()\n\t\treturn err\n\t}\n\n\tcartItem := CartItem{\n\t\tCartID: CartID,\n\t}\n\n\tlog.Printf(\"Duzina: %d\", len(cartData.Items))\n\tfor _, item := range cartData.Items {\n\t\tcartItem.ItemID = item.ItemID\n\t\tcartItem.Amount = item.Amount\n\t\tlog.Printf(\"ITEMID: %d\", item.ItemID)\n\t\tconn.Create(&cartItem)\n\t\t// if createErr != nil {\n\t\t// \tlog.Println(\"Drugi fail\")\n\t\t// \tlog.Println(createErr.Error)\n\t\t// \tconn.Close()\n\t\t// \treturn createErr.Error\n\t\t// }\n\t\t// portions := GetPortionByCategoryID(item.CategoryID)\n\t\t// image := GetImageByItemID(item.ItemID)\n\t\t// ingredients := GetIngredientsByItemID(item.ItemID)\n\t\t// homeItem := HomeItem{\n\t\t// \tItem: item,\n\t\t// \tPortion: portions,\n\t\t// \tIngredient: ingredients,\n\t\t// \tImage: image,\n\t\t// }\n\t\t// homeItems = append(homeItems, homeItem)\n\t}\n\n\tdeliveryAt := time.Now().Add(DefaultOrderWaitTime).Format(\"H:i:s\")\n\tparsedDeliveryAt, parseErr := time.Parse(\"H:i:s\", deliveryAt)\n\tif parseErr != nil {\n\t\tlog.Println(parseErr.Error())\n\t}\n\n\torder := Order{\n\t\tUserID: UserID,\n\t\tCartID: CartID,\n\t\tIsCanceled: 0,\n\t\tIsDelivered: 0,\n\t\tIsAccepted: \"pending\",\n\t\tDeliveryAt: parsedDeliveryAt,\n\t\tCreatedAt: time.Now(),\n\t}\n\n\tconn.Create(&order)\n\t// if createErr != nil {\n\t// \tlog.Println(\"CreateERR\")\n\t// \tlog.Println(createErr.Error)\n\t// }\n\tconn.Close()\n\n\treturn nil\n}", "func (d *DynamoDB) SaveItem(config schema.Template, tableName string) error {\n\titem, err := dynamodbattribute.MarshalMap(config)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to DynamoDB marshal Record, %v\", err)\n\t}\n\n\tinput := &dynamodb.PutItemInput{\n\t\tItem: item,\n\t\tReturnConsumedCapacity: aws.String(\"TOTAL\"),\n\t\tTableName: aws.String(tableName),\n\t}\n\n\t_, err = d.Client.PutItem(input)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogrus.Debugf(\"Item is successfully created: %s\", *config.Name)\n\n\treturn nil\n}", "func (r *r) Insert(description string) (*internal.Item, error) {\n\tuuid := uuid.New()\n\titem := internal.Item{Description: description, ID: uuid, Done: false}\n\tb, err := json.Marshal(&item)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"marshalling item: %w\", err)\n\t}\n\tif status := r.redisClient.Set(uuid.String(), b, 0); status.Err() != nil {\n\t\treturn nil, fmt.Errorf(\"inserting item: %w\", status.Err())\n\t}\n\treturn &item, nil\n}", "func Insert(db gorp.SqlExecutor, i interface{}) error {\n\treturn Mapper.Insert(db, i)\n}", "func (db *BotDB) AddItem(item string) (uint64, error) {\n\tvar id uint64\n\terr := db.standardErr(db.sqlAddItem.QueryRow(item).Scan(&id))\n\n\tif db.CheckError(\"AddItem\", err) != nil {\n\t\treturn 0, err\n\t}\n\treturn id, nil\n}", "func (s *Storage) Create(item interface{}) error {\n\tses := s.GetDBSession()\n\tdefer ses.Close()\n\terr := ses.DB(s.database).C(s.collection).Insert(item)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func putItem(bk *book, stage string) error {\n fmt.Println(\"creating input\")\n input := &dynamodb.PutItemInput{\n TableName: aws.String(getTableName(stage)),\n Item: map[string]*dynamodb.AttributeValue{\n \"ISBN\": {\n S: aws.String(bk.ISBN),\n },\n \"Title\": {\n S: aws.String(bk.Title),\n },\n \"Author\": {\n S: aws.String(bk.Author),\n },\n },\n }\n fmt.Println(\"starting to create item:\", input)\n _, err := db.PutItem(input)\n fmt.Println(\"done to create item:\", err)\n return err\n}", "func Insert(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tif r.Body == nil {\n\t\thttp.Error(w, http.StatusText(400), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tstnds, err := insertDB(r)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tsjson, err := json.Marshal(stnds)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusCreated) // 201\n\tfmt.Fprintf(w, \"%s\\n\", sjson)\n}", "func insert(w http.ResponseWriter, r *http.Request) {\n\tvar todo Todo\n\ttodo.Todo = r.FormValue(\"todo\")\n\ttodo.ID = uuid.NewV4().String()\n\ttodo.CreatedAt = time.Now().UTC()\n\n\t_, err := mainDB.Exec(\"INSERT INTO todos(id, todo, created_at) values($1, $2, $3)\", todo.ID, todo.Todo, todo.CreatedAt)\n\tcheckErr(err)\n\tjsonB, errMarshal := json.Marshal(todo)\n\tcheckErr(errMarshal)\n\n\tw.Header().Set(\"Location\", \"/\")\n\tw.WriteHeader(301)\n\tw.Write(jsonB)\n}", "func (model *SnippetModel) Insert(title, content, expires string) (int, error) {\n\tstmt := `INSERT INTO snippets (title, content, created, expires)\n\tVALUES(?, ?, UTC_TIMESTAMP(), DATE_ADD(UTC_TIMESTAMP(), INTERVAL ? DAY))`\n\n\tresult, err := model.DB.Exec(stmt, title, content, expires)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tid, err := result.LastInsertId()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn int(id), nil\n}", "func (s *CqlStore) Write(item Item) error {\n\tif item.IsEmpty() {\n\t\treturn NewEmptyItemError()\n\t}\n\tif s.session == nil {\n\t\treturn NewStoreClosedError()\n\t}\n\tb, err := json.Marshal(item.Contents)\n\tif err != nil {\n\t\treturn NewItemMarshallError(err)\n\t}\n\terr = s.session.Query(\"insert into items (id, updated, status, type, name, contents) values(?,now(),?,?,?,?)\",\n\t\tIDToString(item.ID), \"ALIVE\", item.Type, item.Name, string(b)).Exec()\n\tif err != nil {\n\t\treturn errors.Wrap(err, 0)\n\t}\n\treturn nil\n}", "func (db *DBService) PutItem(ctx context.Context, o *Object) error {\n\t// log.Printf(\"Put item for %s in DynamoDB\\n\", o.Key)\n\n\titem := &Item{\n\t\tObjectKey: o.Key,\n\t\tSize: o.Size,\n\t\tSequencer: o.Sequencer,\n\t\tJobStatus: \"STARTED\",\n\t\tStartTime: time.Now().Format(\"2006/01/02 15:04:05\"),\n\t\tStartTimestamp: time.Now().Unix(),\n\t}\n\n\titemAttr, err := attributevalue.MarshalMap(item)\n\n\tif err != nil {\n\t\tlog.Printf(\"Unable to Marshal DynamoDB attributes for %s - %s\\n\", o.Key, err.Error())\n\t} else {\n\t\tinput := &dynamodb.PutItemInput{\n\t\t\tTableName: &db.tableName,\n\t\t\tItem: itemAttr,\n\t\t}\n\n\t\t_, err = db.client.PutItem(ctx, input)\n\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to put item for %s in DynamoDB - %s\\n\", o.Key, err.Error())\n\t\t\t// return nil\n\t\t}\n\t}\n\n\treturn err\n}", "func (m *ItemVariant) Save(fields ...string) (err error) {\n\to := orm.NewOrm()\n\tif m.ID > 0 {\n\t\t_, err = o.Update(m, fields...)\n\t} else {\n\t\tm.ID, err = o.Insert(m)\n\t}\n\treturn\n}", "func (m *SnippetModel) Insert(title, content, expires string) (int, error) {\n\t// Create the SQL statement we want to execute. It's split over several lines\n\t// for readability - so it's surrounded by backquotes instead of normal double quotes\n\tstmt := `INSERT INTO snippets (title, content, created, expires)\n\tvalues (?, ?, UTC_TIMESTAMP(), DATE_ADD(UTC_TIMESTAMP, INTERVAL ? DAY))`\n\n\t// Use the Exec() method on the embedded connection pool to execute the statement.\n\t// The first parameter is the SQL statement followed by the table fields.\n\t// The method returns a sql.Result object which contains some basic information\n\t// about what happened when the statement was executed\n\tresult, err := m.DB.Exec(stmt, title, content, expires)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// Use the LastInsertId() method on the result object to get the ID of our\n\t// newly inserted record in the snippets table.\n\tid, err := result.LastInsertId()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// The ID returned has the type int64 so we convert it to an int type before returning\n\treturn int(id), nil\n}", "func InsertLineItem(db *sql.DB, l LineItem) error {\n\tinsertSQL := `INSERT INTO financials(company, start_date, end_date, key, value) VALUES (?, ?, ?, ?, ?)`\n\tstatement, err := db.Prepare(insertSQL)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to prepare insert sql statement: %v\", err)\n\t\treturn err\n\t}\n\t_, err = statement.Exec(l.Company, l.Start_date, l.End_date, l.Key, l.Value)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to insert row: %v\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func postItem(w http.ResponseWriter, r *http.Request) {\n\n\tuser := getParam(r, USER_ID)\n\tproductId := getParam(r, ITEM_ID)\n\n\tcode := getUserCode(r)\n\tredirectURL := HOST + \"/\" + user + \"/items/\" + productId\n\n\tclient, err := sdk.Meli(CLIENT_ID, code, CLIENT_SECRET, redirectURL)\n\n\titem := \"{\\\"title\\\":\\\"Item de test - No Ofertar\\\",\\\"category_id\\\":\\\"MLA1912\\\",\\\"price\\\":10,\\\"currency_id\\\":\\\"ARS\\\",\\\"available_quantity\\\":1,\\\"buying_mode\\\":\\\"buy_it_now\\\",\\\"listing_type_id\\\":\\\"bronze\\\",\\\"condition\\\":\\\"new\\\",\\\"description\\\": \\\"Item:, Ray-Ban WAYFARER Gloss Black RB2140 901 Model: RB2140. Size: 50mm. Name: WAYFARER. Color: Gloss Black. Includes Ray-Ban Carrying Case and Cleaning Cloth. New in Box\\\",\\\"video_id\\\": \\\"YOUTUBE_ID_HERE\\\",\\\"warranty\\\": \\\"12 months by Ray Ban\\\",\\\"pictures\\\":[{\\\"source\\\":\\\"http://upload.wikimedia.org/wikipedia/commons/f/fd/Ray_Ban_Original_Wayfarer.jpg\\\"},{\\\"source\\\":\\\"http://en.wikipedia.org/wiki/File:Teashades.gif\\\"}]}\"\n\n\tresponse, err := client.Post(\"/items/\", item)\n\n\tif err != nil {\n\t\tlog.Printf(\"Error: \", err)\n\t\treturn\n\t}\n\tprintOutput(w, response)\n}", "func (d *DB) Insert(title string, status string) error {\n\tdb, err := gorm.Open(\"sqlite3\", \"model/DB/test.sqlite3\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdb.Create(&Todo{Title: title, Status: status})\n\tdb.Close()\n\n\treturn err\n}", "func (s *nodeBlock) insertItemAt(index int, item Metadata) {\n\t_ = s.items[maxItems-1-s.itemsSize]\n\tcopy(s.items[index+1:], s.items[index:])\n\ts.items[index] = item\n\ts.itemsSize++\n\ts.markDirty()\n}", "func (f *FakeClient) Insert(p *purchase.Purchase) error {\n\treturn nil\n}", "func (item *Item) commit() {\n\tDB.Where(\"id = ?\", item.ID).FirstOrCreate(&item)\n\tDB.Model(item).Update(&item)\n}", "func (r *TaskRepository) Insert(db db.DB, Task *entities.Task) error {\n\t_, err := db.NamedExec(`\n\tINSERT INTO tasks (uuid,title,user_id,status,created_at,updated_at)\n\tVALUES (:uuid, :title, :user_id, :status, now(), now())`, Task)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error inserting task to db: %w\", err)\n\t}\n\n\treturn nil\n}", "func (a *Article) Insert(db *database.DB) error {\n\tq := `insert into bot.articles (title, link, image, published) values (:title, :link, :image, :published);`\n\n\tstmt, stmtErr := db.PrepareNamed(q)\n\tif stmtErr != nil {\n\t\treturn stmtErr\n\t}\n\tdefer stmt.Close()\n\n\t_, execErr := stmt.Exec(a)\n\n\treturn execErr\n}", "func (Model) Insert(model interface{}) {\n\tdb.Insert(model)\n}", "func (c *MySQLClient) Insert(p *purchase.Purchase) error {\n\tif p.ID != 0 {\n\t\treturn fmt.Errorf(\"purchase cannot have a preexisting ID\")\n\t}\n\n\tvar err error\n\tvar buyBytes, sellBytes []byte\n\tif p.BuyOrder != nil {\n\t\tbuyBytes, err = json.Marshal(p.BuyOrder)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to marshal buy order: %v\", err)\n\t\t}\n\t}\n\tif p.SellOrder != nil {\n\t\tsellBytes, err = json.Marshal(p.SellOrder)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to marshal sell order: %v\", err)\n\t\t}\n\t}\n\n\tquery := `INSERT INTO trader_one(buy_order, sell_order) VALUES (?, ?)`\n\tctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancelFunc()\n\tstmt, err := c.db.PrepareContext(ctx, query)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to prepare SQL statement: %v\", err)\n\t}\n\tdefer stmt.Close()\n\n\tres, err := stmt.ExecContext(ctx, jsonString(buyBytes), jsonString(sellBytes))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to insert row: %v\", err)\n\t}\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to find new ID: %v\", err)\n\t}\n\tp.ID = id\n\treturn nil\n}", "func (xpcgi *XPriCompGroupItem) Insert(db XODB) error {\n\tvar err error\n\n\t// if already exist, bail\n\tif xpcgi._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tconst sqlstr = `INSERT INTO x_showroom.x_pri_comp_group_item (` +\n\t\t`name, display_name, type_cd, primary_flag, seq_num, x_pri_comp_group_id, created_by, updated_by, created_at, updated_at` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?, ?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tXOLog(sqlstr, xpcgi.Name, xpcgi.DisplayName, xpcgi.TypeCd, xpcgi.PrimaryFlag, xpcgi.SeqNum, xpcgi.XPriCompGroupID, xpcgi.CreatedBy, xpcgi.UpdatedBy, xpcgi.CreatedAt, xpcgi.UpdatedAt)\n\tres, err := db.Exec(sqlstr, xpcgi.Name, xpcgi.DisplayName, xpcgi.TypeCd, xpcgi.PrimaryFlag, xpcgi.SeqNum, xpcgi.XPriCompGroupID, xpcgi.CreatedBy, xpcgi.UpdatedBy, xpcgi.CreatedAt, xpcgi.UpdatedAt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\txpcgi.ID = uint(id)\n\txpcgi._exists = true\n\n\treturn nil\n}", "func (pm *ProductModel) Insert(product Product) error {\n\tif _, err := pm.DB.Exec(INSERT_PRODUCT_STMT, product.ProductName, product.Price, product.ShortDescription); err != nil {\n\t\tlog.Printf(\"error occured on inserting product : %s\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func add(w http.ResponseWriter, r *http.Request) {\r\n\tif r.Method != \"POST\" {\r\n\t\thttp.Error(w, \"404 not found.\", http.StatusNotFound)\r\n\t\treturn\r\n\t}\r\n\tid, _ := strconv.ParseInt(r.PostFormValue(\"id\"), 10, 64)\r\n\titemsid, _ := strconv.ParseInt(r.PostFormValue(\"item.id\"), 10, 64)\r\n\r\n\t// items given\r\n\titemsof :=content{\r\n\t\tID : itemsid,\r\n\t\tvalue: r.PostFormValue(\"items.value\"),\r\n\t\tcompleted : r.PostFormValue(\"items.completed\"),\r\n\t}\r\n\r\n\t//list given\r\n\ttodo := &toDoList{\r\n\t\tID: id,\r\n\t\titems: itemsof,\r\n\t}\r\n\t//fmt.Println(user)\r\n\tquery := \"INSERT INTO public.item(id, itemId,value,completed) VALUES($1, $2, $3, $4)\"\r\n\terr = db.QueryRow(query, todo.ID, itemsof.ID, itemsof.value,itemsof.completed).Scan(&itemsof.ID)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\tjson.NewEncoder(w).Encode(todo)\r\n}", "func (a *TodoAdapter) Insert(ctx context.Context, t todo.Todo) (domain.ID, error) {\n\tspan, _ := opentracing.StartSpanFromContext(ctx, \"TodoAdapter-Insert\")\n\tdefer span.Finish()\n\n\tvar todoItem Todo\n\n\terr := todoItem.FromModel(&t)\n\n\tif err != nil {\n\t\treturn domain.ZeroID, err\n\t}\n\n\tresult, err := a.collection.InsertOne(ctx, bson.D{\n\t\tprimitive.E{Key: \"_id\", Value: todoItem.ID},\n\t\tprimitive.E{Key: \"title\", Value: todoItem.Title},\n\t\tprimitive.E{Key: \"description\", Value: todoItem.Description},\n\t\tprimitive.E{Key: \"priority_level\", Value: todoItem.Priority},\n\t\tprimitive.E{Key: \"completed\", Value: todoItem.Completed},\n\t\tprimitive.E{Key: \"created_at\", Value: todoItem.CreatedAt},\n\t\tprimitive.E{Key: \"updated_at\", Value: todoItem.UpdatedAt},\n\t})\n\n\tif err != nil {\n\t\treturn domain.ZeroID, err\n\t}\n\n\treturn domain.ID(result.InsertedID.(primitive.ObjectID).Hex()), nil\n}", "func (o *AuthItemGroup) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no auth_item_groups provided for insertion\")\n\t}\n\n\tvar err error\n\tif !boil.TimestampsAreSkipped(ctx) {\n\t\tcurrTime := time.Now().In(boil.GetLocation())\n\n\t\tif o.CreatedAt.IsZero() {\n\t\t\to.CreatedAt = currTime\n\t\t}\n\t\tif queries.MustTime(o.UpdatedAt).IsZero() {\n\t\t\tqueries.SetScanner(&o.UpdatedAt, currTime)\n\t\t}\n\t}\n\n\tif err := o.doBeforeInsertHooks(ctx, exec); err != nil {\n\t\treturn err\n\t}\n\n\tnzDefaults := queries.NonZeroDefaultSet(authItemGroupColumnsWithDefault, o)\n\n\tkey := makeCacheKey(columns, nzDefaults)\n\tauthItemGroupInsertCacheMut.RLock()\n\tcache, cached := authItemGroupInsertCache[key]\n\tauthItemGroupInsertCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl, returnColumns := columns.InsertColumnSet(\n\t\t\tauthItemGroupAllColumns,\n\t\t\tauthItemGroupColumnsWithDefault,\n\t\t\tauthItemGroupColumnsWithoutDefault,\n\t\t\tnzDefaults,\n\t\t)\n\n\t\tcache.valueMapping, err = queries.BindMapping(authItemGroupType, authItemGroupMapping, wl)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcache.retMapping, err = queries.BindMapping(authItemGroupType, authItemGroupMapping, returnColumns)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(wl) != 0 {\n\t\t\tcache.query = fmt.Sprintf(\"INSERT INTO `auth_item_groups` (`%s`) %%sVALUES (%s)%%s\", strings.Join(wl, \"`,`\"), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1))\n\t\t} else {\n\t\t\tcache.query = \"INSERT INTO `auth_item_groups` () VALUES ()%s%s\"\n\t\t}\n\n\t\tvar queryOutput, queryReturning string\n\n\t\tif len(cache.retMapping) != 0 {\n\t\t\tcache.retQuery = fmt.Sprintf(\"SELECT `%s` FROM `auth_item_groups` WHERE %s\", strings.Join(returnColumns, \"`,`\"), strmangle.WhereClause(\"`\", \"`\", 0, authItemGroupPrimaryKeyColumns))\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning)\n\t}\n\n\tvalue := reflect.Indirect(reflect.ValueOf(o))\n\tvals := queries.ValuesFromMapping(value, cache.valueMapping)\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.query)\n\t\tfmt.Fprintln(writer, vals)\n\t}\n\tresult, err := exec.ExecContext(ctx, cache.query, vals...)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to insert into auth_item_groups\")\n\t}\n\n\tvar lastID int64\n\tvar identifierCols []interface{}\n\n\tif len(cache.retMapping) == 0 {\n\t\tgoto CacheNoHooks\n\t}\n\n\tlastID, err = result.LastInsertId()\n\tif err != nil {\n\t\treturn ErrSyncFail\n\t}\n\n\to.ID = int(lastID)\n\tif lastID != 0 && len(cache.retMapping) == 1 && cache.retMapping[0] == authItemGroupMapping[\"id\"] {\n\t\tgoto CacheNoHooks\n\t}\n\n\tidentifierCols = []interface{}{\n\t\to.ID,\n\t}\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.retQuery)\n\t\tfmt.Fprintln(writer, identifierCols...)\n\t}\n\terr = exec.QueryRowContext(ctx, cache.retQuery, identifierCols...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to populate default values for auth_item_groups\")\n\t}\n\nCacheNoHooks:\n\tif !cached {\n\t\tauthItemGroupInsertCacheMut.Lock()\n\t\tauthItemGroupInsertCache[key] = cache\n\t\tauthItemGroupInsertCacheMut.Unlock()\n\t}\n\n\treturn o.doAfterInsertHooks(ctx, exec)\n}", "func (db *DB) Insert(form url.Values, dataFields interface{}) *ResponseMessage {\n\n\t//bucketName := \"master_erp\"\n\t//docID := \"12121\"\n\tbytes := db.ProcessData(form, dataFields)\n\t//db.ProcessData(form, intrfc)\n\t//json.Unmarshal(bytes, intrfc) //***s\n\n\t//fmt.Println(\"DATA>>>>\", intrfc)\n\t//bytes, _ := json.Marshal(intrfc)\n\t//fmt.Println(\"intrfcBytes:\", string(bytes))\n\n\tdocID := form.Get(\"aid\") //docid=aid\n\tbucketName := form.Get(\"bucket\")\n\n\t//json.Unmarshal(bytes, intrfc)\n\tinsertQuery := insertQueryBuilder(bucketName, docID, string(bytes))\n\t//insertQuery := insertQueryBuilder(bucketName, docID, intrfc)\n\n\t//fmt.Println(insertQuery)\n\tnqlInsertStatement := sqlStatementJSON(insertQuery)\n\t//fmt.Println()\n\t//fmt.Println(nqlInsertStatement, form)\n\n\tresponseMessage := db.queryRequest(nqlInsertStatement)\n\t//fmt.Println(responseMessage.Status)\n\tif responseMessage.Status != \"success\" {\n\t\tfmt.Println(nqlInsertStatement)\n\t}\n\n\treturn responseMessage\n}", "func AddItem(da DataAccess, name string, itemType string, username string, value int64) error {\n\t// run standard validation\n\tif err := validateItem(name, itemType, value); err != nil {\n\t\treturn err\n\t}\n\n\t// find the user and verify they exist\n\tuser, err := FindUserByName(da, username)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// try to add the new item\n\treturn da.AddItem(context.Background(), user.Id, name, itemType, value)\n}", "func PostItemsHandler(db *sqlx.DB, v *validator.Validate) gin.HandlerFunc {\n\treturn func (ctx *gin.Context) {\n\t\tcreatedBy, createdByExists := GetUserID(ctx)\n\t\tif !createdByExists {\n\t\t\tctx.String(http.StatusUnauthorized, \"User id not found in authorization token.\")\n\t\t\treturn\n\t\t}\n\n\t\tvar itemData ItemsPostBody\n\t\tif err := ctx.ShouldBindJSON(&itemData); err != nil {\n\t\t\tctx.String(http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\terr := v.Struct(itemData)\n\t\tif err != nil {\n\t\t\tctx.String(http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tuser := PublicToPrivateUserID(db, createdBy)\n\n\t\tuuid, err := nanoid.Nanoid()\n\t\tif err != nil {\n\t\t\tctx.String(http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tquery := sq.Insert(\"items\").Columns(\"public_id\", \"created_by\", \"name\", \"price\", \"unit\").Values(uuid, user.ID, itemData.Name, itemData.Price, itemData.Unit)\n\n\t\tqueryString, queryStringArgs, err := query.ToSql()\n\t\tif err != nil {\n\t\t\tctx.String(http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\ttx, err := db.Begin()\n\t\tif err != nil {\n\t\t\tctx.String(http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tif _, err := tx.Exec(queryString, queryStringArgs...); err != nil {\n\t\t\tctx.String(http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tif err := tx.Commit(); err != nil {\n\t\t\tctx.String(http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tctx.Status(http.StatusOK)\n\t}\n}", "func AddItemToBasket(w http.ResponseWriter, r *http.Request) {\r\n\trouteParams := mux.Vars(r)\r\n\tbasketID, err := strconv.Atoi(routeParams[\"basketId\"])\r\n\r\n\tif err != nil {\r\n\t\trespondWithError(w, http.StatusBadRequest, \"Invalid Basket ID\")\r\n\t}\r\n\r\n\titemID, err := strconv.Atoi(routeParams[\"itemId\"])\r\n\r\n\tif err != nil {\r\n\t\trespondWithError(w, http.StatusBadRequest, \"Invalid Item ID\")\r\n\t}\r\n\r\n\tbi := models.BasketItem{\r\n\t\tBasketID: basketID,\r\n\t\tItemID: itemID,\r\n\t}\r\n\r\n\terr = bi.CreateBasketItem()\r\n\r\n\tif err != nil {\r\n\t\trespondWithError(w, http.StatusNotFound, \"Item or Basket ID does not exist\")\r\n\t\treturn\r\n\t}\r\n\r\n\trespondWithJSON(w, http.StatusOK, bi)\r\n}", "func (s *AppStorage) Insert(ctx context.Context, app *types.App) error {\n\n\tlog.V(logLevel).Debug(\"Storage: App: insert app: %#v\", app)\n\n\tif app == nil {\n\t\terr := errors.New(\"app can not be nil\")\n\t\tlog.V(logLevel).Errorf(\"Storage: App: insert app err: %s\", err.Error())\n\t\treturn err\n\t}\n\n\tclient, destroy, err := s.Client()\n\tif err != nil {\n\t\tlog.V(logLevel).Errorf(\"Storage: App: create client err: %s\", err.Error())\n\t\treturn err\n\t}\n\tdefer destroy()\n\n\tkeyMeta := keyCreate(appStorage, app.Meta.Name, \"meta\")\n\tif err := client.Create(ctx, keyMeta, app.Meta, nil, 0); err != nil {\n\t\tlog.V(logLevel).Errorf(\"Storage: App: insert app err: %s\", err.Error())\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Store(item *Item) {\n\tcollection := getCollection()\n \n lastItem := getLastPrice(item.ID)\n \n if lastItem.Price == item.Price {\n return\n }\n \n\terr := collection.Insert(item)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (issue Issue) insertIntoDB(db *sql.DB) error {\n\t// Determine if the issue has already been entered into the DB\n\tnumInstances, _ := util.NumResults(db, \"SELECT * FROM four_u WHERE article_name = $1 and link = $2 and type = $3\", issue.Name, issue.Link, issue.TypePost);\n\tif numInstances != 0 {\n\t\treturn errors.New(\"issue already exists\")\n\t}\n\n\t// Copy the image attached with the issue into a folder stored onto the server\n\t// Save the issue's image\n\timageLocation, err := saveImage(issue)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Set the Issue's image URL to be the location of the saved image on our server\n\tissue.ImageUrl = fmt.Sprintf(\"%s/api/v1/assets/%s\", util.APIURL, imageLocation)\n\n\t// Push everything into the DB\n\tdb.Exec(\"INSERT INTO four_u (article_name, article_desc, article_publish_date, article_image_url, link, type) VALUES($1, $2, $3::DATE, $4, $5, $6)\",\n\t\tissue.Name, issue.Desc, issue.PublishDate, issue.ImageUrl, issue.Link, issue.TypePost)\n\n\treturn nil\n}", "func insert(ctx context.Context, tx *sqlx.Tx, todo *Todo) error {\n\tres, err := tx.NamedExecContext(ctx, insertTodo, todo)\n\tif err == nil {\n\t\ttodo.ID, err = res.LastInsertId()\n\t}\n\treturn err\n}", "func Insert (w http.ResponseWriter, r *http.Request){\n\tif r.Method == \"POST\"{ // se a requisição for do metodo POST, criar um novo produto\n\t\t//buscando os dados\n\t\tnome:= r.FormValue(\"nome\")\n\t\tdescricao := r.FormValue(\"descricao\")\n\t\tpreco := r.FormValue(\"preco\")\n\t\tquantidade := r.FormValue(\"quantidade\")\n\n\n\t//convertendo os valores necessarios(os valores que vem pra nós sao do tipo string) temos q converter;\n\t\t//convertendo string para float64\n\t\tprecoConvertidoParaFloat, err := strconv.ParseFloat(preco, 64)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Erro na conversão do preço:\", err)\n\t\t}\n\t\t//convertendo string par int\n\t\tquantidadeConvertidaParaInt, err := strconv.Atoi(quantidade)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Erro na conversão do quantidade:\", err)\n\t\t}\n\n\t\t//Pegar os valores e criar (funcao do models)\n\t\tmodels.CriaNovoProduto(nome, descricao, precoConvertidoParaFloat, quantidadeConvertidaParaInt)\n\t}\n\t//depois de passar os dados redirecionar para a pagina inicial\n\thttp.Redirect(w, r, \"/\", 301)\n\treturn\n}", "func (r *Repository) Insert(ctx context.Context, registrant Registrant) error {\n\ttx := r.db.Begin()\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\ttx.Rollback()\n\t\t}\n\t}()\n\n\tif err := tx.Error; err != nil {\n\t\treturn err\n\t}\n\n\tif err := tx.Create(&registrant).Error; err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\treturn tx.Commit().Error\n}", "func (o *ItemSide) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no item_sides provided for insertion\")\n\t}\n\n\tvar err error\n\n\tnzDefaults := queries.NonZeroDefaultSet(itemSideColumnsWithDefault, o)\n\n\tkey := makeCacheKey(columns, nzDefaults)\n\titemSideInsertCacheMut.RLock()\n\tcache, cached := itemSideInsertCache[key]\n\titemSideInsertCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl, returnColumns := columns.InsertColumnSet(\n\t\t\titemSideAllColumns,\n\t\t\titemSideColumnsWithDefault,\n\t\t\titemSideColumnsWithoutDefault,\n\t\t\tnzDefaults,\n\t\t)\n\n\t\tcache.valueMapping, err = queries.BindMapping(itemSideType, itemSideMapping, wl)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcache.retMapping, err = queries.BindMapping(itemSideType, itemSideMapping, returnColumns)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(wl) != 0 {\n\t\t\tcache.query = fmt.Sprintf(\"INSERT INTO \\\"item_sides\\\" (\\\"%s\\\") %%sVALUES (%s)%%s\", strings.Join(wl, \"\\\",\\\"\"), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1))\n\t\t} else {\n\t\t\tcache.query = \"INSERT INTO \\\"item_sides\\\" %sDEFAULT VALUES%s\"\n\t\t}\n\n\t\tvar queryOutput, queryReturning string\n\n\t\tif len(cache.retMapping) != 0 {\n\t\t\tcache.retQuery = fmt.Sprintf(\"SELECT \\\"%s\\\" FROM \\\"item_sides\\\" WHERE %s\", strings.Join(returnColumns, \"\\\",\\\"\"), strmangle.WhereClause(\"\\\"\", \"\\\"\", 0, itemSidePrimaryKeyColumns))\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning)\n\t}\n\n\tvalue := reflect.Indirect(reflect.ValueOf(o))\n\tvals := queries.ValuesFromMapping(value, cache.valueMapping)\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.query)\n\t\tfmt.Fprintln(writer, vals)\n\t}\n\t_, err = exec.ExecContext(ctx, cache.query, vals...)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to insert into item_sides\")\n\t}\n\n\tvar identifierCols []interface{}\n\n\tif len(cache.retMapping) == 0 {\n\t\tgoto CacheNoHooks\n\t}\n\n\tidentifierCols = []interface{}{\n\t\to.ItemID,\n\t\to.SideItemID,\n\t}\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.retQuery)\n\t\tfmt.Fprintln(writer, identifierCols...)\n\t}\n\terr = exec.QueryRowContext(ctx, cache.retQuery, identifierCols...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to populate default values for item_sides\")\n\t}\n\nCacheNoHooks:\n\tif !cached {\n\t\titemSideInsertCacheMut.Lock()\n\t\titemSideInsertCache[key] = cache\n\t\titemSideInsertCacheMut.Unlock()\n\t}\n\n\treturn nil\n}", "func (db *DB) Add(item interface{}) (id string, err error) {\n\tif db.tablename.length() <= 0 {\n\t\treturn \"\", errors.New(MongoDBErrTableName)\n\t}\n\tif err := db.Collection[db.tablename].Insert(item); err != nil {\n\t\treturn \"\", errors.New(err.Error())\n\t}\n\treturn id, nil\n}", "func (smr *StoryMongoRepository) Insert(entity interface{}) (string, error) {\n\ts := entity.(models.Story)\n\treturn smr.bmr.Insert(&s, \"stories\")\n}", "func (t TagAppTable) Insert(\n\tdb DBi,\n\trow *TagApp,\n) (\n\terr error,\n) {\n\n\tif row.TagAppID == \"\" {\n\t\trow.TagAppID = crypto.NewUUID()\n\t}\n\n\t// Validate TagAppID.\n\tif err := validate.UUID(row.TagAppID); err != nil {\n\t\te := err.(errors.Error)\n\t\treturn e.Wrap(\"Validation failed on TagAppID.\")\n\t}\n\n\t// Execute query.\n\t_, err = db.Exec(insertQuery_TagApp,\n\t\trow.TagAppID,\n\t\trow.Name,\n\t\trow.Weight,\n\t\trow.ArchivedAt)\n\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tif err := translateDBError(err); err != nil {\n\t\treturn err\n\t}\n\n\treturn errors.Unexpected.\n\t\tWrap(\"TagApp.Insert failed: %w\", err).\n\t\tAlert()\n}", "func (owwb *OtxWeblinkWeblinkBasket) Insert(db XODB) error {\n\tvar err error\n\n\t// if already exist, bail\n\tif owwb._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\t// sql insert query, primary key provided by sequence\n\tconst sqlstr = `INSERT INTO public.otx_weblink_weblink_baskets (` +\n\t\t`weblink_id, basket_id` +\n\t\t`) VALUES (` +\n\t\t`$1, $2` +\n\t\t`) RETURNING id`\n\n\t// run query\n\tXOLog(sqlstr, owwb.WeblinkID, owwb.BasketID)\n\terr = db.QueryRow(sqlstr, owwb.WeblinkID, owwb.BasketID).Scan(&owwb.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set existence\n\towwb._exists = true\n\n\treturn nil\n}", "func (itl *ItemLine) Save(tx *sql.Tx) error {\n\tquery := `INSERT INTO item_line(item_line_nm, item_line_desc, item_line_dt, item_value, category_id, user_id, rev_by, rev_dt)\n\tVALUES($1, $2, $3, $4, $5, $6, $7, CURRENT_TIMESTAMP) RETURNING id`\n\treturn tx.QueryRow(query,\n\t\titl.itemLineNm,\n\t\titl.itemLineDesc,\n\t\titl.itemLineDt,\n\t\titl.itemLineValue,\n\t\titl.categoryID,\n\t\titl.userID,\n\t\titl.revBy).Scan(&itl.id)\n}", "func (s *SnippetStore) Insert(title, content string, expires int) (int, error) {\n\treturn 2, nil\n}", "func GenerateItemInserts() {\n\tfileData, _ := ioutil.ReadFile(\"data/json/ref.json\")\n\tvar ref map[string]interface{}\n\tif err := json.Unmarshal(fileData, &ref); err != nil {\n\t\tfmt.Println(\"ERROR:\", err)\n\t\treturn\n\t}\n\n\tfileData, _ = ioutil.ReadFile(\"data/json/items.json\")\n\tvar items []map[string]interface{}\n\tif err := json.Unmarshal(fileData, &items); err != nil {\n\t\tfmt.Println(\"ERROR:\", err)\n\t\treturn\n\t}\n\n\tf, err := os.Create(\"data/sql/srd/items_gen.pgsql\")\n\tif err != nil {\n\t\tfmt.Println(\"ERROR:\", err)\n\t\treturn\n\t}\n\n\tx := 0\n\t// BEGIN ITEM LOOP\n\tfor _, item := range items {\n\t\t// FILTER NON STANDARD ITEMS\n\t\tif item[\"source\"].(string) == \"RMBRE\" || item[\"source\"].(string) == \"UA\" {\n\t\t\tcontinue\n\t\t}\n\t\tx++\n\n\t\t// GET ITEM TYPE\n\t\titemType := \"Wondrous Item\"\n\t\tif item[\"type\"] != nil {\n\t\t\titemType = itemTypes[item[\"type\"].(string)]\n\t\t}\n\n\t\t// GET ITEM COST\n\t\tcost := \"null\"\n\t\tif item[\"value\"] != nil {\n\t\t\tcost = strconv.FormatFloat(item[\"value\"].(float64)/100, 'f', -1, 64)\n\t\t}\n\n\t\t// GET ITEM WEIGHT\n\t\tweight := \"null\"\n\t\tif item[\"weight\"] != nil {\n\t\t\tweight = strconv.FormatFloat(item[\"weight\"].(float64), 'f', -1, 64)\n\t\t}\n\n\t\t// GET ITEM WEIGHT\n\t\treqAttune := \"false\"\n\t\tif item[\"reqAttune\"] != nil {\n\t\t\tvar ok bool\n\t\t\treqAttune, ok = item[\"reqAttune\"].(string)\n\t\t\tif !ok {\n\t\t\t\treqAttune = strconv.FormatBool(item[\"reqAttune\"].(bool))\n\t\t\t}\n\t\t}\n\n\t\t// GET ITEM RARITY\n\t\trarity := \"Common\"\n\t\tif item[\"rarity\"] != nil {\n\t\t\trarity = item[\"rarity\"].(string)\n\t\t\tif rarity == \"None\" {\n\t\t\t\trarity = \"Common\"\n\t\t\t}\n\t\t}\n\n\t\t// GET ITEM WEAPON INFO\n\t\tweapon := \"null\"\n\t\tif item[\"weaponCategory\"] != nil {\n\t\t\tdmgType := \"null\"\n\t\t\tif item[\"dmgType\"] != nil {\n\t\t\t\tdmgType = fmt.Sprintf(\"'%s'\", dmgTypes[item[\"dmgType\"].(string)])\n\t\t\t}\n\t\t\tdmg := \"null\"\n\t\t\tif item[\"dmg1\"] != nil {\n\t\t\t\tdmg = fmt.Sprintf(\"'%s'\", item[\"dmg1\"])\n\t\t\t}\n\t\t\tweapon = fmt.Sprintf(\"row('%s', %s, %s)::weapon_info\", item[\"weaponCategory\"], dmg, dmgType)\n\t\t}\n\n\t\t// GET ITEM AC\n\t\tac := \"null\"\n\t\tif item[\"ac\"] != nil {\n\t\t\tac = strconv.FormatFloat(item[\"ac\"].(float64), 'f', -1, 64)\n\t\t}\n\n\t\tvar info []section\n\t\t// LOAD PROPERTIES TO INFO\n\t\tif item[\"property\"] != nil {\n\t\t\tfor _, p := range item[\"property\"].([]interface{}) {\n\t\t\t\tn, d, ok := getProp(p.(string), ref)\n\t\t\t\tif !ok {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif p.(string) == \"V\" {\n\t\t\t\t\tn += \" (\" + item[\"dmg2\"].(string) + \")\"\n\t\t\t\t}\n\t\t\t\tif p.(string) == \"T\" || p.(string) == \"A\" {\n\t\t\t\t\tn += \" (\" + item[\"range\"].(string) + \" ft)\"\n\t\t\t\t}\n\t\t\t\tinfo = append(info, section{Title: n, Body: d})\n\t\t\t}\n\t\t}\n\n\t\t// LOAD ENTRIES INTO INFO\n\t\tinfoInsert := \"null\"\n\t\tif e, ok := item[\"entries\"]; ok {\n\t\t\tinfoInsert = parseEntries(e.([]interface{}))\n\t\t}\n\n\t\tstatement := fmt.Sprintf(\"INSERT INTO items (name, type, cost, weight, attune, rarity, weapon, armor_class, info) VALUES ('%s', '%s', %s, %s, '%s', '%s', %s, %s, %s);\\n\",\n\t\t\tescape(item[\"name\"].(string)), escape(itemType), cost, weight, escape(reqAttune), rarity, weapon, ac, infoInsert)\n\n\t\tf.WriteString(stripFilters(statement))\n\t}\n\n\tif err := f.Sync(); err != nil {\n\t\tfmt.Println(\"ERROR:\", err)\n\t}\n\n\tfmt.Println(x, \"Items\")\n}", "func (h *Handler) InsertBook(w http.ResponseWriter, r *http.Request, param httprouter.Params) {\n\t// TODO: Implement this. Query = INSERT INTO books (id, title, author, isbn, stock) VALUES (<id>, '<title>', '<author>', '<isbn>', <stock>)\n\t// read json body\n\tbody, err := ioutil.ReadAll(r.Body)\n\tdefer r.Body.Close()\n\tif err != nil {\n\t\trenderJSON(w, []byte(`\n\t\t\tmessage: \"Fail to read body\"\n\t\t\t`), http.StatusBadRequest)\n\t\treturn\n\t}\n\t// parse json body\n\tvar book Book\n\terr = json.Unmarshal(body, &book)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\t// executing insert query\n\tquery := fmt.Sprintf(\"INSERT INTO books (id,title,author,isbn,stock) VALUES (%d,'%s','%s','%s',%d) \", book.ID, book.Title, book.Author, book.ISBN, book.Stock)\n\t_, err = h.DB.Query(query)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\trenderJSON(w, []byte(`\n\t{\n\t\tstatus:\"success\",\n\t\tmessage:\"Insert Book Successfully\"\n\t}\n\t`), http.StatusOK)\n\n}", "func (itemHandle) Upsert(c *app.Context) error {\n\tvar it item.Item\n\tif err := json.NewDecoder(c.Request.Body).Decode(&it); err != nil {\n\t\treturn err\n\t}\n\n\tif err := item.Upsert(c.SessionID, c.Ctx[\"DB\"].(*db.DB), &it); err != nil {\n\t\treturn err\n\t}\n\n\tc.Respond(nil, http.StatusNoContent)\n\treturn nil\n}", "func Insert(db DB, table string, src interface{}) error {\n\treturn InsertContext(context.Background(), db, table, src)\n}", "func CreateByID(itemID *int, Quantity *int, Description *string, Discount *float32, Size *string, Color *string, Manufacturer *string, ItemCode *string, Material *string, db *sql.DB) {\n\n\tquery := fmt.Sprintf(`INSERT INTO item_info (item_id, quantity, description, discount, size, color, manufacturer, item_code, material) \n\tVALUES(%v, %v, \"%v\", %v, \"%v\", \"%v\", \"%v\", \"%v\", \"%v\")`, *itemID, *Quantity, *Description,\n\t\t*Discount, *Size, *Color, *Manufacturer, *ItemCode, *Material)\n\n\tdb.Exec(query)\n}", "func (idxer *Indexes) Insert(item *item, to ...string) {\n\tfor _, index := range idxer.storage {\n\t\tif idxer.fit(index.name, to) && match.Match(string(item.key), index.pattern) {\n\t\t\tindex.insert(item)\n\t\t}\n\t}\n}", "func (r *Entity) Insert() (result sql.Result, err error) {\n\treturn Model.Data(r).Insert()\n}", "func (r *Entity) Insert() (result sql.Result, err error) {\n\treturn Model.Data(r).Insert()\n}", "func (r *Entity) Insert() (result sql.Result, err error) {\n\treturn Model.Data(r).Insert()\n}", "func (r *Entity) Insert() (result sql.Result, err error) {\n\treturn Model.Data(r).Insert()\n}", "func (r *Entity) Insert() (result sql.Result, err error) {\n\treturn Model.Data(r).Insert()\n}" ]
[ "0.79157776", "0.7637643", "0.74021834", "0.7138829", "0.7116001", "0.6995403", "0.69375503", "0.6928879", "0.69254255", "0.6888671", "0.6856061", "0.6696047", "0.6660738", "0.665551", "0.6654495", "0.6652986", "0.66388476", "0.65846837", "0.65480274", "0.65152824", "0.6500732", "0.64918", "0.6480039", "0.6469016", "0.64520353", "0.64316106", "0.6429744", "0.642187", "0.63631874", "0.6315212", "0.63121796", "0.62667537", "0.6253201", "0.62475985", "0.6239907", "0.6216864", "0.62064815", "0.6182483", "0.6148894", "0.61364836", "0.6129317", "0.6114761", "0.6103337", "0.6068364", "0.6052454", "0.6043306", "0.60423064", "0.6026272", "0.5988063", "0.59801364", "0.597422", "0.5971096", "0.5966315", "0.59620243", "0.5936036", "0.58988684", "0.58925503", "0.5873264", "0.5871248", "0.5867274", "0.58587354", "0.5852805", "0.5848008", "0.58379865", "0.5813115", "0.5805233", "0.5768894", "0.5760465", "0.5755399", "0.5752486", "0.5751261", "0.5747202", "0.57418585", "0.57277375", "0.5723425", "0.5712247", "0.56971097", "0.5688087", "0.56835526", "0.5678296", "0.5677478", "0.5659846", "0.5659224", "0.56590044", "0.56505543", "0.5638851", "0.5635028", "0.5628", "0.56123173", "0.5592509", "0.5587691", "0.55867773", "0.5584477", "0.5584441", "0.55825967", "0.55794895", "0.55794895", "0.55794895", "0.55794895", "0.55794895" ]
0.77427083
1
DeleteItem deletes the item with the given itemID AND huntID
func DeleteItem(env *config.Env, huntID, itemID int) *response.Error { return db.DeleteItem(itemID, huntID) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func DeleteItem(c *gin.Context) {\n\tvar item model.Item\n\tid := c.Param(\"id\")\n\tif err := util.DB.Where(\"id = ?\", id).Unscoped().Delete(&item).Error; err != nil {\n\t\tc.JSON(http.StatusNotFound, util.FailResponse(http.StatusNotFound, \"Item not found\"))\n\t} else {\n\t\tc.JSON(http.StatusOK, util.MessageResponse(http.StatusOK, \"Success delete item\"))\n\t}\n}", "func DeleteItem(da DataAccess, id int) error {\n\t// try to delete the item\n\treturn da.DeleteItem(context.Background(), id)\n}", "func deleteItem(id string) error {\n\tdeathrow := findItem(id)\n\tfor i, _ := range items {\n\t\tfound := getXidString(deathrow)\n\t\tif id == found {\n\t\t\titems = append(items[:i], items[i+1:]...)\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"Could not find item with id of %v to delete\", id)\n}", "func (a *API) DeleteItem(item Item, reply *Item) error {\n\n\tvar delete Item\n\t\n\n\tfor idx,val := range data {\n\t\tif val.Title == item.Title && val.Body == item.Body {\n\t\t\tdata = append(data[:idx], data[idx+1:]...)\n\n\t\t\tdelete = item\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t*reply = delete // recall function as always\n\treturn nil\n\n}", "func (c *Checklist) DeleteItem(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tif i := r.URL.Query().Get(\"item\"); len(i) != 0 {\n\t\tindex := c.getItemIndex(i)\n\n\t\tif index == -1 {\n\t\t\tc.b.Response(\"\", \"Item doesn't exist\", http.StatusBadRequest, w)\n\t\t\treturn\n\t\t}\n\t\tcopy(c.Items[index:], c.Items[index+1:])\n\t\tc.Items[len(c.Items)-1] = nil\n\t\tc.Items = c.Items[:len(c.Items)-1]\n\n\t\tgo func() {\n\t\t\tc.Finished = c.CheckDone()\n\t\t\tc.saveToRedis()\n\t\t}()\n\t\tjson.NewEncoder(w).Encode(c.Items)\n\t\tgo c.b.WSChecklistUpdate()\n\t\treturn\n\t}\n\tc.b.Response(\"\", \"no item defined\", http.StatusBadRequest, w)\n}", "func DeleteItem(c *gin.Context) {\n\t// Get model if exist\n\tvar item models.Item\n\tif err := models.DB.Where(\"id = ?\", c.Param(\"id\")).First(&item).Error; err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"Record not found!\"})\n\t\treturn\n\t}\n\tmodels.DB.Delete(&item)\n\tc.JSON(http.StatusOK, gin.H{\"data\": true})\n}", "func (n *Node) DeleteItem(kgname, item string, expectError bool) {\n\n\tstatus, err := n.Client.Delete(context.Background(), &client.DeleteRequest{\n\t\tKeygroup: kgname,\n\t\tId: item,\n\t})\n\n\tif err != nil && !expectError {\n\t\tlog.Warn().Msgf(\"Delete: error %s\", err)\n\t\tn.Errors++\n\t\treturn\n\t}\n\n\tif err == nil && expectError {\n\t\tlog.Warn().Msg(\"Delete: Expected Error bot got no error\")\n\t\tn.Errors++\n\t\treturn\n\t}\n\n\tif err == nil && !expectError && status.Status == client.EnumStatus_ERROR {\n\t\tlog.Warn().Msgf(\"Delete: error %s with status %s\", err, status.Status)\n\t\tn.Errors++\n\t}\n}", "func DeleteItem(itemId int, db *sqlx.DB) error {\n\t_, err := squirrel.Delete(Table).Where(squirrel.Eq{RowId: itemId}).RunWith(db.DB).Exec()\n\treturn err\n}", "func (s *InventoryApiService) DeleteItem(id string, w http.ResponseWriter) error {\n\tctx := context.Background()\n\terr := s.db.DeleteItem(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn EncodeJSONStatus(http.StatusOK, \"item deleted\", w)\n}", "func (db Database) DeleteItem(itemID string) error {\n\tquery := `DELETE FROM items WHERE id = $1;`\n\n\t_, err := db.Conn.Exec(query, itemID)\n\tswitch err {\n\tcase sql.ErrNoRows:\n\t\treturn ErrNoMatch\n\tdefault:\n\t\treturn err\n\t}\n}", "func DeleteItem(params items.DeleteItemParams) model.Item {\n\tdb := dbpkg.Connect()\n\tdefer db.Close()\n\n\tvar item model.Item\n\n\tdb.Where(\"id=?\", params.ID).Delete(&item)\n\n\treturn item\n\n}", "func DeleteInventoryItem(writer http.ResponseWriter, req *http.Request) *http_res.HttpResponse {\n\tvars := mux.Vars(req)\n\tuser := (vars[\"part_id\"])\n\trow := services.Db.QueryRow(\"Delete From Inventory Where part_id = ?\", user)\n\trowStruct := Row(row)\n\tif rowStruct.Part_ID == nil {\n\t\treturn http_res.GenerateHttpResponse(http.StatusOK, errors.New(\"Part has been deleted\"))\n\t}\n\treturn http_res.GenerateHttpResponse(http.StatusBadRequest, errors.New(\"Something went wrong\"))\n}", "func deleteItem(ctx context.Context, request *events.APIGatewayProxyRequest) (*events.APIGatewayProxyResponse, error) {\n\tvar params deleteItemRequest\n\n\tif err := json.Unmarshal([]byte(request.Body), &params); err != nil {\n\t\treturn core.MakeHTTPError(http.StatusNotAcceptable, err.Error())\n\t}\n\n\tif params.UserId != 0 {\n\t\treturn deleteUser(params.UserId)\n\t} else if params.BusinessId != 0 {\n\t\treturn deleteBusiness(params.BusinessId)\n\t} else if params.ProductId != 0 {\n\t\treturn deleteProduct(params.ProductId)\n\t} else if params.CategoryId != 0 {\n\t\treturn deleteCategory(params.CategoryId)\n\t}\n\n\treturn core.MakeHTTPError(http.StatusNotAcceptable, \"no id given\")\n}", "func (i Inventory) DelItemById(id int) (string, *ErrHandler) {\n err := i.Db.DelItemById(id)\n if err != nil {\n return \"\", err\n }\n return \"item deleted\", nil\n}", "func DeleteItem(dbc *sqlx.DB, itemID, listID int) error {\n\tif _, err := SelectItem(dbc, itemID, listID); errors.Cause(err) == sql.ErrNoRows {\n\t\treturn sql.ErrNoRows\n\t}\n\n\tif _, err := dbc.Exec(del, itemID); err != nil {\n\t\treturn errors.Wrap(err, \"delete list row\")\n\t}\n\n\treturn nil\n}", "func (itemHandle) Delete(c *app.Context) error {\n\tif err := item.Delete(c.SessionID, c.Ctx[\"DB\"].(*db.DB), c.Params[\"id\"]); err != nil {\n\t\tif err == item.ErrNotFound {\n\t\t\terr = app.ErrNotFound\n\t\t}\n\t\treturn err\n\t}\n\n\tc.Respond(nil, http.StatusNoContent)\n\treturn nil\n}", "func Delete(i Item, conn *redis.Client) error {\n\t//remove the item from the set of items\n\tresponse := conn.Cmd(\"SREM\", i.getMembersKey(), i.getWatchKey())\n\tif response.Err != nil {\n\t\tOnPrimaryFailure()\n\t\treturn response.Err\n\t}\n\n\t//delete the item entry\n\tresponse = conn.Cmd(\"HDEL\", i.getValueKey(), i.listKeys())\n\tif response.Err != nil {\n\t\tOnPrimaryFailure()\n\t\treturn response.Err\n\t}\n\n\t//delete the item watch, to prevent concurrent access\n\tresponse = conn.Cmd(\"DEL\", i.getWatchKey())\n\tif response.Err != nil {\n\t\tOnPrimaryFailure()\n\t\treturn response.Err\n\t}\n\n\t//no errors\n\treturn nil\n}", "func (i Item) Delete() error {\n\t// spec: Delete (OUT ObjectPath Prompt);\n\treturn simpleCall(i.Path(), _ItemDelete)\n}", "func (is *ItemServices) DeleteItem(ctx context.Context, id string) (int64, []error) {\n\titm, errs := is.itemRepo.DeleteItem(ctx, id)\n\tif len(errs) > 0 {\n\t\treturn 0, errs\n\t}\n\treturn itm, errs\n}", "func (i *Item) Delete() error {\n\tif i.UUID == \"\" {\n\t\treturn fmt.Errorf(\"attempted to delete non-existent item\")\n\t}\n\ti.Content = \"\"\n\ti.EncItemKey = \"\"\n\ti.AuthHash = \"\"\n\ti.UpdatedAt = time.Now().UTC()\n\ti.Deleted = true\n\n\treturn db.Query(\n\t\tstrings.TrimSpace(`\n\t\t\tUPDATE items\n\t\t\tSET content='', enc_item_key='', auth_hash='', deleted=1, updated_at=?\n\t\t\tWHERE uuid=? AND user_uuid=?`,\n\t\t),\n\t\ti.UpdatedAt, i.UUID, i.UserUUID,\n\t)\n}", "func DeleteItem(filter interface{}) (DeleteItemResult, error) {\n\t// create connection to database\n\tctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)\n\tdefer cancel()\n\tc := newConnection(ctx)\n\tdefer c.clt.Disconnect(ctx)\n\n\tres, err := c.collection(itemCollection).DeleteOne(context.Background(), filter)\n\tif err != nil {\n\t\treturn DeleteItemResult{}, err\n\t}\n\treturn DeleteItemResult{\n\t\tDeletedCount: res.DeletedCount,\n\t}, nil\n}", "func (slir *ShoppingListItemRepository) DeleteByGUID(dbTransaction *gorm.DB, shoppingListItemGUID string) *systems.ErrorData {\n\tdeleteShoppingListItem := dbTransaction.Where(\"guid = ?\", shoppingListItemGUID).Delete(&ShoppingListItem{})\n\n\tif deleteShoppingListItem.Error != nil {\n\t\treturn Error.InternalServerError(deleteShoppingListItem.Error, systems.DatabaseError)\n\t}\n\n\treturn nil\n}", "func (c *Client) DropItem() error {\n\treturn c.playerAction(4, 0, 0, 0, 0)\n}", "func DeleteOrderItem(db *sqlx.DB) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\torderItemID := c.Param(\"itemID\")\n\t\torderID := c.Param(\"orderID\")\n\t\tif len(orderItemID) == 0 || orderItemID == \"undefined\" {\n\t\t\tc.AbortWithError(422, errors.NewAPIError(422, \"failed to pass order item ID for deletion\", \"internal server error\", c))\n\t\t\treturn\n\t\t}\n\t\tvar rowsAffected int\n\t\terr := db.Get(&rowsAffected, \"DELETE FROM gaea.orderitem WHERE orderitem_id = $1\", orderItemID)\n\t\tif err != nil {\n\t\t\tswitch {\n\t\t\tcase err == sql.ErrNoRows:\n\t\t\t\tc.JSON(200, gin.H{\"order_id\": orderID, \"orderitem_id\": orderItemID})\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tc.AbortWithError(503, errors.NewAPIError(503, fmt.Sprintf(\"msg=failed to delete order item err=%s\", err), \"internal server error\", c))\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif rowsAffected == 0 {\n\t\t\tc.JSON(200, gin.H{\"order_id\": orderID, \"orderitem_id\": nil})\n\t\t}\n\n\t\tc.JSON(200, gin.H{\"order_id\": orderID, \"orderitem_id\": orderItemID})\n\t}\n}", "func (o *Item) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tif o == nil {\n\t\treturn 0, errors.New(\"models: no Item provided for delete\")\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), itemPrimaryKeyMapping)\n\tsql := \"DELETE FROM \\\"items\\\" WHERE \\\"id\\\"=?\"\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, sql)\n\t\tfmt.Fprintln(writer, args...)\n\t}\n\tresult, err := exec.ExecContext(ctx, sql, args...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to delete from items\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by delete for items\")\n\t}\n\n\treturn rowsAff, nil\n}", "func (library *Library) DeleteItem(id string, itemType int) error {\n\tif !library.ItemExists(id, itemType) {\n\t\treturn os.ErrNotExist\n\t}\n\n\tif itemType == LibraryItemCollection {\n\t\t// Remove reference from parent\n\t\titem, _ := library.GetItem(id, itemType)\n\t\tparent := item.(*Collection).Parent\n\n\t\tif parent != nil {\n\t\t\ti := parent.IndexOfChild(id)\n\t\t\tparent.Children = append(parent.Children[:i], parent.Children[i+1:]...)\n\t\t}\n\n\t\t// Delete sub-collections\n\t\tfor _, child := range library.Collections[id].Children {\n\t\t\tlibrary.DeleteItem(child.ID, LibraryItemCollection)\n\t\t}\n\t}\n\n\t// Remove stored JSON\n\tif err := syscall.Unlink(library.getFilePath(id, itemType)); err != nil {\n\t\treturn err\n\t}\n\n\t// Delete item from library\n\tswitch itemType {\n\tcase LibraryItemSourceGroup, LibraryItemMetricGroup:\n\t\tdelete(library.Groups, id)\n\n\tcase LibraryItemScale:\n\t\tdelete(library.Scales, id)\n\n\tcase LibraryItemUnit:\n\t\tdelete(library.Units, id)\n\n\tcase LibraryItemGraph:\n\t\tdelete(library.Graphs, id)\n\n\tcase LibraryItemCollection:\n\t\tdelete(library.Collections, id)\n\t}\n\n\treturn nil\n}", "func (r Item) Delete() error {\n\terr := db.C(\"item\").Remove(&r)\n\treturn err\n}", "func DeleteItem(item Item) error {\n\tcfDict, err := ConvertMapToCFDictionary(item.attr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer Release(C.CFTypeRef(cfDict))\n\n\terrCode := C.SecItemDelete(cfDict)\n\treturn checkError(errCode)\n}", "func (m *ItemListsItemItemsListItemItemRequestBuilder) Delete(ctx context.Context, requestConfiguration *ItemListsItemItemsListItemItemRequestBuilderDeleteRequestConfiguration)(error) {\n requestInfo, err := m.ToDeleteRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n err = m.requestAdapter.SendNoContent(ctx, requestInfo, errorMapping)\n if err != nil {\n return err\n }\n return nil\n}", "func (item *Item) delete() error {\n\tif num := DB.Where(\"id = ?\", item.ID).Delete(&item).RowsAffected; num != 1 {\n\t\treturn fmt.Errorf(\"Item.delete 01\\n RowsAffected = %d\", num)\n\t}\n\treturn nil\n}", "func delete(w http.ResponseWriter, r *http.Request) {\r\n\tid, _ := strconv.ParseInt(r.URL.Query().Get(\"id\"), 10, 64)\r\n\tquery := \"DELETE from public.item where id=$1\"\r\n\t_, err = db.Exec(query,id)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\t//json.NewEncoder(w).Encode()\t\r\n}", "func (a *List) DelItem(i int) {\n\ta.Items = append(a.Items[:i], a.Items[i+1:]...)\n}", "func (o *ItemSide) DeleteG(ctx context.Context) (int64, error) {\n\treturn o.Delete(ctx, boil.GetContextDB())\n}", "func (e *MockDynamoDB) DeleteItem(input *dynamodb.DeleteItemInput) (*dynamodb.DeleteItemOutput, error) {\n\tif len(e.dynaMock.DeleteItemExpect) > 0 {\n\t\tx := e.dynaMock.DeleteItemExpect[0] //get first element of expectation\n\n\t\tif x.table != nil {\n\t\t\tif *x.table != *input.TableName {\n\t\t\t\treturn &dynamodb.DeleteItemOutput{}, fmt.Errorf(\"Expect table %s but found table %s\", *x.table, *input.TableName)\n\t\t\t}\n\t\t}\n\n\t\tif x.key != nil {\n\t\t\tif !reflect.DeepEqual(x.key, input.Key) {\n\t\t\t\treturn &dynamodb.DeleteItemOutput{}, fmt.Errorf(\"Expect key %+v but found key %+v\", x.key, input.Key)\n\t\t\t}\n\t\t}\n\n\t\t// delete first element of expectation\n\t\te.dynaMock.DeleteItemExpect = append(e.dynaMock.DeleteItemExpect[:0], e.dynaMock.DeleteItemExpect[1:]...)\n\n\t\treturn x.output, nil\n\t}\n\n\treturn &dynamodb.DeleteItemOutput{}, fmt.Errorf(\"Delete Item Expectation Not Found\")\n}", "func (m *ItemVariant) DeleteItemVariant() (err error) {\n\tm.IsDeleted = 1\n\tif err = m.Save(\"is_deleted\"); err == nil {\n\t\t// kalau semua item_variant dari item ini di delete maka item nya juga harus di delete\n\t\tvar t int64\n\t\to := orm.NewOrm()\n\t\tif e := o.Raw(\"select count(*) from item_variant where item_id = ? and is_deleted = 0\", m.Item.ID).QueryRow(&t); e == nil && t == 0 {\n\t\t\to.Raw(\"update item set is_deleted = 1 where id = ?\", m.Item.ID).Exec()\n\t\t}\n\t}\n\n\treturn\n}", "func Delete(c *gin.Context) {\n\tid, err := strconv.Atoi(c.Param(\"id\"))\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\terr = utils.DeleteItem(id)\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\tc.JSON(200, gin.H{\"status\": \"Item deleted\"})\n}", "func (h *Heap) DeleteItem(e *Element) {\n\th.size--\n\th.root = deleteItem(e, h.root)\n}", "func (r *ItemsRepository) delete(i *Item) error {\n\tif query := r.databaseHandler.DB().Delete(&i); query.Error != nil {\n\t\treturn query.Error\n\t}\n\treturn nil\n}", "func (c *Client) RemoveItem(ctx context.Context, id, owner string) (model.Item, error) {\n\tif len(id) < 1 {\n\t\treturn model.Item{}, ErrItemIDEmpty\n\t}\n\n\tresp, err := c.sendRequest(ctx, owner, http.MethodDelete, fmt.Sprintf(\"%s/%s/%s\", c.storeBaseURL, c.bucket, id), nil)\n\tif err != nil {\n\t\treturn model.Item{}, err\n\t}\n\n\tif resp.Code != http.StatusOK {\n\t\tlevel.Error(c.getLogger(ctx)).Log(xlog.MessageKey(), \"Argus responded with a non-successful status code for a RemoveItem request\",\n\t\t\t\"code\", resp.Code, \"ErrorHeader\", resp.ArgusErrorHeader)\n\t\treturn model.Item{}, fmt.Errorf(errStatusCodeFmt, resp.Code, translateNonSuccessStatusCode(resp.Code))\n\t}\n\n\tvar item model.Item\n\terr = json.Unmarshal(resp.Body, &item)\n\tif err != nil {\n\t\treturn item, fmt.Errorf(\"RemoveItem: %w: %s\", errJSONUnmarshal, err.Error())\n\t}\n\treturn item, nil\n}", "func (o *ItemSide) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tif o == nil {\n\t\treturn 0, errors.New(\"models: no ItemSide provided for delete\")\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), itemSidePrimaryKeyMapping)\n\tsql := \"DELETE FROM \\\"item_sides\\\" WHERE \\\"item_id\\\"=? AND \\\"side_item_id\\\"=?\"\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, sql)\n\t\tfmt.Fprintln(writer, args...)\n\t}\n\tresult, err := exec.ExecContext(ctx, sql, args...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to delete from item_sides\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by delete for item_sides\")\n\t}\n\n\treturn rowsAff, nil\n}", "func DeleteItemsHandler (db *sqlx.DB, v *validator.Validate) gin.HandlerFunc {\n\treturn func (ctx *gin.Context) {\n\t\tcreatedBy, createdByExists := GetUserID(ctx)\n\t\tif !createdByExists {\n\t\t\tctx.String(http.StatusUnauthorized, \"User id not found in authorization token.\")\n\t\t\treturn\n\t\t}\n\n\t\tvar itemData ItemsDeleteBody\n\t\tif err := ctx.ShouldBindJSON(&itemData); err != nil {\n\t\t\tctx.String(http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\terr := v.Struct(itemData)\n\t\tif err != nil {\n\t\t\tctx.String(http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tuser := PublicToPrivateUserID(db, createdBy)\n\n\t\tquery := sq.Delete(\"items\").Where(sq.Eq{\"public_id\": itemData.PublicID, \"created_by\": user.ID})\n\t\tqueryString, queryStringArgs, err := query.ToSql()\n\t\tif err != nil {\n\t\t\tctx.String(http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\ttx, err := db.Begin()\n\t\tif err != nil {\n\t\t\tctx.String(http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tif _, err := tx.Exec(queryString, queryStringArgs...); err != nil {\n\t\t\tlog.Fatalln(err.Error())\n\t\t}\n\n\t\ttx.Commit()\n\n\t\tctx.Status(http.StatusOK)\n\t}\n}", "func (o *CMFSlideItem) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tif o == nil {\n\t\treturn 0, errors.New(\"models: no CMFSlideItem provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cmfSlideItemPrimaryKeyMapping)\n\tsql := \"DELETE FROM `cmf_slide_item` WHERE `id`=?\"\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, sql)\n\t\tfmt.Fprintln(writer, args...)\n\t}\n\tresult, err := exec.ExecContext(ctx, sql, args...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to delete from cmf_slide_item\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by delete for cmf_slide_item\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn rowsAff, nil\n}", "func (q *TransmitLimitedQueue) deleteItem(cur *limitedBroadcast) {\n\t_ = q.tq.Delete(cur)\n\tif cur.name != \"\" {\n\t\tdelete(q.tm, cur.name)\n\t}\n\n\tif q.tq.Len() == 0 {\n\t\t// At idle there's no reason to let the id generator keep going\n\t\t// indefinitely.\n\t\tq.idGen = 0\n\t}\n}", "func (m *ItemItemsItemWorkbookTablesWorkbookTableItemRequestBuilder) Delete(ctx context.Context, requestConfiguration *ItemItemsItemWorkbookTablesWorkbookTableItemRequestBuilderDeleteRequestConfiguration)(error) {\n requestInfo, err := m.ToDeleteRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n err = m.BaseRequestBuilder.RequestAdapter.SendNoContent(ctx, requestInfo, errorMapping)\n if err != nil {\n return err\n }\n return nil\n}", "func (r *FinancialItemRepository) RemoveItem(tx *sql.Tx, userID int64, itemID int64) error {\n\t_, err := tx.Exec(\"DELETE FROM items WHERE user_id=$1 AND id=$2;\", userID, itemID)\n\treturn err\n}", "func (m *ItemItemsDriveItemItemRequestBuilder) Delete(ctx context.Context, requestConfiguration *ItemItemsDriveItemItemRequestBuilderDeleteRequestConfiguration)(error) {\n requestInfo, err := m.ToDeleteRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n err = m.BaseRequestBuilder.RequestAdapter.SendNoContent(ctx, requestInfo, errorMapping)\n if err != nil {\n return err\n }\n return nil\n}", "func (o *Item) DeleteG(ctx context.Context) (int64, error) {\n\treturn o.Delete(ctx, boil.GetContextDB())\n}", "func (o *Order) RemoveItem(id string) error {\n\ti, err := o.findItem(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Items[i].Removed = true\n\treturn nil\n}", "func (d *Service) DeleteRetroItem(RetroID string, userID string, Type string, ItemID string) ([]*thunderdome.RetroItem, error) {\n\tif _, err := d.DB.Exec(\n\t\t`DELETE FROM thunderdome.retro_item WHERE id = $1 AND type = $2;`, ItemID, Type); err != nil {\n\t\td.Logger.Error(\"delete retro item error\", zap.Error(err))\n\t}\n\n\titems := d.GetRetroItems(RetroID)\n\n\treturn items, nil\n}", "func (m *Mongo) DeleteOrderItem(dbname string, id string) error {\n\tc := m.session.DB(dbname).C(orderItemsCollectionName)\n\treturn c.RemoveId(bson.ObjectIdHex(id))\n}", "func (c *container) RemoveItem(id string) error {\n\treturn c.location.sftpClient.Remove(filepath.Join(c.location.config.basePath, c.name, filepath.FromSlash(id)))\n}", "func DeleteItemsForbidden(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.ItemsController, id int) http.ResponseWriter {\n\t// Setup service\n\tvar (\n\t\tlogBuf bytes.Buffer\n\t\tresp interface{}\n\n\t\trespSetter goatest.ResponseSetterFunc = func(r interface{}) { resp = r }\n\t)\n\tif service == nil {\n\t\tservice = goatest.Service(&logBuf, respSetter)\n\t} else {\n\t\tlogger := log.New(&logBuf, \"\", log.Ltime)\n\t\tservice.WithLogger(goa.NewLogger(logger))\n\t\tnewEncoder := func(io.Writer) goa.Encoder { return respSetter }\n\t\tservice.Encoder = goa.NewHTTPEncoder() // Make sure the code ends up using this decoder\n\t\tservice.Encoder.Register(newEncoder, \"*/*\")\n\t}\n\n\t// Setup request context\n\trw := httptest.NewRecorder()\n\tu := &url.URL{\n\t\tPath: fmt.Sprintf(\"/item/%v\", id),\n\t}\n\treq, err := http.NewRequest(\"DELETE\", u.String(), nil)\n\tif err != nil {\n\t\tpanic(\"invalid test \" + err.Error()) // bug\n\t}\n\tprms := url.Values{}\n\tprms[\"id\"] = []string{fmt.Sprintf(\"%v\", id)}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgoaCtx := goa.NewContext(goa.WithAction(ctx, \"ItemsTest\"), rw, req, prms)\n\tdeleteCtx, err := app.NewDeleteItemsContext(goaCtx, req, service)\n\tif err != nil {\n\t\tpanic(\"invalid test data \" + err.Error()) // bug\n\t}\n\n\t// Perform action\n\terr = ctrl.Delete(deleteCtx)\n\n\t// Validate response\n\tif err != nil {\n\t\tt.Fatalf(\"controller returned %+v, logs:\\n%s\", err, logBuf.String())\n\t}\n\tif rw.Code != 403 {\n\t\tt.Errorf(\"invalid response status code: got %+v, expected 403\", rw.Code)\n\t}\n\n\t// Return results\n\treturn rw\n}", "func (r *Repository) DeleteOrderItem(data *OrderItem) (err error) {\n\n\terr = r.db.Delete(data).Error\n\n\treturn\n}", "func (slir *ShoppingListItemRepository) DeleteByGUIDAndUserGUIDAndShoppingListGUID(dbTransaction *gorm.DB, shoppingListItemGUID string,\n\tuserGUID string, shoppingListGUID string) *systems.ErrorData {\n\n\tdeleteShoppingListItem := dbTransaction.Where(&ShoppingListItem{GUID: shoppingListItemGUID, UserGUID: userGUID, ShoppingListGUID: shoppingListGUID}).Delete(&ShoppingListItem{})\n\n\tif deleteShoppingListItem.Error != nil {\n\t\treturn Error.InternalServerError(deleteShoppingListItem.Error, systems.DatabaseError)\n\t}\n\n\treturn nil\n}", "func (m *ItemItemsItemWorkbookWorksheetsItemChartsItemSeriesWorkbookChartSeriesItemRequestBuilder) Delete(ctx context.Context, requestConfiguration *ItemItemsItemWorkbookWorksheetsItemChartsItemSeriesWorkbookChartSeriesItemRequestBuilderDeleteRequestConfiguration)(error) {\n requestInfo, err := m.ToDeleteRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n err = m.requestAdapter.SendNoContent(ctx, requestInfo, errorMapping)\n if err != nil {\n return err\n }\n return nil\n}", "func (slir *ShoppingListItemRepository) DeleteByShoppingListGUID(dbTransaction *gorm.DB, shoppingListGUID string) *systems.ErrorData {\n\tdeleteShoppingListItem := dbTransaction.Where(\"shopping_list_guid = ?\", shoppingListGUID).Delete(&ShoppingListItem{})\n\n\tif deleteShoppingListItem.Error != nil {\n\t\treturn Error.InternalServerError(deleteShoppingListItem.Error, systems.DatabaseError)\n\t}\n\n\treturn nil\n}", "func deleteTimelineItem(r *http.Request, svc *mirror.Service) string {\n\titemId := r.FormValue(\"itemId\")\n\terr := svc.Timeline.Delete(itemId).Do()\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"An error occurred: %v\\n\", err)\n\t}\n\treturn \"A timeline item has been deleted.\"\n}", "func (api *API) ItemsDelete(items Items) (err error) {\n\tids := make([]string, len(items))\n\tfor i, item := range items {\n\t\tids[i] = item.ID\n\t}\n\n\terr = api.ItemsDeleteByIds(ids)\n\tif err == nil {\n\t\tfor i := range items {\n\t\t\titems[i].ID = \"\"\n\t\t}\n\t}\n\treturn\n}", "func DeleteItems(params items.DeleteItemsParams) model.Item {\n\tdb := dbpkg.Connect()\n\tdefer db.Close()\n\n\tvar item model.Item\n\n\tdb.Delete(&item)\n\n\treturn item\n\n}", "func Delete(txn *badger.Txn, entType schema.EntityType, ID []byte) error {\n\treturn item.Delete(txn, entType.EntityID(ID))\n}", "func (m *ItemInsightsTrendingTrendingItemRequestBuilder) Delete(ctx context.Context, requestConfiguration *ItemInsightsTrendingTrendingItemRequestBuilderDeleteRequestConfiguration)(error) {\n requestInfo, err := m.ToDeleteRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n err = m.BaseRequestBuilder.RequestAdapter.SendNoContent(ctx, requestInfo, errorMapping)\n if err != nil {\n return err\n }\n return nil\n}", "func Delete(Items Item) error {\n\terr := db.C(\"unit\").Remove(&Items)\n\treturn err\n}", "func (s Storage) DeleteItem(item core.Item) bool {\n\tmutex.Lock()\n\tdefer mutex.Unlock()\n\tif !s.deleteItemFile(item) {\n\t\treturn false\n\t}\n\tif !s.deleteItemLink(item) {\n\t\treturn false\n\t}\n\treturn true\n}", "func (m *UsersItemAssignmentsItemSubmissionsItemOutcomesEducationOutcomeItemRequestBuilder) Delete(ctx context.Context, requestConfiguration *UsersItemAssignmentsItemSubmissionsItemOutcomesEducationOutcomeItemRequestBuilderDeleteRequestConfiguration)(error) {\n requestInfo, err := m.ToDeleteRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n err = m.BaseRequestBuilder.RequestAdapter.SendNoContent(ctx, requestInfo, errorMapping)\n if err != nil {\n return err\n }\n return nil\n}", "func (c *ContainerClient) DeleteItem(\n\tctx context.Context,\n\tpartitionKey PartitionKey,\n\titemId string,\n\to *ItemOptions) (ItemResponse, error) {\n\th := headerOptionsOverride{\n\t\tpartitionKey: &partitionKey,\n\t}\n\n\tif o == nil {\n\t\to = &ItemOptions{}\n\t} else {\n\t\th.enableContentResponseOnWrite = &o.EnableContentResponseOnWrite\n\t}\n\n\toperationContext := pipelineRequestOptions{\n\t\tresourceType: resourceTypeDocument,\n\t\tresourceAddress: createLink(c.link, pathSegmentDocument, itemId),\n\t\tisWriteOperation: true,\n\t\theaderOptionsOverride: &h}\n\n\tpath, err := generatePathForNameBased(resourceTypeDocument, operationContext.resourceAddress, false)\n\tif err != nil {\n\t\treturn ItemResponse{}, err\n\t}\n\n\tazResponse, err := c.database.client.sendDeleteRequest(\n\t\tpath,\n\t\tctx,\n\t\toperationContext,\n\t\to,\n\t\tnil)\n\tif err != nil {\n\t\treturn ItemResponse{}, err\n\t}\n\n\treturn newItemResponse(azResponse)\n}", "func (m *Mongo) DeleteListItem(ctx context.Context, i ListItem) (int64, error) {\n\tvar dCount int64\n\n\tcoll := m.C.Database(m.dbName).Collection(listCollection)\n\tf := bson.M{\"name\": i.Name}\n\n\tdel, err := coll.DeleteOne(ctx, f)\n\tif del != nil {\n\t\tdCount = del.DeletedCount\n\t}\n\n\treturn dCount, err\n}", "func DeleteDeviceQueueItem(ctx context.Context, db sqlx.Execer, id int64) error {\n\tres, err := db.Exec(\"delete from device_queue where id = $1\", id)\n\tif err != nil {\n\t\treturn handlePSQLError(err, \"delete error\")\n\t}\n\tra, err := res.RowsAffected()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"get rows affected error\")\n\t}\n\tif ra == 0 {\n\t\treturn ErrDoesNotExist\n\t}\n\n\tlog.WithFields(log.Fields{\n\t\t\"id\": id,\n\t\t\"ctx_id\": ctx.Value(logging.ContextIDKey),\n\t}).Info(\"device-queue deleted\")\n\n\treturn nil\n}", "func (e *engine) deleteItemFromEntityMap(id string) {\n\te.Lock()\n\tdefer e.Unlock()\n\n\tdelete(e.entityMap, id)\n}", "func (slir *ShoppingListItemRepository) DeleteByUserGUIDAndShoppingListGUID(dbTransaction *gorm.DB, userGUID string, shoppingListGUID string) *systems.ErrorData {\n\tdeleteShoppingListItem := dbTransaction.Where(&ShoppingListItem{UserGUID: userGUID, ShoppingListGUID: shoppingListGUID}).Delete(&ShoppingListItem{})\n\n\tif deleteShoppingListItem.Error != nil {\n\t\treturn Error.InternalServerError(deleteShoppingListItem.Error, systems.DatabaseError)\n\t}\n\n\treturn nil\n}", "func ItemTrashed(r *provider.DeleteResponse, req *provider.DeleteRequest, spaceOwner, executant *user.UserId) events.ItemTrashed {\n\topaqueID := utils.ReadPlainFromOpaque(r.Opaque, \"opaque_id\")\n\treturn events.ItemTrashed{\n\t\tSpaceOwner: spaceOwner,\n\t\tExecutant: executant,\n\t\tRef: req.Ref,\n\t\tID: &provider.ResourceId{\n\t\t\tStorageId: req.Ref.GetResourceId().GetStorageId(),\n\t\t\tSpaceId: req.Ref.GetResourceId().GetSpaceId(),\n\t\t\tOpaqueId: opaqueID,\n\t\t},\n\t\tTimestamp: utils.TSNow(),\n\t}\n}", "func Destroy(w http.ResponseWriter, r *http.Request) {\n\tc := flight.Context(w, r)\n\n\t_, err := summary.DeleteSoft(c.DB, c.Param(\"id\"))\n\tif err != nil {\n\t\tc.FlashErrorGeneric(err)\n\t} else {\n\t\tc.FlashNotice(\"Item deleted.\")\n\t}\n\n\tc.Redirect(uri)\n}", "func DeleteGift(ctx context.Context, pk int) {\n\tdeleteGift(ctx, pk)\n}", "func (m *RiskyUsersItemHistoryRiskyUserHistoryItemItemRequestBuilder) Delete(ctx context.Context, requestConfiguration *RiskyUsersItemHistoryRiskyUserHistoryItemItemRequestBuilderDeleteRequestConfiguration)(error) {\n requestInfo, err := m.ToDeleteRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n err = m.BaseRequestBuilder.RequestAdapter.SendNoContent(ctx, requestInfo, errorMapping)\n if err != nil {\n return err\n }\n return nil\n}", "func (m *ItemSitesItemAnalyticsItemActivityStatsItemActivityStatItemRequestBuilder) Delete(ctx context.Context, requestConfiguration *ItemSitesItemAnalyticsItemActivityStatsItemActivityStatItemRequestBuilderDeleteRequestConfiguration)(error) {\n requestInfo, err := m.ToDeleteRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n err = m.BaseRequestBuilder.RequestAdapter.SendNoContent(ctx, requestInfo, errorMapping)\n if err != nil {\n return err\n }\n return nil\n}", "func (s *Store) Delete(id string) error {\n\t// We're going to be modifying our items slice - lock for writing.\n\ts.mutex.Lock()\n\n\t// Unlock once we're done.\n\tdefer s.mutex.Unlock()\n\n\tremainingItems := make([]item, 0, len(s.items))\n\n\t// Only keep items which do not match the ID provided.\n\tfor _, item := range s.items {\n\t\tif item.id != id {\n\t\t\tremainingItems = append(remainingItems, item)\n\t\t}\n\t}\n\n\t// If the number of items is the same then we haven't found anything to delete.\n\tif len(s.items) == len(remainingItems) {\n\t\treturn moodboard.ErrNoSuchItem\n\t}\n\n\ts.items = remainingItems\n\n\treturn nil\n}", "func (db *BotDB) RemoveItem(item uint64, guild uint64) error {\n\t_, err := db.sqlRemoveItem.Exec(item, guild)\n\treturn db.CheckError(\"RemoveItem\", db.standardErr(err))\n}", "func Destroy(w http.ResponseWriter, r *http.Request) {\n\tc := flight.Context(w, r)\n\n\t_, err := code.DeleteSoft(c.DB, c.Param(\"id\"))\n\tif err != nil {\n\t\tc.FlashErrorGeneric(err)\n\t} else {\n\t\tc.FlashNotice(\"Item deleted.\")\n\t}\n\n\tc.Redirect(uri)\n}", "func DeleteItemsNotFound(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.ItemsController, id int) http.ResponseWriter {\n\t// Setup service\n\tvar (\n\t\tlogBuf bytes.Buffer\n\t\tresp interface{}\n\n\t\trespSetter goatest.ResponseSetterFunc = func(r interface{}) { resp = r }\n\t)\n\tif service == nil {\n\t\tservice = goatest.Service(&logBuf, respSetter)\n\t} else {\n\t\tlogger := log.New(&logBuf, \"\", log.Ltime)\n\t\tservice.WithLogger(goa.NewLogger(logger))\n\t\tnewEncoder := func(io.Writer) goa.Encoder { return respSetter }\n\t\tservice.Encoder = goa.NewHTTPEncoder() // Make sure the code ends up using this decoder\n\t\tservice.Encoder.Register(newEncoder, \"*/*\")\n\t}\n\n\t// Setup request context\n\trw := httptest.NewRecorder()\n\tu := &url.URL{\n\t\tPath: fmt.Sprintf(\"/item/%v\", id),\n\t}\n\treq, err := http.NewRequest(\"DELETE\", u.String(), nil)\n\tif err != nil {\n\t\tpanic(\"invalid test \" + err.Error()) // bug\n\t}\n\tprms := url.Values{}\n\tprms[\"id\"] = []string{fmt.Sprintf(\"%v\", id)}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgoaCtx := goa.NewContext(goa.WithAction(ctx, \"ItemsTest\"), rw, req, prms)\n\tdeleteCtx, err := app.NewDeleteItemsContext(goaCtx, req, service)\n\tif err != nil {\n\t\tpanic(\"invalid test data \" + err.Error()) // bug\n\t}\n\n\t// Perform action\n\terr = ctrl.Delete(deleteCtx)\n\n\t// Validate response\n\tif err != nil {\n\t\tt.Fatalf(\"controller returned %+v, logs:\\n%s\", err, logBuf.String())\n\t}\n\tif rw.Code != 404 {\n\t\tt.Errorf(\"invalid response status code: got %+v, expected 404\", rw.Code)\n\t}\n\n\t// Return results\n\treturn rw\n}", "func (tree *SplayTree) Delete(item Item) Item {\n\tif item == nil || tree.root == nil {\n\t\treturn nil\n\t}\n\ttree.splay(item)\n\tif item.Less(tree.root.item) || tree.root.item.Less(item) {\n\t\treturn nil\n\t}\n\treturn tree.DeleteRoot()\n}", "func (m *ItemTodoListsItemTasksTodoTaskItemRequestBuilder) Delete(ctx context.Context, requestConfiguration *ItemTodoListsItemTasksTodoTaskItemRequestBuilderDeleteRequestConfiguration)(error) {\n requestInfo, err := m.ToDeleteRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n err = m.BaseRequestBuilder.RequestAdapter.SendNoContent(ctx, requestInfo, errorMapping)\n if err != nil {\n return err\n }\n return nil\n}", "func (a *ObjectsApiService) DeleteObjectItem(ctx context.Context, templateId string, objectId int32) ( *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 + \"/objects/{template_id}/{object_id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"template_id\"+\"}\", fmt.Sprintf(\"%v\", templateId), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"object_id\"+\"}\", fmt.Sprintf(\"%v\", objectId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\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{\n\t\t\"application/json\",\n\t\t}\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\t localVarHttpResponse, err := a.client.callAPI(r)\n\t if err != nil || localVarHttpResponse == nil {\n\t\t return localVarHttpResponse, err\n\t }\n\t defer localVarHttpResponse.Body.Close()\n\t if localVarHttpResponse.StatusCode >= 300 {\n\t\treturn localVarHttpResponse, reportError(localVarHttpResponse.Status)\n\t }\n\n\treturn localVarHttpResponse, err\n}", "func (m *MeAssignmentsItemSubmissionsItemResourcesEducationSubmissionResourceItemRequestBuilder) Delete(ctx context.Context, requestConfiguration *MeAssignmentsItemSubmissionsItemResourcesEducationSubmissionResourceItemRequestBuilderDeleteRequestConfiguration)(error) {\n requestInfo, err := m.ToDeleteRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n err = m.BaseRequestBuilder.RequestAdapter.SendNoContent(ctx, requestInfo, errorMapping)\n if err != nil {\n return err\n }\n return nil\n}", "func (s *dynamodbStore) executeDynamodbDeleteItem(tableName *string, key map[string]*dynamodb.AttributeValue) (*dynamodb.DeleteItemOutput, error) {\n\tinput := &dynamodb.DeleteItemInput{\n\t\tTableName: tableName,\n\t\tKey: key,\n\t\tReturnConsumedCapacity: s.consumedCapacity,\n\t}\n\n\treturn s.dynamodbService.DeleteItem(input)\n}", "func (xpcgi *XPriCompGroupItem) Delete(db XODB) error {\n\tvar err error\n\n\t// if doesn't exist, bail\n\tif !xpcgi._exists {\n\t\treturn nil\n\t}\n\n\t// if deleted, bail\n\tif xpcgi._deleted {\n\t\treturn nil\n\t}\n\n\t// sql query\n\tconst sqlstr = `DELETE FROM x_showroom.x_pri_comp_group_item WHERE id = ?`\n\n\t// run query\n\tXOLog(sqlstr, xpcgi.ID)\n\t_, err = db.Exec(sqlstr, xpcgi.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set deleted\n\txpcgi._deleted = true\n\n\treturn nil\n}", "func (c *Container) RemoveItem(id string) error {\n\treturn c.Bucket().Object(id).Delete(c.ctx)\n}", "func (c *Client) DropItemStack() error {\n\treturn c.playerAction(3, 0, 0, 0, 0)\n}", "func (gdb *Gdb) CleanItemData(itemInfo DeletedItemsInfo) (TimeRows, error) {\n\tst := time.Now()\n\tgroupName := itemInfo.GroupName\n\tcondition := itemInfo.Condition\n\titems, err := gdb.query(\"select itemName from `\" + groupName + \"` where \" + condition)\n\tif len(items) == 0 {\n\t\treturn TimeRows{}, fmt.Errorf(\"conditionError: \" + condition)\n\t}\n\tif err != nil {\n\t\treturn TimeRows{}, err\n\t}\n\trows, err := gdb.updateItem(\"delete from `\" + groupName + \"` where \" + condition)\n\tif err != nil {\n\t\treturn TimeRows{}, err\n\t}\n\tdataTypes := map[string][]string{} // key is dataType, value is itemNames\n\tfor _, item := range items {\n\t\titemName := item[\"itemName\"] + joiner + groupName\n\t\tdataType, _ := gdb.rtDbFilter.Get(itemName)\n\t\t{\n\t\t\tswitch dataType.(string) {\n\t\t\tcase \"float32\":\n\t\t\t\tif _, ok := dataTypes[\"float32\"]; ok {\n\t\t\t\t\tdataTypes[\"float32\"] = append(dataTypes[\"float32\"], item[\"itemName\"])\n\t\t\t\t} else {\n\t\t\t\t\tdataTypes[\"float32\"] = []string{item[\"itemName\"]}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase \"int32\":\n\t\t\t\tif _, ok := dataTypes[\"int32\"]; ok {\n\t\t\t\t\tdataTypes[\"int32\"] = append(dataTypes[\"int32\"], item[\"itemName\"])\n\t\t\t\t} else {\n\t\t\t\t\tdataTypes[\"int32\"] = []string{item[\"itemName\"]}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase \"string\":\n\t\t\t\tif _, ok := dataTypes[\"string\"]; ok {\n\t\t\t\t\tdataTypes[\"string\"] = append(dataTypes[\"string\"], item[\"itemName\"])\n\t\t\t\t} else {\n\t\t\t\t\tdataTypes[\"string\"] = []string{item[\"itemName\"]}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tif _, ok := dataTypes[\"bool\"]; ok {\n\t\t\t\t\tdataTypes[\"bool\"] = append(dataTypes[\"bool\"], item[\"itemName\"])\n\t\t\t\t} else {\n\t\t\t\t\tdataTypes[\"bool\"] = []string{item[\"itemName\"]}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\t// delete history\n\t// check whether is syncing historical data\n\tt := time.NewTicker(time.Second)\n\tfor {\n\t\tselect {\n\t\tcase <-t.C:\n\t\t\tif !gdb.syncStatus {\n\t\t\t\tt.Stop()\n\t\t\t\tgoto next\n\t\t\t}\n\t\t}\n\t}\nnext:\n\tg := errgroup.Group{}\n\tg.Go(func() error {\n\t\tif itemNames := dataTypes[\"float32\"]; itemNames != nil {\n\t\t\tvar startTimes []int32\n\t\t\tfor i := 0; i < len(dataTypes[\"float32\"]); i++ {\n\t\t\t\tstartTimes = append(startTimes, -1)\n\t\t\t}\n\t\t\tgroupNames := strings.Split(strings.TrimRight(strings.Repeat(groupName+\",\", len(dataTypes[\"float32\"])), \",\"), \",\")\n\t\t\t_, err := gdb.DeleteFloatHistoricalData(groupNames, dataTypes[\"float32\"], startTimes, startTimes)\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\tg.Go(func() error {\n\t\tif itemNames := dataTypes[\"int32\"]; itemNames != nil {\n\t\t\tvar startTimes []int32\n\t\t\tfor i := 0; i < len(dataTypes[\"int32\"]); i++ {\n\t\t\t\tstartTimes = append(startTimes, -1)\n\t\t\t}\n\t\t\tgroupNames := strings.Split(strings.TrimRight(strings.Repeat(groupName+\",\", len(dataTypes[\"int32\"])), \",\"), \",\")\n\t\t\t_, err := gdb.DeleteIntHistoricalData(groupNames, itemNames, startTimes, startTimes)\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\tg.Go(func() error {\n\t\tif itemNames := dataTypes[\"string\"]; itemNames != nil {\n\t\t\tvar startTimes []int32\n\t\t\tfor i := 0; i < len(dataTypes[\"string\"]); i++ {\n\t\t\t\tstartTimes = append(startTimes, -1)\n\t\t\t}\n\t\t\tgroupNames := strings.Split(strings.TrimRight(strings.Repeat(groupName+\",\", len(dataTypes[\"string\"])), \",\"), \",\")\n\t\t\t_, err := gdb.DeleteStringHistoricalData(groupNames, itemNames, startTimes, startTimes)\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\tg.Go(func() error {\n\t\tif itemNames := dataTypes[\"bool\"]; itemNames != nil {\n\t\t\tvar startTimes []int32\n\t\t\tfor i := 0; i < len(dataTypes[\"bool\"]); i++ {\n\t\t\t\tstartTimes = append(startTimes, -1)\n\t\t\t}\n\t\t\tgroupNames := strings.Split(strings.TrimRight(strings.Repeat(groupName+\",\", len(dataTypes[\"bool\"])), \",\"), \",\")\n\t\t\t_, err := gdb.DeleteBoolHistoricalData(groupNames, itemNames, startTimes, startTimes)\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\tif err := g.Wait(); err != nil {\n\t\treturn TimeRows{}, err\n\t}\n\treturn TimeRows{EffectedRows: int(rows), Times: time.Since(st).Milliseconds()}, nil\n}", "func (am *ArtifactMap) DeleteApp(AppGUID string) {\n\tvar desiredApp *ArtifactEntry\n\tindex := 0\n\tfor i, app := range am.AppList {\n\t\tif app.GUID == AppGUID {\n\t\t\tdesiredApp = app\n\t\t\tindex = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif desiredApp != nil {\n\t\tam.AppList = append(am.AppList[:index], am.AppList[index+1:]...)\n\t\tam.appTitleToID.Delete(desiredApp.Title)\n\t\tam.appTitleToItemID.Delete(desiredApp.Title)\n\t}\n}", "func ItemPurged(r *provider.PurgeRecycleResponse, req *provider.PurgeRecycleRequest, executant *user.UserId) events.ItemPurged {\n\treturn events.ItemPurged{\n\t\tExecutant: executant,\n\t\tRef: req.Ref,\n\t\tTimestamp: utils.TSNow(),\n\t}\n}", "func (li *ListItem) Delete(i int) {\n\tif i >= 0 && i < len(li.items) {\n\t\tli.items = append(li.items[:i], li.items[i+1:]...)\n\t}\n}", "func (c *Client) DeleteGroceryItem(ctx context.Context, l *ent.GroceryList, i *ent.GroceryItem) error {\n\t_, err := c.db.GroceryItem.Delete().Where(\n\t\tgroceryitem.HasGrocerylistWith(grocerylist.ID(l.ID)),\n\t\tgroceryitem.ID(i.ID),\n\t).Exec(ctx)\n\treturn err\n}", "func (m *ItemOnenoteNotebooksItemSectionsItemPagesOnenotePageItemRequestBuilder) Delete(ctx context.Context, requestConfiguration *ItemOnenoteNotebooksItemSectionsItemPagesOnenotePageItemRequestBuilderDeleteRequestConfiguration)(error) {\n requestInfo, err := m.ToDeleteRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n err = m.BaseRequestBuilder.RequestAdapter.SendNoContent(ctx, requestInfo, errorMapping)\n if err != nil {\n return err\n }\n return nil\n}", "func (o *Order) RemoveItem(itemID int) error {\n\tif o.State != Ongoing {\n\t\treturn fmt.Errorf(\"order in wrong state\")\n\t}\n\t_, ok := o.Items[itemID]\n\tif !ok {\n\t\treturn fmt.Errorf(\"item not present\")\n\t}\n\to.TrackChange(o, &ItemRemoved{ItemID: itemID})\n\treturn nil\n}", "func (b *Bag) DeleteAt(index int) {\n\tb.items[index] = b.items[len(b.items)-1]\n\tb.items = b.items[:len(b.items)-1]\n}", "func (m *ItemVariant) Delete() (err error) {\n\to := orm.NewOrm()\n\tif m.ID > 0 {\n\t\tvar i int64\n\t\tif i, err = o.Delete(m); i == 0 && err == nil {\n\t\t\terr = orm.ErrNoAffected\n\t\t}\n\t\treturn\n\t}\n\treturn orm.ErrNoRows\n}", "func (self *QueuedSet) delete(item interface{}) {\n\tcount := self.set[item]\n\tif count <= 1 {\n\t\tdelete(self.set, item)\n\t} else {\n\t\tself.set[item] = count - 1\n\t}\n\treturn\n\n}", "func (m *TeamsAppItemRequestBuilder) Delete(ctx context.Context, requestConfiguration *TeamsAppItemRequestBuilderDeleteRequestConfiguration)(error) {\n requestInfo, err := m.CreateDeleteRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n err = m.requestAdapter.SendNoContentAsync(ctx, requestInfo, errorMapping)\n if err != nil {\n return err\n }\n return nil\n}", "func DeleteItemsNoContent(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.ItemsController, id int) http.ResponseWriter {\n\t// Setup service\n\tvar (\n\t\tlogBuf bytes.Buffer\n\t\tresp interface{}\n\n\t\trespSetter goatest.ResponseSetterFunc = func(r interface{}) { resp = r }\n\t)\n\tif service == nil {\n\t\tservice = goatest.Service(&logBuf, respSetter)\n\t} else {\n\t\tlogger := log.New(&logBuf, \"\", log.Ltime)\n\t\tservice.WithLogger(goa.NewLogger(logger))\n\t\tnewEncoder := func(io.Writer) goa.Encoder { return respSetter }\n\t\tservice.Encoder = goa.NewHTTPEncoder() // Make sure the code ends up using this decoder\n\t\tservice.Encoder.Register(newEncoder, \"*/*\")\n\t}\n\n\t// Setup request context\n\trw := httptest.NewRecorder()\n\tu := &url.URL{\n\t\tPath: fmt.Sprintf(\"/item/%v\", id),\n\t}\n\treq, err := http.NewRequest(\"DELETE\", u.String(), nil)\n\tif err != nil {\n\t\tpanic(\"invalid test \" + err.Error()) // bug\n\t}\n\tprms := url.Values{}\n\tprms[\"id\"] = []string{fmt.Sprintf(\"%v\", id)}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgoaCtx := goa.NewContext(goa.WithAction(ctx, \"ItemsTest\"), rw, req, prms)\n\tdeleteCtx, err := app.NewDeleteItemsContext(goaCtx, req, service)\n\tif err != nil {\n\t\tpanic(\"invalid test data \" + err.Error()) // bug\n\t}\n\n\t// Perform action\n\terr = ctrl.Delete(deleteCtx)\n\n\t// Validate response\n\tif err != nil {\n\t\tt.Fatalf(\"controller returned %+v, logs:\\n%s\", err, logBuf.String())\n\t}\n\tif rw.Code != 204 {\n\t\tt.Errorf(\"invalid response status code: got %+v, expected 204\", rw.Code)\n\t}\n\n\t// Return results\n\treturn rw\n}", "func (i *Item) drop(cmd *command.Command) (handled bool) {\n\tif m, ok := cmd.Issuer.(location.Locateable); ok {\n\t\tif inv, ok := cmd.Issuer.(inventory.Interface); ok {\n\t\t\tif inv.Contains(i) {\n\t\t\t\tinv.Remove(i)\n\t\t\t\tcmd.Respond(\"You drop %s.\", i.Name())\n\t\t\t\tcmd.Broadcast([]thing.Interface{cmd.Issuer}, \"You see %s drop %s.\", cmd.Issuer.Name(), i.Name())\n\n\t\t\t\tm.Locate().Add(i)\n\n\t\t\t\thandled = true\n\t\t\t}\n\t\t}\n\t} else {\n\t\tcmd.Respond(\"You don't see anywhere to drop %s.\", i.Name())\n\t\tcmd.Broadcast([]thing.Interface{cmd.Issuer}, \"You see %s try and drop %s.\", cmd.Issuer.Name(), i.Name())\n\t\thandled = true\n\t}\n\treturn\n}", "func (catalogItem *CatalogItem) Delete() error {\n\tutil.Logger.Printf(\"[TRACE] Deleting catalog item: %#v\", catalogItem.CatalogItem)\n\tcatalogItemHREF := catalogItem.client.VCDHREF\n\tcatalogItemHREF.Path += \"/catalogItem/\" + catalogItem.CatalogItem.ID[23:]\n\n\tutil.Logger.Printf(\"[TRACE] Url for deleting catalog item: %#v and name: %s\", catalogItemHREF, catalogItem.CatalogItem.Name)\n\n\treturn catalogItem.client.ExecuteRequestWithoutResponse(catalogItemHREF.String(), http.MethodDelete,\n\t\t\"\", \"error deleting Catalog item: %s\", nil)\n}" ]
[ "0.70132077", "0.68461764", "0.684266", "0.6773586", "0.66925764", "0.6645942", "0.6609907", "0.66031665", "0.6583193", "0.6573642", "0.65414166", "0.6467582", "0.64610535", "0.6455101", "0.63934666", "0.62482566", "0.62280536", "0.6144563", "0.60750765", "0.60697055", "0.60035026", "0.5970608", "0.586661", "0.5833178", "0.5828139", "0.5827461", "0.58206487", "0.5803983", "0.5794267", "0.5793076", "0.57730734", "0.5766947", "0.57505256", "0.5721128", "0.5702643", "0.56845", "0.5683133", "0.5669369", "0.5666704", "0.56565017", "0.56331396", "0.5629467", "0.562057", "0.5592363", "0.55828357", "0.5582586", "0.5561235", "0.556101", "0.5541084", "0.5535633", "0.55103916", "0.55098665", "0.548983", "0.542602", "0.54099727", "0.53931254", "0.53765", "0.53713006", "0.53530455", "0.535081", "0.5323709", "0.5311725", "0.5301428", "0.5295731", "0.527874", "0.52594954", "0.5252229", "0.5240252", "0.5217361", "0.5212083", "0.5202647", "0.5197689", "0.51854706", "0.5176138", "0.51745844", "0.5169769", "0.5163793", "0.51573074", "0.5149381", "0.51415473", "0.51365775", "0.5132002", "0.5131117", "0.5130509", "0.51193285", "0.5105305", "0.5104612", "0.5103785", "0.5096908", "0.50962263", "0.50960684", "0.50937665", "0.50932413", "0.5088764", "0.5087796", "0.5087561", "0.5074884", "0.5069219", "0.50676996", "0.5054696" ]
0.78681725
0
UpdateItem executes a partial update of the item with the given id. NOTE: item_id and hunt_id are not eligible to be changed
func UpdateItem(env *config.Env, item *models.Item) *response.Error { return item.Update(env) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func UpdateItem(c *gin.Context) {\n\tvar item model.Item\n\tid := c.Param(\"id\")\n\tif err := util.DB.Where(\"id = ?\", id).First(&item).Error; err != nil {\n\t\tc.JSON(http.StatusNotFound, util.FailResponse(http.StatusNotFound, \"Item not found\"))\n\t} else {\n\t\tc.ShouldBindJSON(&item)\n\t\tutil.DB.Save(&item)\n\t\tc.JSON(http.StatusOK, util.SuccessResponse(http.StatusOK, \"Success update item\", item))\n\n\t}\n}", "func (s *InventoryApiService) UpdateItem(id string, item Item, w http.ResponseWriter) error {\n\tif id != item.Id {\n\t\tmessage := fmt.Sprintf(\"Mismatched path id: %s and item.Id: %s \", id, item.Id)\n\t\treturn EncodeJSONStatus(http.StatusBadRequest, message, w)\n\t}\n\tif item.Name == \"\" {\n\t\treturn requiredFieldMissing(\"name\", w)\n\t}\n\n\tctx := context.Background()\n\tr, err := s.db.UpdateItem(ctx, &item)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn EncodeJSONResponse(r, nil, w)\n}", "func UpdateItem(c *gin.Context) {\n\t// Validate input\n\tvar input UpdateItemInput\n\tif err := c.ShouldBindJSON(&input); err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\t// Get model if exist\n\tvar item models.Item\n\tif err := models.DB.Where(\"id = ?\", c.Param(\"id\")).First(&item).Error; err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"Record not found!\"})\n\t\treturn\n\t}\n\t// Update the values\n\titem.Name = input.Name\n\titem.Type = input.Type\n\titem.Rarity = input.Rarity\n\titem.Cost = input.Cost\n\tmodels.DB.Model(&item).Updates(item)\n\n\tc.JSON(http.StatusOK, gin.H{\"data\": item})\n}", "func (res ItemsResource) Update(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"Todo item update by id\"))\n}", "func UpdateItem(dbc *sqlx.DB, r Item) error {\n\tif _, err := SelectItem(dbc, r.ID, r.ListID); errors.Cause(err) == sql.ErrNoRows {\n\t\treturn sql.ErrNoRows\n\t}\n\n\tr.Modified = time.Now()\n\n\tif _, err := dbc.Exec(update, r.Name, r.Quantity, r.Modified, r.ID, r.ListID); err != nil {\n\t\treturn errors.Wrap(err, \"update item row\")\n\t}\n\n\treturn nil\n}", "func (db *JSONLite) Update(id string, partialItem Item) (string, error) {\n\treturn \"\", errors.New(\"not yet implemented\")\n}", "func handleUpdateItem(w http.ResponseWriter, r *http.Request) {\n\tupdateBody := modifierBody{}\n\n\terr := parseBodyForJSON(w, r, &updateBody)\n\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"Failed to update item\")\n\t}\n\n\tdb.UpdateItemInMenu(updateBody.MenuID, updateBody.Item)\n\thandleGetMenu(w, r, updateBody.MenuID)\n}", "func UpdateItem(da DataAccess, id int, name string, itemType string, username string, value int64) error {\n\t// verify the item id already exists\n\titem, err := da.FindItemById(context.Background(), id)\n\tif err != nil || item == nil {\n\t\treturn &ItemDoesNotExistError{Id: id}\n\t}\n\n\t// run standard validation\n\tif err := validateItem(name, itemType, value); err != nil {\n\t\treturn err\n\t}\n\n\t// find the user and verify they exist\n\tuser, err := FindUserByName(da, username)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// try to update the item\n\treturn da.UpdateItem(context.Background(), id, user.Id, name, itemType, value)\n}", "func (db Database) UpdateItem(itemID string, itemData models.Item) (models.Item, error) {\n\titem := models.Item{}\n\tquery := `UPDATE items SET name=$1, description=$2 WHERE id=$3 RETURNING id, name, description, created_at;`\n\n\tif err := db.Conn.QueryRow(\n\t\tquery, itemData.Name, itemData.Description, itemID,\n\t).Scan(\n\t\t&item.ID, &item.Name, &item.Description, &item.Creation,\n\t); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn item, ErrNoMatch\n\t\t}\n\t\treturn models.Item{}, err\n\t}\n\n\treturn item, nil\n}", "func (s *InventoryItemServiceOp) Update(item InventoryItem) (*InventoryItem, error) {\n\tpath := fmt.Sprintf(\"%s/%d.json\", inventoryItemsBasePath, item.ID)\n\twrappedData := InventoryItemResource{InventoryItem: &item}\n\tresource := new(InventoryItemResource)\n\terr := s.client.Put(path, wrappedData, resource)\n\treturn resource.InventoryItem, err\n}", "func (r *FinancialItemRepository) UpdateItem(tx *sql.Tx, userID int64, itemID int64, item *models.FinancialItem) error {\n\t_, err := tx.Exec(\"UPDATE items SET PLAID_ITEM_ID=$3, PLAID_ACCESS_TOKEN=$4, PLAID_INSTITUTION_ID=$5, INSTITUTION_NAME=$6, INSTITUTION_COLOR=$7, INSTITUTION_LOGO=$8, ERROR_CODE=$9, ERROR_DEV_MSG=$10, ERROR_USER_MSG=$11 WHERE id=$1 AND user_id=$2\",\n\t\titemID, userID, item.PlaidItemID, item.PlaidAccessToken, item.PlaidInstitutionID, item.InstitutionName,\n\t\titem.InstitutionColor, item.InstitutionLogo, item.ErrorCode, item.ErrorDevMessage, item.ErrorUserMessage)\n\treturn err\n}", "func Edit(c *gin.Context) {\n\tid, err := strconv.Atoi(c.Param(\"id\"))\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\tvar json utils.WishlistItem\n\tif err := c.ShouldBindJSON(&json); err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\terr = utils.EditItem(id, json)\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\tc.JSON(200, gin.H{\"status\": \"Item updated\"})\n}", "func UpdateItem(filter interface{}, update interface{}) (UpdateItemResult, error) {\n\t// create connection to database\n\tctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)\n\tdefer cancel()\n\tc := newConnection(ctx)\n\tdefer c.clt.Disconnect(ctx)\n\n\tres, err := c.collection(itemCollection).UpdateOne(context.Background(), filter, update)\n\tif err != nil {\n\t\treturn UpdateItemResult{}, err\n\t}\n\treturn UpdateItemResult{\n\t\tMatchedCount: res.MatchedCount,\n\t\tModifiedCount: res.ModifiedCount,\n\t\tUpsertedCount: res.UpsertedCount,\n\t}, nil\n}", "func (r Item) Update() error {\n\terr := db.C(\"item\").Update(bson.M{\"_id\": r.ID}, &r)\n\treturn err\n}", "func (i *Item) Update() error {\n\ti.UpdatedAt = time.Now().UTC()\n\tlogger.LogIfDebug(\"Update:\", i.UUID)\n\treturn db.Query(\n\t\tstrings.TrimSpace(`\n\t\tUPDATE items\n\t\tSET content=?, content_type=?, enc_item_key=?, auth_hash=?, deleted=?, updated_at=?\n\t\tWHERE uuid=? AND user_uuid=?`,\n\t\t),\n\t\ti.Content, i.ContentType, i.EncItemKey, i.AuthHash, i.Deleted, i.UpdatedAt,\n\t\ti.UUID, i.UserUUID,\n\t)\n}", "func (o *Item) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) {\n\tvar err error\n\tkey := makeCacheKey(columns, nil)\n\titemUpdateCacheMut.RLock()\n\tcache, cached := itemUpdateCache[key]\n\titemUpdateCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl := columns.UpdateColumnSet(\n\t\t\titemAllColumns,\n\t\t\titemPrimaryKeyColumns,\n\t\t)\n\n\t\tif !columns.IsWhitelist() {\n\t\t\twl = strmangle.SetComplement(wl, []string{\"created_at\"})\n\t\t}\n\t\tif len(wl) == 0 {\n\t\t\treturn 0, errors.New(\"models: unable to update items, could not build whitelist\")\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(\"UPDATE \\\"items\\\" SET %s WHERE %s\",\n\t\t\tstrmangle.SetParamNames(\"\\\"\", \"\\\"\", 0, wl),\n\t\t\tstrmangle.WhereClause(\"\\\"\", \"\\\"\", 0, itemPrimaryKeyColumns),\n\t\t)\n\t\tcache.valueMapping, err = queries.BindMapping(itemType, itemMapping, append(wl, itemPrimaryKeyColumns...))\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tvalues := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping)\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.query)\n\t\tfmt.Fprintln(writer, values)\n\t}\n\tvar result sql.Result\n\tresult, err = exec.ExecContext(ctx, cache.query, values...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to update items row\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by update for items\")\n\t}\n\n\tif !cached {\n\t\titemUpdateCacheMut.Lock()\n\t\titemUpdateCache[key] = cache\n\t\titemUpdateCacheMut.Unlock()\n\t}\n\n\treturn rowsAff, nil\n}", "func Update(w http.ResponseWriter, r *http.Request) {\n\tc := flight.Context(w, r)\n\n\tif !c.FormValid(\"name\") {\n\t\tEdit(w, r)\n\t\treturn\n\t}\n\n\t_, err := summary.Update(c.DB, r.FormValue(\"name\"), c.Param(\"id\"))\n\tif err != nil {\n\t\tc.FlashErrorGeneric(err)\n\t\tEdit(w, r)\n\t\treturn\n\t}\n\n\tc.FlashSuccess(\"Item updated.\")\n\tc.Redirect(uri)\n}", "func (d *Database) MutateItem(\n\tid int64,\n\tfn func(*structs.Item) structs.EntityUpdate) (*structs.Item, error) {\n\td.lock.Lock()\n\tdefer d.lock.Unlock()\n\n\tif err := d.checkClosed(); err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\n\ttx, err := d.db.Begin()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\tdefer tx.Rollback()\n\n\tit, err := getItem(tx, id)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tupdate := fn(it)\n\tif update.Noop() {\n\t\terr = tx.Commit()\n\t\treturn it, err\n\t}\n\n\terr = updateEntity(tx, update)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tnewIt, err := getItem(tx, id)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\n\treturn newIt, nil\n}", "func update(w http.ResponseWriter, r *http.Request) {\r\n\tif r.Method != \"PUT\" {\r\n\t\thttp.Error(w, \"404 not found.\", http.StatusNotFound)\r\n\t\treturn\r\n\t}\r\n\tid, _ := strconv.ParseInt(r.URL.Query().Get(\"id\"), 10, 64)\r\n\tcontents := &content{\r\n\t\tID: id,\r\n\t\tvalue: r.PostFormValue(\"value\"),\r\n\t\tcompleted: r.PostFormValue(\"completed\"),\r\n\t}\r\n\t//fmt.Println(user)\r\n\tquery := \"UPDATE public.item SET completed=$3,value=$2 WHERE id = $1;\"\r\n\t_, err = db.Exec(query, contents.ID, contents.value,contents.completed)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\tjson.NewEncoder(w).Encode(contents)\r\n}", "func (db *DBService) UpdateItem(ctx context.Context, key *string, result *TransferResult) error {\n\t// log.Printf(\"Update item for %s in DynamoDB\\n\", *key)\n\n\tetag := \"\"\n\tif result.etag != nil {\n\t\tetag = *result.etag\n\t}\n\n\texpr := \"set JobStatus = :s, Etag = :tg, EndTime = :et, EndTimestamp = :etm, SpentTime = :etm - StartTimestamp\"\n\n\tinput := &dynamodb.UpdateItemInput{\n\t\tTableName: &db.tableName,\n\t\tKey: map[string]dtype.AttributeValue{\n\t\t\t\"ObjectKey\": &dtype.AttributeValueMemberS{Value: *key},\n\t\t},\n\t\tExpressionAttributeValues: map[string]dtype.AttributeValue{\n\t\t\t\":s\": &dtype.AttributeValueMemberS{Value: result.status},\n\t\t\t\":tg\": &dtype.AttributeValueMemberS{Value: etag},\n\t\t\t\":et\": &dtype.AttributeValueMemberS{Value: time.Now().Format(\"2006/01/02 15:04:05\")},\n\t\t\t\":etm\": &dtype.AttributeValueMemberN{Value: fmt.Sprintf(\"%d\", time.Now().Unix())},\n\t\t},\n\t\tReturnValues: \"NONE\",\n\t\tUpdateExpression: &expr,\n\t}\n\n\t_, err := db.client.UpdateItem(ctx, input)\n\n\tif err != nil {\n\t\tlog.Printf(\"Failed to update item for %s in DynamoDB - %s\\n\", *key, err.Error())\n\t\t// return nil\n\t}\n\t// item = &Item{}\n\n\t// err = attributevalue.UnmarshalMap(output.Attributes, item)\n\t// if err != nil {\n\t// \tlog.Printf(\"failed to unmarshal Dynamodb Scan Items, %v\", err)\n\t// }\n\treturn err\n}", "func (r *ItemsRepository) update(i *Item) error {\n\tif query := r.databaseHandler.DB().Save(&i); query.Error != nil {\n\t\treturn query.Error\n\t}\n\treturn nil\n}", "func (app *application) UpdateItemQty(w http.ResponseWriter, r *http.Request) {\r\n\t// a seller does not have a shopping cart\r\n\tisSeller := app.isSeller(r)\r\n\tif isSeller {\r\n\t\tw.WriteHeader(http.StatusUnauthorized)\r\n\t\tapp.render(w, r, \"error.page.tmpl\", &templateData{\r\n\t\t\tError: http.StatusText(http.StatusUnauthorized),\r\n\t\t})\r\n\t\treturn\r\n\t}\r\n\t// retrieves userid from the session cookie\r\n\tuserid := app.session.GetString(r, \"userid\")\r\n\r\n\t// retrieve productid & quantity from URL\r\n\t// both should be valid\r\n\tproductid, err1 := strconv.Atoi(r.URL.Query().Get(\"productid\"))\r\n\tquantity, err2 := strconv.Atoi(r.URL.Query().Get(\"quantity\"))\r\n\tif err1 != nil || err2 != nil {\r\n\t\tw.WriteHeader(http.StatusBadRequest)\r\n\t\tapp.render(w, r, \"error.page.tmpl\", &templateData{\r\n\t\t\tError: http.StatusText(http.StatusBadRequest),\r\n\t\t})\r\n\t\treturn\r\n\t}\r\n\r\n\t// perform the update at the database\r\n\terr := app.cart.Update(quantity, productid, userid)\r\n\tif err != nil {\r\n\t\t// if an error did not occur when communicating\r\n\t\t// with the database, but no row was affected\r\n\t\tif errors.Is(err, models.ErrNoRowsAffected) {\r\n\t\t\thttp.Redirect(w, r, \"/shoppingcart\", http.StatusSeeOther)\r\n\t\t\treturn\r\n\t\t}\r\n\t\t// if an error occured when communicating with\r\n\t\t// the database\r\n\t\tw.WriteHeader(http.StatusInternalServerError)\r\n\t\tapp.render(w, r, \"error.page.tmpl\", &templateData{\r\n\t\t\tError: http.StatusText(http.StatusInternalServerError),\r\n\t\t})\r\n\t\treturn\r\n\t}\r\n\r\n\tapp.session.Put(r, \"flash\", \"Cart item successfully updated.\")\r\n\r\n\thttp.Redirect(w, r, \"/shoppingcart/\", http.StatusSeeOther)\r\n}", "func (r *repository) Update(ctx context.Context, item *model.BundleReference) error {\n\tif item == nil {\n\t\treturn apperrors.NewInternalError(\"item cannot be nil\")\n\t}\n\n\tfieldName, err := r.referenceObjectFieldName(item.ObjectType)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tupdater := r.updater.Clone()\n\n\tidColumns := make([]string, 0)\n\tif item.BundleID == nil {\n\t\tidColumns = append(idColumns, fieldName)\n\t\tupdater.SetUpdatableColumns(updatableColumnsWithoutBundleID)\n\t} else {\n\t\tidColumns = append(idColumns, fieldName, bundleIDColumn)\n\t}\n\n\tupdater.SetIDColumns(idColumns)\n\n\tentity := r.conv.ToEntity(*item)\n\n\treturn updater.UpdateSingleGlobal(ctx, entity)\n}", "func (m *mockDynamoDB) UpdateItem(input *dynamodb.UpdateItemInput) (*dynamodb.UpdateItemOutput, error) {\n\treturn nil, nil\n}", "func UpdateOrderItem(db *sqlx.DB) gin.HandlerFunc {\n\n\treturn func(c *gin.Context) {\n\t\tvar updateItem OrderItem\n\n\t\terr := c.Bind(&updateItem)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tc.JSON(422, gin.H{\"error\": \"Data provided in wrong format, unable to complete request.\"})\n\t\t\treturn\n\t\t}\n\n\t\t// if ok := auth.MustUser(c, updateItem.UserName); !ok {\n\t\t// \twanted, _ := c.Get(\"user\")\n\t\t// \tc.AbortWithError(401, errors.NewAPIError(401, fmt.Sprintf(\"tried to update order item to another user's order, wanted: %s got %s\", wanted.(string), updateItem.UserName), \"internal server error\", c))\n\t\t// \treturn\n\t\t// }\n\n\t\t// Check order is still open before updating\n\t\tsaleOpen, err := CheckOrderOpen(updateItem.OrderId, db)\n\t\tif err != nil {\n\t\t\tc.AbortWithError(503, errors.NewAPIError(503, fmt.Sprintf(\"CheckOpenOrder returned an error : %s\", err), \"Internal Server Error\", c))\n\t\t\treturn\n\t\t}\n\t\tif !saleOpen {\n\t\t\tc.AbortWithError(409, errors.NewAPIError(409, \"sale not open\", \"Cannot fufill request because the associated sale is not open.\", c))\n\t\t\treturn\n\t\t}\n\n\t\tvar returnItem OrderItem\n\t\tdbErr := db.Get(&returnItem, `UPDATE gaea.orderitem SET qty=$1, updated_at=$2 WHERE\n\t\t\torderitem_id=$3 RETURNING *`, updateItem.Qty, time.Now(), updateItem.OrderitemId)\n\t\tif dbErr != nil {\n\t\t\tfmt.Println(dbErr)\n\t\t\tc.AbortWithError(503, errors.NewAPIError(503, \"failed on updating order item\", \"internal server error\", c))\n\t\t\treturn\n\t\t}\n\n\t\tc.JSON(200, returnItem)\n\t}\n}", "func (repo *MySQLRepository) UpdateItem(item item.Item, currentVersion int) error {\n\ttx, err := repo.db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\titemInsertQuery := `UPDATE item \n\t\tSET\n\t\t\tname = ?,\n\t\t\tdescription = ?,\n\t\t\tmodified_at = ?,\n\t\t\tmodified_by = ?,\n\t\t\tversion = ?\n\t\tWHERE id = ? AND version = ?`\n\n\tres, err := tx.Exec(itemInsertQuery,\n\t\titem.Name,\n\t\titem.Description,\n\t\titem.ModifiedAt,\n\t\titem.ModifiedBy,\n\t\titem.Version,\n\t\titem.ID,\n\t\tcurrentVersion,\n\t)\n\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\taffected, err := res.RowsAffected()\n\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\tif affected == 0 {\n\t\ttx.Rollback()\n\t\treturn business.ErrZeroAffected\n\t}\n\n\t//TODO: maybe better if we only delete the record that we need to delete\n\t//add logic slice to find which deleted and which want to added\n\ttagDeleteQuery := \"DELETE FROM item_tag WHERE item_id = ?\"\n\t_, err = tx.Exec(tagDeleteQuery, item.ID)\n\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\ttagUpsertQuery := \"INSERT INTO item_tag (item_id, tag) VALUES (?, ?)\"\n\n\tfor _, tag := range item.Tags {\n\t\t_, err = tx.Exec(tagUpsertQuery, item.ID, tag)\n\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\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func workItemPutHandler(w http.ResponseWriter, r *http.Request) {\n\tdefer r.Body.Close()\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tfmt.Fprintln(w, err.Error())\n\t\treturn\n\t}\n\t_ = json.Unmarshal(body, updatedWorkItem)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tfmt.Fprintln(w, string(body))\n}", "func (_m *MutationResolver) UpdateItem(ctx context.Context, id int64, data gqlgen.ItemInput) (*pg.Item, error) {\n\tret := _m.Called(ctx, id, data)\n\n\tvar r0 *pg.Item\n\tif rf, ok := ret.Get(0).(func(context.Context, int64, gqlgen.ItemInput) *pg.Item); ok {\n\t\tr0 = rf(ctx, id, data)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*pg.Item)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, int64, gqlgen.ItemInput) error); ok {\n\t\tr1 = rf(ctx, id, data)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *Usecase) UpdateItem(c context.Context, id string, it *models.Item) (*models.Item, error) {\n\tret := _m.Called(c, id, it)\n\n\tvar r0 *models.Item\n\tif rf, ok := ret.Get(0).(func(context.Context, string, *models.Item) *models.Item); ok {\n\t\tr0 = rf(c, id, it)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*models.Item)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, string, *models.Item) error); ok {\n\t\tr1 = rf(c, id, it)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (o *ItemSide) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) {\n\tvar err error\n\tkey := makeCacheKey(columns, nil)\n\titemSideUpdateCacheMut.RLock()\n\tcache, cached := itemSideUpdateCache[key]\n\titemSideUpdateCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl := columns.UpdateColumnSet(\n\t\t\titemSideAllColumns,\n\t\t\titemSidePrimaryKeyColumns,\n\t\t)\n\n\t\tif !columns.IsWhitelist() {\n\t\t\twl = strmangle.SetComplement(wl, []string{\"created_at\"})\n\t\t}\n\t\tif len(wl) == 0 {\n\t\t\treturn 0, errors.New(\"models: unable to update item_sides, could not build whitelist\")\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(\"UPDATE \\\"item_sides\\\" SET %s WHERE %s\",\n\t\t\tstrmangle.SetParamNames(\"\\\"\", \"\\\"\", 0, wl),\n\t\t\tstrmangle.WhereClause(\"\\\"\", \"\\\"\", 0, itemSidePrimaryKeyColumns),\n\t\t)\n\t\tcache.valueMapping, err = queries.BindMapping(itemSideType, itemSideMapping, append(wl, itemSidePrimaryKeyColumns...))\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tvalues := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping)\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.query)\n\t\tfmt.Fprintln(writer, values)\n\t}\n\tvar result sql.Result\n\tresult, err = exec.ExecContext(ctx, cache.query, values...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to update item_sides row\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by update for item_sides\")\n\t}\n\n\tif !cached {\n\t\titemSideUpdateCacheMut.Lock()\n\t\titemSideUpdateCache[key] = cache\n\t\titemSideUpdateCacheMut.Unlock()\n\t}\n\n\treturn rowsAff, nil\n}", "func Update(w http.ResponseWriter, r *http.Request) {\n\tc := flight.Context(w, r)\n\n\tif !c.FormValid(\"amount\") {\n\t\tEdit(w, r)\n\t\treturn\n\t}\n\n\t_, err := code.Update(c.DB, r.FormValue(\"trans_datetime\"), r.FormValue(\"amount\"), r.FormValue(\"details\"), c.Param(\"id\"))\n\tif err != nil {\n\t\tc.FlashErrorGeneric(err)\n\t\tEdit(w, r)\n\t\treturn\n\t}\n\n\tc.FlashSuccess(\"Item updated.\")\n\tc.Redirect(uri)\n}", "func (_m *Usecase) UpdateItem(_a0 context.Context, _a1 *request.ItemRequest) error {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, *request.ItemRequest) error); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (a *API) EditItem(item Item, reply *Item) error { \n\n\tvar manipulate Item\n\n\tfor idx, val := range data {\n\t\tif val.Title == item.Title { // verify real Title string\n\t\t\tdata[idx] = Item{item.Title, item.Body} // store Title and Body\n\t\t\tmanipulate = data[idx]\n\t\t}\n\t}\n\n\t*reply = manipulate\n\treturn nil\n}", "func (r *pgRepository) Update(ctx context.Context, tenant string, item *model.APIDefinition) error {\n\tif item == nil {\n\t\treturn apperrors.NewInternalError(\"item cannot be nil\")\n\t}\n\n\tentity := r.conv.ToEntity(item)\n\n\treturn r.updater.UpdateSingle(ctx, resource.API, tenant, entity)\n}", "func (o *CMFSlideItem) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) {\n\tvar err error\n\tif err = o.doBeforeUpdateHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\tkey := makeCacheKey(columns, nil)\n\tcmfSlideItemUpdateCacheMut.RLock()\n\tcache, cached := cmfSlideItemUpdateCache[key]\n\tcmfSlideItemUpdateCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl := columns.UpdateColumnSet(\n\t\t\tcmfSlideItemAllColumns,\n\t\t\tcmfSlideItemPrimaryKeyColumns,\n\t\t)\n\n\t\tif !columns.IsWhitelist() {\n\t\t\twl = strmangle.SetComplement(wl, []string{\"created_at\"})\n\t\t}\n\t\tif len(wl) == 0 {\n\t\t\treturn 0, errors.New(\"models: unable to update cmf_slide_item, could not build whitelist\")\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(\"UPDATE `cmf_slide_item` SET %s WHERE %s\",\n\t\t\tstrmangle.SetParamNames(\"`\", \"`\", 0, wl),\n\t\t\tstrmangle.WhereClause(\"`\", \"`\", 0, cmfSlideItemPrimaryKeyColumns),\n\t\t)\n\t\tcache.valueMapping, err = queries.BindMapping(cmfSlideItemType, cmfSlideItemMapping, append(wl, cmfSlideItemPrimaryKeyColumns...))\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tvalues := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping)\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.query)\n\t\tfmt.Fprintln(writer, values)\n\t}\n\tvar result sql.Result\n\tresult, err = exec.ExecContext(ctx, cache.query, values...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to update cmf_slide_item row\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by update for cmf_slide_item\")\n\t}\n\n\tif !cached {\n\t\tcmfSlideItemUpdateCacheMut.Lock()\n\t\tcmfSlideItemUpdateCache[key] = cache\n\t\tcmfSlideItemUpdateCacheMut.Unlock()\n\t}\n\n\treturn rowsAff, o.doAfterUpdateHooks(ctx, exec)\n}", "func UpdateCartItem(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"message\": \"NOT IMPLEMENTED\"})\n}", "func PutItemsHandler(db *sqlx.DB, v *validator.Validate) gin.HandlerFunc {\n\treturn func (ctx *gin.Context) {\n\t\tcreatedBy, createdByExists := GetUserID(ctx)\n\t\tif !createdByExists {\n\t\t\tctx.String(http.StatusUnauthorized, \"User id not found in authorization token.\")\n\t\t\treturn\n\t\t}\n\n\t\tvar itemData ItemsPutBody\n\t\tif err := ctx.ShouldBindJSON(&itemData); err != nil {\n\t\t\tctx.String(http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\terr := v.Struct(itemData)\n\t\tif err != nil {\n\t\t\tctx.String(http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tuser := PublicToPrivateUserID(db, createdBy)\n\n\t\tquery := sq.Update(\"items\")\n\n\t\tif itemData.Name != \"\" {\n\t\t\tquery = query.Set(\"name\", itemData.Name)\n\t\t}\n\t\tif itemData.Price != 0.0 {\n\t\t\tquery = query.Set(\"price\", itemData.Price)\n\t\t}\n\t\tif itemData.Unit != \"\" {\n\t\t\tquery = query.Set(\"unit\", itemData.Unit)\n\t\t}\n\n\t\tquery = query.Set(\"updated_at\", time.Now())\n\n\t\tqueryString, queryStringArgs, err := query.Where(sq.Eq{\"public_id\": itemData.PublicID, \"created_by\": user.ID}).ToSql()\n\t\tif err != nil {\n\t\t\tctx.String(http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\ttx, err := db.Begin()\n\t\tif err != nil {\n\t\t\tctx.String(http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tif _, err := tx.Exec(queryString, queryStringArgs...); err != nil {\n\t\t\tctx.String(http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tif err := tx.Commit(); err != nil {\n\t\t\tctx.String(http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tctx.Status(http.StatusOK)\n\t}\n}", "func UpdateContentItem(id string, item models.Content) (bson.M, error) {\n\titem.SetUpdateDate(time.Now())\n\tobjID, _ := primitive.ObjectIDFromHex(id)\n\tupdate := bson.M{\"$set\": item}\n\tupsert := true\n\tafter := options.After\n\topt := options.FindOneAndUpdateOptions{\n\t\tReturnDocument: &after,\n\t\tUpsert: &upsert,\n\t}\n\tresult := db.Collection(contentCollection).FindOneAndUpdate(context.Background(), bson.M{\"_id\": objID}, update, &opt)\n\tif result.Err() != nil {\n\t\tlog.Fatal(result.Err())\n\t\treturn nil, result.Err()\n\t}\n\tdoc := bson.M{}\n\terr := result.Decode(&doc)\n\treturn doc, err\n}", "func (t *Item) Edit(c *gin.Context) {\n\tid := c.Param(\"id\")\n\taid, err := strconv.ParseInt(id, 10, 64)\n\tif err != nil {\n\t\tc.String(500, \"%s\", err)\n\t\treturn\n\t}\n\titem, err := model.ItemOne(t.DB, aid)\n\tif err != nil {\n\t\tc.String(500, \"%s\", err)\n\t\treturn\n\t}\n\tc.HTML(http.StatusOK, \"edit.tmpl\", gin.H{\n\t\t\"item\": item,\n\t\t\"context\": c,\n\t\t\"csrf\": csrf.GetToken(c),\n\t})\n}", "func (is *ItemServices) UpdateItem(ctx context.Context, item *entity.Item) (*entity.Item, []error) {\n\titm, errs := is.itemRepo.UpdateItem(ctx, item)\n\tif len(errs) > 0 {\n\t\treturn nil, errs\n\t}\n\treturn itm, errs\n}", "func (d *DB) itemUpdater(catogoryID uint16) {\n\tarticles, err := FeedzillaArticles(catogoryID, NumberToGet)\n\tif err != nil {\n\t\tglog.Error(err)\n\t\treturn\n\t}\n\n\tfor _, art := range articles.List {\n\t\tart.CategoryID = catogoryID\n\t\t_, err := d.Items.Upsert(bson.M{\"url\": art.URL}, art)\n\t\tif err != nil {\n\t\t\tglog.Error(err)\n\t\t\tcontinue\n\t\t}\n\t\tglog.Infof(\"%+v\", art)\n\t}\n}", "func Update(writer http.ResponseWriter, request *http.Request) {\n\tsp := getByID(request.FormValue(\"id\"))\n\tfmt.Println(sp)\n\ttemplate_html.ExecuteTemplate(writer, \"Update\", sp)\n}", "func (h *CategoryHandler) PartialUpdate(ctx iris.Context) {\n\tid := ctx.Params().GetInt64Default(\"id\", 0)\n\n\tvar attrs map[string]interface{}\n\tif err := ctx.ReadJSON(&attrs); err != nil {\n\t\treturn\n\t}\n\n\taffected, err := h.service.PartialUpdate(ctx.Request().Context(), id, attrs)\n\tif err != nil {\n\t\tif err == sql.ErrUnprocessable {\n\t\t\tctx.StopWithJSON(iris.StatusUnprocessableEntity, newError(iris.StatusUnprocessableEntity, ctx.Request().Method, ctx.Path(), \"unsupported value(s)\"))\n\t\t\treturn\n\t\t}\n\n\t\tdebugf(\"CategoryHandler.PartialUpdate(DB): %v\", err)\n\t\twriteInternalServerError(ctx)\n\t\treturn\n\t}\n\n\tstatus := iris.StatusOK\n\tif affected == 0 {\n\t\tstatus = iris.StatusNotModified\n\t}\n\n\tctx.StatusCode(status)\n}", "func (n *Node) PutItem(kgname, item string, data string, expectError bool) {\n\tstatus, err := n.Client.Update(context.Background(), &client.UpdateRequest{\n\t\tKeygroup: kgname,\n\t\tId: item,\n\t\tData: data,\n\t})\n\n\tif err != nil && !expectError {\n\t\tlog.Warn().Msgf(\"Update: error %s\", err)\n\t\tn.Errors++\n\t\treturn\n\t}\n\n\tif err == nil && expectError {\n\t\tlog.Warn().Msg(\"Update: Expected Error bot got no error\")\n\t\tn.Errors++\n\t\treturn\n\t}\n\n\tif err == nil && status.Status == client.EnumStatus_ERROR && !expectError {\n\t\tlog.Warn().Msgf(\"Update: error %s with status %s\", err, status.Status)\n\t\tn.Errors++\n\t}\n}", "func (c WorkItemTypeResource) Update(obj interface{}, r api2go.Request) (api2go.Responder, error) {\n\tworkItemType, ok := obj.(models.WorkItemType)\n\tif !ok {\n\t\treturn &api2go.Response{}, api2go.NewHTTPError(errors.New(\"Invalid instance given\"), \"Invalid instance given\", http.StatusBadRequest)\n\t}\n\terr := c.WorkItemTypeStorage.Update(workItemType)\n\treturn &api2go.Response{Res: workItemType, Code: http.StatusNoContent}, err\n}", "func UpdateItem(queryItem Item, updateItem Item) error {\n\tcfDict, err := ConvertMapToCFDictionary(queryItem.attr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer Release(C.CFTypeRef(cfDict))\n\tcfDictUpdate, err := ConvertMapToCFDictionary(updateItem.attr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer Release(C.CFTypeRef(cfDictUpdate))\n\terrCode := C.SecItemUpdate(cfDict, cfDictUpdate)\n\terr = checkError(errCode)\n\treturn err\n}", "func updateItem(tableName, channelID, username string) {\n\t// Create DynamoDB client\n\tmySession := session.Must(session.NewSession())\n\n\t// Create a DynamoDB client with additional configuration\n\tsvc := dynamodb.New(mySession, aws.NewConfig().WithRegion(\"eu-west-1\"))\n\n\t// Get the actual version of the item\n\toldItem := readItem(tableName, channelID)\n\n\t// Append the actual Usernames list with the new username\n\tnewUsernames := append(oldItem.Usernames, username)\n\n\titem := item{\n\t\tChanelID: channelID,\n\t\tUsernames: newUsernames,\n\t}\n\n\t// Marshal the Item into a readable format for DynamoDB\n\tav, err := dynamodbattribute.MarshalMap(item)\n\tif err != nil {\n\t\tfmt.Println(\"Got error marshalling new movie item:\")\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\n\t// Create the PutItemInput object\n\tinput := &dynamodb.PutItemInput{\n\t\tItem: av,\n\t\tTableName: aws.String(tableName),\n\t}\n\n\t// Put the item into the DynamoDB table\n\t_, err = svc.PutItem(input)\n\tif err != nil {\n\t\tfmt.Println(\"Got error calling PutItem:\")\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n}", "func (m *Client) UpdateDynamicContentItem(arg0 context.Context, arg1 int64, arg2 zendesk.DynamicContentItem) (zendesk.DynamicContentItem, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateDynamicContentItem\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(zendesk.DynamicContentItem)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func ModifyItemsForbidden(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.ItemsController, id int, payload *app.ModifyItemPayload) http.ResponseWriter {\n\t// Setup service\n\tvar (\n\t\tlogBuf bytes.Buffer\n\t\tresp interface{}\n\n\t\trespSetter goatest.ResponseSetterFunc = func(r interface{}) { resp = r }\n\t)\n\tif service == nil {\n\t\tservice = goatest.Service(&logBuf, respSetter)\n\t} else {\n\t\tlogger := log.New(&logBuf, \"\", log.Ltime)\n\t\tservice.WithLogger(goa.NewLogger(logger))\n\t\tnewEncoder := func(io.Writer) goa.Encoder { return respSetter }\n\t\tservice.Encoder = goa.NewHTTPEncoder() // Make sure the code ends up using this decoder\n\t\tservice.Encoder.Register(newEncoder, \"*/*\")\n\t}\n\n\t// Validate payload\n\terr := payload.Validate()\n\tif err != nil {\n\t\te, ok := err.(goa.ServiceError)\n\t\tif !ok {\n\t\t\tpanic(err) // bug\n\t\t}\n\t\tt.Errorf(\"unexpected payload validation error: %+v\", e)\n\t\treturn nil\n\t}\n\n\t// Setup request context\n\trw := httptest.NewRecorder()\n\tu := &url.URL{\n\t\tPath: fmt.Sprintf(\"/item/%v\", id),\n\t}\n\treq, err := http.NewRequest(\"PUT\", u.String(), nil)\n\tif err != nil {\n\t\tpanic(\"invalid test \" + err.Error()) // bug\n\t}\n\tprms := url.Values{}\n\tprms[\"id\"] = []string{fmt.Sprintf(\"%v\", id)}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgoaCtx := goa.NewContext(goa.WithAction(ctx, \"ItemsTest\"), rw, req, prms)\n\tmodifyCtx, err := app.NewModifyItemsContext(goaCtx, req, service)\n\tif err != nil {\n\t\tpanic(\"invalid test data \" + err.Error()) // bug\n\t}\n\tmodifyCtx.Payload = payload\n\n\t// Perform action\n\terr = ctrl.Modify(modifyCtx)\n\n\t// Validate response\n\tif err != nil {\n\t\tt.Fatalf(\"controller returned %+v, logs:\\n%s\", err, logBuf.String())\n\t}\n\tif rw.Code != 403 {\n\t\tt.Errorf(\"invalid response status code: got %+v, expected 403\", rw.Code)\n\t}\n\n\t// Return results\n\treturn rw\n}", "func (_m *Delivery) UpdateItem(c echo.Context) error {\n\tret := _m.Called(c)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(echo.Context) error); ok {\n\t\tr0 = rf(c)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (e *engine) UpdateOne(c *httpEngine.ServerContext) {\n\t// check iid exists or not\n\tid, err := c.GetURLParam(\"iid\")\n\tif err != nil {\n\t\tc.ErrorHandler(400, err)\n\t\treturn\n\t}\n\n\tvar product = &domain.Product{}\n\t// check is valid json for product\n\terr = c.BindToJson(product)\n\tif err != nil {\n\t\tc.ErrorHandler(400, err)\n\t\treturn\n\n\t}\n\tproduct.Iid = id\n\tres, err := e.ProductLogic.UpdateProduct(product)\n\tif err != nil {\n\t\tc.ErrorHandler(400, err)\n\t\treturn\n\n\t}\n\tc.JSON(200, res)\n}", "func (itemHandle) Upsert(c *app.Context) error {\n\tvar it item.Item\n\tif err := json.NewDecoder(c.Request.Body).Decode(&it); err != nil {\n\t\treturn err\n\t}\n\n\tif err := item.Upsert(c.SessionID, c.Ctx[\"DB\"].(*db.DB), &it); err != nil {\n\t\treturn err\n\t}\n\n\tc.Respond(nil, http.StatusNoContent)\n\treturn nil\n}", "func UpdateWithID(c *server.Context) error {\n\tvar (\n\t\terr error\n\t\tw *ware.Ware\n\t\treq struct {\n\t\t\tID uint32 `json:\"id\" validate:\"required\"`\n\t\t\tName string `json:\"name\"`\n\t\t\tDesc string `json:\"desc\" validate:\"max=50\"`\n\t\t\tParentCategoryID uint32 `json:\"parent_category_id\"`\n\t\t\tCategoryID uint32 `json:\"category_id\"`\n\t\t\tTotalSale uint32 `json:\"total_sale\"`\n\t\t\tAvatar string `json:\"avatar\"`\n\t\t\tImage string `json:\"image\"`\n\t\t\tDetailPic string `json:\"detail_pic\"`\n\t\t\tInventory uint32 `json:\"inventory\"`\n\t\t}\n\t)\n\n\tisAdmin := c.Request().Context().Value(\"user\").(jwtgo.MapClaims)[util.IsAdmin].(bool)\n\tif !isAdmin {\n\t\tlogger.Error(\"You don't have access\")\n\t\treturn core.WriteStatusAndDataJSON(c, constants.ErrToken, nil)\n\t}\n\n\terr = c.JSONBody(&req)\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn core.WriteStatusAndDataJSON(c, constants.ErrInvalidParam, nil)\n\t}\n\n\terr = c.Validate(req)\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn core.WriteStatusAndDataJSON(c, constants.ErrInvalidParam, nil)\n\t}\n\n\tconn, err := mysql.Pool.Get()\n\tdefer mysql.Pool.Release(conn)\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn core.WriteStatusAndDataJSON(c, constants.ErrMysql, nil)\n\t}\n\n\tw, err = ware.Service.GetByID(conn, req.ID)\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn core.WriteStatusAndDataJSON(c, constants.ErrMysql, nil)\n\t}\n\n\tif len(req.Avatar) > 0 {\n\t\terr = util.UpdatePic(req.Avatar, w.Avatar)\n\t\tif err != nil {\n\t\t\tlogger.Error(err)\n\t\t\treturn core.WriteStatusAndDataJSON(c, constants.ErrInternalServerError, nil)\n\t\t}\n\t}\n\tif len(req.Image) > 0 {\n\t\terr = util.UpdatePic(req.Image, w.Image)\n\t\tif err != nil {\n\t\t\tlogger.Error(err)\n\t\t\treturn core.WriteStatusAndDataJSON(c, constants.ErrInternalServerError, nil)\n\t\t}\n\t}\n\tif len(req.DetailPic) > 0 {\n\t\terr = util.UpdatePic(req.DetailPic, w.DetailPic)\n\t\tif err != nil {\n\t\t\tlogger.Error(err)\n\t\t\treturn core.WriteStatusAndDataJSON(c, constants.ErrInternalServerError, nil)\n\t\t}\n\t}\n\n\tw.Name = req.Name\n\tw.CategoryID = req.CategoryID\n\tw.Desc = req.Desc\n\tw.ParentCategoryID = req.ParentCategoryID\n\tw.TotalSale = req.TotalSale\n\tw.Inventory = req.Inventory\n\n\terr = ware.Service.UpdateWare(conn, w)\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn core.WriteStatusAndDataJSON(c, constants.ErrMysql, nil)\n\t}\n\n\treturn core.WriteStatusAndDataJSON(c, constants.ErrSucceed, nil)\n}", "func (m *MockSubTaskDao) UpdateItem(item *task.OwlExecItem) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateItem\", item)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func Update(Items Item) error {\n\terr := db.C(\"unit\").Update(bson.M{\"_id\": Items.ID}, &Items)\n\treturn err\n}", "func (c *Checklist) ToggleItem(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tif i := r.URL.Query().Get(\"item\"); len(i) != 0 {\n\t\titem := c.getItem(i)\n\n\t\tif item == nil {\n\t\t\tc.b.Response(\"\", \"Item doesn't exist\", http.StatusBadRequest, w)\n\t\t\treturn\n\t\t}\n\n\t\titem.Done = !item.Done\n\n\t\tgo c.b.WSChecklistUpdate()\n\t\tjson.NewEncoder(w).Encode(c.Items)\n\t\tc.Finished = c.CheckDone()\n\t\treturn\n\t}\n\tc.b.Response(\"\", \"no item defined\", http.StatusBadRequest, w)\n}", "func (api *MediaApi) update(c *routing.Context) error {\n\tid := c.Param(\"id\")\n\n\tmodel, fetchErr := api.dao.GetByID(id)\n\tif fetchErr != nil {\n\t\treturn utils.NewNotFoundError(fmt.Sprintf(\"Media item with id \\\"%v\\\" doesn't exist!\", id))\n\t}\n\n\tform := &models.MediaUpdateForm{}\n\tif readErr := c.Read(form); readErr != nil {\n\t\treturn utils.NewBadRequestError(\"Oops, an error occurred while updating media item.\", readErr)\n\t}\n\n\tform.Model = model\n\n\tupdatedModel, updateErr := api.dao.Update(form)\n\n\tif updateErr != nil {\n\t\treturn utils.NewBadRequestError(\"Oops, an error occurred while updating media item.\", updateErr)\n\t}\n\n\tupdatedModel = daos.ToAbsMediaPath(updatedModel)\n\n\treturn c.Write(updatedModel)\n}", "func (id *ItemDescription) Update() *ItemDescriptionUpdateOne {\n\treturn (&ItemDescriptionClient{config: id.config}).UpdateOne(id)\n}", "func (r *PolicySetItemRequest) Update(ctx context.Context, reqObj *PolicySetItem) error {\n\treturn r.JSONRequest(ctx, \"PATCH\", \"\", reqObj, nil)\n}", "func (a *TodoAdapter) Update(ctx context.Context, t todo.Todo) error {\n\tspan, _ := opentracing.StartSpanFromContext(ctx, \"TodoAdapter-Update\")\n\tdefer span.Finish()\n\n\toid, err := primitive.ObjectIDFromHex(string(t.ID))\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//Filter\n\tfilter := bson.M{\"_id\": bson.M{\"$eq\": oid}}\n\n\t//Update fields\n\tdocument := bson.M{\"$set\": bson.M{\n\t\t\"title\": t.Title,\n\t\t\"description\": t.Description,\n\t\t\"priority_level\": t.Priority,\n\t\t\"completed\": t.Completed,\n\t\t\"updated_at\": t.UpdatedAt,\n\t}}\n\n\t//Update Item\n\tresult, err := a.collection.UpdateOne(ctx, filter, document)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif result.MatchedCount > 0 {\n\t\treturn nil\n\t}\n\n\treturn ErrNoItemsUpdated\n}", "func (s *OrderItemService) Update(ctx context.Context, id string, uoi entity.UpdateOrderItem) error {\n\treturn s.repo.Update(ctx, id, uoi)\n}", "func (t *Procure2Pay) UpdateItemForSupplier(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tvar obj_uiitem item\n\tvar obj_bcitem item\n\tvar err error\n\n\tfmt.Println(\"Entering UpdateItemForSupplier\")\n\n\tif (len(args) < 1) {\n\t\tfmt.Println(\"Invalid number of args\")\n\t\treturn shim.Error(err.Error())\n\t\t//return nil,nil\n\t}\n\n\terr = json.Unmarshal([]byte(args[0]), &obj_uiitem)\n if err != nil {\n\t\tfmt.Printf(\"Unable to marshal createTransaction input UpdateTransaction : %s\\n\", err)\n\t\treturn shim.Error(err.Error())\n\t\t//return nil, nil\n\t}\n\n\tfmt.Println(\"\\n refno variable value is : \",obj_uiitem.SupplierID); \n\n\t// code to get data from blockchain using dynamic key starts here\n\tvar bytesread []byte\t\n\tbytesread, err = stub.GetState(obj_uiitem.SupplierID)\n\terr = json.Unmarshal(bytesread, &obj_bcitem)\n\t// code to get data from blockchain using dynamic key ends here\n\n\tfmt.Printf(\"\\nobj_bcitem : %s \", obj_bcitem)\n\t\n\tobj_bcitem.SupplierID=obj_uiitem.SupplierID\n\tobj_bcitem.ItemID=obj_uiitem.ItemID\n\t//obj_bcitem.Item=obj_uiitem.Item\n\t//obj_bcitem.Quantity=obj_uiitem.Quantity\n\tobj_bcitem.PriceUnit=obj_uiitem.PriceUnit\n\n\t// Data insertion for Couch DB starts here \n\ttransJSONasBytes, err := json.Marshal(obj_bcitem)\n\terr = stub.PutState(obj_uiitem.SupplierID, transJSONasBytes)\n\t// Data insertion for Couch DB ends here \n\t\t\n\tfmt.Println(\"UpdateItemForSupplier Successfully updated.\")\t\n\n\tif err != nil {\n\t\t\t\tfmt.Printf(\"\\nUnable to make transevent inputs : %v \", err)\n\t\t\t\treturn shim.Error(err.Error())\n\t\t\t\t//return nil,nil\n\t\t\t}\n\treturn shim.Success(nil)\n\t//return nil, nil\n}", "func (o *ItemSide) SetItem(ctx context.Context, exec boil.ContextExecutor, insert bool, related *Item) error {\n\tvar err error\n\tif insert {\n\t\tif err = related.Insert(ctx, exec, boil.Infer()); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to insert into foreign table\")\n\t\t}\n\t}\n\n\tupdateQuery := fmt.Sprintf(\n\t\t\"UPDATE \\\"item_sides\\\" SET %s WHERE %s\",\n\t\tstrmangle.SetParamNames(\"\\\"\", \"\\\"\", 0, []string{\"item_id\"}),\n\t\tstrmangle.WhereClause(\"\\\"\", \"\\\"\", 0, itemSidePrimaryKeyColumns),\n\t)\n\tvalues := []interface{}{related.ID, o.ItemID, o.SideItemID}\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, updateQuery)\n\t\tfmt.Fprintln(writer, values)\n\t}\n\tif _, err = exec.ExecContext(ctx, updateQuery, values...); err != nil {\n\t\treturn errors.Wrap(err, \"failed to update local table\")\n\t}\n\n\tqueries.Assign(&o.ItemID, related.ID)\n\tif o.R == nil {\n\t\to.R = &itemSideR{\n\t\t\tItem: related,\n\t\t}\n\t} else {\n\t\to.R.Item = related\n\t}\n\n\tif related.R == nil {\n\t\trelated.R = &itemR{\n\t\t\tItemSide: o,\n\t\t}\n\t} else {\n\t\trelated.R.ItemSide = o\n\t}\n\n\treturn nil\n}", "func ModifyItemsNotFound(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.ItemsController, id int, payload *app.ModifyItemPayload) http.ResponseWriter {\n\t// Setup service\n\tvar (\n\t\tlogBuf bytes.Buffer\n\t\tresp interface{}\n\n\t\trespSetter goatest.ResponseSetterFunc = func(r interface{}) { resp = r }\n\t)\n\tif service == nil {\n\t\tservice = goatest.Service(&logBuf, respSetter)\n\t} else {\n\t\tlogger := log.New(&logBuf, \"\", log.Ltime)\n\t\tservice.WithLogger(goa.NewLogger(logger))\n\t\tnewEncoder := func(io.Writer) goa.Encoder { return respSetter }\n\t\tservice.Encoder = goa.NewHTTPEncoder() // Make sure the code ends up using this decoder\n\t\tservice.Encoder.Register(newEncoder, \"*/*\")\n\t}\n\n\t// Validate payload\n\terr := payload.Validate()\n\tif err != nil {\n\t\te, ok := err.(goa.ServiceError)\n\t\tif !ok {\n\t\t\tpanic(err) // bug\n\t\t}\n\t\tt.Errorf(\"unexpected payload validation error: %+v\", e)\n\t\treturn nil\n\t}\n\n\t// Setup request context\n\trw := httptest.NewRecorder()\n\tu := &url.URL{\n\t\tPath: fmt.Sprintf(\"/item/%v\", id),\n\t}\n\treq, err := http.NewRequest(\"PUT\", u.String(), nil)\n\tif err != nil {\n\t\tpanic(\"invalid test \" + err.Error()) // bug\n\t}\n\tprms := url.Values{}\n\tprms[\"id\"] = []string{fmt.Sprintf(\"%v\", id)}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgoaCtx := goa.NewContext(goa.WithAction(ctx, \"ItemsTest\"), rw, req, prms)\n\tmodifyCtx, err := app.NewModifyItemsContext(goaCtx, req, service)\n\tif err != nil {\n\t\tpanic(\"invalid test data \" + err.Error()) // bug\n\t}\n\tmodifyCtx.Payload = payload\n\n\t// Perform action\n\terr = ctrl.Modify(modifyCtx)\n\n\t// Validate response\n\tif err != nil {\n\t\tt.Fatalf(\"controller returned %+v, logs:\\n%s\", err, logBuf.String())\n\t}\n\tif rw.Code != 404 {\n\t\tt.Errorf(\"invalid response status code: got %+v, expected 404\", rw.Code)\n\t}\n\n\t// Return results\n\treturn rw\n}", "func (slir *ShoppingListItemRepository) UpdateByUserGUIDAndDealGUID(dbTransaction *gorm.DB, userGUID string, dealGUID string,\n\tdata map[string]interface{}) *systems.ErrorData {\n\n\tupdateData := map[string]interface{}{}\n\n\tfor key, value := range data {\n\t\tif data, ok := value.(string); ok && value.(string) != \"\" {\n\t\t\tupdateData[snaker.CamelToSnake(key)] = data\n\t\t}\n\n\t\tif data, ok := value.(int); ok {\n\t\t\tif key == \"Quantity\" && data != 0 {\n\t\t\t\tupdateData[snaker.CamelToSnake(key)] = data\n\t\t\t}\n\n\t\t\tif key != \"Quantity\" {\n\t\t\t\tupdateData[snaker.CamelToSnake(key)] = data\n\t\t\t}\n\t\t}\n\t}\n\n\tresult := dbTransaction.Model(&ShoppingListItem{}).Where(&ShoppingListItem{UserGUID: userGUID, DealGUID: &dealGUID}).\n\t\tUpdates(updateData)\n\n\tif result.Error != nil {\n\t\treturn Error.InternalServerError(result.Error, systems.DatabaseError)\n\t}\n\n\treturn nil\n}", "func (r *HealthResource) Edit(id string, item HealthConfig) error {\n\tif err := r.c.ModQuery(\"PUT\", BasePath+HealthEndpoint+\"/\"+id, item); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (w *HotCache) Update(item *HotPeerStat) {\n\tswitch item.Kind {\n\tcase WriteFlow:\n\t\tw.writeFlow.Update(item)\n\tcase ReadFlow:\n\t\tw.readFlow.Update(item)\n\t}\n\n\tif item.IsNeedDelete() {\n\t\tw.incMetrics(\"remove_item\", item.StoreID, item.Kind)\n\t} else if item.IsNew() {\n\t\tw.incMetrics(\"add_item\", item.StoreID, item.Kind)\n\t} else {\n\t\tw.incMetrics(\"update_item\", item.StoreID, item.Kind)\n\t}\n}", "func (pi *PillorderItem) Update() *PillorderItemUpdateOne {\n\treturn (&PillorderItemClient{config: pi.config}).UpdateOne(pi)\n}", "func (gi *Sensor) Update(db *pg.DB) error {\r\n\tlog.Printf(\"===>sensorItem.Update()\")\r\n\r\n\t_, updateErr := db.Model(gi).\r\n\t\tWhere(\"id = ?0\", gi.ID).Update()\r\n\tif updateErr != nil {\r\n\t\tlog.Printf(\"Error while updating item in sensorItem.Update()\\n\")\r\n\t\tlog.Printf(\"Reason %v\\n\", updateErr)\r\n\t\treturn updateErr\r\n\t}\r\n\tlog.Printf(\"Product %s updated successfully in table\", gi.Sensorname)\r\n\treturn nil\r\n}", "func (r *ExternalItemRequest) Update(ctx context.Context, reqObj *ExternalItem) error {\n\treturn r.JSONRequest(ctx, \"PATCH\", \"\", reqObj, nil)\n}", "func UpdatePart(writer http.ResponseWriter, req *http.Request) *http_res.HttpResponse {\n\treqMap := util.RequestBodyAsMap(req)\n\tif !util.ValidateUpdate(*reqMap, \"inventory\") {\n\t\tfmt.Println(\"Bad input\")\n\t\treturn http_res.GenerateHttpResponse(http.StatusBadRequest, errors.New(\"Bad Input\"))\n\t}\n\n\tvars := mux.Vars(req)\n\terr := util.UpdateTable(\"inventory\", (vars[\"part_id\"]), \"part_id\", *reqMap)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\treturn http_res.GenerateHttpResponse(http.StatusBadRequest, errors.New(\"Badder Input\"))\n\t}\n\treturn http_res.GenerateHttpResponse(http.StatusOK, \"Successful Update\")\n}", "func (t *Baggage) updateItemStatus(stub shim.ChaincodeStubInterface, args []string) pb.Response {\r\n\r\n\t//checking the number of argument\r\n\tif len(args) < 3 {\r\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 3\")\r\n\t}\r\n\r\n\trecBytes := args[0]\r\n\tupdatedAt := args[1]\r\n\t//identity := args[2]\r\n\r\n\tvar lineItemRecordMap map[string]interface{}\r\n\r\n\terr := json.Unmarshal([]byte(recBytes), &lineItemRecordMap)\r\n\tif err != nil {\r\n\t\treturn shim.Error(\"Failed to unmarshal recBytes\")\r\n\t}\r\n\r\n\t//==== Check if Pnr already exists ====\r\n\tfetchedPnrDetails, err := stub.GetState(\"ITEM:\" + getSafeString(lineItemRecordMap[\"itemId\"]))\r\n\tif err != nil {\r\n\t\treturn shim.Error(\"Failed to get ITEM details: \" + err.Error())\r\n\t} else if fetchedPnrDetails == nil {\r\n\t\tfmt.Println(\"This ITEM does not exists:\" + getSafeString(lineItemRecordMap[\"itemId\"]))\r\n\t\treturn shim.Error(\"This ITEM does not exists:\" + getSafeString(lineItemRecordMap[\"itemId\"]))\r\n\t}\r\n\r\n\tvar itemMap map[string]interface{}\r\n\terr = json.Unmarshal(fetchedPnrDetails, &itemMap)\r\n\tif err != nil {\r\n\t\treturn shim.Error(\"Failed to unmarshal item\")\r\n\t}\r\n\titemMap[\"status\"] = getSafeString(lineItemRecordMap[\"status\"])\r\n\titemMap[\"updatedAt\"] = updatedAt\r\n\r\n\toutputMapBytes, _ := json.Marshal(itemMap)\r\n\t//Store the records\r\n\tstub.PutState(\"ITEM:\"+getSafeString(itemMap[\"itemId\"]), outputMapBytes)\r\n\tif err != nil {\r\n\t\treturn shim.Error(err.Error())\r\n\t}\r\n\r\n\treturn shim.Success([]byte(\"SUCCESS\"))\r\n}", "func (d *Dump) Update(f func(items []Item) error) error {\n\td.mutex.Lock()\n\tdefer d.mutex.Unlock()\n\n\tif err := f(d.items); err != nil {\n\t\treturn err\n\t}\n\n\tif d.persist == PERSIST_WRITES {\n\t\treturn d.save()\n\t}\n\n\treturn nil\n}", "func (h Handler) Update(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\tdata := postData{}\n\terr := json.NewDecoder(r.Body).Decode(&data)\n\tif err != nil {\n\t\th.log.Println(err)\n\t\tres := response.Resp{\n\t\t\tStatus: \"error\",\n\t\t\tData: \"There was an problem, please try again\",\n\t\t}\n\t\tresponse.Writer(w, res)\n\t\treturn\n\t}\n\tif data.Name == \"\" || data.Desc == \"\" {\n\t\tres := response.Resp{\n\t\t\tStatus: \"error\",\n\t\t\tData: \"Empty post values\",\n\t\t}\n\t\tresponse.Writer(w, res)\n\t\treturn\n\t}\n\tid, err := strconv.ParseUint(p.ByName(\"id\"), 10, 64)\n\tif err != nil {\n\t\th.log.Println(err)\n\t\tres := response.Resp{\n\t\t\tStatus: \"error\",\n\t\t\tData: \"There was an problem, please try again\",\n\t\t}\n\t\tresponse.Writer(w, res)\n\t\treturn\n\t}\n\ttodo, err := h.m.Update(id, model.Todo{Name: data.Name, Description: data.Desc})\n\tif err != nil {\n\t\th.log.Println(err)\n\t\tres := response.Resp{\n\t\t\tStatus: \"error\",\n\t\t\tData: \"There was an problem, please try again\",\n\t\t}\n\t\tresponse.Writer(w, res)\n\t\treturn\n\t}\n\tres := response.Resp{\n\t\tStatus: \"succes\",\n\t\tData: todo,\n\t}\n\tresponse.Writer(w, res)\n}", "func (m *Mongo) UpdateOrderItem(dbname string, id string, item *proto.OrderRecord_Item) error {\n\tc := m.session.DB(dbname).C(orderItemsCollectionName)\n\tselector := bson.ObjectIdHex(id)\n\tupdataData := bson.M{\"$set\": bson.M{\n\t\t\"quantity\": item.Quantity,\n\t\t// \"unitPrice\": item.UnitPrice,\n\t\t\"updated_at\": time.Now()}}\n\n\treturn c.UpdateId(selector, updataData)\n}", "func (o *Block) UpdateConfigurationItem(ctx context.Context, oldItem struct {\n\tV0 string\n\tV1 map[string]dbus.Variant\n}, newItem struct {\n\tV0 string\n\tV1 map[string]dbus.Variant\n}, options map[string]dbus.Variant) (err error) {\n\terr = o.object.CallWithContext(ctx, InterfaceBlock+\".UpdateConfigurationItem\", 0, oldItem, newItem, options).Store()\n\treturn\n}", "func Update(id string, params *InvoiceItemParams) (*InvoiceItem, error) {\n\treturn getC().Update(id, params)\n}", "func (s *Stack) Update(id uint64, newValue []byte) (*Item, error) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\t// Check if stack is closed.\n\tif !s.isOpen {\n\t\treturn nil, ErrDBClosed\n\t}\n\n\t// Check if item exists in stack.\n\tif id > s.head || id <= s.tail {\n\t\treturn nil, ErrOutOfBounds\n\t}\n\n\t// Create new Item.\n\titem := &Item{\n\t\tID: id,\n\t\tKey: idToKey(id),\n\t\tValue: newValue,\n\t}\n\n\t// Update this item in the stack.\n\tif err := s.db.Update(func(txn *badger.Txn) error {\n\t\terr := txn.Set(item.Key, item.Value)\n\t\treturn err\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn item, nil\n}", "func updateMenuItemHandler(w http.ResponseWriter, request *http.Request) {\n\n\tvar reqPayload restaurantReqBody\n\t_ = json.NewDecoder(request.Body).Decode(&reqPayload)\n\tfmt.Println(\"Menu ItemPayload \", reqPayload.Item)\n\tinfo := &mgo.DialInfo{\n\t\tAddrs: []string{mongodb_server},\n\t\tTimeout: 60 * time.Second,\n\t\tDatabase: mongodb_database,\n\t\tUsername: mongo_username,\n\t\tPassword: mongo_password,\n\t}\n\n\tsession, err := mgo.DialWithInfo(info)\n\tif err != nil {\n\t\tErrorWithJSON(w, \"Internal server error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tdefer session.Close()\n\tmongo_collection := session.DB(mongodb_database).C(mongodb_collection)\n\n\tvar menu RestaurantMenu\n\terr = mongo_collection.Find(bson.M{\"restaurantid\": reqPayload.RestaurantId}).One(&menu)\n\tif err != nil {\n\t\tfmt.Println(\"error: \", err)\n\t\tErrorWithJSON(w, \"Restaurant not found\", http.StatusNotFound)\n\t\treturn\n\t} else {\n\t\tfor i := 0; i < len(menu.Items); i++ {\n\t\t\tif menu.Items[i].Id == reqPayload.Item.Id {\n\t\t\t\tmenu.Items[i].Name = reqPayload.Item.Name\n\t\t\t\tmenu.Items[i].Price = reqPayload.Item.Price\n\t\t\t\tmenu.Items[i].Description = reqPayload.Item.Description\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\terror := mongo_collection.Update(bson.M{\"restaurantid\": menu.RestaurantId}, bson.M{\"$set\": bson.M{\"items\": menu.Items}})\n\t\tif error != nil {\n\t\t\tErrorWithJSON(w, \"Internal server error\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n\n\trespBody, err := json.MarshalIndent(menu, \"\", \" \")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tResponseWithJSON(w, respBody, http.StatusOK)\n\n}", "func Update(w http.ResponseWriter, r *http.Request) {\n\tc := flight.Context(w, r)\n\n\tif !c.FormValid(\"tittle\", \"issian\") {\n\t\tEdit(w, r)\n\t\treturn\n\t}\n\n\t_, err := article.Update(c.DB, r.FormValue(\"tittle\"), r.FormValue(\"issian\"), c.Param(\"id\"), c.UserID)\n\tif err != nil {\n\t\tc.FlashErrorGeneric(err)\n\t\tEdit(w, r)\n\t\treturn\n\t}\n\n\tc.FlashSuccess(\"Article updated.\")\n\tc.Redirect(uri)\n}", "func (r *PoolNAPTRResource) Edit(id string, item Pool) error {\n\tif err := r.c.ModQuery(\"PUT\", BasePath+PoolNAPTREndpoint+\"/\"+id, item); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (api *FoodRecipeAPI) partialRecipeUpdate(w http.ResponseWriter, req *http.Request) {\n\tdefer DrainBody(req)\n\tctx := req.Context()\n\n\tvars := mux.Vars(req)\n\tid := vars[\"id\"]\n\tlogData := log.Data{\"id\": id}\n\n\tvar errorObjects []*models.ErrorObject\n\n\tpatchJSON, recipePatches, err := patch.Get(ctx, req.Body)\n\tif err != nil {\n\t\terrorObjects = append(errorObjects, &models.ErrorObject{Error: err.Error()})\n\t\tErrorResponse(ctx, w, http.StatusBadRequest, &models.ErrorResponse{Errors: errorObjects})\n\t\treturn\n\t}\n\n\t// Validate patch request\n\tfor i, recipePatch := range *recipePatches {\n\t\tif err = recipePatch.Validate(nil); err != nil {\n\t\t\tif _, ok := err.(*validator.InvalidValidationError); ok {\n\t\t\t\terrorObjects = append(errorObjects, &models.ErrorObject{Error: errs.ErrInternalServer.Error()})\n\t\t\t\tErrorResponse(ctx, w, http.StatusInternalServerError, &models.ErrorResponse{Errors: errorObjects})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor _, err := range err.(validator.ValidationErrors) {\n\t\t\t\terrorObjects = append(errorObjects, models.HandleValidationErrors(strconv.Itoa(i), err.ActualTag(), err.StructField(), err.Value().(string), err.Param()))\n\t\t\t}\n\t\t}\n\t}\n\tif len(errorObjects) > 0 {\n\t\tErrorResponse(ctx, w, http.StatusBadRequest, &models.ErrorResponse{Errors: errorObjects})\n\t\treturn\n\t}\n\n\t// apply patch against recipe resource\n\tp, err := jsonpatch.DecodePatch(patchJSON)\n\tif err != nil {\n\t\tlog.Error(ctx, \"patch recipe: unable to decode patch\", err)\n\t\terrorObjects = append(errorObjects, &models.ErrorObject{Error: err.Error()})\n\t\tErrorResponse(ctx, w, http.StatusBadRequest, &models.ErrorResponse{Errors: errorObjects})\n\t\treturn\n\t}\n\n\t// find current recipe doc\n\tvar recipe models.Recipe\n\n\tcollection := api.MongoClient.Database(\"food-recipes\").Collection(\"recipes\")\n\tif err = collection.FindOne(ctx, bson.M{\"_id\": id}).Decode(&recipe); err != nil {\n\t\tif err == mongo.ErrNoDocuments {\n\t\t\tlog.Warn(ctx, \"patch recipe: failed to find recipe\", log.FormatErrors([]error{err}), logData)\n\t\t\terrorObjects = append(errorObjects, &models.ErrorObject{Error: errs.ErrRecipeNotFound.Error()})\n\t\t\tErrorResponse(ctx, w, http.StatusNotFound, &models.ErrorResponse{Errors: errorObjects})\n\t\t\treturn\n\t\t}\n\n\t\tlog.Error(ctx, \"patch recipe: failed to find recipe, bad connection?\", err)\n\t\terrorObjects = append(errorObjects, &models.ErrorObject{Error: errs.ErrInternalServer.Error()})\n\t\tErrorResponse(ctx, w, http.StatusInternalServerError, &models.ErrorResponse{Errors: errorObjects})\n\t\treturn\n\t}\n\n\tb, err := json.Marshal(recipe)\n\tif err != nil {\n\t\tlog.Error(ctx, \"patch recipe: error returned from json marshal\", err, logData)\n\t\terrorObjects = append(errorObjects, &models.ErrorObject{Error: errs.ErrInternalServer.Error()})\n\t\tErrorResponse(ctx, w, http.StatusInternalServerError, &models.ErrorResponse{Errors: errorObjects})\n\t\treturn\n\t}\n\n\t// apply patch to existing recipe\n\tmodified, err := p.Apply(b)\n\tif err != nil {\n\t\tlog.Error(ctx, \"patch recipe: unable to apply patch to recipe\", err, logData)\n\t\terrorObjects = append(errorObjects, &models.ErrorObject{Error: err.Error()})\n\t\tErrorResponse(ctx, w, http.StatusBadRequest, &models.ErrorResponse{Errors: errorObjects})\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(modified, &recipe)\n\tif err != nil {\n\t\tlog.Error(ctx, \"patch recipe: unmarshal modified recipe into recipe struct\", err, logData)\n\t\terrorObjects = append(errorObjects, &models.ErrorObject{Error: err.Error()})\n\t\tErrorResponse(ctx, w, http.StatusBadRequest, &models.ErrorResponse{Errors: errorObjects})\n\t\treturn\n\t}\n\n\t// store new recipe\n\tif _, err = collection.ReplaceOne(ctx, bson.M{\"_id\": id}, recipe); err != nil {\n\t\tif err == mongo.ErrNoDocuments {\n\t\t\tlog.Error(ctx, \"update recipe: failed to update recipe, recipe deos not exists\", err, logData)\n\t\t\terrorObjects = append(errorObjects, &models.ErrorObject{Error: errs.ErrRecipeNotFound.Error()})\n\t\t\tErrorResponse(ctx, w, http.StatusNotFound, &models.ErrorResponse{Errors: errorObjects})\n\t\t\treturn\n\t\t}\n\n\t\tlog.Error(ctx, \"update recipe: failed to insert recipe\", err, logData)\n\t\terrorObjects = append(errorObjects, &models.ErrorObject{Error: errs.ErrInternalServer.Error()})\n\t\tErrorResponse(ctx, w, http.StatusInternalServerError, &models.ErrorResponse{Errors: errorObjects})\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\n\tlog.Info(ctx, \"update recipe: request successful\", logData)\n}", "func (a *Client) UpdateHomepageItem(params *UpdateHomepageItemParams) (*UpdateHomepageItemOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewUpdateHomepageItemParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"update_homepage_item\",\n\t\tMethod: \"PATCH\",\n\t\tPathPattern: \"/homepage_items/{homepage_item_id}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &UpdateHomepageItemReader{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.(*UpdateHomepageItemOK)\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 update_homepage_item: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (s *DynamoDB) Update(ctx context.Context, kind, id string, factory datastore.Factory, updater datastore.Updater) error {\n\t// Get existing data item.\n\tentity := factory()\n\terr := s.Get(ctx, kind, id, entity)\n\tif errors.Is(err, datastore.ErrNotFound) {\n\t\treturn datastore.ErrNotFound\n\t}\n\tif err != nil {\n\t\ts.logger.Error(\"failed to retrieve entity\",\n\t\t\tzap.String(\"id\", id),\n\t\t\tzap.String(\"kind\", kind),\n\t\t\tzap.Error(err),\n\t\t)\n\t\treturn err\n\t}\n\n\t// Update entity by updater.\n\tif err := updater(entity); err != nil {\n\t\ts.logger.Error(\"failed to update entity\",\n\t\t\tzap.String(\"id\", id),\n\t\t\tzap.String(\"kind\", kind),\n\t\t\tzap.Error(err),\n\t\t)\n\t\treturn err\n\t}\n\n\t// Put back the updated data to database.\n\tav, err := dynamodbattribute.MarshalMap(entity)\n\tif err != nil {\n\t\ts.logger.Error(\"failed to marshal entity\",\n\t\t\tzap.String(\"id\", id),\n\t\t\tzap.String(\"kind\", kind),\n\t\t\tzap.Error(err),\n\t\t)\n\t\treturn err\n\t}\n\t// Only update in case the data item which contains key with specificed value existed.\n\texpr, err := buildDynamoDBKeyExistedExpression(\"Id\", id)\n\tif err != nil {\n\t\ts.logger.Error(\"failed to build condition expresion for update\",\n\t\t\tzap.String(\"id\", id),\n\t\t\tzap.String(\"kind\", kind),\n\t\t\tzap.Error(err),\n\t\t)\n\t\treturn err\n\t}\n\n\tinput := &dynamodb.PutItemInput{\n\t\tTableName: aws.String(kind),\n\t\tItem: av,\n\t\tConditionExpression: expr.Condition(),\n\t\tExpressionAttributeNames: expr.Names(),\n\t\tExpressionAttributeValues: expr.Values(),\n\t}\n\t_, err = s.client.PutItemWithContext(ctx, input)\n\tif err != nil {\n\t\ts.logger.Error(\"failed to update entity\",\n\t\t\tzap.String(\"id\", id),\n\t\t\tzap.String(\"kind\", kind),\n\t\t\tzap.Error(err),\n\t\t)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (o *CMFSlideItem) Upsert(ctx context.Context, exec boil.ContextExecutor, updateColumns, insertColumns boil.Columns) error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no cmf_slide_item provided for upsert\")\n\t}\n\n\tif err := o.doBeforeUpsertHooks(ctx, exec); err != nil {\n\t\treturn err\n\t}\n\n\tnzDefaults := queries.NonZeroDefaultSet(cmfSlideItemColumnsWithDefault, o)\n\tnzUniques := queries.NonZeroDefaultSet(mySQLCMFSlideItemUniqueColumns, o)\n\n\tif len(nzUniques) == 0 {\n\t\treturn errors.New(\"cannot upsert with a table that cannot conflict on a unique column\")\n\t}\n\n\t// Build cache key in-line uglily - mysql vs psql problems\n\tbuf := strmangle.GetBuffer()\n\tbuf.WriteString(strconv.Itoa(updateColumns.Kind))\n\tfor _, c := range updateColumns.Cols {\n\t\tbuf.WriteString(c)\n\t}\n\tbuf.WriteByte('.')\n\tbuf.WriteString(strconv.Itoa(insertColumns.Kind))\n\tfor _, c := range insertColumns.Cols {\n\t\tbuf.WriteString(c)\n\t}\n\tbuf.WriteByte('.')\n\tfor _, c := range nzDefaults {\n\t\tbuf.WriteString(c)\n\t}\n\tbuf.WriteByte('.')\n\tfor _, c := range nzUniques {\n\t\tbuf.WriteString(c)\n\t}\n\tkey := buf.String()\n\tstrmangle.PutBuffer(buf)\n\n\tcmfSlideItemUpsertCacheMut.RLock()\n\tcache, cached := cmfSlideItemUpsertCache[key]\n\tcmfSlideItemUpsertCacheMut.RUnlock()\n\n\tvar err error\n\n\tif !cached {\n\t\tinsert, ret := insertColumns.InsertColumnSet(\n\t\t\tcmfSlideItemAllColumns,\n\t\t\tcmfSlideItemColumnsWithDefault,\n\t\t\tcmfSlideItemColumnsWithoutDefault,\n\t\t\tnzDefaults,\n\t\t)\n\t\tupdate := updateColumns.UpdateColumnSet(\n\t\t\tcmfSlideItemAllColumns,\n\t\t\tcmfSlideItemPrimaryKeyColumns,\n\t\t)\n\n\t\tif !updateColumns.IsNone() && len(update) == 0 {\n\t\t\treturn errors.New(\"models: unable to upsert cmf_slide_item, could not build update column list\")\n\t\t}\n\n\t\tret = strmangle.SetComplement(ret, nzUniques)\n\t\tcache.query = buildUpsertQueryMySQL(dialect, \"`cmf_slide_item`\", update, insert)\n\t\tcache.retQuery = fmt.Sprintf(\n\t\t\t\"SELECT %s FROM `cmf_slide_item` WHERE %s\",\n\t\t\tstrings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, ret), \",\"),\n\t\t\tstrmangle.WhereClause(\"`\", \"`\", 0, nzUniques),\n\t\t)\n\n\t\tcache.valueMapping, err = queries.BindMapping(cmfSlideItemType, cmfSlideItemMapping, insert)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(ret) != 0 {\n\t\t\tcache.retMapping, err = queries.BindMapping(cmfSlideItemType, cmfSlideItemMapping, ret)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tvalue := reflect.Indirect(reflect.ValueOf(o))\n\tvals := queries.ValuesFromMapping(value, cache.valueMapping)\n\tvar returns []interface{}\n\tif len(cache.retMapping) != 0 {\n\t\treturns = queries.PtrsFromMapping(value, cache.retMapping)\n\t}\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.query)\n\t\tfmt.Fprintln(writer, vals)\n\t}\n\tresult, err := exec.ExecContext(ctx, cache.query, vals...)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to upsert for cmf_slide_item\")\n\t}\n\n\tvar lastID int64\n\tvar uniqueMap []uint64\n\tvar nzUniqueCols []interface{}\n\n\tif len(cache.retMapping) == 0 {\n\t\tgoto CacheNoHooks\n\t}\n\n\tlastID, err = result.LastInsertId()\n\tif err != nil {\n\t\treturn ErrSyncFail\n\t}\n\n\to.ID = uint(lastID)\n\tif lastID != 0 && len(cache.retMapping) == 1 && cache.retMapping[0] == cmfSlideItemMapping[\"id\"] {\n\t\tgoto CacheNoHooks\n\t}\n\n\tuniqueMap, err = queries.BindMapping(cmfSlideItemType, cmfSlideItemMapping, nzUniques)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to retrieve unique values for cmf_slide_item\")\n\t}\n\tnzUniqueCols = queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), uniqueMap)\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.retQuery)\n\t\tfmt.Fprintln(writer, nzUniqueCols...)\n\t}\n\terr = exec.QueryRowContext(ctx, cache.retQuery, nzUniqueCols...).Scan(returns...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to populate default values for cmf_slide_item\")\n\t}\n\nCacheNoHooks:\n\tif !cached {\n\t\tcmfSlideItemUpsertCacheMut.Lock()\n\t\tcmfSlideItemUpsertCache[key] = cache\n\t\tcmfSlideItemUpsertCacheMut.Unlock()\n\t}\n\n\treturn o.doAfterUpsertHooks(ctx, exec)\n}", "func (c *Client) UpdateGroceryItem(ctx context.Context, l *ent.GroceryList, i *ent.GroceryItem) error {\n\tq := c.db.GroceryItem.Update().Where(\n\t\tgroceryitem.HasGrocerylistWith(grocerylist.ID(l.ID)),\n\t\tgroceryitem.ID(i.ID),\n\t)\n\n\tif i.Name != \"\" {\n\t\tq = q.SetName(i.Name)\n\t}\n\n\t// this isn't optimal at all\n\tif i.Price != 0.0 {\n\t\tq = q.SetPrice(i.Price)\n\t}\n\n\tif i.Status != \"\" {\n\t\tq = q.SetStatus(i.Status)\n\t}\n\n\tmodified, err := q.SetModifiedAt(time.Now()).Save(ctx)\n\tif modified != 1 && err == nil {\n\t\treturn fmt.Errorf(\"no row modified\")\n\t}\n\n\treturn err\n}", "func (tx *Transaction) UpdateItem(input *dynamodb.UpdateItemInput) (*dynamodb.UpdateItemOutput, error) {\n\ttx.mutex.Lock()\n\tdefer tx.mutex.Unlock()\n\tif tx.txErr != nil {\n\t\treturn nil, tx.txErr\n\t}\n\n\tres, err := updateItem(tx, input, true)\n\tif err != nil {\n\t\ttx.txErr = errors.Wrap(err, \"updateItem\")\n\t\treturn nil, err\n\t}\n\treturn res, nil\n}", "func (item *Item) commit() {\n\tDB.Where(\"id = ?\", item.ID).FirstOrCreate(&item)\n\tDB.Model(item).Update(&item)\n}", "func (u *ItemUpsertOne) Update(set func(*ItemUpsert)) *ItemUpsertOne {\n\tu.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {\n\t\tset(&ItemUpsert{UpdateSet: update})\n\t}))\n\treturn u\n}", "func (iu *ItemUpdate) Save(ctx context.Context) (int, error) {\n\tvar (\n\t\terr error\n\t\taffected int\n\t)\n\tif len(iu.hooks) == 0 {\n\t\taffected, err = iu.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*ItemMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\tiu.mutation = mutation\n\t\t\taffected, err = iu.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn affected, err\n\t\t})\n\t\tfor i := len(iu.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = iu.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, iu.mutation); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn affected, err\n}", "func (m *MockSubTaskDao) UpdateItemByBackupId(item *task.OwlExecItem) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateItemByBackupId\", item)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (r *r) Upsert(id string, item *internal.Item) (*internal.Item, error) {\n\tb, err := json.Marshal(&item)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"marshalling item: %w\", err)\n\t}\n\tif _, err := r.redisClient.Set(item.ID.String(), b, 0).Result(); err != nil {\n\t\treturn nil, fmt.Errorf(\"updating item: %w\", err)\n\t}\n\treturn item, nil\n}", "func workItemStatePutHandler(w http.ResponseWriter, r *http.Request) {\n\tdefer r.Body.Close()\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tfmt.Fprintln(w, err.Error())\n\t\treturn\n\t}\n\t_ = json.Unmarshal(body, updatedWorkItemState)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tfmt.Fprintln(w, string(body))\n}", "func (r *DeviceComplianceActionItemRequest) Update(ctx context.Context, reqObj *DeviceComplianceActionItem) error {\n\treturn r.JSONRequest(ctx, \"PATCH\", \"\", reqObj, nil)\n}", "func BenchmarkUpdateByID(b *testing.B) {\n\tasks := linkedList{}\n\ts := newStack()\n\tasksSnapshot := Items{\n\t\t{Price: 1, Amount: 1, ID: 1},\n\t\t{Price: 3, Amount: 1, ID: 3},\n\t\t{Price: 5, Amount: 1, ID: 5},\n\t\t{Price: 7, Amount: 1, ID: 7},\n\t\t{Price: 9, Amount: 1, ID: 9},\n\t\t{Price: 11, Amount: 1, ID: 11},\n\t}\n\tasks.load(asksSnapshot, s)\n\n\tfor i := 0; i < b.N; i++ {\n\t\terr := asks.updateByID(Items{\n\t\t\t{Price: 1, Amount: 1, ID: 1},\n\t\t\t{Price: 3, Amount: 1, ID: 3},\n\t\t\t{Price: 5, Amount: 1, ID: 5},\n\t\t\t{Price: 7, Amount: 1, ID: 7},\n\t\t\t{Price: 9, Amount: 1, ID: 9},\n\t\t\t{Price: 11, Amount: 1, ID: 11},\n\t\t})\n\t\tif err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t}\n}", "func (iuo *ItemUpdateOne) Save(ctx context.Context) (*Item, error) {\n\tvar (\n\t\terr error\n\t\tnode *Item\n\t)\n\tif len(iuo.hooks) == 0 {\n\t\tnode, err = iuo.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*ItemMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\tiuo.mutation = mutation\n\t\t\tnode, err = iuo.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn node, err\n\t\t})\n\t\tfor i := len(iuo.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = iuo.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, iuo.mutation); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn node, err\n}", "func (c *Client) UpdateItem(ctx context.Context, params *UpdateItemInput, optFns ...func(*Options)) (*UpdateItemOutput, error) {\n\tif params == nil {\n\t\tparams = &UpdateItemInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"UpdateItem\", params, optFns, c.addOperationUpdateItemMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*UpdateItemOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (c *ContainerClient) PatchItem(\n\tctx context.Context,\n\tpartitionKey PartitionKey,\n\titemId string,\n\tops PatchOperations,\n\to *ItemOptions) (ItemResponse, error) {\n\th := headerOptionsOverride{\n\t\tpartitionKey: &partitionKey,\n\t}\n\n\tif o == nil {\n\t\to = &ItemOptions{}\n\t} else {\n\t\th.enableContentResponseOnWrite = &o.EnableContentResponseOnWrite\n\t}\n\n\toperationContext := pipelineRequestOptions{\n\t\tresourceType: resourceTypeDocument,\n\t\tresourceAddress: createLink(c.link, pathSegmentDocument, itemId),\n\t\tisWriteOperation: true,\n\t\theaderOptionsOverride: &h}\n\n\tpath, err := generatePathForNameBased(resourceTypeDocument, operationContext.resourceAddress, false)\n\tif err != nil {\n\t\treturn ItemResponse{}, err\n\t}\n\n\tazResponse, err := c.database.client.sendPatchRequest(\n\t\tpath,\n\t\tctx,\n\t\tops,\n\t\toperationContext,\n\t\to,\n\t\tnil)\n\tif err != nil {\n\t\treturn ItemResponse{}, err\n\t}\n\n\treturn newItemResponse(azResponse)\n}", "func ModifyItemsNoContent(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.ItemsController, id int, payload *app.ModifyItemPayload) http.ResponseWriter {\n\t// Setup service\n\tvar (\n\t\tlogBuf bytes.Buffer\n\t\tresp interface{}\n\n\t\trespSetter goatest.ResponseSetterFunc = func(r interface{}) { resp = r }\n\t)\n\tif service == nil {\n\t\tservice = goatest.Service(&logBuf, respSetter)\n\t} else {\n\t\tlogger := log.New(&logBuf, \"\", log.Ltime)\n\t\tservice.WithLogger(goa.NewLogger(logger))\n\t\tnewEncoder := func(io.Writer) goa.Encoder { return respSetter }\n\t\tservice.Encoder = goa.NewHTTPEncoder() // Make sure the code ends up using this decoder\n\t\tservice.Encoder.Register(newEncoder, \"*/*\")\n\t}\n\n\t// Validate payload\n\terr := payload.Validate()\n\tif err != nil {\n\t\te, ok := err.(goa.ServiceError)\n\t\tif !ok {\n\t\t\tpanic(err) // bug\n\t\t}\n\t\tt.Errorf(\"unexpected payload validation error: %+v\", e)\n\t\treturn nil\n\t}\n\n\t// Setup request context\n\trw := httptest.NewRecorder()\n\tu := &url.URL{\n\t\tPath: fmt.Sprintf(\"/item/%v\", id),\n\t}\n\treq, err := http.NewRequest(\"PUT\", u.String(), nil)\n\tif err != nil {\n\t\tpanic(\"invalid test \" + err.Error()) // bug\n\t}\n\tprms := url.Values{}\n\tprms[\"id\"] = []string{fmt.Sprintf(\"%v\", id)}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgoaCtx := goa.NewContext(goa.WithAction(ctx, \"ItemsTest\"), rw, req, prms)\n\tmodifyCtx, err := app.NewModifyItemsContext(goaCtx, req, service)\n\tif err != nil {\n\t\tpanic(\"invalid test data \" + err.Error()) // bug\n\t}\n\tmodifyCtx.Payload = payload\n\n\t// Perform action\n\terr = ctrl.Modify(modifyCtx)\n\n\t// Validate response\n\tif err != nil {\n\t\tt.Fatalf(\"controller returned %+v, logs:\\n%s\", err, logBuf.String())\n\t}\n\tif rw.Code != 204 {\n\t\tt.Errorf(\"invalid response status code: got %+v, expected 204\", rw.Code)\n\t}\n\n\t// Return results\n\treturn rw\n}", "func (slir *ShoppingListItemRepository) UpdateByUserGUIDShoppingListGUIDAndShoppingListItemGUID(dbTransaction *gorm.DB, userGUID string,\n\tshoppingListGUID string, shoppingListItemGUID string, data map[string]interface{}) *systems.ErrorData {\n\n\tupdateData := map[string]interface{}{}\n\n\tfor key, value := range data {\n\t\tif data, ok := value.(string); ok && value.(string) != \"\" {\n\t\t\tupdateData[snaker.CamelToSnake(key)] = data\n\t\t}\n\n\t\tif data, ok := value.(int); ok {\n\t\t\tif key == \"Quantity\" && data != 0 {\n\t\t\t\tupdateData[snaker.CamelToSnake(key)] = data\n\t\t\t}\n\n\t\t\tif key != \"Quantity\" {\n\t\t\t\tupdateData[snaker.CamelToSnake(key)] = data\n\t\t\t}\n\t\t}\n\t}\n\n\tresult := dbTransaction.Model(&ShoppingListItem{}).Where(&ShoppingListItem{GUID: shoppingListItemGUID, ShoppingListGUID: shoppingListGUID, UserGUID: userGUID}).\n\t\tUpdates(updateData)\n\n\tif result.Error != nil {\n\t\treturn Error.InternalServerError(result.Error, systems.DatabaseError)\n\t}\n\n\treturn nil\n}" ]
[ "0.7068579", "0.6719442", "0.66551864", "0.6525335", "0.6331886", "0.6250671", "0.62262404", "0.6090824", "0.60514545", "0.59900945", "0.59710205", "0.59433424", "0.59312993", "0.5888979", "0.5857523", "0.58521247", "0.5781352", "0.5777081", "0.5775421", "0.5743207", "0.5714918", "0.56597424", "0.56424195", "0.56059426", "0.5596242", "0.5596004", "0.5588601", "0.5583612", "0.5552511", "0.55422217", "0.5528448", "0.54952824", "0.5489732", "0.5473343", "0.5432529", "0.5423547", "0.5404325", "0.53837556", "0.5341812", "0.5340582", "0.5290138", "0.52768767", "0.52708364", "0.52595", "0.5250309", "0.524285", "0.5234617", "0.52112794", "0.52091783", "0.52021945", "0.5199436", "0.51972026", "0.51599556", "0.51586074", "0.51583093", "0.5146405", "0.5129024", "0.50743455", "0.50681084", "0.5066014", "0.5065483", "0.5063766", "0.50616103", "0.505864", "0.5057311", "0.505633", "0.50293577", "0.50167924", "0.5001512", "0.5001108", "0.4988994", "0.4983764", "0.49812925", "0.4978685", "0.4974795", "0.49574396", "0.49567693", "0.49562594", "0.4948721", "0.49351975", "0.4927546", "0.4927285", "0.49252173", "0.49206054", "0.49131635", "0.4908709", "0.4906166", "0.4905529", "0.49035653", "0.48889583", "0.48862717", "0.48628503", "0.48543483", "0.48476228", "0.48421544", "0.4839287", "0.48283446", "0.48216996", "0.48179922", "0.48151392" ]
0.5960974
11
New returns an initialized FillsGrp instance
func New() *FillsGrp { var m FillsGrp return &m }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func New() *AllocGrp {\n\tvar m AllocGrp\n\treturn &m\n}", "func New(dir string) *Group {\n\tg := &Group{\n\t\tdir: dir,\n\t}\n\tg.Clear()\n\treturn g\n}", "func New() *ClrInstGrp {\n\tvar m ClrInstGrp\n\treturn &m\n}", "func New() *LegPreAllocGrp {\n\tvar m LegPreAllocGrp\n\treturn &m\n}", "func New(gid string) *Group {\n return &Group{\n Client: client.New().Init(),\n GroupID: gid,\n }\n}", "func New(directory string) (*Group, []error) {\n\tthis := new(Group)\n\n\tthis.t = template.New(\"\")\n\tthis.t.Parse(\"\")\n\n\terrs := this.loadFolder(directory)\n\n\treturn this, errs\n}", "func newGroup() *Group {\n\tg := new(Group)\n\tg.handlers = make([]HandlerFunc, 0)\n\treturn g\n}", "func New(ctx context.Context, concurrency int) (*Group, context.Context) {\n\tif concurrency < 1 {\n\t\tconcurrency = 1\n\t}\n\n\tparent, ctx := errgroup.WithContext(ctx)\n\treturn &Group{\n\t\tlimiter: make(chan struct{}, concurrency),\n\t\tparent: parent,\n\t\tctx: ctx,\n\t}, ctx\n}", "func New(s []string) Group {\n\treturn Group{str: s}\n}", "func New() *BidCompReqGrp {\n\tvar m BidCompReqGrp\n\treturn &m\n}", "func New(ds datastore.Datastore, parameters Parameters) (Group, error) {\n\thandler, err := NewFSMHandler(parameters)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\td := handler.(fsmHandler)\n\treturn &stateGroup{StateGroup: statemachine.New(ds, handler, parameters.StateType), d: d}, nil\n}", "func New(ctx context.Context) *Group {\n\t// Monitor goroutine context and cancelation.\n\tmctx, cancel := context.WithCancel(ctx)\n\n\tg := &Group{\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\n\t\taddC: make(chan struct{}),\n\t\tlenC: make(chan int),\n\t}\n\n\tg.wg.Add(1)\n\tgo func() {\n\t\tdefer g.wg.Done()\n\t\tg.monitor(mctx)\n\t}()\n\n\treturn g\n}", "func New(app, account, region, stack, cluster string) InstanceGroup {\n\treturn group{\n\t\tapp: app,\n\t\taccount: account,\n\t\tregion: region,\n\t\tstack: stack,\n\t\tcluster: cluster,\n\t}\n}", "func New(servers ...Server) *Group {\n\treturn &Group{servers: servers, shutdownTimeout: DefaultShutdownTimeout}\n}", "func NewGrouping(arg string) *Grouping {\n\tsplit := strings.Split(arg, \",\")\n\tvar grouping *Grouping\n\tif len(split) > 0 {\n\t\tgrouping = &Grouping{\n\t\t\tName: split[0],\n\t\t}\n\t}\n\tif len(split) >= 2 {\n\t\tindex, _ := strconv.ParseInt(split[1], 0, 64)\n\t\tgrouping.Index = int(index)\n\t}\n\tif len(split) >= 3 {\n\t\tduration, _ := time.ParseDuration(split[2])\n\t\tgrouping.Max = duration\n\t}\n\treturn grouping\n}", "func New(controllerManager *generic.ControllerManager, informers informers.Interface,\n\tclient clientset.Interface) Interface {\n\treturn &group{\n\t\tcontrollerManager: controllerManager,\n\t\tinformers: informers,\n\t\tclient: client,\n\t}\n}", "func NewGroup(field string) Group {\n\treturn Group{\n\t\tField: field,\n\t}\n}", "func NewGroup()(*Group) {\n m := &Group{\n DirectoryObject: *NewDirectoryObject(),\n }\n odataTypeValue := \"#microsoft.graph.group\";\n m.SetOdataType(&odataTypeValue);\n return m\n}", "func New(client *marathon.Client) *Groups {\n\n\tif client != nil {\n\t\treturn &Groups{\n\t\t\tclient: client,\n\t\t\tgroup: &Group{},\n\t\t\tdeploy: &data.Response{},\n\t\t\tfail: &data.FailureMessage{},\n\t\t}\n\t}\n\treturn nil\n}", "func New(opt ...option) *Group {\n\tr := &Group{wait_register: map[int]bool{}}\n\tfor _, o := range opt {\n\t\to(r)\n\t}\n\tif r.CancelFunc == nil {\n\t\tWith_cancel_nowait(nil)(r)\n\t}\n\tif r.parent == nil {\n\t\tr.local_wg = &sync.WaitGroup{}\n\t}\n\tif r.sig != nil {\n\t\tr.wg().Add(1)\n\t\tgo func() {\n\t\t\tdefer r.wg().Done()\n\t\t\tch := make(chan os.Signal, 1)\n\t\t\tdefer close(ch)\n\t\t\tsignal.Notify(ch, r.sig...)\n\t\t\tdefer signal.Stop(ch)\n\t\t\tselect {\n\t\t\tcase <-r.Done():\n\t\t\tcase <-ch:\n\t\t\t\tr.Interrupted = true\n\t\t\t\tfmt.Fprintf(os.Stderr, \"%v\", r.line_end)\n\t\t\t}\n\t\t\tr.Cancel()\n\t\t}()\n\t}\n\treturn r\n}", "func NewGroup(name string, maxSize int) *Group {\n\treturn &Group{\n\t\tName: name,\n\t\tMembers: []Person{},\n\t\tMaxSize: maxSize,\n\t}\n}", "func newBucketGroup(mBuckets int64) bucketGroup {\n\treturn make(bucketGroup, mBuckets)\n}", "func New(lv Level) Group {\n\treturn NewGroupWithHandle(lv, os.Stderr, nil, nil)\n}", "func NewGroups(filename string, bad BadLineHandler) (*HTGroup, error) {\n\thtGroup := HTGroup{\n\t\tfilePath: filename,\n\t}\n\treturn &htGroup, htGroup.ReloadGroups(bad)\n}", "func NewGroup(thresholds ...*Threshold) *Group {\n\treturn &Group{Thresholds: thresholds}\n}", "func NewGroup(ctx context.Context, options ...GroupOption) *Group {\n\tctx, cancel := context.WithCancel(ctx)\n\tg := &Group{\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\tpool: dummyPool{},\n\t\trecover: false,\n\t}\n\tfor _, opt := range options {\n\t\topt(g)\n\t}\n\treturn g\n}", "func HAGroup_Factory(partners []string) *HighAvailabilityGroup {\n\tg := new(HighAvailabilityGroup)\n\tg.Partners = partners\n\n\treturn g\n}", "func newRunnerGroup(scope RunnerGroupScope, name string) RunnerGroup {\n\tif name == \"\" {\n\t\treturn RunnerGroup{\n\t\t\tScope: scope,\n\t\t\tKind: Default,\n\t\t\tName: \"\",\n\t\t}\n\t}\n\n\treturn RunnerGroup{\n\t\tScope: scope,\n\t\tKind: Custom,\n\t\tName: name,\n\t}\n}", "func NewGroup(bootles []Bottle, water uint32) Group {\n\treturn Group{\n\t\tWater: water,\n\t\tBottles: bootles,\n\t}\n}", "func New(glabel string, flags int) (*GlvlStruct, error) {\n\treturn newll(glabel, flags, LflagsDef, nil, false)\n}", "func NewGroup(name string, cacheBytes int64, getter Getter) *Group {\n\tif getter == nil {\n\t\tpanic(\"Nil Getter\")\n\t}\n\n\tmu.Lock()\n\tdefer mu.Unlock()\n\n\tg := &Group{\n\t\tname: name,\n\t\tmainCache: &SafeCache{maxBytes: cacheBytes},\n\t\tgetter: getter,\n\t}\n\tgroups[name] = g\n\treturn g\n}", "func NewGroup() *Group {\n\treturn &Group{}\n}", "func NewGroup() *Group {\n\treturn &Group{}\n}", "func newGroup(groupId string, broadcastChannelCap int64) *group {\n\n\tg := &group{\n\t\tId: groupId,\n\t\tclients: make(map[string]*socketClient),\n\t\tbroadcastChannel: make(chan interface{}, broadcastChannelCap),\n\t\tshutdownChannel: make(chan interface{}),\n\t\tdownChannel: make(chan interface{}, broadcastChannelCap),\n\t}\n\n\tAppLogger.Infof(\"[newGroup] group: %s created\", groupId)\n\treturn g\n}", "func NewGroup(m *algebra.Matrix) *Group {\n\tmat := m\n\tif m == nil || len(m.Get()) != 4 || len(m.Get()[0]) != 4 {\n\t\tmat = algebra.IdentityMatrix(4)\n\t}\n\temptyShapes := make([]Shape, 0, 0)\n\treturn &Group{transform: mat, parent: nil, shapes: emptyShapes, bounds: [2]*algebra.Vector{}}\n}", "func NewGroup(list []*Identity, threshold int, genesis int64, period, catchupPeriod time.Duration,\n\tsch *crypto.Scheme, beaconID string) *Group {\n\treturn &Group{\n\t\tNodes: copyAndSort(list),\n\t\tThreshold: threshold,\n\t\tGenesisTime: genesis,\n\t\tPeriod: period,\n\t\tCatchupPeriod: catchupPeriod,\n\t\tScheme: sch,\n\t\tID: beaconID,\n\t}\n}", "func NewSplit(splitDTO *dtos.SplitDTO, ctx *injection.Context, logger logging.LoggerInterface) *Split {\n\tconditions := make([]*Condition, 0)\n\tfor _, cond := range splitDTO.Conditions {\n\t\tconditions = append(conditions, NewCondition(&cond, ctx, logger))\n\t}\n\n\tsplit := Split{\n\t\tconditions: conditions,\n\t\tsplitData: splitDTO,\n\t}\n\n\treturn &split\n}", "func newRouteGroup(prefix string, router *Router, handlers []Handler) *RouteGroup {\n\treturn &RouteGroup{\n\t\tprefix: prefix,\n\t\trouter: router,\n\t\thandlers: handlers,\n\t}\n}", "func NewGroup(system SystemUtils) *Group {\n\treturn &Group{\n\t\tsystem: system,\n\t}\n}", "func NewGroup(lv Level, w io.Writer) Group {\n\treturn NewGroupWithHandle(lv, w, nil, nil)\n}", "func New(m map[string]interface{}) (group.Manager, error) {\n\tc, err := parseConfig(m)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tf, err := os.ReadFile(c.Groups)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgroups := []*grouppb.Group{}\n\n\terr = json.Unmarshal(f, &groups)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &manager{\n\t\tgroups: groups,\n\t}, nil\n}", "func NewGroupPolicyDefinition()(*GroupPolicyDefinition) {\n m := &GroupPolicyDefinition{\n Entity: *NewEntity(),\n }\n return m\n}", "func New(r *registry.R) *FlowBuilder {\n\treturn &FlowBuilder{\n\t\tregistry: r,\n\t\tOperationMap: map[string]flow.Operation{},\n\t\tnodeTrack: map[string]bool{},\n\t}\n}", "func NewProtectGroup()(*ProtectGroup) {\n m := &ProtectGroup{\n LabelActionBase: *NewLabelActionBase(),\n }\n odataTypeValue := \"#microsoft.graph.protectGroup\"\n m.SetOdataType(&odataTypeValue)\n return m\n}", "func NewCalendarGroup()(*CalendarGroup) {\n m := &CalendarGroup{\n Entity: *NewEntity(),\n }\n return m\n}", "func New(spec data.Spec, dp *data.Points, width, height int) chart.Chart {\n\tseries := []chart.Series{}\n\tmarkers := []chart.GridLine{}\n\tfor _, f := range spec.Fields {\n\t\tvals := dp.Get(f.ID)\n\t\tif f.IsMarker {\n\t\t\tfor i, v := range vals {\n\t\t\t\tif v > 0 {\n\t\t\t\t\tmarkers = append(markers, chart.GridLine{Value: float64(i)})\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tseries = append(series, chart.ContinuousSeries{\n\t\t\tName: fmt.Sprintf(\"%s: %s\", f.Name, siValueFormater(vals[len(vals)-1])),\n\t\t\tYValues: vals,\n\t\t})\n\t}\n\treturn newChart(series, markers, width, height)\n}", "func NewLogGroup(ctx *pulumi.Context,\n\tname string, args *LogGroupArgs, opts ...pulumi.ResourceOpt) (*LogGroup, error) {\n\tinputs := make(map[string]interface{})\n\tif args == nil {\n\t\tinputs[\"kmsKeyId\"] = nil\n\t\tinputs[\"name\"] = nil\n\t\tinputs[\"namePrefix\"] = nil\n\t\tinputs[\"retentionInDays\"] = nil\n\t\tinputs[\"tags\"] = nil\n\t} else {\n\t\tinputs[\"kmsKeyId\"] = args.KmsKeyId\n\t\tinputs[\"name\"] = args.Name\n\t\tinputs[\"namePrefix\"] = args.NamePrefix\n\t\tinputs[\"retentionInDays\"] = args.RetentionInDays\n\t\tinputs[\"tags\"] = args.Tags\n\t}\n\tinputs[\"arn\"] = nil\n\ts, err := ctx.RegisterResource(\"aws:cloudwatch/logGroup:LogGroup\", name, true, inputs, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &LogGroup{s: s}, nil\n}", "func (s PathReq) NewHpCfgs(n int32) (HPGroupId_List, error) {\n\tl, err := NewHPGroupId_List(s.Struct.Segment(), n)\n\tif err != nil {\n\t\treturn HPGroupId_List{}, err\n\t}\n\terr = s.Struct.SetPtr(0, l.List.ToPtr())\n\treturn l, err\n}", "func NewProtectionGroup(ctx *pulumi.Context,\n\tname string, args *ProtectionGroupArgs, opts ...pulumi.ResourceOption) (*ProtectionGroup, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.Aggregation == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Aggregation'\")\n\t}\n\tif args.Pattern == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Pattern'\")\n\t}\n\tif args.ProtectionGroupId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'ProtectionGroupId'\")\n\t}\n\tvar resource ProtectionGroup\n\terr := ctx.RegisterResource(\"aws:shield/protectionGroup:ProtectionGroup\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewGroup(ctx context.Context) *Group {\n\tctx, cancel := context.WithCancel(ctx)\n\n\tg := &Group{\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\tdone: make(chan struct{}),\n\t}\n\n\tgo g.wait()\n\n\treturn g\n}", "func NewGroup(client *gosip.SPClient, endpoint string, config *RequestConfig) *Group {\n\treturn &Group{\n\t\tclient: client,\n\t\tendpoint: endpoint,\n\t\tconfig: config,\n\t\tmodifiers: NewODataMods(),\n\t}\n}", "func newll(glabel string, flags int, logFlags int, iowr *IowrStruct, panicErr bool) (*GlvlStruct, error) {\n\tg := &GlvlStruct{firstIowr: IowrDefault()}\n\tif iowr != nil {\n\t\tg.firstIowr = *iowr\n\t}\n\t// test g.firstIowr.Error = nil\n\n\tmuGrplogCount.Lock()\n\tgrplogCount++\n\tg.Name = fmt.Sprintf(\"%s<%d>\", glabel, grplogCount) //ensure an unique name\n\tmuGrplogCount.Unlock()\n\n\tfor _, v := range g.lvlList() {\n\t\tif *v.iowr == nil {\n\t\t\terrnew := errors.New(v.name + \" io.Writer is nil, if you want to discard use ioutil.Discard\")\n\t\t\tif panicErr {\n\t\t\t\tlog.Panic(errnew)\n\t\t\t}\n\t\t\treturn nil, errnew\n\t\t}\n\t\t*v.level = &LvlStruct{\n\t\t\tlog: log.New(*v.iowr, glabel+v.Blab, logFlags),\n\t\t\tlogOutput: *v.iowr,\n\t\t\tflags: flags,\n\t\t\tmu: &g.mu,\n\t\t\tpar: g,\n\t\t\tname: v.name,\n\t\t\talign: alignStruct{filea: LogAlignFileDef, funca: LogAlignFuncDef},\n\t\t}\n\t}\n\treturn g, nil\n}", "func newStatGroup(size uint64) *statGroup {\n\treturn &statGroup{\n\t\tvalues: make([]float64, size),\n\t\tcount: 0,\n\t}\n}", "func NewGroup(name string, members ...string) *Group {\n\treturn &Group{\n\t\tName: name,\n\t\tpassword: \"\",\n\t\tGID: -1,\n\t\tUserList: members,\n\t}\n}", "func (tzGrpCol TimeZoneGroupCollection) New() TimeZoneGroupCollection {\n\tnewTzGrp := TimeZoneGroupCollection{}\n\n\tnewTzGrp.tzGroups = make([]TimeZoneGroupDto, 0, 300)\n\n\treturn newTzGrp\n}", "func New(logger *logrus.Logger, g *echo.Group) error {\n\tp := &projects{\n\t\tLogger: logger,\n\t}\n\n\tg.GET(\"\", p.getProjects())\n\n\treturn nil\n}", "func NewGroup(name string) Group {\n\treturn Group{\n\t\tname: name,\n\t\treadyCh: make(chan struct{}),\n\t}\n}", "func NewCheckGroup(options []string, changed func([]string)) *CheckGroup {\n\tr := &CheckGroup{\n\t\tDisableableWidget: DisableableWidget{},\n\t\tOptions: options,\n\t\tOnChanged: changed,\n\t}\n\tr.ExtendBaseWidget(r)\n\tr.update()\n\treturn r\n}", "func newRouteGroups(c *ZalandoV1Client, namespace string) *routeGroups {\n\treturn &routeGroups{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}", "func NewGroup(name string, o Owner) *Group {\n\tng := new(Group)\n\tng.Own = o\n\tng.Name = name\n\n\tvar nid OwnerID\n\tnid.Type = 'g'\n\tnid.UserDefined = name2userdefined(name)\n\t// nid.Stamp = newstamp()\n\n\tng.ID = nid\n\n\treturn ng\n}", "func (visual *Visual) NewGroup(parts []string, effect string) (*Group, error) {\n\tgroup, err := newGroup(parts, effect)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvisual.mux.Lock()\n\tvisual.groups = append(visual.groups, group)\n\tvisual.mux.Unlock()\n\n\treturn group, nil\n}", "func NewGroupLogger(dir string, appName string, expire time.Duration, logSlice []string, flag int, lv int) *GroupLogger {\n\tgl := &GroupLogger{\n\t\tloggerMap: map[string]*PeriodLogger{},\n\t\tdefaultLogger: NewPeriodLogger(appName, \"\", dir, true, flag, lv),\n\t\texpire: expire,\n\t\tflag: flag,\n\t\tlevel: lv,\n\t}\n\n\tfor i := 0; i < len(logSlice); i++ {\n\t\tsliceName := logSlice[i]\n\t\tif len(sliceName) <= 0 {\n\t\t\tcontinue\n\t\t}\n\t\tdownloadLogger := NewPeriodLogger(appName, sliceName, filepath.Join(dir, sliceName), false, flag, lv)\n\t\tgl.loggerMap[sliceName] = downloadLogger\n\t}\n\n\tif expire < time.Hour*24 {\n\t\tgl.expire = time.Hour * 24\n\t}\n\n\tfc := cleaner.New(dir, gl.expire, time.Hour, -1)\n\tfc.SetFilter(func(path string, info os.FileInfo) (willClean bool) {\n\t\tfor _, excludePath := range gl.excludes {\n\t\t\tif excludePath == path {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n\tfc.StartCleanTask()\n\n\treturn gl\n}", "func NewGroup(owner, name string) Group {\n\tnow := time.Now()\n\treturn Group{\n\t\tOwner: owner,\n\t\tName: name,\n\t\tDescription: name,\n\t\tAccess: \"private\",\n\t\tBirthtime: now,\n\t\tMTime: now,\n\t}\n}", "func New(fname string, runTests bool) error {\n\tml = make(map[string]lfList)\n\treturn readFilterList(fname, runTests)\n}", "func NewPatchGroup(ctx *pulumi.Context,\n\tname string, args *PatchGroupArgs, opts ...pulumi.ResourceOption) (*PatchGroup, error) {\n\tif args == nil || args.BaselineId == nil {\n\t\treturn nil, errors.New(\"missing required argument 'BaselineId'\")\n\t}\n\tif args == nil || args.PatchGroup == nil {\n\t\treturn nil, errors.New(\"missing required argument 'PatchGroup'\")\n\t}\n\tif args == nil {\n\t\targs = &PatchGroupArgs{}\n\t}\n\tvar resource PatchGroup\n\terr := ctx.RegisterResource(\"aws:ssm/patchGroup:PatchGroup\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func newRouteGroup(prefix string, router *Router, handlers []Handler, startupHandlers []Handler, anteriorHandlers []Handler, posteriorHandlers []Handler, shutdownHandlers []Handler) *RouteGroup {\n\treturn &RouteGroup{\n\t\tprefix: prefix,\n\t\trouter: router,\n\t\thandlers: handlers,\n\t\tstartupHandlers: startupHandlers,\n\t\tanteriorHandlers: anteriorHandlers,\n\t\tposteriorHandlers: posteriorHandlers,\n\t\tshutdownHandlers: shutdownHandlers,\n\t}\n}", "func New(t testing.TB) lg.Log {\n\treturn NewWith(t, FactoryFn)\n}", "func NewGroup(dataframe *DataFrame, columns ...string) *Groups {\n\t// ret := &Groups{Columns: []string{}, Grouper: columns, Group: make(map[types.C][]indices.Index), Df: dataframe}\n\tret := &Groups{Keys: []Keys{}, Columns: []string{}, Grouper: columns, Group: make(map[types.C][]indices.Index), Df: dataframe}\n\n\treturn ret\n}", "func New(ctx context.Context, wg *sync.WaitGroup, poolSize int) *pool {\n\tp := &pool{\n\t\tctx: ctx,\n\t\twg: wg,\n\t\tsize: poolSize,\n\t\tworkers: make(chan Worker),\n\t\ttickets: make(chan bool, poolSize),\n\t}\n\n\tgo p.process()\n\n\treturn p\n}", "func New() *ApplIDRequestAckGrp {\n\tvar m ApplIDRequestAckGrp\n\treturn &m\n}", "func New(groups ...string) *Store {\n\ts := &Store{\n\t\tgroups: make(map[string]*group, len(groups)),\n\t}\n\tfor _, name := range groups {\n\t\tg := &group{\n\t\t\tname: name,\n\t\t\tentities: make(map[string][][]rune, DefaultGroupSize),\n\t\t}\n\t\ts.groups[name] = g\n\t}\n\treturn s\n}", "func NewGroup(gvr client.GVR) ResourceViewer {\n\tg := Group{ResourceViewer: NewBrowser(gvr)}\n\tg.AddBindKeysFn(g.bindKeys)\n\tg.SetContextFn(g.subjectCtx)\n\n\treturn &g\n}", "func NewGroupFileOps(t mockConstructorTestingTNewGroupFileOps) *GroupFileOps {\n\tmock := &GroupFileOps{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func New(option PoolOption) (*SizedWaitGroup, error) {\n\tif option.Size <= 0 {\n\t\treturn nil, fmt.Errorf(\"size must great than 0\")\n\t}\n\n\treturn &SizedWaitGroup{\n\t\tSize: option.Size,\n\t\tName: option.Name,\n\t\tcurrent: make(chan struct{}, option.Size),\n\t\tqueue: make(chan func()),\n\t\tfutureQueue: make(chan *FutureTask),\n\t\twg: sync.WaitGroup{},\n\t}, nil\n}", "func (c *Container) NewFiller(r *Root, bus FillingBus) (fl *Filler) {\n\n\tc.Debugln(FillVerbosePin, \"NewFiller\", r.Short())\n\n\tfl = new(Filler)\n\n\tfl.c = c\n\n\tfl.bus = bus\n\n\tfl.r = r\n\tfl.gotq = make(chan []byte, 1)\n\n\tfl.closeq = make(chan struct{})\n\n\tfl.tp = time.Now() // time point\n\n\tgo fl.fill()\n\treturn\n}", "func New(servers ...Server) *ServerGroup {\n\tresult := &ServerGroup{state: StateIdle, StateChan: make(chan int32, 4)}\n\tfor _, s := range servers {\n\t\tresult.Add(s, true)\n\t}\n\treturn result\n}", "func NewDkgGroup(dishonestThreshold int, size int) *Group {\n\tmemberIDs := make([]MemberIndex, size)\n\tfor i := 0; i < size; i++ {\n\t\tmemberIDs[i] = MemberIndex(i + 1)\n\t}\n\n\treturn &Group{\n\t\tdishonestThreshold: dishonestThreshold,\n\t\tdisqualifiedMemberIDs: []MemberIndex{},\n\t\tinactiveMemberIDs: []MemberIndex{},\n\t\tmemberIDs: memberIDs,\n\t}\n}", "func New(cnt int) []Aggregator {\n\treturn make([]Aggregator, cnt)\n}", "func New(cnt int) []Aggregator {\n\treturn make([]Aggregator, cnt)\n}", "func WindowGroupNew() (*WindowGroup, error) {\n\tc := C.gtk_window_group_new()\n\tif c == nil {\n\t\treturn nil, nilPtrErr\n\t}\n\treturn wrapWindowGroup(glib.Take(unsafe.Pointer(c))), nil\n}", "func FileGroupFactory() Module {\n\tmodule := &fileGroup{}\n\tmodule.AddProperties(&module.properties)\n\tInitAndroidModule(module)\n\treturn module\n}", "func (t *OpenconfigQos_Qos_ForwardingGroups) NewForwardingGroup(Name string) (*OpenconfigQos_Qos_ForwardingGroups_ForwardingGroup, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.ForwardingGroup == nil {\n\t\tt.ForwardingGroup = make(map[string]*OpenconfigQos_Qos_ForwardingGroups_ForwardingGroup)\n\t}\n\n\tkey := Name\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.ForwardingGroup[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list ForwardingGroup\", key)\n\t}\n\n\tt.ForwardingGroup[key] = &OpenconfigQos_Qos_ForwardingGroups_ForwardingGroup{\n\t\tName: &Name,\n\t}\n\n\treturn t.ForwardingGroup[key], nil\n}", "func NewGroupBy() []GroupBy {\n\treturn []GroupBy{{Type: \"time\", Interval: \"auto\"}}\n}", "func New(it *msvc.ProjectIterator) *Graph {\n\tgr := &Graph{\n\t\tg: simple.NewDirectedGraph(),\n\t\tallNodes: rbtree.New(),\n\t\tnextID: 1,\n\t}\n\n\tit.Foreach(gr.newNode)\n\tait := rbtree.NewWalkInorder(gr.allNodes)\n\tait.Foreach(gr.newEdges)\n\n\treturn gr\n}", "func New(factories ...metrics.Factory) *Factory {\n\treturn &Factory{\n\t\tfactories: factories,\n\t}\n}", "func NewGroupBy(name string, ex goexpr.Expr) GroupBy {\n\treturn GroupBy{\n\t\tExpr: ex,\n\t\tName: name,\n\t}\n}", "func Newf(classFormat string, args ...interface{}) *Ex {\n\treturn &Ex{class: fmt.Sprintf(classFormat, args...), stack: callers()}\n}", "func New(width, height int, cond *sync.Cond) Grid {\n\treturn &grid{\n\t\tcond: cond,\n\t\twidth: width,\n\t\theight: height,\n\t\tdata: make([]*locator, width*height),\n\t}\n}", "func NewGroupBy(selectedExprs, groupByExprs []sql.Expression, child sql.Node) *GroupBy {\n\treturn &GroupBy{\n\t\tUnaryNode: UnaryNode{Child: child},\n\t\tSelectedExprs: selectedExprs,\n\t\tGroupByExprs: groupByExprs,\n\t}\n}", "func NewSectionGroup()(*SectionGroup) {\n m := &SectionGroup{\n OnenoteEntityHierarchyModel: *NewOnenoteEntityHierarchyModel(),\n }\n odataTypeValue := \"#microsoft.graph.sectionGroup\";\n m.SetOdataType(&odataTypeValue);\n return m\n}", "func New(numStacks, totalCapacity int) Stacks {\n\tif numStacks < 1 || totalCapacity < 1 {\n\t\tlog.Panicln(\"number of stacks and total capacity must be greater than or equal to one.\")\n\t}\n\tdata := make([]interface{}, 0, totalCapacity)\n\tpositions := make([][]int, numStacks)\n\tfor i := 0; i < numStacks; i++ {\n\t\tpositions[i] = make([]int, 0, numStacks)\n\t}\n\treturn &stacks{stacks: numStacks, data: data, positions: positions}\n}", "func New(pc chan []string) *Drawer {\n\td := Drawer{nil, nil, nil, nil}\n\td.list = ld.New(pc)\n\td.sparkline = sd.New(pc)\n\td.table = td.New(pc)\n\td.packetChannel = pc\n\n\treturn &d\n}", "func NewSpecial(glabel string, flags int, logFlagsGroup int, iowr IowrStruct) (*GlvlStruct, error) {\n\treturn newll(glabel, flags, logFlagsGroup, &iowr, false)\n}", "func newGroupMutation(c config, op Op, opts ...groupOption) *GroupMutation {\n\tm := &GroupMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeGroup,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}", "func newGroupMutation(c config, op Op, opts ...groupOption) *GroupMutation {\n\tm := &GroupMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeGroup,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}", "func (l *GroupLookup) newKeyGroup(entries []groupKeyListElement) *groupKeyList {\n\tid := l.nextID\n\tl.nextID++\n\treturn &groupKeyList{\n\t\tid: id,\n\t\telements: entries,\n\t}\n}", "func New() *FS {\n\treturn &FS{}\n}", "func (r *RouteGroup) NewGroup(path string) *RouteGroup {\n\treturn NewRouteGroup(r.r, r.subPath(path))\n}", "func New() {\n\ttypeOfProject()\n}", "func New() *PKGBUILD {\n\treturn &PKGBUILD{\n\t\tinfo: atom.NewInfoList(),\n\t}\n}" ]
[ "0.6597681", "0.65568674", "0.6489955", "0.61960477", "0.61632395", "0.61583596", "0.6039248", "0.6018359", "0.59911543", "0.59713113", "0.592528", "0.5820535", "0.57798296", "0.57044864", "0.5674156", "0.56696665", "0.56621194", "0.565151", "0.56454813", "0.56247896", "0.56063485", "0.55777824", "0.5564392", "0.55455863", "0.55274564", "0.5489491", "0.5485363", "0.54747236", "0.54436094", "0.54379594", "0.5380831", "0.5344904", "0.5344904", "0.53215146", "0.53019685", "0.5301732", "0.5297825", "0.52945477", "0.5287537", "0.5249977", "0.52411634", "0.52286243", "0.5223419", "0.52111286", "0.52021146", "0.5191847", "0.5164246", "0.5159689", "0.51465577", "0.51422715", "0.5140106", "0.51368743", "0.51268685", "0.5122265", "0.51184565", "0.51153374", "0.510899", "0.5105772", "0.5080329", "0.506205", "0.505934", "0.5034843", "0.50342375", "0.50331175", "0.50302607", "0.50273013", "0.5026017", "0.50234854", "0.5000774", "0.4988938", "0.49860802", "0.4981217", "0.4981037", "0.49788368", "0.49766546", "0.49765947", "0.49764207", "0.4973612", "0.4973612", "0.49681702", "0.49657613", "0.49589905", "0.49361116", "0.49345997", "0.49061084", "0.48989376", "0.4893794", "0.4882", "0.48819315", "0.48775563", "0.48755458", "0.48731223", "0.48719174", "0.4864925", "0.4864925", "0.48615202", "0.4859697", "0.4858551", "0.48558918", "0.48314264" ]
0.8539913
0
NewNoFills returns an initialized NoFills instance
func NewNoFills() *NoFills { var m NoFills return &m }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func New() *FillsGrp {\n\tvar m FillsGrp\n\treturn &m\n}", "func newEmptyBoard() *FixBoard {\n\tb := &FixBoard{\n\t\tGophers: make([]*pieces.Gopher, 0),\n\t\tGoals: make([]pieces.Goal, 0),\n\t}\n\n\treturn b\n}", "func NewNoAllocs(val int) NoAllocsField {\n\treturn NoAllocsField{quickfix.FIXInt(val)}\n}", "func NewBlank() Square {\n\treturn Square{\n\t\tArea: 0,\n\t\tPossible: make([]Rect, 0, 5),\n\t}\n}", "func NewNoGrowMap(initialSize int) *NoGrowMap {\n\t// make an iterator that has initialSize items left to go\n\titerator := make(chan struct{}, initialSize)\n\tfor i := 0; i < initialSize; i++ {\n\t\titerator <- struct{}{}\n\t}\n\treturn &NoGrowMap{\n\t\tSize: initialSize,\n\t\tIterator: iterator,\n\t}\n}", "func NewNoAllocs() *NoAllocs {\n\tvar m NoAllocs\n\treturn &m\n}", "func NewNoAllocs() *NoAllocs {\n\tvar m NoAllocs\n\treturn &m\n}", "func NewBlank(t interface {\n\tmock.TestingT\n\tCleanup(func())\n}) *Blank {\n\tmock := &Blank{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewNoOrders(val int) NoOrdersField {\n\treturn NoOrdersField{quickfix.FIXInt(val)}\n}", "func NewNoLegs() *NoLegs {\n\tvar m NoLegs\n\treturn &m\n}", "func NewNoLegs() *NoLegs {\n\tvar m NoLegs\n\treturn &m\n}", "func NewNoLegs() *NoLegs {\n\tvar m NoLegs\n\treturn &m\n}", "func NewNoLegs() *NoLegs {\n\tvar m NoLegs\n\treturn &m\n}", "func NewNoLegs() *NoLegs {\n\tvar m NoLegs\n\treturn &m\n}", "func NewNoLegs() *NoLegs {\n\tvar m NoLegs\n\treturn &m\n}", "func NewNoMDEntries(val int) NoMDEntriesField {\n\treturn NoMDEntriesField{quickfix.FIXInt(val)}\n}", "func newImageWithoutInit(width, height int, volatile bool) *Image {\n\ti := &Image{\n\t\timage: graphics.NewImage(width, height),\n\t\tvolatile: volatile,\n\t}\n\ttheImages.add(i)\n\treturn i\n}", "func newEmpty() *TypedEmpty {\n\ttypedEmpty := TypedEmpty{\n\t\tBytes: make([]byte, 0),\n\t\tType: ValueType_EMPTY,\n\t}\n\treturn &typedEmpty\n}", "func NewEmpty() Empty {\n\treturn Empty{}\n}", "func NewEmpty() Empty {\n\treturn Empty{}\n}", "func NewNoAllocsRepeatingGroup() NoAllocsRepeatingGroup {\n\treturn NoAllocsRepeatingGroup{\n\t\tquickfix.NewRepeatingGroup(tag.NoAllocs,\n\t\t\tquickfix.GroupTemplate{quickfix.GroupElement(tag.AllocAccount), quickfix.GroupElement(tag.IndividualAllocID), NewNoNestedPartyIDsRepeatingGroup(), quickfix.GroupElement(tag.AllocQty)})}\n}", "func NewFilled(size int, val float64) Vec {\n\treturn New(size).Fill(val)\n}", "func New() (*T) {\n\n\tme := T{\n\t\tcount: 0,\n\t\tdatum: \"\",\n\t}\n\n\treturn &me\n}", "func New() Entries {\n\t// Check against empty entries results in current goroutine list\n\treturn Entries{}.Check()\n}", "func NewNoLegAllocs() *NoLegAllocs {\n\tvar m NoLegAllocs\n\treturn &m\n}", "func NewDummy(product string, format, dx, dy int) (comp *Composite) {\n\tcomp = &Composite{Product: product, Format: format, Dx: dx, Dy: dy}\n\tcomp.calibrateProjection()\n\treturn\n}", "func NewNoClearingInstructions() *NoClearingInstructions {\n\tvar m NoClearingInstructions\n\treturn &m\n}", "func Fill(i interface{}) {\n\tf := NewFiller()\n\tf.Seed = time.Now().Unix() + rand.Int63n(100)\n\tf.Fill(i)\n}", "func New() Type {\n\treturn Type(0)\n}", "func NewNoRpts(val int) NoRptsField {\n\treturn NoRptsField{quickfix.FIXInt(val)}\n}", "func New(capacity int32) *FreeArray {\n\titems := make([]node, capacity)\n\tfor i := range items {\n\t\titems[i] = node{\n\t\t\tnext: int32(i + 1),\n\t\t\tprev: int32(i - 1),\n\t\t\tdata: nil,\n\t\t}\n\t}\n\titems[0].prev = -1\n\titems[capacity-1].next = -1\n\treturn &FreeArray{\n\t\titems: items,\n\t\tfreehead: 0,\n\t\tbusyhead: -1,\n\t}\n}", "func NewNoStipulationsRepeatingGroup() NoStipulationsRepeatingGroup {\n\treturn NoStipulationsRepeatingGroup{\n\t\tquickfix.NewRepeatingGroup(tag.NoStipulations,\n\t\t\tquickfix.GroupTemplate{quickfix.GroupElement(tag.StipulationType), quickfix.GroupElement(tag.StipulationValue)})}\n}", "func FromScratch() *Empty {\n\n\te := Empty{}\n\n\treturn &e\n}", "func NewNil() NilVal { return NilVal{} }", "func NewDummyNCC() NCC {\n\treturn &dummyNCC{}\n}", "func NewNoHelp(psof ...param.ParamSetOptFunc) (*param.ParamSet, error) {\n\treturn param.NewSet(append(psof, param.SetHelper(nh))...)\n}", "func NewEmpty() *Deck {\n\tdeck := &Deck{}\n\treturn deck\n}", "func New(shuffleTheDeck bool) Deck {\n\tvar newDeck Deck\n\tfor i := 0; i < numSuits; i++ {\n\t\tfor j := 0; j < numCardsPerSuit; j++ {\n\t\t\tnewDeck.AddCard(buildCard(i, j), false)\n\t\t}\n\t}\n\n\tif shuffleTheDeck {\n\t\tnewDeck.Shuffle()\n\t}\n\n\treturn newDeck\n}", "func NewNone() *None {\n\treturn nil\n}", "func New(spec data.Spec, dp *data.Points, width, height int) chart.Chart {\n\tseries := []chart.Series{}\n\tmarkers := []chart.GridLine{}\n\tfor _, f := range spec.Fields {\n\t\tvals := dp.Get(f.ID)\n\t\tif f.IsMarker {\n\t\t\tfor i, v := range vals {\n\t\t\t\tif v > 0 {\n\t\t\t\t\tmarkers = append(markers, chart.GridLine{Value: float64(i)})\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tseries = append(series, chart.ContinuousSeries{\n\t\t\tName: fmt.Sprintf(\"%s: %s\", f.Name, siValueFormater(vals[len(vals)-1])),\n\t\t\tYValues: vals,\n\t\t})\n\t}\n\treturn newChart(series, markers, width, height)\n}", "func NewNoQuoteSets(val int) NoQuoteSetsField {\n\treturn NoQuoteSetsField{quickfix.FIXInt(val)}\n}", "func New() lock.Locker {\n\tc := make(chan struct{}, 1)\n\tc <- struct{}{}\n\treturn &trivial {\n\t\tc: c,\n\t}\n}", "func NewUnlocked(seed int64) *Faker {\n\t// If passing 0 create crypto safe int64 for initial seed number\n\tif seed == 0 {\n\t\tbinary.Read(crand.Reader, binary.BigEndian, &seed)\n\t}\n\n\treturn &Faker{Rand: rand.New(rand.NewSource(seed))}\n}", "func New() target.Locker {\n\treturn &Noop{}\n}", "func NewNoMiscFees() *NoMiscFees {\n\tvar m NoMiscFees\n\treturn &m\n}", "func New() *Novis {\n\treturn &Novis{\n\t\tRoot: &Branch{\n\t\t\tbranches: make(map[string]*Branch),\n\t\t},\n\t}\n}", "func MustNew(glabel string, flags int) *GlvlStruct {\n\tg, _ := newll(glabel, flags, LflagsDef, nil, true)\n\treturn g\n}", "func newBoard() *board {\n\tfield := make([][]piece, 8)\n\n\tfield[0] = []piece{\n\t\tnewPiece(rookType, white), newPiece(knightType, white), newPiece(bishopType, white), newPiece(queenType, white),\n\t\tnewPiece(kingType, white), newPiece(bishopType, white), newPiece(knightType, white), newPiece(rookType, white),\n\t}\n\tfor i := 1; i < 7; i++ {\n\t\tfield[i] = make([]piece, 8)\n\t}\n\tfor i := 0; i < 8; i++ {\n\t\tfield[1][i] = newPiece(pawnType, white)\n\t}\n\tfor i := 2; i < 6; i++ {\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tfield[i][j] = newPiece(emptyType, none)\n\t\t}\n\t}\n\tfor i := 0; i < 8; i++ {\n\t\tfield[6][i] = newPiece(pawnType, black)\n\t}\n\tfield[7] = []piece{\n\t\tnewPiece(rookType, black), newPiece(knightType, black), newPiece(bishopType, black), newPiece(queenType, black),\n\t\tnewPiece(kingType, black), newPiece(bishopType, black), newPiece(knightType, black), newPiece(rookType, black),\n\t}\n\n\treturn &board{field: field}\n}", "func (b *Bucket) newRingWithoutLock(ring *types.RingState) {\n\t//新环生成后,需要将对应的订单、环路信息修改\n\tfor _,ord := range ring.RawRing.Orders {\n\t\t//todo:需要根据成交的金额等信息进行修改, 现在简单删除\n\t\tif o,ok := b.orders[ord.OrderState.OrderHash]; ok {\n\t\t\tfor _,pos := range o.postions {\n\t\t\t\tdelete(b.semiRings, pos.semiRingKey)\n\t\t\t\tdelete(b.orders, ord.OrderState.OrderHash)\n\t\t\t}\n\t\t}\n\t}\n}", "func NewDummy(log logr.Logger, zones []dnsname.Name) *Dummy {\n\treturn &Dummy{\n\t\tlog: log.WithName(\"providers\").WithName(\"Dummy\"),\n\t\tzones: zones,\n\t}\n}", "func New() *List {\n return &List{size:0}\n}", "func New(length int) (nid string) {\n nid = \"\"\n\n for i := 0; i < length; i++ {\n var (\n r1 int\n )\n\n r1 = rnd.Intn(9)\n\n if i == 0 {\n for r1 == 0 {\n r1 = rnd.Intn(9)\n }\n }\n\n nid += strconv.Itoa(r1)\n }\n return\n}", "func NewDiscard() *zap.Logger {\n\treturn zap.NewNop()\n}", "func newItems() *items {\n\treturn &items{\n\t\tdata: make([]*list, 0),\n\t\tlen: 0,\n\t}\n}", "func New(opts ...func([]Card) []Card) []Card {\n\tdeck := make([]Card, 52)\n\tfor i := range deck {\n\t\tdeck[i] = Card{Suit: Suit(i % 4), Rank: Rank((i % 13) + 1)}\n\t}\n\tfor _, opt := range opts {\n\t\tdeck = opt(deck)\n\t}\n\treturn deck\n\n}", "func (b *Bucketer) NewNonCumulativeDistribution() *NonCumulativeDistribution {\n\treturn (*NonCumulativeDistribution)(newDistribution(b, true))\n}", "func New(n uint64) *BitSet {\n\t// dens := bitDensity * float64(n)\n\t// if dens < 1.0 {\n\t// \tdens = 1.0\n\t// }\n\treturn &BitSet{set: make(blockAry)}\n}", "func NewDiscard() PlainLogger {\n\treturn PlainLogger{debug: io.Discard}\n}", "func NewNoMDEntriesRepeatingGroup() NoMDEntriesRepeatingGroup {\n\treturn NoMDEntriesRepeatingGroup{\n\t\tquickfix.NewRepeatingGroup(tag.NoMDEntries,\n\t\t\tquickfix.GroupTemplate{quickfix.GroupElement(tag.MDEntryType), quickfix.GroupElement(tag.MDEntryPx), quickfix.GroupElement(tag.Currency), quickfix.GroupElement(tag.MDEntrySize), quickfix.GroupElement(tag.MDEntryDate), quickfix.GroupElement(tag.MDEntryTime), quickfix.GroupElement(tag.TickDirection), quickfix.GroupElement(tag.MDMkt), quickfix.GroupElement(tag.TradingSessionID), quickfix.GroupElement(tag.QuoteCondition), quickfix.GroupElement(tag.TradeCondition), quickfix.GroupElement(tag.MDEntryOriginator), quickfix.GroupElement(tag.LocationID), quickfix.GroupElement(tag.DeskID), quickfix.GroupElement(tag.OpenCloseSettleFlag), quickfix.GroupElement(tag.TimeInForce), quickfix.GroupElement(tag.ExpireDate), quickfix.GroupElement(tag.ExpireTime), quickfix.GroupElement(tag.MinQty), quickfix.GroupElement(tag.ExecInst), quickfix.GroupElement(tag.SellerDays), quickfix.GroupElement(tag.OrderID), quickfix.GroupElement(tag.QuoteEntryID), quickfix.GroupElement(tag.MDEntryBuyer), quickfix.GroupElement(tag.MDEntrySeller), quickfix.GroupElement(tag.NumberOfOrders), quickfix.GroupElement(tag.MDEntryPositionNo), quickfix.GroupElement(tag.Text), quickfix.GroupElement(tag.EncodedTextLen), quickfix.GroupElement(tag.EncodedText)}),\n\t}\n}", "func NewFullFaker() *Minerva {\n\treturn &Minerva{\n\t\tconfig: Config{\n\t\t\tPowMode: ModeFullFake,\n\t\t},\n\t}\n}", "func NewDeduper(n int, factory func() boom.Filter) *Deduper {\n\td := &Deduper{\n\t\tring: ring.New(n),\n\t\tfactory: factory,\n\t}\n\n\t// init each element to an empty bloom filter\n\tfor i := 0; i < n; i++ {\n\t\t// expect 100k items, allow fp rate of 1%\n\t\td.ring.Value = d.factory()\n\t\td.ring = d.ring.Next()\n\t}\n\n\treturn d\n}", "func NewFilledInstance(data []byte, typ interface{}) interface{} {\n\tif typ == nil {\n\t\treturn nil\n\t}\n\n\tfuzzer := randparam.NewFuzzer(data)\n\tobj := reflect.New(reflect.TypeOf(typ)).Interface()\n\tfuzzer.Fuzz(obj)\n\n\treturn obj\n}", "func New(n int, size int) Number {\n\tz2n := zero2nine.FromInt(n)\n\tnum := &number{size: size}\n\tswitch z2n {\n\tcase zero2nine.Zero:\n\t\treturn &zero{num}\n\tcase zero2nine.One:\n\t\treturn &one{num}\n\tcase zero2nine.Two:\n\t\treturn &two{num}\n\tcase zero2nine.Three:\n\t\treturn &three{num}\n\tcase zero2nine.Four:\n\t\treturn &four{num}\n\tcase zero2nine.Five:\n\t\treturn &five{num}\n\tcase zero2nine.Six:\n\t\treturn &six{num}\n\tcase zero2nine.Seven:\n\t\treturn &seven{num}\n\tcase zero2nine.Eight:\n\t\treturn &eight{num}\n\tcase zero2nine.Nine:\n\t\treturn &nine{num}\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (m NoSides) SetNoAllocs(f NoAllocsRepeatingGroup) {\n\tm.SetGroup(f)\n}", "func NewNoMiscFees(val int) NoMiscFeesField {\n\treturn NoMiscFeesField{quickfix.FIXInt(val)}\n}", "func New() NopPrinter { return NopPrinter{} }", "func (c *Container) NewFiller(r *Root, bus FillingBus) (fl *Filler) {\n\n\tc.Debugln(FillVerbosePin, \"NewFiller\", r.Short())\n\n\tfl = new(Filler)\n\n\tfl.c = c\n\n\tfl.bus = bus\n\n\tfl.r = r\n\tfl.gotq = make(chan []byte, 1)\n\n\tfl.closeq = make(chan struct{})\n\n\tfl.tp = time.Now() // time point\n\n\tgo fl.fill()\n\treturn\n}", "func NewBare() *Proxier {\n\tp := &Proxier{}\n\tp.proxySources = map[proxy.ProxySource]bool{}\n\tp.ProxyTimeout = DefaultProxyDBTimeout\n\treturn p\n}", "func NewAllDashboardsNotFound() *AllDashboardsNotFound {\n return &AllDashboardsNotFound{\n }\n}", "func NewMemoNone() *Memo {\n\treturn &Memo{Type: MemoTypeNone}\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 (f *FDTable) initNoLeakCheck() {\n\tvar slice descriptorBucketSlice // Empty slice.\n\tf.slice.Store(&slice)\n}", "func (ms DoubleDataPoint) InitEmpty() {\n\t*ms.orig = &otlpmetrics.DoubleDataPoint{}\n}", "func (i InputCheckPasswordEmpty) construct() InputCheckPasswordSRPClass { return &i }", "func (n NetworkTypeNone) construct() NetworkTypeClass { return &n }", "func defaultsFactory() android.Module {\n\treturn DefaultsFactory()\n}", "func fillNaNDense(m *mat.Dense) {\n\tr, c := m.Dims()\n\tfor i := 0; i < r; i++ {\n\t\tfor j := 0; j < c; j++ {\n\t\t\tm.Set(i, j, math.NaN())\n\t\t}\n\t}\n}", "func NewNoop() Logger {\n\treturn &noop{}\n}", "func NewScratch() *Scratch {\n\treturn &Scratch{values: make(map[string]any)}\n}", "func NewNoSidesRepeatingGroup() NoSidesRepeatingGroup {\n\treturn NoSidesRepeatingGroup{\n\t\tquickfix.NewRepeatingGroup(tag.NoSides,\n\t\t\tquickfix.GroupTemplate{quickfix.GroupElement(tag.Side), quickfix.GroupElement(tag.OrigClOrdID), quickfix.GroupElement(tag.ClOrdID), quickfix.GroupElement(tag.SecondaryClOrdID), quickfix.GroupElement(tag.ClOrdLinkID), quickfix.GroupElement(tag.OrigOrdModTime), NewNoPartyIDsRepeatingGroup(), quickfix.GroupElement(tag.TradeOriginationDate), quickfix.GroupElement(tag.Account), quickfix.GroupElement(tag.AccountType), quickfix.GroupElement(tag.DayBookingInst), quickfix.GroupElement(tag.BookingUnit), quickfix.GroupElement(tag.PreallocMethod), NewNoAllocsRepeatingGroup(), quickfix.GroupElement(tag.QuantityType), quickfix.GroupElement(tag.OrderQty), quickfix.GroupElement(tag.CashOrderQty), quickfix.GroupElement(tag.OrderPercent), quickfix.GroupElement(tag.RoundingDirection), quickfix.GroupElement(tag.RoundingModulus), quickfix.GroupElement(tag.Commission), quickfix.GroupElement(tag.CommType), quickfix.GroupElement(tag.CommCurrency), quickfix.GroupElement(tag.FundRenewWaiv), quickfix.GroupElement(tag.OrderCapacity), quickfix.GroupElement(tag.OrderRestrictions), quickfix.GroupElement(tag.CustOrderCapacity), quickfix.GroupElement(tag.ForexReq), quickfix.GroupElement(tag.SettlCurrency), quickfix.GroupElement(tag.Text), quickfix.GroupElement(tag.EncodedTextLen), quickfix.GroupElement(tag.EncodedText), quickfix.GroupElement(tag.PositionEffect), quickfix.GroupElement(tag.CoveredOrUncovered), quickfix.GroupElement(tag.CashMargin), quickfix.GroupElement(tag.ClearingFeeIndicator), quickfix.GroupElement(tag.SolicitedFlag), quickfix.GroupElement(tag.SideComplianceID)})}\n}", "func NewNoStrikes(val int) NoStrikesField {\n\treturn NoStrikesField{quickfix.FIXInt(val)}\n}", "func NewNoPosf(format string, a ...interface{}) (err error) {\n\treturn &ErrInfo{Err: fmt.Errorf(format, a...)}\n}", "func newEmptyFormulaArg() formulaArg {\n\treturn formulaArg{Type: ArgEmpty}\n}", "func (*IQ) NoOp() {\n\n}", "func makeBlankAdapterMetrics(disabledMetrics config.DisabledMetrics) *AdapterMetrics {\n\tblankMeter := &metrics.NilMeter{}\n\tnewAdapter := &AdapterMetrics{\n\t\tNoCookieMeter: blankMeter,\n\t\tErrorMeters: make(map[AdapterError]metrics.Meter),\n\t\tNoBidMeter: blankMeter,\n\t\tGotBidsMeter: blankMeter,\n\t\tRequestTimer: &metrics.NilTimer{},\n\t\tPriceHistogram: &metrics.NilHistogram{},\n\t\tBidsReceivedMeter: blankMeter,\n\t\tPanicMeter: blankMeter,\n\t\tMarkupMetrics: makeBlankBidMarkupMetrics(),\n\t}\n\tif !disabledMetrics.AdapterConnectionMetrics {\n\t\tnewAdapter.ConnCreated = metrics.NilCounter{}\n\t\tnewAdapter.ConnReused = metrics.NilCounter{}\n\t\tnewAdapter.ConnWaitTime = &metrics.NilTimer{}\n\t}\n\tif !disabledMetrics.AdapterGDPRRequestBlocked {\n\t\tnewAdapter.GDPRRequestBlocked = blankMeter\n\t}\n\tfor _, err := range AdapterErrors() {\n\t\tnewAdapter.ErrorMeters[err] = blankMeter\n\t}\n\treturn newAdapter\n}", "func GenerateEmpty(n, m int) Matrix {\n\tout := make([]Row, n)\n\n\tfor i := 0; i < n; i++ {\n\t\tout[i] = NewRow(m)\n\t}\n\n\treturn Matrix(out)\n}", "func MustNew(area image.Rectangle) *braille.Canvas {\n\tcvs, err := braille.New(area)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"braille.New => unexpected error: %v\", err))\n\t}\n\treturn cvs\n}", "func (b *BallotBox) newFilledBallot(voter types.Partition, vote uint64) ballot {\n\treturn ballot{\n\t\tfrom: voter,\n\t\ttimestamp: vote,\n\t}\n}", "func randomNoAloneNoPickupSetup(splits [][]deck.Card) euchre.Setup {\n dealer := r.Intn(4)\n caller := r.Intn(4)\n pickedUp := false\n top := splits[4][3]\n trump := deck.SUITS[r.Intn(len(deck.SUITS))]\n var discard deck.Card\n\n return euchre.Setup {\n dealer,\n caller,\n pickedUp,\n top,\n trump,\n discard,\n -1,\n }\n}", "func New() *Check {\n\treturn &Check{}\n}", "func MustNew(cfg Config) *Notifier {\n\tnotifier, err := New(cfg)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn notifier\n}", "func Dummy() *log.Logger {\n\treturn log.New(ioutil.Discard, \"\", 0)\n}", "func NewFoo() *Foo {\n return &Foo{}\n}", "func New() Builder {\n\treturn newBuilder()\n}", "func (me XsdGoPkgHasElems_Fill) FillDefault() xsdt.Boolean {\r\n\tvar x = new(xsdt.Boolean)\r\n\tx.Set(\"1\")\r\n\treturn *x\r\n}", "func New() *Nitro {\n\treturn NewWithConfig(DefaultConfig())\n}", "func mustNew(hash string, size int64) *repb.Digest {\n\tdigest, err := New(hash, size)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn digest\n}", "func MakeEmptyMetricData(name string, step, start, stop int64) *MetricData {\n\tvalues := make([]float64, 0)\n\tfor i := start; i < stop; i += step {\n\t\tvalues = append(values, math.NaN())\n\t}\n\treturn &MetricData{\n\t\tName: name,\n\t\tValues: values,\n\t\tStartTime: start,\n\t\tStepTime: step,\n\t\tStopTime: stop,\n\t}\n}", "func (m NoSides) GetNoAllocs() (NoAllocsRepeatingGroup, quickfix.MessageRejectError) {\n\tf := NewNoAllocsRepeatingGroup()\n\terr := m.GetGroup(f)\n\treturn f, err\n}", "func TestEmptyNewList(t *testing.T) {\n\tdl:=DList{}\n\trequire.Equal(t,0,dl.Len(),\"New empty List should has a length 0\")\n}" ]
[ "0.6507192", "0.6199866", "0.617042", "0.5738209", "0.5639149", "0.5600072", "0.5600072", "0.5494039", "0.53572273", "0.5356669", "0.5356669", "0.5356669", "0.5356669", "0.5356669", "0.5356669", "0.534152", "0.53205913", "0.5306964", "0.5291138", "0.5291138", "0.52845097", "0.526881", "0.52639675", "0.5263181", "0.5260298", "0.52391964", "0.5222328", "0.51930916", "0.51750463", "0.51666164", "0.5162893", "0.5158392", "0.51214266", "0.51156425", "0.5112285", "0.5108646", "0.51068497", "0.50936174", "0.5086106", "0.5081402", "0.5078512", "0.5076317", "0.50716746", "0.50705045", "0.50543714", "0.50264364", "0.5017409", "0.5015941", "0.5013996", "0.5013424", "0.5008377", "0.50008696", "0.49972615", "0.4979275", "0.4970207", "0.4968917", "0.49553764", "0.49534073", "0.49470356", "0.49445426", "0.49392587", "0.49364406", "0.4912762", "0.4912514", "0.49074164", "0.4905134", "0.4893403", "0.48918706", "0.48790744", "0.48736763", "0.48731342", "0.48726302", "0.4865676", "0.48570034", "0.48553318", "0.48482642", "0.48446757", "0.48440284", "0.4838356", "0.48375043", "0.48302484", "0.48277026", "0.48253816", "0.48212087", "0.48137", "0.48123664", "0.48063952", "0.4802238", "0.47915077", "0.47912195", "0.47908983", "0.47812977", "0.47762543", "0.47761136", "0.47736305", "0.47650808", "0.47621563", "0.4753863", "0.4751254", "0.47475338" ]
0.83670175
0
base64Encode takes in a string and returns a base 64 encoded string
func base64Encode(src string) string { return strings. TrimRight(base64.URLEncoding. EncodeToString([]byte(src)), "=") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Base64Encode(str string) string {\n\treturn base64.StdEncoding.EncodeToString([]byte(str))\n}", "func Base64Encode(src string) string {\n\treturn base64.StdEncoding.EncodeToString([]byte(src))\n}", "func Base64Encode(text string) string {\n\treturn base64.StdEncoding.EncodeToString([]byte(text))\n}", "func base64Encode(value string) string {\n\treturn base64.StdEncoding.EncodeToString([]byte(value))\n}", "func Base64Encode(operand string) string { return base64.StdEncoding.EncodeToString([]byte(operand)) }", "func BASE64EncodeString(str string) string {\n\treturn base64.StdEncoding.EncodeToString([]byte(str))\n}", "func EncodeBase64(value string) string {\n\treturn base64.StdEncoding.EncodeToString([]byte(value))\n}", "func EncodeBase64(bytes []byte) string {\n\treturn base64.URLEncoding.EncodeToString(bytes)\n}", "func Base64Encode(raw []byte) string {\n\treturn base64.URLEncoding.EncodeToString(raw)\n}", "func base64Encode(data string) string {\n\t// Check whether the data is already Base64 encoded; don't double-encode\n\tif isBase64Encoded(data) {\n\t\treturn data\n\t}\n\t// data has not been encoded encode and return\n\treturn base64.StdEncoding.EncodeToString([]byte(data))\n}", "func base64encode(v string) string {\n\treturn base64.StdEncoding.EncodeToString([]byte(v))\n}", "func base64Encode(b []byte) string {\n\treturn strings.TrimSuffix(base64.URLEncoding.EncodeToString(b), \"==\")\n}", "func base64Encode(src interface{}) (string, error) {\n\tif src == nil {\n\t\treturn \"\", consts.ErrNilInterface\n\t}\n\tsrcMarshal, err := json.Marshal(src)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tsrcString := string(srcMarshal)\n\t// TODO maybe use Trim\n\treturn strings.TrimRight(base64.URLEncoding.EncodeToString([]byte(srcString)), \"=\"), nil\n}", "func encodeBase64(source []byte) string {\n\t// make a byte slice just big enough for the result of the encode operation\n\tdest := make([]byte, base64.StdEncoding.EncodedLen(len(source)))\n\t// encode it\n\tbase64.StdEncoding.Encode(dest, source)\n\t// convert this byte buffer to a string\n\treturn bytes.NewBuffer(dest).String()\n}", "func base64Encode(toEncode []byte) string {\n\treturn base64.StdEncoding.EncodeToString(toEncode)\n}", "func base64encode(src []byte) string {\n\tvar buf bytes.Buffer\n\tencoder := base64.NewEncoder(base64.StdEncoding, &buf)\n\tencoder.Write(src)\n\tencoder.Close()\n\treturn buf.String()\n}", "func Base64Encode(src []byte) []byte {\n\treturn DefaultEncoding.Base64Encode(src)\n}", "func base64Encode(src []byte) string {\n\tbuf := make([]byte, base64EncodedLen(len(src)))\n\n\t// mehhhhh actually base64 encoding is a bit more involved\n\t// and it feels like not a good use of time to implement it myself right now,\n\t// I should come back to it. Basically you take 3 bytes of input,\n\t// and then break it into 4 groups of 6 bits, and then encode that\n\t// to produce 4 bytes of base64\n\tbase64.StdEncoding.Encode(buf, src)\n\treturn string(buf)\n}", "func Base64(str []byte, alphaSet ...string) string {\n\tencoding := base64.StdEncoding\n\tif len(alphaSet) != 0 && alphaSet[0] != \"\" {\n\t\tencoding = base64.NewEncoding(alphaSet[0])\n\t}\n\treturn encoding.EncodeToString(str)\n}", "func Base64Encode(b []byte) []byte {\r\n\tbuf := make([]byte, base64.RawURLEncoding.EncodedLen(len(b)))\r\n\tbase64.RawURLEncoding.Encode(buf, b)\r\n\treturn buf\r\n}", "func Base64Encode(vm *otto.Otto) {\n\tvm.Set(\"base64encode\", func(call otto.FunctionCall) otto.Value {\n\t\ta0 := call.Argument(0)\n\t\tif !a0.IsString() {\n\t\t\tfmt.Println(\"ERROR\", \"base64encode(string)\")\n\t\t\treturn otto.Value{}\n\t\t}\n\t\ts, err := a0.ToString()\n\t\tif err != nil {\n\t\t\tfmt.Println(\"ERROR\", err)\n\t\t\treturn otto.Value{}\n\t\t}\n\t\ts = base64.StdEncoding.EncodeToString([]byte(s))\n\t\tv, err := vm.ToValue(s)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"ERROR\", err)\n\t\t\treturn otto.Value{}\n\t\t}\n\t\treturn v\n\t})\n}", "func BASE64UrlEncodeString(str string) string {\n\tstr = HmacMd5Encode(str)\n\treturn base64.URLEncoding.EncodeToString([]byte(str))\n}", "func Base64Encode(input []byte) []byte {\n\tenc := base64.StdEncoding\n\tencLength := enc.EncodedLen(len(input))\n\toutput := make([]byte, encLength)\n\tenc.Encode(output, input)\n\treturn output\n}", "func EncodeBase64(data []byte) (out []byte) {\n\tout = make([]byte, Encoding.EncodedLen(len(data)))\n\tEncoding.Encode(out, data)\n\treturn\n}", "func encodeAuthToBase64(authConfig types.AuthConfig) (string, error) {\n\tbuf, err := json.Marshal(authConfig)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn base64.URLEncoding.EncodeToString(buf), nil\n}", "func Base64(data []byte) string {\n\treturn base64.StdEncoding.EncodeToString(data)\n}", "func Base64(bin []byte) string {\n\treturn base64.StdEncoding.EncodeToString(bin)\n}", "func Encode64(inputStr string) string {\n\treturn base64.StdEncoding.EncodeToString([]byte(inputStr))\n}", "func (enc *Base64Encoding) Base64Encode(src []byte) []byte {\n\tn := enc.Encoding.EncodedLen(len(src))\n\tdst := make([]byte, n)\n\tenc.Encoding.Encode(dst, src)\n\tfor n > 0 && dst[n-1] == '=' {\n\t\tn--\n\t}\n\treturn dst[:n]\n}", "func EncodeAsBase64(e interface{}) string {\n\tvar b bytes.Buffer\n\tenc := gob.NewEncoder(&b)\n\tif err := enc.Encode(e); err != nil {\n\t\tpanic(err)\n\t}\n\tbytes := b.Bytes()\n\tsha := sha1.New()\n\tsha.Write(bytes)\n\tbytes = sha.Sum(nil)\n\tb64 := base64.StdEncoding.EncodeToString(bytes)\n\treturn b64\n}", "func base64Str(b []byte) string {\n\treturn base64.StdEncoding.EncodeToString(b)\n}", "func Base64Encoded() (string, error) {\n\tbyt, err := generateBytes()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tencoded := base64.StdEncoding.EncodeToString(byt)\n\treturn encoded, nil\n}", "func EncryptBase64(data []byte) string {\n\treturn base64.StdEncoding.EncodeToString(data)\n}", "func B64Encode(data []byte) string {\n\tenc := base64.StdEncoding.EncodeToString(data)\n\treturn enc\n}", "func runtimeEncodeBase64(ic *interop.Context) error {\n\tsrc := ic.VM.Estack().Pop().Bytes()\n\tresult := base64.StdEncoding.EncodeToString(src)\n\tic.VM.Estack().PushVal([]byte(result))\n\treturn nil\n}", "func AuthenticateToBase64(auth *Authenticate) (string, error) {\n\tjs, err := json.Marshal(auth)\n\tif err != nil {\n\t\treturn \"\", nil\n\t}\n\n\treturn b64.StdEncoding.EncodeToString(js), nil\n}", "func EncodeToBase64(ext string, value []byte) string {\n\tn := 5 + 8 + len(ext) + base64.StdEncoding.EncodedLen(len(value))\n\thas := strings.HasPrefix(ext, \"image/\")\n\tif !has {\n\t\tn += 6\n\t}\n\tbuilder := strings.Builder{}\n\tbuilder.Grow(n)\n\tbuilder.WriteString(\"data:\")\n\tif !has {\n\t\tbuilder.WriteString(\"image/\")\n\t}\n\tbuilder.WriteString(ext)\n\tbuilder.WriteString(\";base64,\")\n\tbuilder.WriteString(base64.StdEncoding.EncodeToString(value))\n\treturn builder.String()\n}", "func EncodeBase64(savePath string, fileNama string) string {\n\tfile, err := os.Open(savePath + fileNama)\n\tdefer file.Close()\n\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\tfi, _ := file.Stat() // interface\n\tsize := fi.Size() // file size\n\n\tdata := make([]byte, size)\n\tfile.Read(data)\n\n\treturn base64.StdEncoding.EncodeToString(data)\n}", "func EncodeString(data []byte) string {\n\treturn base64.StdEncoding.EncodeToString(data)\n}", "func EncryptStringToBase64EncodedString(key, stringToEncrypt string) (base64String string, err error) {\n\tif IsEncryptionOn == false {\n\t\treturn stringToEncrypt, nil\n\t}\n\tkeyBytes := []byte(key)\n\tstringToEncryptBytes := []byte(stringToEncrypt)\n\tencryptedByteArray, err := EncryptByteArray(keyBytes, stringToEncryptBytes)\n\tencryptedString := base64.StdEncoding.EncodeToString(encryptedByteArray)\n\treturn encryptedString, err\n}", "func Base64Encoder(asBytes Bytes16) string {\n\treturn base64.StdEncoding.EncodeToString(asBytes[:])\n}", "func HashBase64(input string) string {\n\thash512 := sha512.Sum512([]byte(input))\n\n\treturn base64.StdEncoding.EncodeToString(hash512[:])\n}", "func Base64MimeEncoder(b string) (m string) {\n\n\tm = base64.StdEncoding.EncodeToString([]byte(b))\n\tthe_len := len(m)\n\n\tif (the_len <= maxLen) {\n\t\treturn m\n\t}\n\n\tnew_m := []byte(m)\n\n\t// set the slice capacity to the slice len + each newline delimiters\n\tm1 := make([]byte, 0, the_len+(len(delimiter)*int(the_len/maxLen)))\n\tii := 0\n\tfor i := 0; i < int(the_len/maxLen); i++ {\n\t\tm1 = append(m1, new_m[i*maxLen:(i+1)*maxLen]...)\n\t\tm1 = append(m1, delimiter...)\n\t\tii++\n\t}\n\tm1 = append(m1, new_m[ii*maxLen:the_len]...)\n\tm = string(m1)\n\treturn m\n}", "func (c *publicKey) Base64() (string, error) {\n\tb, err := c.Raw()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn base64.StdEncoding.EncodeToString(b), nil\n}", "func Base64UrlSafeEncode(source []byte) string {\n\tbyteArr := base64.StdEncoding.EncodeToString(source)\n\tsafeUrl := strings.Replace(byteArr, \"/\", \"_\", -1)\n\tsafeUrl = strings.Replace(safeUrl, \"+\", \"-\", -1)\n\tsafeUrl = strings.Replace(safeUrl, \"=\", \"\", -1)\n\treturn safeUrl\n}", "func Encode(in []byte) (string, error) {\n\treturn b64.StdEncoding.EncodeToString(in), nil\n}", "func __b64encode(out *[]byte, src *[]byte, mode int)", "func (p *policy) Base64() string {\n\treturn base64.StdEncoding.EncodeToString([]byte(p.String()))\n}", "func tob64(in []byte) string {\n\treturn base64.RawURLEncoding.EncodeToString(in)\n}", "func Encode(src []byte) string {\n\treturn base64.RawURLEncoding.EncodeToString(src)\n}", "func ExportAsBase64String(insta *goinsta.Instagram) (string, error) {\n\tbytes, err := ExportAsBytes(insta)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsEnc := base64.StdEncoding.EncodeToString(bytes)\n\treturn sEnc, nil\n}", "func joseBase64UrlEncode(b []byte) string {\n\treturn strings.TrimRight(base64.URLEncoding.EncodeToString(b), \"=\")\n}", "func tob64S(s string) string {\n\treturn base64.RawURLEncoding.EncodeToString([]byte(s))\n}", "func EncodeBlessingsBase64(blessings security.Blessings) (string, error) {\n\tif blessings.IsZero() {\n\t\treturn \"\", fmt.Errorf(\"no blessings found\")\n\t}\n\tstr, err := base64urlVomEncode(blessings)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"base64url-vom encoding failed: %v\", err)\n\t}\n\treturn str, nil\n}", "func Base64(n int) string { return String(n, Base64Chars) }", "func EncodeBase64(scope *Scope, input tf.Output, optional ...EncodeBase64Attr) (output tf.Output) {\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: \"EncodeBase64\",\n\t\tInput: []tf.Input{\n\t\t\tinput,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func (s Signature) Base64() ([]byte, error) {\n\treturn jose.Base64Encode(s), nil\n}", "func Encode(value []byte) []byte {\n var length int = len(value)\n encoded := make([]byte, base64.URLEncoding.EncodedLen(length))\n base64.URLEncoding.Encode(encoded, value)\n return encoded\n}", "func EncodeString(s string) string {\n\tif IsEncoded(s) {\n\t\treturn s\n\t}\n\tencoded := base64.StdEncoding.EncodeToString([]byte(s))\n\treturn encoded\n}", "func Base64EncodedString(i interface{}, k string) ([]string, []error) {\n\tv, ok := i.(string)\n\tif !ok {\n\t\treturn nil, []error{fmt.Errorf(\"expected type of %q to be string\", k)}\n\t}\n\n\tif strings.TrimSpace(v) == \"\" {\n\t\treturn nil, []error{fmt.Errorf(\"%q must not be empty\", k)}\n\t}\n\n\tif _, err := base64.StdEncoding.DecodeString(v); err != nil {\n\t\treturn nil, []error{fmt.Errorf(\"%q must be a valid base64 encoded string\", k)}\n\t}\n\n\treturn nil, nil\n}", "func (s Sig) Base64Encoded() (string, error) {\n\tsig, ok := s.Layer.Annotations[CosignSigKey]\n\tif !ok {\n\t\treturn \"\", errors.New(\"cosign signature not found in the layer annotations\")\n\t}\n\tif _, err := encoding.DecodeString(sig); err != nil {\n\t\treturn \"\", fmt.Errorf(\"invalid base64 encoded signature: %w\", err)\n\t}\n\treturn sig, nil\n}", "func ConvertToBase64Str(key []byte) string {\n\treturn base64.StdEncoding.EncodeToString(key)\n}", "func EncodeUUIDBase64(id *uuid.UUID) string {\n\tif id == nil {\n\t\treturn \"\"\n\t}\n\treturn base64.RawStdEncoding.EncodeToString(id.Bytes())\n}", "func Base64(n int) (ss string, err error) {\n\tbs, err := Bytes(n)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tss = base64.StdEncoding.EncodeToString(bs)\n\n\treturn\n}", "func Encode(value string) string {\n\tencoded := make([]byte, base64.URLEncoding.EncodedLen(len(value)))\n\tbase64.URLEncoding.Encode(encoded, []byte(value))\n\treturn string(encoded)\n}", "func EncodeToString(src []byte) string {\n\treturn base64.StdEncoding.EncodeToString(src)\n}", "func Encode(part []byte) string {\n\treturn strings.TrimRight(base64.URLEncoding.EncodeToString(part), \"=\")\n}", "func toBase64Json(data any) (string, error) {\n\tif data == nil {\n\t\treturn \"\", nil\n\t}\n\tb, err := json.Marshal(data)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn base64.URLEncoding.EncodeToString(b), nil\n}", "func EncryptToBase64(cryptKey, text string) (string, error) {\n\tencrypter, err := newDefaultBase64(cryptKey)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn encrypter.Encrypt(text)\n}", "func encode(value []byte) []byte {\n\tencoded := make([]byte, base64.URLEncoding.EncodedLen(len(value)))\n\tbase64.URLEncoding.Encode(encoded, value)\n\treturn encoded\n}", "func ToBase64Query(s *string) *string {\n\treturn String(base64.StdEncoding.EncodeToString([]byte(StringValue(s))))\n}", "func (kp *Full) SignBase64(input []byte) (string, error) {\n\tsig, err := kp.Sign(input)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn base64.StdEncoding.EncodeToString(sig), nil\n}", "func EncodePublicKeyBase64(key security.PublicKey) (string, error) {\n\tbuf, err := key.MarshalBinary()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn base64.URLEncoding.EncodeToString(buf), nil\n}", "func writeBase64(data []byte, partWriter io.Writer) error {\n\tbufsiz := base64.StdEncoding.EncodedLen(len(data))\n\tbuffer := make([]byte, bufsiz)\n\tbase64.StdEncoding.Encode(buffer, data)\n\t_, err := partWriter.Write(buffer)\n\n\treturn err\n}", "func Base64Transaction(tx []byte) (bs string) {\n jtx, _ := json.Marshal(tx)\n bs = base64.StdEncoding.EncodeToString(jtx)\n return bs\n}", "func (cs CryptoService) EncryptBase64(plain []byte) (base64Cipher []byte, err error) {\n\tcipher, err := cs.Encrypt(plain)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbase64Cipher = make([]byte, base64.RawStdEncoding.EncodedLen(len(cipher)))\n\tbase64.RawStdEncoding.Encode(base64Cipher, cipher)\n\n\treturn\n}", "func B64EncodeByteToStr(inputBytes []byte) string {\r\n\treturn base64.StdEncoding.EncodeToString(inputBytes)\r\n}", "func BytesToBase64(b []byte) string {\n\treturn base64.URLEncoding.EncodeToString(b)\n}", "func B64Encrypt(qrToken string) string {\n\tsalt := \"/qr-g3nerat0r/\"\n\tdata := salt + qrToken\n\treturn base64.StdEncoding.EncodeToString([]byte(data))\n}", "func EcbEncryptBase64(key, src string) (string, error) {\n\tkeyBytes, err := getKeyBytes(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsrcBytes, err := base64.StdEncoding.DecodeString(src)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tencryptedBytes, err := EcbEncrypt(keyBytes, srcBytes)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn base64.StdEncoding.EncodeToString(encryptedBytes), nil\n}", "func (n *NameTransform) B64EncodeToString(src []byte) string {\n\treturn n.B64.EncodeToString(src)\n}", "func (n *NameTransform) B64EncodeToString(src []byte) string {\n\treturn n.B64.EncodeToString(src)\n}", "func Base64EncodeMap(m Map) string {\n\tdata, err := json.Marshal(m)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tencoded := base64.URLEncoding.EncodeToString(data)\n\treturn encoded\n}", "func Hex2Base64(s string) string {\n\t// The std library way, for future reference\n\tdecoded, err := hex.DecodeString(s)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn base64.StdEncoding.EncodeToString(decoded)\n}", "func (b Base64) String() string {\n\treturn base64.StdEncoding.EncodeToString(b.data)\n}", "func Base64ToBytes(h string) []byte {\n\ts, err := base64.URLEncoding.DecodeString(h)\n\tif err != nil {\n\t\tfmt.Errorf(\"faild to convert Base64ToBytes(%s) with error : %s\", h, err.Error())\n\t\treturn []byte(\"\")\n\t}\n\treturn s\n}", "func Encode(data []byte) string {\n\t// Factorio\n\tvar b bytes.Buffer\n\tencoder := base64.NewEncoder(base64.StdEncoding, &b)\n\tcompress := zlib.NewWriter(encoder)\n\tcompress.Write(data)\n\tcompress.Close()\n\tencoder.Close()\n\treturn b.String()\n}", "func SHA1Base64String(data string) string {\n\thash := sha1.Sum([]byte(data))\n\treturn base64.StdEncoding.EncodeToString(hash[:])\n}", "func (a I2PAddr) Base64() string {\n\treturn string(a)\n}", "func (me TCryptoBinary) String() string { return xsdt.Base64Binary(me).String() }", "func NewBase64Encoding(alphabet string) *Base64Encoding {\n\treturn &Base64Encoding{\n\t\tAlphabet: alphabet,\n\t\tEncoding: base64.NewEncoding(alphabet),\n\t}\n}", "func EncodeToken64(token string) string {\n\trefreshToken := base64.StdEncoding.EncodeToString([]byte(token))\n\treturn refreshToken\n}", "func Encode(src []byte) []byte {\n\tdst := make([]byte, base64.StdEncoding.EncodedLen(len(src)))\n\tbase64.StdEncoding.Encode(dst, src)\n\treturn dst\n}", "func Base64IfNotPrintable(val []byte) string {\n\tif IsPrintable(string(val)) {\n\t\treturn string(val)\n\t}\n\n\treturn base64.StdEncoding.EncodeToString(val)\n}", "func HexToBase64(hex []byte) string {\n\tencoder := base64.StdEncoding\n\treturn encoder.EncodeToString(hex)\n}", "func hexToBase64(hexStr string) string {\n\thex, err := hex.DecodeString(hexStr)\n\tcheck(err)\n\treturn base64.StdEncoding.EncodeToString(hex)\n}", "func EncodeString(objs ...interface{}) (out string, err error) {\n\tbbuf, err := EncodeBytes(objs...)\n\tif err != nil {\n\t\treturn\n\t}\n\tout = base64.URLEncoding.EncodeToString(bbuf)\n\treturn\n}", "func DecodeBase64(s string) []byte { \n bytes, err := base64.URLEncoding.DecodeString(s) \n if err != nil { \n \tfmt.Println(\"ERROR: There was an error decoding string (my_server.go: DecodeBase64)\")\n \tfmt.Println(err)\n \treturn []byte{}\n } \n return bytes \n}", "func Img2Base64Str(img *image.Image)(string, error) {\n var b bytes.Buffer\n w := bufio.NewWriter(&b)\n jpeg.Encode(w, *img, nil)\n encoded := base64.StdEncoding.EncodeToString(b.Bytes())\n return encoded, nil\n}", "func (a *AttributeEndorsement) ToBase64() string {\n\treturn base64.StdEncoding.EncodeToString(a.ToBytes())\n}" ]
[ "0.84703225", "0.83077854", "0.83015156", "0.8226953", "0.82128876", "0.81633633", "0.8149859", "0.810932", "0.80856764", "0.8074903", "0.807217", "0.7981776", "0.7970947", "0.79534185", "0.7880615", "0.7826774", "0.77798414", "0.7763966", "0.77257025", "0.7722197", "0.76544267", "0.7644352", "0.7639274", "0.76368695", "0.75320166", "0.75295836", "0.7524305", "0.75055265", "0.7501723", "0.7496619", "0.7420788", "0.74161303", "0.73587793", "0.7332434", "0.73073226", "0.72833055", "0.72471046", "0.7233196", "0.72090036", "0.71837723", "0.7133237", "0.7066083", "0.7063969", "0.70571935", "0.7051319", "0.69938904", "0.69783014", "0.69599503", "0.69573075", "0.69494313", "0.69474274", "0.6915671", "0.6909882", "0.69059074", "0.689906", "0.6856532", "0.6855544", "0.6836718", "0.683272", "0.6832324", "0.6825051", "0.6819605", "0.68030167", "0.6754644", "0.67380404", "0.6730731", "0.6729388", "0.6717444", "0.67084736", "0.6702962", "0.6702122", "0.6677766", "0.66748", "0.6664505", "0.666301", "0.6625404", "0.6619496", "0.6619119", "0.661375", "0.6597452", "0.6544421", "0.6544421", "0.651228", "0.65102714", "0.64645153", "0.64470476", "0.64283967", "0.6414403", "0.6397489", "0.635599", "0.6341429", "0.6336923", "0.631937", "0.6305768", "0.6303461", "0.6301056", "0.6300746", "0.626006", "0.6241642", "0.62398297" ]
0.8182063
5
base64Decode takes in a base 64 encoded string and returns the actual string or an error of it fails to decode the string
func base64Decode(src string) (string, error) { if l := len(src) % 4; l > 0 { src += strings.Repeat("=", 4-l) } decoded, err := base64.URLEncoding.DecodeString(src) if err != nil { errMsg := fmt.Errorf("Decoding Error %s", err) return "", errMsg } return string(decoded), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func base64Decode(src string) (string, error) {\n\tif strings.TrimSpace(src) == \"\" {\n\t\treturn \"\", consts.ErrEmptyString\n\t}\n\tif l := len(src) % 4; l > 0 {\n\t\tsrc += strings.Repeat(\"=\", 4-l)\n\t}\n\tdecoded, err := base64.URLEncoding.DecodeString(src)\n\tif err != nil {\n\t\terrMsg := fmt.Errorf(\"decoding error %s\", err)\n\t\treturn \"\", errMsg\n\t}\n\treturn string(decoded), nil\n}", "func base64Decode(value string) (string, error) {\n\tres, err := base64.StdEncoding.DecodeString(value)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(res), nil\n}", "func Base64Decode(src string) (string, error) {\n\tif len(src) == 0 {\n\t\treturn \"\", fmt.Errorf(\"cannot decode empty string, occurred in sxutil package\")\n\t}\n\tdata, err := base64.StdEncoding.DecodeString(src)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(data), nil\n}", "func Base64Decode(encoded string) (string, error) {\n\tresult, err := base64.StdEncoding.DecodeString(encoded)\n\treturn string(result), err\n}", "func base64Decode(b string) string {\n\tdata, err := base64.StdEncoding.DecodeString(b)\n\tif err != nil {\n\t\treturn string(b)\n\t}\n\treturn string(data)\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 Base64Decode(input string) (string, error) {\n\tdata, err := base64.StdEncoding.DecodeString(input)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdecoded := string(data)\n\treturn decoded, nil\n}", "func Base64Decode(operand string) (string, error) {\n\tbytes, err := base64.StdEncoding.DecodeString(operand)\n\treturn string(bytes), err\n}", "func base64decode(v string) string {\n\tdata, err := base64.StdEncoding.DecodeString(v)\n\tif err != nil {\n\t\tLogger.Println(\"[ERROR] Failed decoding base64 encoded string\", err)\n\t\treturn err.Error()\n\t}\n\treturn string(data)\n}", "func DecodeBase64(s string) []byte { \n bytes, err := base64.URLEncoding.DecodeString(s) \n if err != nil { \n \tfmt.Println(\"ERROR: There was an error decoding string (my_server.go: DecodeBase64)\")\n \tfmt.Println(err)\n \treturn []byte{}\n } \n return bytes \n}", "func Base64Decode(src string) (string, error) {\n if l := len(src) % 4; l > 0 {\n src += strings.Repeat(\"=\", 4-l)\n }\n decoded, err := base64.URLEncoding.DecodeString(src)\n if err != nil {\n errMsg := fmt.Errorf(\"Error al desencodear %s\", err)\n return \"\", errMsg\n }\n return string(decoded), nil\n}", "func BASE64DecodeString(str string) string {\n\tresult, _ := base64.StdEncoding.DecodeString(str)\n\treturn string(result)\n}", "func Base64Decode(encoded string) ([]byte, error) {\n\treturn base64.URLEncoding.DecodeString(encoded)\n}", "func Base64Decode(src []byte) ([]byte, error) {\n\treturn DefaultEncoding.Base64Decode(src)\n}", "func DecodeBase64(value string) (string, error) {\n\tdecoded, err := base64.StdEncoding.DecodeString(value)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(decoded), nil\n}", "func Base64Decode(b []byte) ([]byte, error) {\r\n\tbuf := make([]byte, base64.RawURLEncoding.DecodedLen(len(b)))\r\n\tn, err := base64.RawURLEncoding.Decode(buf, b)\r\n\treturn buf[:n], err\r\n}", "func DecodeBase64(source string) ([]byte, error) {\n\tout, err := base64.StdEncoding.DecodeString(source)\n\treturn out, err\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 Base64Decode(vm *otto.Otto) {\n\tvm.Set(\"base64decode\", func(call otto.FunctionCall) otto.Value {\n\t\ta0 := call.Argument(0)\n\t\tif !a0.IsString() {\n\t\t\tfmt.Println(\"ERROR\", \"base64decode(string)\")\n\t\t\treturn otto.Value{}\n\t\t}\n\t\ts, err := a0.ToString()\n\t\tif err != nil {\n\t\t\tfmt.Println(\"ERROR\", err)\n\t\t\treturn otto.Value{}\n\t\t}\n\t\tsb, err := base64.StdEncoding.DecodeString(s)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"ERROR\", err)\n\t\t\treturn otto.Value{}\n\t\t}\n\t\tv, err := vm.ToValue(string(sb))\n\t\tif err != nil {\n\t\t\tfmt.Println(\"ERROR\", err)\n\t\t\treturn otto.Value{}\n\t\t}\n\t\treturn v\n\t})\n}", "func Base64Decode(input []byte) []byte {\n\tdec := base64.StdEncoding\n\tdecLength := dec.DecodedLen(len(input))\n\toutput := make([]byte, decLength)\n\tn, err := dec.Decode(output, input)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif n < decLength {\n\t\toutput = output[:n]\n\t}\n\treturn output\n}", "func DecodeString(data string) ([]byte, error) {\n\treturn base64.StdEncoding.DecodeString(data)\n}", "func Decode(in string) ([]byte, error) {\n\to, err := b64.StdEncoding.DecodeString(in)\n\tif err != nil {\n\t\t// maybe it's in the URL variant?\n\t\to, err = b64.URLEncoding.DecodeString(in)\n\t\tif err != nil {\n\t\t\t// ok, just give up...\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn o, nil\n}", "func decodeBase64Upload(fileUpload string) ([]byte, error) {\n\t// Split the file uploads into the various parts\n\tfileParts := strings.Split(fileUpload, \";\")\n\tif len(fileParts) != 3 {\n\t\terr := errors.New(\"Error parsing the uploaded file\")\n\t\tlog.Error(err.Error())\n\t\treturn []byte{}, err\n\t}\n\t// [0] - file:[filename of uploaded file]\n\t// [1] - data:[data type (text/plain)]\n\t// [2] - base64,[data]\n\n\t// Decode the base64 file content\n\tdecodedBytes, err := base64.StdEncoding.DecodeString(fileParts[2][7:])\n\tif err != nil {\n\t\tlog.WithField(\"error\", err).Error(\"Error parsing the base64 file contents\")\n\t\treturn []byte{}, err\n\t}\n\n\t// Return the decoded bytes\n\treturn decodedBytes, nil\n}", "func DecodeString(encode, content string) (string, error) {\n\tif strings.EqualFold(\"base64\", encode) {\n\t\tdecode, err := base64.StdEncoding.DecodeString(content)\n\t\treturn string(decode), err\n\t}\n\n\treturn content, nil\n}", "func runtimeDecodeBase64(ic *interop.Context) error {\n\tsrc := ic.VM.Estack().Pop().String()\n\tresult, err := base64.StdEncoding.DecodeString(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tic.VM.Estack().PushVal(result)\n\treturn nil\n}", "func DecodeBase64(encoded []byte) (out []byte, err error) {\n\tout = make([]byte, Encoding.DecodedLen(len(encoded)))\n\t_, err = Encoding.Decode(out, encoded)\n\treturn\n}", "func B64Decode(data string) []byte {\n\tdec, err := base64.StdEncoding.DecodeString(data)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn dec\n}", "func DecodeBase64(img string) (string, []byte, error) {\n\tss := strings.Split(img, \",\")\n\tif len(ss) != 2 {\n\t\treturn \"\", nil, errors.New(\"invalid base64 image data\")\n\t}\n\n\ttp := strings.TrimSuffix(strings.TrimPrefix(ss[0], \"data:\"), \";base64\")\n\tbv, err := base64.StdEncoding.DecodeString(ss[1])\n\treturn tp, bv, err\n}", "func TestBase64Decode(t *testing.T) {\n\twant := \"Hello World\"\n\tg, _ := phpfuncs.Base64Decode(\"SGVsbG8gV29ybGQ=\")\n\tCoverCheck(t, g, want)\n}", "func (b *baseSemanticUTF8Base64) Decode() string {\n\treturn b.decoded\n}", "func Decode(s string, l int) ([]byte, error) {\n\tr, err := base64.RawURLEncoding.DecodeString(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(r) != l {\n\t\treturn nil, fmt.Errorf(\"base64: wrong length %d (expecting %d): %s\", 2*len(r), 2*l, s)\n\t}\n\treturn r, nil\n}", "func fnBase64Decode(ctx Context, doc *JDoc, params []string) interface{} {\n\tstats := ctx.Value(EelTotalStats).(*ServiceStats)\n\tif params == nil || len(params) != 1 {\n\t\tctx.Log().Error(\"error_type\", \"func_base64decode\", \"op\", \"base64decode\", \"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 base64decode function\"), \"base64decode\", params})\n\t\treturn \"\"\n\t}\n\n\tbs, err := base64.StdEncoding.DecodeString(extractStringParam(params[0]))\n\tif err != nil {\n\t\tctx.Log().Error(\"error_type\", \"func_base64decode\", \"op\", \"base64decode\", \"cause\", \"error_decode\", \"params\", params, \"error\", err.Error())\n\t\tstats.IncErrors()\n\t\tAddError(ctx, RuntimeError{err.Error(), \"base64decode\", params})\n\t\treturn \"\"\n\t}\n\n\treturn string(bs)\n}", "func DecodeString(s string) string {\n\tif !IsEncoded(s) {\n\t\treturn s\n\t}\n\tdecodedBytes, e := base64.StdEncoding.DecodeString(s)\n\tif e != nil {\n\t\tlog.Println(\"Unexpected decoding error:\", e)\n\t\treturn s\n\t}\n\treturn string(decodedBytes)\n}", "func Decode(value []byte) ([]byte, error) {\n var length int = len(value)\n decoded := make([]byte, base64.URLEncoding.DecodedLen(length))\n\n n, err := base64.URLEncoding.Decode(decoded, value)\n if err != nil {\n return nil, err\n }\n return decoded[:n], nil\n}", "func Base64UrlDecode(s string) ([]byte, error) {\n\tpad := len(s) % 4\n\tfor pad > 0 {\n\t\ts += \"=\"\n\t\tpad--\n\t}\n\n\treturn base64.StdEncoding.DecodeString(urlDecodeRe.Replace(s))\n}", "func B64DecodeStrToByte(inputString string) ([]byte, error) {\r\n\tdecoded, err := base64.StdEncoding.DecodeString(inputString)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\treturn decoded, nil\r\n}", "func (n *NameTransform) B64DecodeString(s string) ([]byte, error) {\n\treturn n.B64.DecodeString(s)\n}", "func (n *NameTransform) B64DecodeString(s string) ([]byte, error) {\n\treturn n.B64.DecodeString(s)\n}", "func fromb64(in string) string {\n\ts, err := base64.RawURLEncoding.DecodeString(in)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn string(s)\n}", "func __b64decode(out *[]byte, src unsafe.Pointer, len int, mode int) (ret int)", "func vaultDecode(data interface{}) ([]byte, error) {\n\tencoded, ok := data.(string)\n\tif !ok {\n\t\treturn nil, errors.New(\"Received non-string data\")\n\t}\n\n\treturn base64.StdEncoding.DecodeString(prefixRegex.ReplaceAllString(encoded, \"\"))\n}", "func DecodeBase64(scope *Scope, input tf.Output) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"DecodeBase64\",\n\t\tInput: []tf.Input{\n\t\t\tinput,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func DecodeB64(msg []byte) ([]byte, error) {\n\tb64 := base64.StdEncoding\n\tencoded := bytes.TrimSpace(msg)\n\trest := make([]byte, b64.DecodedLen(len(encoded)))\n\tif n, err := b64.Decode(rest, encoded); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\trest = rest[:n]\n\t}\n\treturn rest, 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 (i Base64Image) Decode() (string, error) {\n\tdecoded, err := base64.StdEncoding.DecodeString(string(i))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(decoded), nil\n}", "func Decode(data []byte) ([]byte, error) {\n\tvar (\n\t\tsrc = make([]byte, base64.StdEncoding.DecodedLen(len(data)))\n\t\tn, err = base64.StdEncoding.Decode(src, data)\n\t)\n\tif err != nil {\n\t\terr = gerror.Wrap(err, `base64.StdEncoding.Decode failed`)\n\t}\n\treturn src[:n], err\n}", "func DecodeUUIDBase64(in string) *uuid.UUID {\n\tif in == \"\" {\n\t\treturn nil\n\t}\n\tstr, err := base64.RawStdEncoding.DecodeString(in)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tid := uuid.FromBytesOrNil([]byte(str))\n\tif id != uuid.Nil {\n\t\treturn &id\n\t}\n\treturn nil\n}", "func Base64(s string) bool {\n\tif len(s) == 0 {\n\t\treturn false\n\t}\n\t_, err := base64.StdEncoding.DecodeString(s)\n\n\treturn err == nil\n}", "func Decode(part string) ([]byte, error) {\n\tif l := len(part) % 4; l > 0 {\n\t\tpart += strings.Repeat(\"=\", 4-l)\n\t}\n\n\treturn base64.URLEncoding.DecodeString(part)\n}", "func Decode(value string) (string, error) {\n\tvalue = value\n\tdecoded := make([]byte, base64.URLEncoding.DecodedLen(len(value)))\n\tb, err := base64.URLEncoding.Decode(decoded, []byte(value))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(decoded[:b]), nil\n}", "func vaultDecode(data interface{}) ([]byte, error) {\n\tencoded, ok := data.(string)\n\tif !ok {\n\t\treturn nil, errors.New(\"Received non-string data\")\n\t}\n\treturn base64.StdEncoding.DecodeString(strings.TrimPrefix(encoded, vaultV1DataPrefix))\n}", "func Decode(in string, obj interface{}) error {\n\tb, err := base64.StdEncoding.DecodeString(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(b, obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Decode(in string, obj interface{}) {\n\tb, err := base64.StdEncoding.DecodeString(in)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = json.Unmarshal(b, obj)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func Decode(in string, obj interface{}) {\n\tb, err := base64.StdEncoding.DecodeString(in)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = json.Unmarshal(b, obj)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func base64DecodeBytes(encodedBytes []byte) []byte {\n\tdecodedLen := base64.StdEncoding.DecodedLen(len(encodedBytes))\n\tdecodedBytes := make([]byte, decodedLen)\n\tnumBytesRead := 0\n\tnumBytesWritten := 0\n\tfor numBytesRead+3 < len(encodedBytes) {\n\t\tn, _ := base64.StdEncoding.Decode(decodedBytes[numBytesWritten:], encodedBytes[numBytesRead:])\n\t\tnumBytesWritten += n\n\t\tnumBytesRead += base64.StdEncoding.EncodedLen(n)\n\t}\n\treturn decodedBytes[:numBytesWritten]\n}", "func DecodeToken64(token string) (string, error) {\n\trefreshToken, err := base64.StdEncoding.DecodeString(token)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\treturn \"\", errors.New(\"Error decoding access token\")\n\t}\n\n\treturn string(refreshToken), nil\n}", "func decodeFromBase64(encodedXdr string) *b.TransactionEnvelopeBuilder {\n // Unmarshall from base64 encoded XDR format\n var decoded xdr.TransactionEnvelope\n e := xdr.SafeUnmarshalBase64(encodedXdr, &decoded)\n if e != nil {\n log.Fatal(e)\n }\n\n // convert to TransactionEnvelopeBuilder\n txEnvelopeBuilder := b.TransactionEnvelopeBuilder{E: &decoded}\n txEnvelopeBuilder.Init()\n\n return &txEnvelopeBuilder\n}", "func decodeFromBase64(encodedXdr string) *b.TransactionEnvelopeBuilder {\n // Unmarshall from base64 encoded XDR format\n var decoded xdr.TransactionEnvelope\n e := xdr.SafeUnmarshalBase64(encodedXdr, &decoded)\n if e != nil {\n log.Fatal(e)\n }\n\n // convert to TransactionEnvelopeBuilder\n txEnvelopeBuilder := b.TransactionEnvelopeBuilder{E: &decoded}\n txEnvelopeBuilder.Init()\n\n return &txEnvelopeBuilder\n}", "func EcbDecryptBase64(key, src string) (string, error) {\n\tkeyBytes, err := getKeyBytes(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tencryptedBytes, err := base64.StdEncoding.DecodeString(src)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdecryptedBytes, err := EcbDecrypt(keyBytes, encryptedBytes)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn base64.StdEncoding.EncodeToString(decryptedBytes), nil\n}", "func convertBase64(input string) (strfmt.Base64, error) {\n\ttemp, err := formats.Parse(\"byte\", input)\n\tif err != nil {\n\t\treturn strfmt.Base64{}, err\n\t}\n\treturn *temp.(*strfmt.Base64), nil\n}", "func IsBase64(s string) bool {\n\treturn s != \"\" && rxBase64.MatchString(s)\n}", "func DecryptFromBase64(cryptKey, text string) (string, error) {\n\tdecrypter, err := newDefaultBase64(cryptKey)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn decrypter.Decrypt(text)\n}", "func DecodeString(in string, objs ...interface{}) (err error) {\n\tbbuf, err := base64.URLEncoding.DecodeString(in)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = DecodeBytes(bbuf, objs...)\n\treturn\n}", "func decodeBase62(encStr string) string {\n\treturn string(noPad62Encoding.DecodeToBigInt(encStr).Bytes())\n}", "func decodeFromBase64(encodedXdr string) *b.TransactionEnvelopeBuilder {\n\t// Unmarshall from base64 encoded XDR format\n\tvar decoded xdr.TransactionEnvelope\n\te := xdr.SafeUnmarshalBase64(encodedXdr, &decoded)\n\tif e != nil {\n\t\tlog.Fatal(e)\n\t}\n\n\t// convert to TransactionEnvelopeBuilder\n\ttxEnvelopeBuilder := b.TransactionEnvelopeBuilder{E: &decoded}\n\ttxEnvelopeBuilder.Init()\n\n\treturn &txEnvelopeBuilder\n}", "func (cs CryptoService) DecryptBase64(base64Cipher []byte) (plain []byte, err error) {\n\tcipher := make([]byte, base64.RawStdEncoding.DecodedLen(len(base64Cipher)))\n\t_, err = base64.RawStdEncoding.Decode(cipher, base64Cipher)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cs.Decrypt(cipher)\n}", "func unmarshalProtoBase64(base64Str string, msg proto.Message) error {\n\tb, _ := base64.StdEncoding.DecodeString(base64Str)\n\treturn proto.Unmarshal(b, msg)\n}", "func (store *SessionCookieStore) decode(src string) ([]byte, error) {\n\tsize := len(src)\n\trem := (4 - size%4) % 4\n\tbuf := make([]byte, size+rem)\n\tcopy(buf, src)\n\tfor i := 0; i < rem; i++ {\n\t\tbuf[size+i] = '='\n\t}\n\tn, err := base64.URLEncoding.Decode(buf, buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf[:n], nil\n}", "func Base64EncodedString(i interface{}, k string) ([]string, []error) {\n\tv, ok := i.(string)\n\tif !ok {\n\t\treturn nil, []error{fmt.Errorf(\"expected type of %q to be string\", k)}\n\t}\n\n\tif strings.TrimSpace(v) == \"\" {\n\t\treturn nil, []error{fmt.Errorf(\"%q must not be empty\", k)}\n\t}\n\n\tif _, err := base64.StdEncoding.DecodeString(v); err != nil {\n\t\treturn nil, []error{fmt.Errorf(\"%q must be a valid base64 encoded string\", k)}\n\t}\n\n\treturn nil, nil\n}", "func loadPrivateKeyBase64(base64key string) (*rsa.PrivateKey, error) {\n\tkeybytes, err := base64.StdEncoding.DecodeString(base64key)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"base64 decode failed, error=%s\\n\", err.Error())\n\t}\n\n\tprivatekey, err := x509.ParsePKCS1PrivateKey(keybytes)\n\tif err != nil {\n\t\treturn nil, errors.New(\"parse private key error!\")\n\t}\n\n\treturn privatekey, nil\n}", "func decrypt(encoded string, key []byte) (string, error) {\n\tcipherText, err := base64.URLEncoding.DecodeString(encoded)\n\tif err != nil {\n\t\treturn encoded, err\n\t}\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn encoded, err\n\t}\n\tif len(cipherText) < aes.BlockSize {\n\t\terr = errors.New(\"ciphertext block size is too short\")\n\t\treturn encoded, err\n\t}\n\tiv := cipherText[:aes.BlockSize]\n\tcipherText = cipherText[aes.BlockSize:]\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\tstream.XORKeyStream(cipherText, cipherText)\n\tdecoded := string(cipherText)\n\n\t// By design decrypt with incorrect key must end up with the value\n\tif strings.Index(decoded, anchor) != 0 {\n\t\treturn encoded, nil\n\t}\n\n\tdecoded = strings.Replace(decoded, anchor, \"\", 1) // remove anchor from string\n\treturn decoded, nil\n}", "func decodeSimpleString(r BytesReader) (interface{}, error) {\n\tv, err := r.ReadBytes('\\r')\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Presume next byte was \\n\n\t_, err = r.ReadByte()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn string(v[:len(v)-1]), nil\n}", "func decodeBase64DERCert(certStr string) (*x509.Certificate, error) {\n\t// decode base64\n\tderBytes, err := base64.StdEncoding.DecodeString(certStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// parse the DER-encoded certificate\n\treturn x509.ParseCertificate(derBytes)\n}", "func (s *hashingServer) Decode(ctx context.Context, request *proto.HashingDecodeRequest) (*proto.HashingDecodeResponse, error) {\n\thashedText := request.GetHashedText()\n\n\tbytePlainText, err := base64.StdEncoding.DecodeString(hashedText)\n\n\tif err == nil {\n\t\treturn &proto.HashingDecodeResponse{PlainText: string(bytePlainText)}, nil\n\t} else {\n\t\treturn &proto.HashingDecodeResponse{PlainText: err.Error()}, nil\n\t}\n}", "func DecryptString(key []byte, cryptoText string) (string, error) {\n ciphertext, _ := base64.StdEncoding.DecodeString(cryptoText)\n ciphertext, err:=Decrypt(key, ciphertext)\n if err!=nil{\n return \"\", err\n }\n return fmt.Sprintf(\"%s\", ciphertext), nil\n}", "func decodeCert(cert string) string {\n\tdValue, _ := base64.URLEncoding.DecodeString(cert)\n\treturn string(dValue)\n}", "func DecodeCursor(val *string) (string, error) {\n\tif val == nil {\n\t\treturn \"\", nil\n\t}\n\n\tdecoded, err := base64.StdEncoding.DecodeString(*val)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(decoded), nil\n}", "func DecodeCursor(val *string) (string, error) {\n\tif val == nil {\n\t\treturn \"\", nil\n\t}\n\n\tdecoded, err := base64.StdEncoding.DecodeString(*val)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(decoded), nil\n}", "func DecodeToString(payload string) string {\n\tsDec, _ := b64.StdEncoding.DecodeString(payload)\n\treturn string(sDec)\n}", "func decodeString(b byteReader) (string, error) {\n\tlength, err := binary.ReadVarint(b)\n\tif length < 0 {\n\t\terr = fmt.Errorf(\"found negative string length during decoding: %d\", length)\n\t}\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tbuf := getBuf(int(length))\n\tdefer putBuf(buf)\n\n\tif _, err := io.ReadFull(b, buf); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(buf), nil\n}", "func Base64Extract(imageB64In string) (secret string, err error) {\n\t// Load tampered image\n\tvar tamperedImg StegImage\n\tif err = tamperedImg.LoadImageFromB64(imageB64In); err != nil {\n\t\tlog.Error(err)\n\t\treturn \"\", err\n\t}\n\n\tsecret, err = tamperedImg.DoStegExtract()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn \"\", err\n\t}\n\n\treturn secret, nil\n}", "func (c *Cursor) FromBase64(b64 string) (err error) {\n\tcursor, err := base64.URLEncoding.DecodeString(b64)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal(cursor, c)\n}", "func DeserializeProtoBase64(s string, pb proto.Message) error {\n\tb, err := base64.RawStdEncoding.DecodeString(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn proto.Unmarshal(b, pb)\n}", "func (ev Vars) Base64(key string, defaults ...[]byte) []byte {\n\tif value, hasValue := ev[key]; hasValue && len(value) > 0 {\n\t\tresult, _ := util.Base64.Decode(value)\n\t\treturn result\n\t}\n\tif len(defaults) > 0 {\n\t\treturn defaults[0]\n\t}\n\treturn nil\n}", "func (s *String) decode(b []byte) error {\n\tobj, err := DecodeObject(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif IsExpired(obj, Now()) {\n\t\treturn ErrKeyNotFound\n\t}\n\n\tif obj.Type != ObjectString {\n\t\treturn ErrTypeMismatch\n\t}\n\n\tif obj.Encoding != ObjectEncodingRaw {\n\t\treturn ErrTypeMismatch\n\t}\n\ts.Meta.Object = *obj\n\tif len(b) >= ObjectEncodingLength {\n\t\ts.Meta.Value = b[ObjectEncodingLength:]\n\t}\n\treturn nil\n}", "func DecodeBase64Reader(out io.Writer, src io.Reader) (err error) {\n\tdecoder := base64.NewDecoder(Encoding, src)\n\t_, err = io.Copy(out, decoder)\n\treturn\n}", "func Decode(encoding Encoding, str string) ([]byte, error) {\n\tswitch {\n\tcase !encoding.valid():\n\t\treturn nil, errInvalidEncoding\n\tcase len(str) == 0:\n\t\treturn nil, nil\n\tcase encoding == CB58 && len(str) > maxCB58DecodeSize:\n\t\treturn nil, fmt.Errorf(\"string length (%d) > maximum for cb58 (%d)\", len(str), maxCB58DecodeSize)\n\t}\n\n\tvar (\n\t\tdecodedBytes []byte\n\t\terr error\n\t)\n\tswitch encoding {\n\tcase Hex:\n\t\tif !strings.HasPrefix(str, hexPrefix) {\n\t\t\treturn nil, errMissingHexPrefix\n\t\t}\n\t\tdecodedBytes, err = hex.DecodeString(str[2:])\n\tcase CB58:\n\t\tdecodedBytes, err = base58.Decode(str)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(decodedBytes) < checksumLen {\n\t\treturn nil, errMissingChecksum\n\t}\n\t// Verify the checksum\n\trawBytes := decodedBytes[:len(decodedBytes)-checksumLen]\n\tif len(rawBytes) > maxCB58EncodeSize {\n\t\treturn nil, fmt.Errorf(\"byte slice length (%d) > maximum for cb58 (%d)\", len(decodedBytes), maxCB58EncodeSize)\n\t}\n\n\tchecksum := decodedBytes[len(decodedBytes)-checksumLen:]\n\tif !bytes.Equal(checksum, hashing.Checksum(rawBytes, checksumLen)) {\n\t\treturn nil, errBadChecksum\n\t}\n\treturn rawBytes, nil\n}", "func _decode_map(mapstr string) []byte {\n\tbitset, err := base64.StdEncoding.DecodeString(mapstr)\n\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn bitset\n}", "func NewByteSliceFromBase64Str(s string) (ByteSlice, error) {\n\ttmp := make([]byte, base64.StdEncoding.DecodedLen(len(s)))\n\tn, err := base64.StdEncoding.Decode(tmp, []byte(s))\n\tif err != nil {\n\t\treturn ByteSlice{}, err\n\t}\n\treturn ByteSlice{\n\t\tByteSlice: tmp[:n],\n\t\tValid: true,\n\t}, nil\n\n}", "func Decode(in string, obj interface{}) {\n\tb, err := base64.StdEncoding.DecodeString(in)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif compress {\n\t\tb = unzip(b)\n\t}\n\n\terr = json.Unmarshal(b, obj)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func decodeAesBase64ByDynamics(src, key, iv string) ([]byte, error) {\n //base64\n s1, err := base64.URLEncoding.DecodeString(src)\n if err != nil {\n logrus.Error(\"decode base64 error : \", err)\n return nil, err\n }\n\n //aes128\n out, err := decodeAesCbcByDynamics(s1, key, iv)\n if err != nil {\n logrus.Error(\"decode aes cbc error : \", err)\n return nil, err\n }\n\n return out, nil\n}", "func (s *SAMLResponse) GetBase64Encoded() *string {\n\treturn &s.original\n}", "func Decode(in string) (string, error) {\n\tout, err := Client().Decode(in)\n\tTrace(\"Decode\", err, logrus.Fields{\"in\": in, \"out\": out})\n\treturn string(out), err\n}", "func decodeCredentials(encoded string) (string, string, error) {\n\t// Decode the original hash\n\tdata, err := base64.StdEncoding.DecodeString(encoded)\n\tif err != nil {\n\t\tlog.Errorf(\"[decodeCredentials] %v\", err)\n\t\treturn \"\", \"\", fmt.Errorf(\"[decodeCredentials] %v\", err)\n\t}\n\tlog.Debugf(\"%s => %s\\n\", encoded, string(data))\n\n\t// Separate user and password informations\n\tuser := strings.Split(string(data), \":\")[0]\n\tpasswd := strings.Split(string(data), \":\")[1]\n\treturn user, passwd, nil\n}", "func ConvertBase64StrToBytes(key string) ([]byte, error) {\n\treturn base64.StdEncoding.DecodeString(key)\n}", "func AuthenticateToBase64(auth *Authenticate) (string, error) {\n\tjs, err := json.Marshal(auth)\n\tif err != nil {\n\t\treturn \"\", nil\n\t}\n\n\treturn b64.StdEncoding.EncodeToString(js), nil\n}", "func DecodeBlessingsBase64(encoded string) (security.Blessings, error) {\n\tvar b security.Blessings\n\tif err := base64urlVomDecode(encoded, &b); err != nil {\n\t\treturn security.Blessings{}, fmt.Errorf(\"failed to decode %v: %v\", encoded, err)\n\t}\n\treturn b, nil\n}", "func URLDecode(s string) string {\n\tencoder := base64.URLEncoding\n\tdecoded := make([]byte, encoder.EncodedLen(len([]byte(s))))\n\t_, err := encoder.Decode(decoded, []byte(s))\n\tif err != nil {\n\t\treturn fmt.Sprintln(err)\n\t}\n\treturn string(decoded)\n}", "func (c *Client) CheckBase64(data string) (float64, error) {\n\tu, err := url.Parse(c.addr + \"/nudebox/check\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif !u.IsAbs() {\n\t\treturn 0, errors.New(\"box address must be absolute\")\n\t}\n\tform := url.Values{}\n\tform.Set(\"base64\", data)\n\treq, err := http.NewRequest(\"POST\", u.String(), strings.NewReader(form.Encode()))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\treq.Header.Set(\"Accept\", \"application/json; charset=utf-8\")\n\tresp, err := c.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode < 200 || resp.StatusCode >= 300 {\n\t\treturn 0, errors.New(resp.Status)\n\t}\n\treturn c.parseCheckResponse(resp.Body)\n}" ]
[ "0.8075996", "0.8069602", "0.8045261", "0.7992034", "0.79698575", "0.7959148", "0.7959148", "0.7789961", "0.77893597", "0.778479", "0.77656174", "0.7649702", "0.7619644", "0.76058924", "0.7525648", "0.7510042", "0.7429252", "0.7379714", "0.7274151", "0.7263695", "0.7197686", "0.710987", "0.70828223", "0.7073518", "0.70361394", "0.6995991", "0.69559574", "0.69543725", "0.6901911", "0.6894668", "0.68918574", "0.6878538", "0.6859073", "0.6858242", "0.67384094", "0.67161554", "0.66854066", "0.6667727", "0.6667727", "0.6666499", "0.6663846", "0.66131836", "0.6610378", "0.6577805", "0.6562356", "0.65487355", "0.65475285", "0.6537195", "0.65336514", "0.65013325", "0.6494696", "0.64866894", "0.6432918", "0.6418828", "0.6418828", "0.64164466", "0.641389", "0.6340153", "0.6340153", "0.6328862", "0.6300245", "0.6287039", "0.6285013", "0.6252075", "0.6206932", "0.618129", "0.6157129", "0.6152863", "0.61474776", "0.6125581", "0.60609764", "0.6045888", "0.60293996", "0.6024797", "0.59742004", "0.59718627", "0.5968442", "0.5932378", "0.5932378", "0.59309804", "0.5886982", "0.58549577", "0.58549017", "0.5839668", "0.5814719", "0.58094645", "0.5807647", "0.57941175", "0.5787827", "0.5786124", "0.5785397", "0.57808125", "0.5754054", "0.5752215", "0.57503414", "0.5747155", "0.5721106", "0.57159626", "0.57142115", "0.57129794" ]
0.7998288
3
hash generates a Hmac256 hash of a string using a secret
func generateHash(src, secret string) string { key := []byte(secret) h := hmac.New(sha256.New, key) h.Write([]byte(src)) return base64.StdEncoding.EncodeToString(h.Sum(nil)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Hash(src string, secret string) string {\n key := []byte(secret)\n h := hmac.New(sha256.New, key)\n h.Write([]byte(src))\n return base64.StdEncoding.EncodeToString(h.Sum(nil))\n}", "func secretHash(sec *v1.Secret) (string, error) {\n\tencoded, err := encodeSecret(sec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\th, err := hasher.Encode(hasher.Hash(encoded))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn h, nil\n}", "func Hashit(tox string) string {\n h:= sha256.New()\n h.Write([]byte(tox))\n bs := h.Sum([]byte{})\n str := base64.StdEncoding.EncodeToString(bs)\n return str\n}", "func hash(s string) string {\n\th := fnv.New32a()\n\t_, err := h.Write([]byte(s))\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprint(h.Sum32())\n}", "func strhash(p *string, h uintptr) uintptr", "func hash(passphrase, token string, timestamp int64) string {\n\tbase := fmt.Sprintf(\"%s-%s-%d\", passphrase, token, timestamp)\n\treturn fmt.Sprintf(\"%x\", sha512.Sum512([]byte(base)))\n}", "func hash(s string) uint32 {\n h := fnv.New32a()\n h.Write([]byte(s))\n return h.Sum32()\n}", "func (h *hasht) hash(input string) uint64 {\n\tvar hash uint64 = FNVOffset\n\tfor _, char := range input {\n\t\thash ^= uint64(char)\n\t\thash *= FNVPrime\n\t}\n\treturn hash\n}", "func hash(s string) string {\n\thash := fnv.New32a()\n\thash.Write([]byte(s))\n\tintHash := hash.Sum32()\n\tresult := fmt.Sprintf(\"%08x\", intHash)\n\treturn result\n}", "func Hash(input string) (string, error) {\n\tbytes, err := bcrypt.GenerateFromPassword([]byte(input), 14)\n\treturn string(bytes), err\n}", "func (authSvc *AuthService) computeHash(s string) hash.Hash {\n\t\n\tvar hash hash.Hash = sha256.New()\n\tvar bytes []byte = []byte(s)\n\thash.Write(authSvc.secretSalt)\n\thash.Write(bytes)\n\treturn hash\n}", "func calculateHash(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}", "func calculateHash(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}", "func calculateHash(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}", "func hexHash(input string) string {\n return idToString(hash([]byte(input)))\n}", "func hash(ba string) string {\n\th := sha256.New()\n\th.Write([]byte(ba))\n\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}", "func hashString(input string) string {\n\tdefer loggerHighwayHasher.Reset()\n\tloggerHighwayHasher.Write([]byte(input))\n\tchecksum := loggerHighwayHasher.Sum(nil)\n\treturn hex.EncodeToString(checksum)\n}", "func computeNonceSecretHash(nonce string, secret string) string {\n\th := md5.New()\n\th.Write([]byte(nonce + secret))\n\tstr := hex.EncodeToString(h.Sum(nil))\n\treturn str\n}", "func hash(s string) string {\n\treturn fmt.Sprintf(\"%x\", md5.Sum([]byte(s)))\n}", "func generatePasswordHash(password string) string {\n sum := sha256.Sum256([]byte(password))\n return hex.EncodeToString(sum[:])\n}", "func Sha256Hash(password string) string {\n h := sha256.Sum256([]byte(password))\n return \"{SHA256}\" + base64.StdEncoding.EncodeToString(h[:])\n}", "func Hash(t *Token) (hash []byte) {\n var sum []byte\n\n // Compute the SHA1 sum of the Token\n {\n shasum := sha1.Sum([]byte(salt+string(*t)))\n copy(sum[:], shasum[:20])\n }\n\n // Encode the sum to hexadecimal\n hex.Encode(sum, sum)\n\n return\n}", "func strhash(a unsafe.Pointer, h uintptr) uintptr", "func HashHmac(message, secret string, hashAlgo func() hash.Hash) string {\n\th := hmac.New(hashAlgo, []byte(secret))\n\th.Write([]byte(message))\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}", "func hashSHA256(input string) string {\n\th := sha1.New()\n\th.Write([]byte(input))\n\treturn hex.EncodeToString(h.Sum(nil))\n}", "func (s sha256hashing) HashString(hashme string, digest []byte) error {\n\thashAlgo := sha256.New()\n\thashAlgo.Write([]byte(hashme))\n\n\tcopySHA256(digest, hashAlgo.Sum(nil))\n\n\treturn nil\n}", "func hash(value string) uint32 {\n\th := fnv.New32a()\n\th.Write([]byte(value))\n\n\treturn h.Sum32()\n}", "func stringHash(s string, seed uintptr) uintptr", "func Hashbin(tox string) []byte {\n h:= sha256.New()\n h.Write([]byte(tox))\n bs := h.Sum([]byte{})\n return bs \n}", "func ComputeNonceSecretHash(nonce string, secret string) string {\n\th := md5.New()\n\th.Write([]byte(nonce + secret))\n\tstr := hex.EncodeToString(h.Sum(nil))\n\treturn str\n}", "func hashString(str string) string {\n\thash := sha256.Sum256([]byte(str))\n\treturn base64.StdEncoding.EncodeToString(hash[:])\n}", "func hashString(str string) (string, error) {\n hash, err := ssdeep.HashString(str)\n if err != nil {\n return \"\", err\n }\n return hash, nil\n}", "func calcHash(data string) string {\n\th := sha256.New()\n\th.Write([]byte(data))\n\thash := fmt.Sprintf(\"%x\", h.Sum(nil))\n\treturn hash\n}", "func Hash(str string) string {\n\thasher := fnv.New64a()\n\thasher.Write([]byte(str))\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}", "func createHash(tokenId []byte) []byte {\n\tu := TOKEN_HASH_BYTES_POOL.Get().([]byte)\n\tdefer TOKEN_HASH_BYTES_POOL.Put(u)\n\n\t//let's generate real hash...\n\tcopy(u, TOKEN_HASH_SECRET)\n\tcopy(u[len(TOKEN_HASH_SECRET):], tokenId)\n\n\t//\tlogx.D(\"u:\", base64.URLEncoding.EncodeToString(u), \", len(U):\", len(u))\n\n\thash := sha256.Sum256(u)\n\n\treturn hash[0:32]\n}", "func hash(s string) int {\n\th := fnv.New32a()\n\tif _, err := h.Write([]byte(s)); err != nil {\n\t\tpanic(err) // should never happen\n\t}\n\n\treturn int(h.Sum32() & 0x7FFFFFFF) // mask MSB of uint32 as this will be sign bit\n}", "func ComputeHash(body []byte) string {\n\th := md5.New()\n\th.Write(body)\n\th.Write(kSecret)\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}", "func Hash(s string) string {\n\tfmt.Println(\"Hashing string:\", s)\n\thash := sha256.Sum256([]byte(s))\n\tniceHash := fmt.Sprintf(\"%x\", hash)\n\tfmt.Println(\"Created hash:\", hash)\n\treturn niceHash\n}", "func strhash0(p unsafe.Pointer, h uintptr) uintptr", "func HashString(salter *salt.Salt, data string) string {\n\treturn salter.GetIdentifiedHMAC(data)\n}", "func hashSHA256(str string) string {\n\ts := sha256.New()\n\ts.Write([]byte(str))\n\treturn base64.StdEncoding.EncodeToString(s.Sum(nil))\n}", "func hash(password string) string {\n\thash := sha512.New()\n\thash.Write([]byte(password))\n\tb := hash.Sum(nil)\n\treturn base64.StdEncoding.EncodeToString(b)\n}", "func compareHmac(value string, hash string, secret string) bool {\n return hash == Hash(value, secret)\n}", "func hashPassword(password string) string {\n //TODO: hash password with salt?\n sum := sha256.Sum256([]byte(password))\n return hex.EncodeToString(sum[:])\n}", "func HashString(stringValue string) string {\n\th := sha256.New()\n\t_, _ = h.Write([]byte(stringValue))\n\treturn base64.StdEncoding.EncodeToString(h.Sum(nil))\n}", "func Hash(strings ...string) uint32 {\n\tdigester := fnv.New32()\n\tfor _, s := range strings {\n\t\t_, _ = io.WriteString(digester, s)\n\t}\n\treturn digester.Sum32()\n}", "func Hash(key string) uint32 {\n\treturn uint32(aeshashstr(noescape(unsafe.Pointer(&key)), 0))\n}", "func hash(f []byte) (string, error) {\n\tsha := sha256.New()\n\t_, err := sha.Write(f)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(\"%x\", sha.Sum(nil)), nil\n}", "func Hash(input []byte) string {\n\treturn fmt.Sprintf(\"%x\", sha256.Sum256(input))\n}", "func Hash(length int, key string) int64 {\n\tif key == \"\" {\n\t\treturn 0\n\t}\n\thc := hashCode(key)\n\treturn (hc ^ (hc >> 16)) % int64(length)\n}", "func CalcHash(data string) string {\r\n\thashed := sha256.Sum256([]byte(data))\r\n\treturn hex.EncodeToString(hashed[:])\r\n}", "func hashChallenge(challenge string) string {\n\tsha256Local := sha256.New()\n\t_, _ = sha256Local.Write([]byte(challenge))\n\treturn strings.ToUpper(hex.EncodeToString(sha256Local.Sum(nil)))\n}", "func Sha256Hmac(secret string, data string) string {\n\t// Create a new HMAC by defining the hash type and the key (as byte array)\n\th := hmac.New(sha256.New, []byte(secret))\n\n\t// Write Data to it\n\th.Write([]byte(data))\n\n\t// Get result and encode as hexadecimal string\n\tsha := hex.EncodeToString(h.Sum(nil))\n\n\treturn sha\n}", "func new256Asm() hash.Hash { return nil }", "func h(s string) []byte {\n\thash := md5.Sum([]byte(s))\n\treturn hash[:]\n}", "func hashPass(pass string) string {\n\tpassword := []byte(pass + Salt)\n\tif len(password) > 72 {\n\t\tpassword = password[:72]\n\t}\n\thash, err := bcrypt.GenerateFromPassword(password, bcryptDiff)\n\tif err != nil {\n\t\tTrail(ERROR, \"uadmin.auth.hashPass.GenerateFromPassword: %s\", err)\n\t\treturn \"\"\n\t}\n\treturn string(hash)\n}", "func CalculateHash(args []string) string {\n\tvar str = \"\"\n\tfor _,v := range args {\n\t\tstr += v\n\t}\n\thasher := sha256.New()\n\thasher.Write([]byte(str))\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}", "func genHash(text string) string {\n\th := sha1.New()\n\th.Write([]byte(text))\n\thashed := h.Sum(nil)\n\treturn fmt.Sprintf(\"%v\", hashed)\n}", "func hashString(s string) int {\n\tvar h uint32\n\tfor i := 0; i < len(s); i++ {\n\t\th ^= uint32(s[i])\n\t\th *= 16777619\n\t}\n\treturn int(h)\n}", "func Hash(p string) (string, string) {\n\ts := GenString(32)\n\treturn ComputeHash(p, s), s\n}", "func (t *Table) hash(s string) int {\n\t// Good enough.\n\th := fnv.New32()\n\th.Write([]byte(s))\n\treturn int(h.Sum32()) % t.m\n}", "func hashmaker(pass string) string {\n\thash, _ := bcrypt.GenerateFromPassword([]byte(pass), bcrypt.DefaultCost)\n\treturn string(hash)\n}", "func hash(id, app string) string {\n\treturn id + \"|\" + app\n}", "func TestHash(t *testing.T) {\n\tdata := \"bce-auth-v1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/2015-04-27T08:23:49Z/1800\"\n\tkey := \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n\tresult := \"1d5ce5f464064cbee060330d973218821825ac6952368a482a592e6615aef479\"\n\ttestResult := hash(data, key)\n\tif result == testResult {\n\t\tt.Log(\"hash test success\")\n\t} else {\n\t\tt.Error(\"hash test fail\")\n\t}\n}", "func Hash(password string) (string, error) {\n\tbytes, err := bcrypt.GenerateFromPassword([]byte(password), cost)\n\treturn string(bytes), err\n}", "func generateSHA256HashInHexForm(preimage string) string {\n\thasher := sha256.New()\n\thasher.Write([]byte(preimage))\n\tshaHash := hasher.Sum(nil)\n\tshaHashHex := hex.EncodeToString(shaHash)\n\treturn shaHashHex\n}", "func GetHash(b string) (hash string) {\n\t// Hash input b and capture/format its output as a string literal\n\thash = fmt.Sprintf(\"%X\", sha256.Sum256([]byte(b)[:]))\n\treturn\n}", "func hashIt(s string, bit int) int {\n\th := sha1.New()\n\th.Write([]byte(s))\n\tbs := h.Sum(nil)\n\thashValue := math.Mod(float64(bs[len(bs)-1]), math.Exp2(float64(bit)))\n\treturn int(hashValue)\n}", "func HashASM(k0, k1 uint64, p []byte) uint64", "func Hash(plain string) ([]byte, error) {\n\treturn bcrypt.GenerateFromPassword([]byte(plain), bcrypt.DefaultCost)\n}", "func hasher(s string) []byte {\n\tval := sha256.Sum256([]byte(s))\n\tvar hex []string\n\n\t// Iterate through the bytes.\n\tfor i := 0; i < len(val); i++ {\n\t\t// We want each number to be represented by 2 chars.\n\t\tplaceHolder := []string{\"0\"}\n\t\tvalue := strconv.FormatInt(int64(val[i]), 16)\n\n\t\tif len(value) != 2 {\n\t\t\tplaceHolder = append(placeHolder, value)\n\t\t\thex = append(hex, strings.Join(placeHolder, \"\"))\n\t\t} else {\n\t\t\thex = append(hex, value)\n\t\t}\n\t}\n\treturn []byte(strings.Join(hex, \"\"))\n\n}", "func getHash(s string) uint32 {\n\ttbl := crc32.MakeTable(crc32.IEEE)\n\treturn crc32.Checksum([]byte(s), tbl)\n}", "func (p PlainTextHasher) Hash(str string) string { return str }", "func GenerateSHA256Hash() string {\n\tkey := getSecretPhrase()\n\thasher := sha256.New()\n\thasher.Write([]byte(key))\n\n\tactual, err := strkey.Encode(strkey.VersionByteHashX, hasher.Sum(nil))\n\tif err != nil {\n\t\tpanic(err);\n\t\t//LOGGER.Fatal(err)\n\t\treturn \"\"\n\t}\n\treturn actual\n}", "func (c *HashRing) generateHash(key string) uint32 {\n\treturn crc32.ChecksumIEEE([]byte(key))\n}", "func hashString(data string) string {\n\treturn fmt.Sprintf(\"%x\", hashBytes([]byte(data)))\n}", "func byteshash(p *[]byte, h uintptr) uintptr", "func newSHA256() hash.Hash { return sha256.New() }", "func (pssOpts *PSSOptions) HashFunc() crypto.Hash", "func Hash(msg string, nonce uint64) uint64 {\r\n\thasher := sha256.New()\r\n\thasher.Write([]byte(fmt.Sprintf(\"%s %d\", msg, nonce)))\r\n\treturn binary.BigEndian.Uint64(hasher.Sum(nil))\r\n}", "func hash(key string) int{\n\tvar num = 0\n\t// get the lenght of the key\n\tvar length = len(key)\n\n\t// add the ascii character value to creat a sum \n\tfor i := 0; i < length; i++{\n\n\t\tnum += int(key[i])\n\t}\n\t\n\t// square in the middle hash method\n\tvar avg = num * int((math.Pow(5.0, 0.5) - 1)) / 2\n\tvar numeric = avg - int(math.Floor(float64(avg)))\n\n\n\t// hash value to place into the table slice between -1 and CAPACITY - 1\n\treturn int(math.Floor(float64(numeric * CAPACITY)))\n}", "func HashString(dataString string) (string, error) {\n\tdataBytes, err := hex.DecodeString(dataString)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn hex.EncodeToString(crypto.Keccak256(dataBytes)), nil\n}", "func h(data string) string {\n\tdigest := md5.New()\n\tdigest.Write([]byte(data))\n\treturn fmt.Sprintf(\"%x\", digest.Sum(nil))\n}", "func Sha256d(input []byte) Hash {\n sha := sha256.New()\n sha.Write(input)\n intermediate := sha.Sum(nil)\n sha.Reset()\n sha.Write(intermediate)\n hash, err := HashFromBytes(sha.Sum(nil), LittleEndian)\n if err != nil {\n panic(\"impossible flow, this is a bug: \" + err.Error())\n }\n return hash\n}", "func calculateHash (block Block) string{\n h := sha256.New()\n unique := block.Data + block.PrevHash + block.TimeStamp + strconv.Itoa(block.Nonce)\n h.Write([]byte(unique))\n \n return hex.EncodeToString(h.Sum(nil))\n}", "func Hash(text string) (string, error) {\n\treturn hashText(fnv.New64a(), text)\n}", "func computeHash(w http.ResponseWriter, req *http.Request) {\n\tvalues := req.URL.Query()\n\tdata := values.Get(\"data\")\n\tif data == \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"400 - data param not present\"))\n\t\treturn\n\t}\n\tsalt := values.Get(\"salt\")\n\tif salt == \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"400 - salt param not present\"))\n\t\treturn\n\t}\n\th := sha256.Sum256([]byte(data+salt))\n\tencodedStr := hex.EncodeToString(h[:])\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(encodedStr))\n}", "func HMACHeader(secret string, body []byte) (string, error) {\n\th := hmac.New(sha1.New, []byte(secret))\n\t_, err := h.Write(body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"sha1=%s\", hex.EncodeToString(h.Sum(nil))), nil\n}", "func HashHmac(data string, tag string, algo string) (string, error) {\n\ta, err := GetSupportedAlgorithm(algo)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\th := hmac.New(a.New, []byte(tag))\n\th.Write([]byte(data))\n\tval := h.Sum(nil)\n\n\treturn base64.StdEncoding.EncodeToString(val), nil\n}", "func stringHash(s string) uint32 {\n\tbytes := []byte(s)\n\tn := len(bytes)\n\thash := uint32(0)\n\tfor index, b := range bytes {\n\t\thash += uint32(b) * uint32(math.Pow(31, float64(n-index)))\n\t}\n\treturn hash\n}", "func (h Hash) String() string { return hex.EncodeToString(h[:]) }", "func hash(path string) string {\n\th, err := files.Sha256(path)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\treturn h[:10]\n}", "func hash(data []byte) [32]byte {\n\tvar hash [32]byte\n\n\th := sha256.New()\n\t// The hash interface never returns an error, for that reason\n\t// we are not handling the error below. For reference, it is\n\t// stated here https://golang.org/pkg/hash/#Hash\n\t// #nosec G104\n\th.Write(data)\n\th.Sum(hash[:0])\n\n\treturn hash\n}", "func (gen *IDGenerator) Hash(string) string {\n\tid := <-gen.ch\n\treturn strconv.FormatUint(id, 10)\n}", "func (h Bcrypt) Hash(raw string) (string, error) {\n\thash, err := bcrypt.GenerateFromPassword([]byte(raw), bcrypt.DefaultCost)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(hash), nil\n}", "func genHash(password string) (string, error) {\n\thashedBytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(hashedBytes), nil\n}", "func hash(path string) string {\n\th, err := files.Sha256(path)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn h[:10]\n}", "func hashSignature(alg Algorithm, signatureValue string, secret *pbauth.Secret) (string, error) {\n\tif strings.TrimSpace(signatureValue) == \"\" {\n\t\treturn \"\", consts.ErrInvalidSignatureValue\n\t}\n\tif err := ValidateSecret(secret); err != nil {\n\t\treturn \"\", err\n\t}\n\tkey := []byte(secret.Key)\n\tvar h hash.Hash\n\tswitch alg {\n\tcase Hs256:\n\t\th = hmac.New(sha256.New, key)\n\tcase Hs512:\n\t\th = hmac.New(sha512.New, key)\n\tdefault:\n\t\treturn \"\", consts.ErrNoHashAlgorithm\n\t}\n\th.Write([]byte(signatureValue))\n\treturn base64.URLEncoding.EncodeToString(h.Sum(nil)), nil\n}", "func Hash(str string) ([]byte, error) {\n\t// generate hash from password\n\thash, err := HashBytes([]byte(str))\n\tif err != nil {\n\t\treturn nil, xo.W(err)\n\t}\n\n\treturn hash, nil\n}", "func Hash(b []byte, seed uint64) uint64" ]
[ "0.76456904", "0.754611", "0.7141423", "0.7066216", "0.7059082", "0.7037359", "0.7004514", "0.6981299", "0.6954003", "0.69420254", "0.6924159", "0.6924104", "0.6924104", "0.6924104", "0.6895148", "0.68863875", "0.68669903", "0.6845643", "0.6827959", "0.68180865", "0.6774375", "0.67321426", "0.67155904", "0.67118436", "0.6708292", "0.6695102", "0.66823936", "0.665241", "0.663779", "0.662507", "0.6620677", "0.660903", "0.6567335", "0.6562528", "0.6560312", "0.65474343", "0.65427846", "0.65423286", "0.6539483", "0.6531299", "0.6516182", "0.65146405", "0.6503243", "0.64964473", "0.649509", "0.64939666", "0.64813405", "0.64766127", "0.64571464", "0.64546835", "0.6451293", "0.64459556", "0.64448047", "0.64373386", "0.6422405", "0.64175946", "0.6395324", "0.63879174", "0.6376453", "0.6371435", "0.63707185", "0.634824", "0.6342283", "0.63411564", "0.6335907", "0.63310933", "0.6322313", "0.63221556", "0.6317002", "0.63086814", "0.6306758", "0.6305715", "0.62888664", "0.628568", "0.6284064", "0.6281715", "0.6276658", "0.625913", "0.62506884", "0.6250099", "0.6247857", "0.6243607", "0.6242616", "0.62412924", "0.6229528", "0.6227197", "0.62268746", "0.6225461", "0.62230915", "0.62222695", "0.6216967", "0.62082726", "0.6205958", "0.62024814", "0.620008", "0.6196871", "0.6187446", "0.6186865", "0.61819553", "0.6179154" ]
0.72181696
2
getAllIPList get mongo all IPList
func getAllIPList(provider string, model store.ClusterManagerModel) map[string]struct{} { condProd := operator.NewLeafCondition(operator.Eq, operator.M{"provider": provider}) clusterStatus := []string{common.StatusInitialization, common.StatusRunning, common.StatusDeleting} condStatus := operator.NewLeafCondition(operator.In, operator.M{"status": clusterStatus}) cond := operator.NewBranchCondition(operator.And, condProd, condStatus) clusterList, err := model.ListCluster(context.Background(), cond, &storeopt.ListOption{All: true}) if err != nil { blog.Errorf("getAllIPList ListCluster failed: %v", err) return nil } ipList := make(map[string]struct{}) for i := range clusterList { for ip := range clusterList[i].Master { ipList[ip] = struct{}{} } } condIP := make(operator.M) condIP["status"] = common.StatusRunning condP := operator.NewLeafCondition(operator.Eq, condIP) nodes, err := model.ListNode(context.Background(), condP, &storeopt.ListOption{All: true}) if err != nil { blog.Errorf("getAllIPList ListNode failed: %v", err) return nil } for i := range nodes { ipList[nodes[i].InnerIP] = struct{}{} } return ipList }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *IPsService) List(ctx context.Context) ([]IP, *Response, error) {\n\tpath := fmt.Sprintf(\"%v/detail/\", ipsBasePath)\n\n\treq, err := s.client.NewRequest(http.MethodGet, path, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\troot := new(ipsRoot)\n\tresp, err := s.client.Do(ctx, req, root)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\tif m := root.Meta; m != nil {\n\t\tresp.Meta = m\n\t}\n\n\treturn root.IPs, resp, nil\n}", "func (i *ProjectIPServiceOp) List(projectID string, opts *ListOptions) ([]IPAddressReservation, *Response, error) {\n\tif validateErr := ValidateUUID(projectID); validateErr != nil {\n\t\treturn nil, nil, validateErr\n\t}\n\tendpointPath := path.Join(projectBasePath, projectID, ipBasePath)\n\tapiPathQuery := opts.WithQuery(endpointPath)\n\treservations := new(struct {\n\t\tReservations []IPAddressReservation `json:\"ip_addresses\"`\n\t})\n\n\tresp, err := i.client.DoRequest(\"GET\", apiPathQuery, nil, reservations)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\treturn reservations.Reservations, resp, nil\n}", "func (db *DB) GetAll(ip string) (*Record, error) { return db.query(ip, ModeDB24) }", "func ListInstanceIP(ctx context.Context, tx *sql.Tx, request *models.ListInstanceIPRequest) (response *models.ListInstanceIPResponse, err error) {\n\tvar rows *sql.Rows\n\tqb := &common.ListQueryBuilder{}\n\tqb.Auth = common.GetAuthCTX(ctx)\n\tspec := request.Spec\n\tqb.Spec = spec\n\tqb.Table = \"instance_ip\"\n\tqb.Fields = InstanceIPFields\n\tqb.RefFields = InstanceIPRefFields\n\tqb.BackRefFields = InstanceIPBackRefFields\n\tresult := []*models.InstanceIP{}\n\n\tif spec.ParentFQName != nil {\n\t\tparentMetaData, err := common.GetMetaData(tx, \"\", spec.ParentFQName)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"can't find parents\")\n\t\t}\n\t\tspec.Filters = common.AppendFilter(spec.Filters, \"parent_uuid\", parentMetaData.UUID)\n\t}\n\n\tquery := qb.BuildQuery()\n\tcolumns := qb.Columns\n\tvalues := qb.Values\n\tlog.WithFields(log.Fields{\n\t\t\"listSpec\": spec,\n\t\t\"query\": query,\n\t}).Debug(\"select query\")\n\trows, err = tx.QueryContext(ctx, query, values...)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"select query failed\")\n\t}\n\tdefer rows.Close()\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, errors.Wrap(err, \"row error\")\n\t}\n\n\tfor rows.Next() {\n\t\tvaluesMap := map[string]interface{}{}\n\t\tvalues := make([]interface{}, len(columns))\n\t\tvaluesPointers := make([]interface{}, len(columns))\n\t\tfor _, index := range columns {\n\t\t\tvaluesPointers[index] = &values[index]\n\t\t}\n\t\tif err := rows.Scan(valuesPointers...); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"scan failed\")\n\t\t}\n\t\tfor column, index := range columns {\n\t\t\tval := valuesPointers[index].(*interface{})\n\t\t\tvaluesMap[column] = *val\n\t\t}\n\t\tm, err := scanInstanceIP(valuesMap)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"scan row failed\")\n\t\t}\n\t\tresult = append(result, m)\n\t}\n\tresponse = &models.ListInstanceIPResponse{\n\t\tInstanceIPs: result,\n\t}\n\treturn response, nil\n}", "func (c *MockPublicIPAddressesClient) List(ctx context.Context, resourceGroupName string) ([]network.PublicIPAddress, error) {\n\tvar l []network.PublicIPAddress\n\tfor _, lb := range c.PubIPs {\n\t\tl = append(l, lb)\n\t}\n\treturn l, nil\n}", "func (j *JoinHelper) getAllIPs () ([]string, error){\n\n\tvpnName := j.getVPNNicName()\n\tips := make ([]string, 0)\n\n\tinterfaces, err := net.Interfaces()\n\tif err != nil {\n\t\treturn ips, err\n\t}\n\tfor _, iface := range interfaces {\n\t\tif iface.Name != vpnName {\n\t\t\taddresses, err := iface.Addrs()\n\t\t\tif err != nil {\n\t\t\t\treturn ips, err\n\t\t\t}\n\t\t\tfor _, addr := range addresses {\n\t\t\t\tnetIP, ok := addr.(*net.IPNet)\n\t\t\t\tif ok && !netIP.IP.IsLoopback() && netIP.IP.To4() != nil {\n\t\t\t\t\tip := netIP.IP.String()\n\t\t\t\t\tips = append(ips, ip)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ips, nil\n}", "func (h Hostingv4) ListIPs(ipfilter hosting.IPFilter) ([]hosting.IPAddress, error) {\n\tipmap, err := ipFilterToMap(ipfilter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response = []iPAddressv4{}\n\tif err = h.Send(\"hosting.ip.list\", []interface{}{ipmap}, &response); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar ips []hosting.IPAddress\n\tfor _, iip := range response {\n\t\tips = append(ips, toIPAddress(iip))\n\t}\n\n\treturn ips, nil\n}", "func ListIPAddress(ipAddressID string) error {\n\tclient, err := NewExtPacketClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tip, _, err := client.IPs.Get(ipAddressID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\te := MarshallAndPrint(ip)\n\treturn e\n}", "func (c *Client) IPs() (IPAddrs, error) {\n\tresp, err := c.Get(\"/public-ip-list\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar m map[string][]string\n\tif err := decodeBodyMap(resp.Body, &m); err != nil {\n\t\treturn nil, err\n\t}\n\treturn IPAddrs(m[\"addresses\"]), nil\n}", "func (this *iplist) IPs() []net.IP {\n\tthis.mu.Lock()\n\tdefer this.mu.Unlock()\n\n\tif this.ipl == nil {\n\t\tthis.ipl = make([]net.IP, len(this.ipm))\n\t}\n\tthis.ipl = this.ipl[0:0]\n\n\tfor ip := range this.ipm {\n\t\tvar tmp [4]byte\n\t\tcopy(tmp[:], ip[:])\n\t\tthis.ipl = append(this.ipl, net.IP(tmp[:]))\n\t}\n\n\treturn this.ipl\n}", "func (a *adapter) getList() []*net.IPNet {\n\treturn a.atomicList.Load().([]*net.IPNet)\n}", "func GetendpointsIP(url string) (list []string, e error) {\n\tcode, res, err := GetjsonData(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif code != 200 {\n\t\treturn nil, errors.New(\"return http code:\" + strconv.Itoa(code))\n\t}\n\tdata := &Endpoints{}\n\tjson.Unmarshal(res, &data)\n\t//len := len(data.Subsets)\n\n\tfor _, v := range data.Subsets {\n\t\tvar iplist []string\n\t\tvar portlist []string\n\n\t\tfor _, v1 := range v.Addresses {\n\t\t\tip := v1.Ip\n\t\t\tiplist = append(iplist, ip)\n\t\t}\n\n\t\tfor _, v2 := range v.Ports {\n\t\t\tport := strconv.Itoa(int(v2.Port))\n\t\t\tportlist = append(portlist, port)\n\t\t}\n\n\t\tfor _, v3 := range iplist {\n\t\t\tfor _, v4 := range portlist {\n\t\t\t\tl := v3 + \":\" + v4\n\t\t\t\tlist = append(list, l)\n\t\t\t}\n\t\t}\n\t}\n\treturn list, nil\n}", "func (service *HTTPRestService) getAllIPAddresses(w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"[Azure CNS] getAllIPAddresses\")\n\tlog.Request(service.Name, \"getAllIPAddresses\", nil)\n\n\tswitch r.Method {\n\tcase \"GET\":\n\tdefault:\n\t}\n\n\tresp := cns.Response{ReturnCode: 0}\n\tipResp := &cns.GetIPAddressesResponse{Response: resp}\n\terr := service.Listener.Encode(w, &ipResp)\n\n\tlog.Response(service.Name, ipResp, resp.ReturnCode, ReturnCodeToString(resp.ReturnCode), err)\n}", "func (i *DeviceIPServiceOp) List(deviceID string, opts *ListOptions) ([]IPAddressAssignment, *Response, error) {\n\tif validateErr := ValidateUUID(deviceID); validateErr != nil {\n\t\treturn nil, nil, validateErr\n\t}\n\tendpointPath := path.Join(deviceBasePath, deviceID, ipBasePath)\n\tapiPathQuery := opts.WithQuery(endpointPath)\n\n\t// ipList represents collection of IP Address reservations\n\ttype ipList struct {\n\t\tIPs []IPAddressAssignment `json:\"ip_addresses,omitempty\"`\n\t}\n\n\tips := new(ipList)\n\n\tresp, err := i.client.DoRequest(\"GET\", apiPathQuery, nil, ips)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn ips.IPs, resp, err\n}", "func (a *Client) ListIPs(params *ListIPsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListIPsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListIPsParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"listIPs\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/v1/ip\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &ListIPsReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*ListIPsOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\tunexpectedSuccess := result.(*ListIPsDefault)\n\treturn nil, runtime.NewAPIError(\"unexpected success response: content available as default response in error\", unexpectedSuccess, unexpectedSuccess.Code())\n}", "func (r *PoolNAPTRResource) ListAll() (*PoolList, error) {\n\tvar list PoolList\n\tif err := r.c.ReadQuery(BasePath+PoolNAPTREndpoint, &list); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &list, nil\n}", "func (d *DB) Get_all(ipaddress string) (IP2Locationrecord, error) {\n\treturn d.query(ipaddress, all)\n}", "func Get_all(ipaddress string) IP2Locationrecord {\n\treturn handleError(defaultDB.query(ipaddress, all))\n}", "func SelectAllIps(db *sql.DB) *sql.Rows {\n\trows, err := db.Query(\"SELECT id, ip, name, timestamp FROM raspberrypis ORDER BY timestamp DESC\")\n\tcheckErr(err)\n\n\treturn rows\n}", "func boundIPs(c *caddy.Controller) (ips []net.IP) {\n\tconf := dnsserver.GetConfig(c)\n\thosts := conf.ListenHosts\n\tif hosts == nil || hosts[0] == \"\" {\n\t\thosts = nil\n\t\taddrs, err := net.InterfaceAddrs()\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t\tfor _, addr := range addrs {\n\t\t\thosts = append(hosts, addr.String())\n\t\t}\n\t}\n\tfor _, host := range hosts {\n\t\tip, _, _ := net.ParseCIDR(host)\n\t\tip4 := ip.To4()\n\t\tif ip4 != nil && !ip4.IsLoopback() {\n\t\t\tips = append(ips, ip4)\n\t\t\tcontinue\n\t\t}\n\t\tip6 := ip.To16()\n\t\tif ip6 != nil && !ip6.IsLoopback() {\n\t\t\tips = append(ips, ip6)\n\t\t}\n\t}\n\treturn ips\n}", "func initIPs(n int, prefixLen int) {\n\tipDB.ips = make(map[string]string)\n\tipDB.interfaces = make(map[string]string)\n\tipDB.prefixLen = prefixLen\n\n\tfor i := 1; i <= n; i++ {\n\t\tk := fmt.Sprintf(\"10.0.%d.1\", i)\n\t\tipDB.ips[k] = \"\"\n\t}\n}", "func (rhost *rhostData) getIPs() (ips []string, err error) {\n\tifaces, err := net.Interfaces()\n\tif err != nil {\n\t\treturn\n\t}\n\tfor _, i := range ifaces {\n\t\taddrs, err := i.Addrs()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, addr := range addrs {\n\t\t\tvar ip net.IP\n\t\t\tswitch v := addr.(type) {\n\t\t\tcase *net.IPNet:\n\t\t\t\tip = v.IP\n\t\t\tcase *net.IPAddr:\n\t\t\t\tip = v.IP\n\t\t\t}\n\t\t\ta := ip.String()\n\t\t\t// Check ipv6 address add [] if ipv6 allowed and\n\t\t\t// skip this address if ipv6 not allowed\n\t\t\tif strings.IndexByte(a, ':') >= 0 {\n\t\t\t\tif !rhost.teo.param.IPv6Allow {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\ta = \"[\" + a + \"]\"\n\t\t\t}\n\t\t\tips = append(ips, a)\n\t\t}\n\t}\n\treturn\n}", "func (ml *Memberlist) List() (map[string]*IpAddress, error) {\n\n\t// Send request to service\n\tres, err := http.Post(ml.ServiceUrl+\"/list\",\n\t\t\"application/x-www-form-urlencoded\", nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to list memberlist (%v): %v\\n\", ml, err)\n\t}\n\n\t// Read response body in JSON\n\tbody, err := ioutil.ReadAll(res.Body)\n\tres.Body.Close()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read response of memberlist list (%v): %v\\n\", ml, err)\n\t}\n\n\t// Unmarshall all ip addresses as map\n\tvar memberlist map[string]*IpAddress\n\tjson.Unmarshal(body, &memberlist)\n\n\treturn memberlist, nil\n}", "func NewIpAddress_List(s *capnp.Segment, sz int32) (IpAddress_List, error) {\n\tl, err := capnp.NewCompositeList(s, capnp.ObjectSize{DataSize: 16, PointerCount: 0}, sz)\n\treturn IpAddress_List{l}, err\n}", "func (i *InstanceServiceHandler) ListIPv4(ctx context.Context, instanceID string, options *ListOptions) ([]IPv4, *Meta, error) {\n\turi := fmt.Sprintf(\"%s/%s/ipv4\", instancePath, instanceID)\n\treq, err := i.client.NewRequest(ctx, http.MethodGet, uri, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tnewValues, err := query.Values(options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq.URL.RawQuery = newValues.Encode()\n\tips := new(ipBase)\n\tif err = i.client.DoWithContext(ctx, req, ips); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn ips.IPv4s, ips.Meta, nil\n}", "func buscarIps(c *cli.Context) {\n\t//retorna o valor da flag Host\n\thost := c.String(\"host\")\n\n\t//net - busca os ips\n\tips, erro := net.LookupIP(host)\n\tif erro != nil {\n\t\tlog.Fatal(erro)\n\t}\n\n\tfor _, ip := range ips {\n\t\tfmt.Println(ip)\n\t}\n}", "func (c *Consul) IPs(ctx context.Context, tag string) ([]string, error) {\n\turl := fmt.Sprintf(\"http://%s/v1/catalog/datacenters\", c.hostport)\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"datacenters request: %s\", err)\n\t}\n\treq = req.WithContext(ctx)\n\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"http call: %s\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tdcs, err := ParseConsulDatacentersResponse(resp.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"get datacenters: %s\", err)\n\t}\n\n\tvar ret []string\n\tfor _, dc := range dcs {\n\t\tips, err := c.IPsDC(ctx, dc, tag)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"ips for datacenter %s: %s\", dc, err)\n\t\t}\n\t\tret = append(ret, ips...)\n\t}\n\treturn ret, nil\n}", "func (v *InvoiceCollection) List() string {\n\tvar b bytes.Buffer\n\tfor ip, pv := range *v {\n\t\tfmt.Fprintf(&b, \"%s\", pv.Table(util.Sf(\"發票 %d\", ip+1)))\n\t}\n\treturn b.String()\n}", "func (k8s *Client) ListPodIPs() []string {\n\t// Decided to simply dump this and leave it up to consumer\n\t// as k8s package currently doesn't need to be concerned about what's\n\t// a signficant annotation to process, that is left up to store/server\n\treturn k8s.podIndexer.ListIndexFuncValues(podIPIndexName)\n}", "func NetList(ip net.IP, subnet net.IP) (IPlist []net.IP) {\n\t//ip, ipnet, err := net.ParseCIDR(cidrNet)\n\tmask := net.IPv4Mask(subnet[0], subnet[1], subnet[2], subnet[3])\n\tipnet := net.IPNet{ip, mask}\n\tfor ip := ip.Mask(mask); ipnet.Contains(ip); incIP(ip) {\n\t\tIPlist = append(IPlist, net.IP{ip[0], ip[1], ip[2], ip[3]})\n\t}\n\treturn\n}", "func (p *pgSerDe) ListDbClientIps() ([]string, error) {\n\tconst sql = \"SELECT DISTINCT(client_addr) FROM pg_stat_activity\"\n\trows, err := p.dbConn.Query(sql)\n\tif err != nil {\n\t\tlog.Printf(\"ListDbClientIps(): error querying database: %v\", err)\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tresult := make([]string, 0)\n\tfor rows.Next() {\n\t\tvar addr *string\n\t\tif err := rows.Scan(&addr); err != nil {\n\t\t\tlog.Printf(\"ListDbClientIps(): error scanning row: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tif addr != nil {\n\t\t\tresult = append(result, *addr)\n\t\t}\n\t}\n\treturn result, nil\n}", "func (pool *PoolHandler) List(request *restful.Request, response *restful.Response) {\n\tstarted := time.Now()\n\t//list all pools\n\tnetRes := &types.NetResponse{\n\t\tType: types.ResponseType_POOL,\n\t}\n\tallPools, err := pool.netSvr.ListPool()\n\tif err != nil {\n\t\tblog.Errorf(\"NetPool List all request err: %s\", err.Error())\n\t\tnetRes.Code = 1\n\t\tnetRes.Message = err.Error()\n\t\tresponse.WriteEntity(netRes)\n\t\treportMetrics(\"listIPPool\", \"5xx\", started)\n\t\treturn\n\t}\n\tnetRes.Code = 0\n\tnetRes.Message = SUCCESS\n\tnetRes.Pool = allPools\n\tnetRes.Data = netRes.Pool\n\tif err := response.WriteEntity(netRes); err != nil {\n\t\tblog.Errorf(\"PoolHandler reply client GET request Err: %v\", err)\n\t}\n\treportMetrics(\"listIPPool\", \"2xx\", started)\n}", "func (client *PublicIPAddressesClient) listAllHandleResponse(resp *http.Response) (PublicIPAddressesClientListAllResponse, error) {\n\tresult := PublicIPAddressesClientListAllResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.PublicIPAddressListResult); err != nil {\n\t\treturn PublicIPAddressesClientListAllResponse{}, err\n\t}\n\treturn result, nil\n}", "func (a InstancePoolsAPI) List() (ipl InstancePoolList, err error) {\n\terr = a.C.Get(\"/instance-pools/list\", nil, &ipl)\n\treturn\n}", "func GetIPList(ip string) []string {\n\tif len(ip) == 0 {\n\t\treturn make([]string, 0)\n\t}\n\n\treturn strings.Split(ip, \",\")\n}", "func (c *epCache) list(options metav1.ListOptions) (*corev1.EndpointsList, error) {\n\tepList := &corev1.EndpointsList{\n\t\tItems: []corev1.Endpoints{},\n\t}\n\tif c.store == nil {\n\t\tklog.V(6).Info(\"endpoints listed from remote\")\n\t\treturn c.client.CoreV1().Endpoints(c.namespace).List(context.TODO(), options)\n\t}\n\n\teps := c.store.List()\n\tif eps == nil {\n\t\tklog.V(6).Info(\"endpoints listed from remote\")\n\t\treturn c.client.CoreV1().Endpoints(c.namespace).List(context.TODO(), options)\n\t}\n\n\tfor _, ep := range eps {\n\t\tepList.Items = append(epList.Items, ep.(corev1.Endpoints))\n\t}\n\n\tklog.V(6).Info(\"endpoints listed from cache\")\n\treturn epList, nil\n}", "func (vr *VirtualResource) ListAll() (*VirtualServerConfigList, error) {\n\tresp, err := vr.doRequest(\"GET\", \"\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif err := vr.readError(resp); err != nil {\n\t\treturn nil, err\n\t}\n\tvar vsc VirtualServerConfigList\n\tdec := json.NewDecoder(resp.Body)\n\tif err := dec.Decode(&vsc); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &vsc, nil\n}", "func retrieveIPAddresses(ch api.Channel, name string, index interface_types.InterfaceIndex) {\n\tlogHeader(\"Retrieving interface data from %s\", name)\n\treq := &ip.IPAddressDump{\n\t\tSwIfIndex: index,\n\t}\n\treqCtx := ch.SendMultiRequest(req)\n\n\tlogInfo(\"Dump IP addresses for interface index %d ..\\n\", index)\n\tfor {\n\t\tmsg := &ip.IPAddressDetails{}\n\t\tstop, err := reqCtx.ReceiveReply(msg)\n\t\tif err != nil {\n\t\t\tlogError(err, \"dumping IP addresses\")\n\t\t\treturn\n\t\t}\n\t\tif stop {\n\t\t\tbreak\n\t\t}\n\t\tprefix := ip_types.Prefix(msg.Prefix)\n\t\tlogInfo(\" - ip address: %v\\n\", prefix)\n\t}\n\n\tlogInfo(\"OK\\n\")\n\tfmt.Println()\n}", "func IPListWriteFromCIDR(cidrStr string) error {\n\t_, ipnet, err := net.ParseCIDR(cidrStr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmask := binary.BigEndian.Uint32(ipnet.Mask)\n\tstart := binary.BigEndian.Uint32(ipnet.IP)\n\tend := (start & mask) | (mask ^ 0xffffffff)\n\n\tfor i := start; i <= end; i++ {\n\t\tip := make(net.IP, 4)\n\t\tbinary.BigEndian.PutUint32(ip, i)\n\t\tfmt.Println(ip)\n\t}\n\n\treturn nil\n}", "func dataSourceNetboxIPAddressesRead(d *schema.ResourceData, meta interface{}) error {\n c := meta.(*ProviderNetboxClient).client\n\n // primary key lookup, direct\n if id, idOk := d.GetOk(\"id\"); idOk {\n parm := ipam.NewIPAMIPAddressesReadParams()\n\t\tparm.SetID(int64(id.(int)))\n\n\t\tout, err := c.IPAM.IPAMIPAddressesRead(parm, nil)\n\n\t\tif err != nil {\n log.Printf(\"error from IPAMIPAddressesRead: %v\\n\", err)\n\t\t\treturn err\n }\n\n dataSourceNetboxIPAddressParse(d, out.Payload)\n } else { // anything else, requires a search\n param := ipam.NewIPAMIPAddressesListParams()\n\n // Add any lookup params\n\n if query, queryOk := d.GetOk(\"query\"); queryOk {\n query_str := query.(string)\n param.SetQ(&query_str)\n }\n\n if family, familyOk := d.GetOk(\"family\"); familyOk {\n family_str := family.(string)\n param.SetFamily(&family_str)\n }\n\n if parent, parentOk := d.GetOk(\"parent\"); parentOk {\n parent_str := parent.(string)\n param.SetParent(&parent_str)\n }\n\n if tenant, tenantOk := d.GetOk(\"tenant\"); tenantOk {\n tenant_str := dataSourceNetboxIPAddressAttrPrep(tenant.(string))\n param.SetTenant(&tenant_str)\n }\n\n //if site, siteOk := d.GetOk(\"site\"); siteOk {\n // site_str := dataSourceNetboxIPAddressAttrPrep(site.(string))\n // param.SetSite(&site_str)\n //}\n\n //if role, roleOk := d.GetOk(\"role\"); roleOk {\n // role_str := dataSourceNetboxIPAddressAttrPrep(role.(string))\n // param.SetRole(&role_str)\n //}\n\n // limit to 2\n limit := int64(2)\n param.SetLimit(&limit)\n\n\t\tout, err := c.IPAM.IPAMIPAddressesList(param, nil)\n\n\t\tif err != nil {\n log.Printf(\"error from IPAMIPAddressesList: %v\\n\", err)\n\t\t\treturn err\n }\n\n if *out.Payload.Count == 0 {\n\t\t\treturn errors.New(\"IPAddress not found\")\n } else if *out.Payload.Count > 1 {\n return errors.New(\"More than one prefix matches search terms, please narrow\")\n }\n\n dataSourceNetboxIPAddressParse(d, out.Payload.Results[0])\n }\n\n\treturn nil\n}", "func getIPs() ([]string, error) {\n\t// In most cases we will have 3 and more interfaces\n\tIPs := make([]string, 0, 3)\n\n\tifaces, err := net.Interfaces()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, i := range ifaces {\n\t\taddrs, err := i.Addrs()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, addr := range addrs {\n\t\t\tvar ip net.IP\n\t\t\tswitch v := addr.(type) {\n\t\t\tcase *net.IPNet:\n\t\t\t\tip = v.IP\n\t\t\tcase *net.IPAddr:\n\t\t\t\tip = v.IP\n\t\t\t}\n\t\t\tif ip.To4() != nil {\n\t\t\t\tIPs = append(IPs, ip.String())\n\t\t\t}\n\t\t}\n\t}\n\treturn IPs, nil\n}", "func getVips(rw http.ResponseWriter, req *http.Request) {\n\tvips, err := common.GetVips()\n\tif err != nil {\n\t\twriteError(rw, req, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\twriteBody(rw, req, vips, http.StatusOK)\n}", "func (obj *conns) All() []Connection {\n\treturn obj.list\n}", "func ListIPReservations(projectID string) error {\n\tclient, err := NewExtPacketClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treservations, _, err := client.IPReservations.List(projectID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\te := MarshallAndPrint(reservations)\n\treturn e\n}", "func (service *HTTPRestService) getAvailableIPAddresses(w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"[Azure CNS] getAvailableIPAddresses\")\n\tlog.Request(service.Name, \"getAvailableIPAddresses\", nil)\n\n\tswitch r.Method {\n\tcase \"GET\":\n\tdefault:\n\t}\n\n\tresp := cns.Response{ReturnCode: 0}\n\tipResp := &cns.GetIPAddressesResponse{Response: resp}\n\terr := service.Listener.Encode(w, &ipResp)\n\n\tlog.Response(service.Name, ipResp, resp.ReturnCode, ReturnCodeToString(resp.ReturnCode), err)\n}", "func List(c *gin.Context){\n\tlimitStr := c.Query(\"limit\")\n\tlimit, err := strconv.Atoi(limitStr)\n\tif err != nil {\n\t\tlimit = 0\n\t}\n\tres, err := list(limit)\n\tif err != nil {\n\t\tresponese.Error(c, err, nil)\n\t\treturn\n\t}\n\tresponese.Success(c, \"successed\", res)\n}", "func (udp *UdpServer) getItfIps(itf *net.Interface) ([]net.IP, error) {\n var ip net.IP\n var ips []net.IP\n\n addresses, err := itf.Addrs()\n if err != nil {\n return ips, err\n }\n\n for _, address := range addresses {\n switch v := address.(type) {\n case *net.IPNet:\n ip = v.IP\n case *net.IPAddr:\n ip = v.IP\n }\n }\n\n ip = ip.To4()\n if ip != nil {\n ips = append(ips, ip)\n }\n\n return ips, nil\n}", "func (c *Client) List(ctx context.Context) (res StoredBottleCollection, err error) {\n\tvar ires any\n\tires, err = c.ListEndpoint(ctx, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn ires.(StoredBottleCollection), nil\n}", "func (h *httpCloud) List(filter string) ([]string, error) {\n\tvar resp []string\n\tif err := h.get(h.instancesURL+path.Join(InstancesPath, filter), &resp); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func (a *CleanEniAction) getEniIPs() (pbcommon.ErrCode, string) {\n\texistedObjects, err := a.storeIf.ListIPObject(a.ctx, map[string]string{\n\t\tkube.CrdNameLabelsEni: a.req.EniID,\n\t})\n\tif err != nil {\n\t\treturn pbcommon.ErrCode_ERROR_CLOUD_NETSERVICE_STOREOPS_FAILED,\n\t\t\tfmt.Sprintf(\"list node ips failed, err %s\", err.Error())\n\t}\n\ta.ipObjs = existedObjects\n\treturn pbcommon.ErrCode_ERROR_OK, \"\"\n}", "func List(client *gophercloud.ServiceClient, loadBalancerID int) pagination.Pager {\n\turl := rootURL(client, loadBalancerID)\n\treturn pagination.NewPager(client, url, func(r pagination.PageResult) pagination.Page {\n\t\treturn VIPPage{pagination.SinglePageBase(r)}\n\t})\n}", "func (s *cloudPrivateIPConfigLister) List(selector labels.Selector) (ret []*v1.CloudPrivateIPConfig, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.CloudPrivateIPConfig))\n\t})\n\treturn ret, err\n}", "func (test *Test) GetIPs(projectName string) ([]models.IP, error) {\n\treturn tests.NormalIPs, nil\n}", "func (lbuo *LoadBalanceUpdateOne) SetIPList(s string) *LoadBalanceUpdateOne {\n\tlbuo.mutation.SetIPList(s)\n\treturn lbuo\n}", "func (api *nodeAPI) ApisrvList(ctx context.Context, opts *api.ListWatchOptions) ([]*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 nil, err\n\t\t}\n\n\t\treturn apicl.ClusterV1().Node().List(context.Background(), opts)\n\t}\n\n\t// List from local cache\n\tctkitObjs, err := api.List(ctx, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar ret []*cluster.Node\n\tfor _, obj := range ctkitObjs {\n\t\tret = append(ret, &obj.Node)\n\t}\n\treturn ret, nil\n}", "func (api *hostAPI) ApisrvList(ctx context.Context, opts *api.ListWatchOptions) ([]*cluster.Host, 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 nil, err\n\t\t}\n\n\t\treturn apicl.ClusterV1().Host().List(context.Background(), opts)\n\t}\n\n\t// List from local cache\n\tctkitObjs, err := api.List(ctx, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar ret []*cluster.Host\n\tfor _, obj := range ctkitObjs {\n\t\tret = append(ret, &obj.Host)\n\t}\n\treturn ret, nil\n}", "func (gc *Collector) listIPs(project string, regions []string) (res []*addressWrapper, allSucceeded bool) {\n\tallSucceeded = true\n\tres = []*addressWrapper{}\n\n\tfor _, region := range regions {\n\t\tipAddresses, allProcessed, err := gc.listRegionIPs(project, region)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Could not list IP Addresses in Region \\\"%s\\\": %v\", region, err)\n\t\t\tallSucceeded = false\n\t\t\tcontinue\n\t\t}\n\n\t\tif !allProcessed {\n\t\t\tallSucceeded = false\n\t\t}\n\n\t\tres = append(res, ipAddresses...)\n\t}\n\n\treturn res, allSucceeded\n}", "func (db *DB) List(items interface{}) error {\n\tif db.tablename.length() <= 0 {\n\t\treturn errors.New(MongoDBErrTableName)\n\t}\n\tif err := db.Collection[db.tablename].Find(nil).All(items); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func IPListWriteFromIPRange(ipStrStart string, ipStrEnd string) error {\n\tvar ipStart, ipEnd net.IP\n\n\tif ipStart = net.ParseIP(ipStrStart); ipStart == nil {\n\t\treturn ErrNotIP\n\t}\n\tif ipEnd = net.ParseIP(ipStrEnd); ipEnd == nil {\n\t\treturn ErrNotIP\n\t}\n\n\tstart := binary.BigEndian.Uint32(ipStart.To4())\n\tend := binary.BigEndian.Uint32(ipEnd.To4())\n\n\tif start > end {\n\t\t// return decreasing list if range is flipped.\n\t\tfor i := start; i >= end; i-- {\n\t\t\tip := make(net.IP, 4)\n\t\t\tbinary.BigEndian.PutUint32(ip, i)\n\t\t\tfmt.Println(ip)\n\t\t}\n\t} else {\n\t\tfor i := start; i <= end; i++ {\n\t\t\tip := make(net.IP, 4)\n\t\t\tbinary.BigEndian.PutUint32(ip, i)\n\t\t\tfmt.Println(ip)\n\t\t}\n\t}\n\n\treturn nil\n}", "func TaskList(w http.ResponseWriter, r *http.Request) {\n\tvar res Tasks\n\terr := collection.Find(nil).Sort(\"-_id\").All(&res)\n\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(res)\n}", "func (c *countryFieldResolver) List(_ graphql.ResolveParams) (interface{}, error) {\n\treturn c.countryRepo.FetchAll()\n}", "func queryIpApi(ip string) []byte {\n\tquery := \"http://ip-api.com/json/\" + ip\n\tres, err := http.Get(query)\n\tcheck(err)\n\tdefer res.Body.Close()\n\tdata, err := ioutil.ReadAll(res.Body)\n\tcheck(err)\n\treturn data\n}", "func AllListMembers(w http.ResponseWriter, r *http.Request) {\r\n\tvar listMembers []ListMember\r\n\r\n\tdb.Find(&listMembers)\r\n\tjson.NewEncoder(w).Encode(listMembers)\r\n\t// fmt.Fprintf(w, \"All listMembers Endpoint Hit\")\r\n}", "func (client *IPPoolClient) GetAllPool() []*hcipamTypes.NSIPPool {\n\tvar pooList []*hcipamTypes.NSIPPool\n\tstrList := etcdcli.GetList(hcipamTypes.NS_POOL_Key_Prefix)\n\tfor _, str := range strList {\n\t\tif str == \"\" {\n\t\t\tlog.IPPool.Error(\"empty str to unmarshal\")\n\t\t\tcontinue\n\t\t}\n\t\tpool := &hcipamTypes.NSIPPool{}\n\t\terr := json.Unmarshal([]byte(str), pool)\n\t\tif err != nil {\n\t\t\tlog.IPPool.Errorf(\"unmarshal %s to pool err \", str)\n\t\t\treturn nil\n\t\t}\n\t\tpooList = append(pooList, pool)\n\t}\n\treturn pooList\n}", "func doGetAllIpKeys(d *db.DB, dbSpec *db.TableSpec) ([]db.Key, error) {\n\n var keys []db.Key\n\n intfTable, err := d.GetTable(dbSpec)\n if err != nil {\n return keys, err\n }\n\n keys, err = intfTable.GetKeys()\n log.Infof(\"Found %d INTF table keys\", len(keys))\n return keys, err\n}", "func (hd *Datapath) convertIPs(addresses []string) ([]*halproto.IPAddressObj, error) {\n\tvar halAddresses []*halproto.IPAddressObj\n\tfor _, a := range addresses {\n\t\tif ip := net.ParseIP(strings.TrimSpace(a)); len(ip) > 0 {\n\t\t\t// try parsing as an octet\n\n\t\t\thalAddr := &halproto.IPAddressObj{\n\t\t\t\tFormats: &halproto.IPAddressObj_Address{\n\t\t\t\t\tAddress: &halproto.Address{\n\t\t\t\t\t\tAddress: &halproto.Address_Prefix{\n\t\t\t\t\t\t\tPrefix: &halproto.IPSubnet{\n\t\t\t\t\t\t\t\tSubnet: &halproto.IPSubnet_Ipv4Subnet{\n\t\t\t\t\t\t\t\t\tIpv4Subnet: &halproto.IPPrefix{\n\t\t\t\t\t\t\t\t\t\tAddress: &halproto.IPAddress{\n\t\t\t\t\t\t\t\t\t\t\tIpAf: halproto.IPAddressFamily_IP_AF_INET,\n\t\t\t\t\t\t\t\t\t\t\tV4OrV6: &halproto.IPAddress_V4Addr{\n\t\t\t\t\t\t\t\t\t\t\t\tV4Addr: ipv4Touint32(ip),\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\tPrefixLen: uint32(32),\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\thalAddresses = append(halAddresses, halAddr)\n\t\t} else if ip, network, err := net.ParseCIDR(strings.TrimSpace(a)); err == nil {\n\t\t\t// try parsing as IPMask\n\t\t\tprefixLen, _ := network.Mask.Size()\n\n\t\t\thalAddr := &halproto.IPAddressObj{\n\t\t\t\tFormats: &halproto.IPAddressObj_Address{\n\t\t\t\t\tAddress: &halproto.Address{\n\t\t\t\t\t\tAddress: &halproto.Address_Prefix{\n\t\t\t\t\t\t\tPrefix: &halproto.IPSubnet{\n\t\t\t\t\t\t\t\tSubnet: &halproto.IPSubnet_Ipv4Subnet{\n\t\t\t\t\t\t\t\t\tIpv4Subnet: &halproto.IPPrefix{\n\t\t\t\t\t\t\t\t\t\tAddress: &halproto.IPAddress{\n\t\t\t\t\t\t\t\t\t\t\tIpAf: halproto.IPAddressFamily_IP_AF_INET,\n\t\t\t\t\t\t\t\t\t\t\tV4OrV6: &halproto.IPAddress_V4Addr{\n\t\t\t\t\t\t\t\t\t\t\t\tV4Addr: ipv4Touint32(ip),\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\tPrefixLen: uint32(prefixLen),\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\thalAddresses = append(halAddresses, halAddr)\n\n\t\t} else if ipRange := strings.Split(strings.TrimSpace(a), \"-\"); len(ipRange) == 2 {\n\t\t\t// try parsing as hyphen separated range\n\t\t\thalAddr, err := hd.convertIPRange(ipRange[0], ipRange[1])\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"failed to parse IP Range {%v}. Err: %v\", ipRange, err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\thalAddresses = append(halAddresses, halAddr)\n\t\t} else if a == \"any\" {\n\t\t\t// Interpret it as 0.0.0.0/0\n\t\t\thalAddr := &halproto.IPAddressObj{\n\t\t\t\tFormats: &halproto.IPAddressObj_Address{\n\t\t\t\t\tAddress: &halproto.Address{\n\t\t\t\t\t\tAddress: &halproto.Address_Prefix{\n\t\t\t\t\t\t\tPrefix: &halproto.IPSubnet{\n\t\t\t\t\t\t\t\tSubnet: &halproto.IPSubnet_Ipv4Subnet{\n\t\t\t\t\t\t\t\t\tIpv4Subnet: &halproto.IPPrefix{\n\t\t\t\t\t\t\t\t\t\tAddress: &halproto.IPAddress{\n\t\t\t\t\t\t\t\t\t\t\tIpAf: halproto.IPAddressFamily_IP_AF_INET,\n\t\t\t\t\t\t\t\t\t\t\tV4OrV6: &halproto.IPAddress_V4Addr{},\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\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t\thalAddresses = append(halAddresses, halAddr)\n\t\t} else {\n\t\t\t// give up\n\t\t\treturn nil, fmt.Errorf(\"invalid IP Address format {%v}. Should either be in an octet, CIDR or hyphen separated IP Range\", a)\n\t\t}\n\n\t}\n\treturn halAddresses, nil\n}", "func GetIPs(userID string) ([]IP, error) {\n\tvar result []IP\n\trows, err := db.Query(\"SELECT * FROM web_ips WHERE user_id = ?\", userID)\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tnextIP := IP{}\n\t\terr = rows.Scan(&nextIP.UserID, &nextIP.IP, &nextIP.LastUsed)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult = append(result, nextIP)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}", "func validateIPAllowlist(l *protocol.AuthIPWhitelist) error {\n\tfor _, subnet := range l.Subnets {\n\t\tif _, _, err := net.ParseCIDR(subnet); err != nil {\n\t\t\treturn fmt.Errorf(\"bad subnet %q - %s\", subnet, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (fs *Ipfs) List(path string) ([]*oss.Object, error) {\n\tdir := ipath.New(path)\n\tentries, err := fs.coreAPI.Unixfs().Ls(context.Background(), dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdl := make([]*oss.Object, 0)\n\tnow := time.Now()\nloop:\n\tfor {\n\t\tselect {\n\t\tcase entry, ok := <-entries:\n\t\t\tif !ok {\n\t\t\t\tbreak loop\n\t\t\t}\n\n\t\t\tvar n string\n\t\t\tp := entry.Cid.String()\n\t\t\tif strings.HasPrefix(p, \"/ipfs/\") {\n\t\t\t\tn = strings.Split(p, \"/\")[2]\n\t\t\t} else {\n\t\t\t\tn = p\n\t\t\t\tp = \"/ipfs/\" + p\n\t\t\t}\n\n\t\t\tdl = append(dl, &oss.Object{\n\t\t\t\tPath: p,\n\t\t\t\tName: n,\n\t\t\t\tLastModified: &now,\n\t\t\t\tStorageInterface: fs,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn dl, nil\n}", "func getLocalIP() ([]string, error) {\n\tvar ipList []string\n\n\taddrs, err := net.InterfaceAddrs()\n\tif err != nil {\n\t\treturn ipList, err\n\t}\n\n\tfor _, address := range addrs {\n\t\t// check the address type and if it is not a loopback the display it\n\t\tif ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {\n\t\t\tif ipnet.IP.To4() != nil {\n\t\t\t\tipList = append(ipList, ipnet.IP.String())\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(ipList) == 0 {\n\t\terr = errors.New(\"Can't find host ip!\")\n\t\treturn ipList, err\n\t}\n\n\treturn ipList, nil\n\n}", "func GetAllIPs(deploymentVms []gogobosh.VM) []string {\n\tvar ips []string\n\tfor _, deployment := range deploymentVms {\n\t\tips = append(ips, deployment.IPs...)\n\t}\n\tutility.RemoveDuplicates(&ips)\n\treturn ips\n}", "func (api *objectAPI) ApisrvList(ctx context.Context, opts *api.ListWatchOptions) ([]*objstore.Object, 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 nil, err\n\t\t}\n\n\t\treturn apicl.ObjstoreV1().Object().List(context.Background(), opts)\n\t}\n\n\t// List from local cache\n\tctkitObjs, err := api.List(ctx, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar ret []*objstore.Object\n\tfor _, obj := range ctkitObjs {\n\t\tret = append(ret, &obj.Object)\n\t}\n\treturn ret, nil\n}", "func HostIP() []string {\n\tvar out []string\n\taddrs, err := net.InterfaceAddrs()\n\tif err != nil {\n\t\tlogs.WithFields(logs.Fields{\n\t\t\t\"Error\": err,\n\t\t}).Error(\"Unable to resolve net.InterfaceAddrs\")\n\t}\n\tfor _, addr := range addrs {\n\t\t// check the address type and if it is not a loopback the display it\n\t\tif ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {\n\t\t\tif ipnet.IP.To4() != nil {\n\t\t\t\tout = append(out, ipnet.IP.String())\n\t\t\t}\n\t\t\tif ipnet.IP.To16() != nil {\n\t\t\t\tout = append(out, ipnet.IP.String())\n\t\t\t}\n\t\t}\n\t}\n\treturn List2Set(out)\n}", "func GetIPs() ([]BoundIP, error) {\n\n\tvar namespaces []string\n\n\tfiles, err := ioutil.ReadDir(\"/var/run/netns/\")\n\tif err == nil {\n\t\tfor _, file := range files {\n\t\t\tnamespaces = append(namespaces,\n\t\t\t\tfilepath.Join(\"/var/run/netns\", file.Name()))\n\t\t}\n\t}\n\n\t// Check for running docker containers\n\tcontainers, err := runningDockerContainers()\n\tif err == nil {\n\t\tdockerNamespaces := dockerNetworkNamespaces(containers)\n\t\tnamespaces = append(namespaces, dockerNamespaces...)\n\t}\n\n\t// First get all the IPs in the main namespace\n\thandle, err := netlink.NewHandle()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfoundIps, err := getIpsOnHandle(handle)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Enter each namesapce, get handles\n\tfor _, nsPath := range namespaces {\n\t\terr := ns.WithNetNSPath(nsPath, func(_ ns.NetNS) error {\n\n\t\t\thandle, err = netlink.NewHandle()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer handle.Delete()\n\n\t\t\tnewIps, err := getIpsOnHandle(handle)\n\t\t\tfoundIps = append(foundIps, newIps...)\n\t\t\treturn err\n\t\t})\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Enumerating namespace failure %v\", err)\n\t\t}\n\t}\n\n\treturn foundIps, nil\n}", "func (o *NetworkingProjectNetadpCreate) 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 (r *FirewallManagementIPRulesResource) ListAll() (*FirewallManagementIPRulesConfigList, error) {\n\tvar list FirewallManagementIPRulesConfigList\n\tif err := r.c.ReadQuery(BasePath+FirewallManagementIPRulesEndpoint, &list); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &list, nil\n}", "func getAllMaskForIP(ip net.IP) net.IPMask {\n\tif ip.To4() != nil {\n\t\t// This is an ipv4 address. Return 4 byte mask.\n\t\treturn ipv4AllMask\n\t}\n\t// Assume ipv6 address. Return 16 byte mask.\n\treturn ipv6AllMask\n}", "func (c *OperatorDNS) List() (srvRecords map[string][]SrvRecord, err error) {\n\treturn nil, ErrNotImplemented\n}", "func ListMysql(c *gin.Context) {\n\tns := c.Param(\"ns\")\n\n\tmyList, err := cli.KubedbClientSet.MySQLs(ns).List(metav1.ListOptions{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"message\": fmt.Sprintf(\"have %d instance in ns %s\", len(myList.Items), ns),\n\t})\n}", "func doGetIntfIpKeys(d *db.DB, tblName string, intfName string) ([]db.Key, error) {\n ipKeys, err := d.GetKeys(&db.TableSpec{Name: tblName+\"|\"+intfName})\n log.Info(\"doGetIntfIpKeys for interface: \", intfName, \" - \", ipKeys)\n return ipKeys, err\n}", "func (m *Message) AllAIP() ([]*AIP, error) {\n\tpss, err := m.ParseAll(\"AIP\")\n\treturn pss.([]*AIP), err\n}", "func (r *DOSProfileDOSNetworkResource) ListAll() (*DOSProfileDOSNetworkConfigList, error) {\n\tvar list DOSProfileDOSNetworkConfigList\n\tif err := r.c.ReadQuery(BasePath+DOSProfileDOSNetworkEndpoint, &list); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &list, nil\n}", "func (r *FailoverResource) ListAll() (*FailoverConfigList, error) {\n\tvar list FailoverConfigList\n\tif err := r.c.ReadQuery(BasePath+FailoverEndpoint, &list); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &list, nil\n}", "func (sp *ServiceProcessor) getNodeIPs() *renderer.IPAddresses {\n\tnodeIPs := renderer.NewIPAddresses()\n\n\tfor _, node := range sp.NodeSync.GetAllNodes() {\n\t\tfor _, vppIP := range node.VppIPAddresses {\n\t\t\tnodeIPs.Add(vppIP.Address)\n\t\t}\n\t\tfor _, mgmtIP := range node.MgmtIPAddresses {\n\t\t\tnodeIPs.Add(mgmtIP)\n\t\t}\n\t}\n\n\treturn nodeIPs\n}", "func geturls(w http.ResponseWriter, r *http.Request) {\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tvar urls []Myurl\n\tdb.Find(&urls)\n\tjson.NewEncoder(w).Encode(urls)\n}", "func getLocalIPs() (ips []string) {\n\tips = make([]string, 0, 6)\n\n\taddrs, err := net.InterfaceAddrs()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, addr := range addrs {\n\t\tif ipnet, ok := addr.(*net.IPNet); ok {\n\t\t\tif ipnet.IP.To4() != nil {\n\t\t\t\tips = append(ips, ipnet.IP.String())\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func ListIPReservation(id string) error {\n\tclient, err := NewExtPacketClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treservation, _, err := client.IPReservations.Get(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\te := MarshallAndPrint(reservation)\n\treturn e\n}", "func (c *Client) DBList() []string {\n\tres, _ := r.DBList().Run(c.session)\n\tdbs := []string{}\n\tres.All(&dbs)\n\treturn dbs\n}", "func ExtractPublicIPs(page pagination.Page) ([]PublicIP, error) {\n\tvar res []PublicIP\n\tcasted := page.(PublicIPPage).Body\n\terr := mapstructure.Decode(casted, &res)\n\n\tvar rawNodesDetails []interface{}\n\tswitch casted.(type) {\n\tcase interface{}:\n\t\trawNodesDetails = casted.([]interface{})\n\tdefault:\n\t\treturn res, fmt.Errorf(\"Unknown type: %v\", reflect.TypeOf(casted))\n\t}\n\n\tfor i := range rawNodesDetails {\n\t\tthisNodeDetails := (rawNodesDetails[i]).(map[string]interface{})\n\n\t\tif t, ok := thisNodeDetails[\"created\"].(string); ok && t != \"\" {\n\t\t\tcreationTime, err := time.Parse(time.RFC3339, t)\n\t\t\tif err != nil {\n\t\t\t\treturn res, err\n\t\t\t}\n\t\t\tres[i].CreatedAt = creationTime\n\t\t}\n\n\t\tif t, ok := thisNodeDetails[\"updated\"].(string); ok && t != \"\" {\n\t\t\tupdatedTime, err := time.Parse(time.RFC3339, t)\n\t\t\tif err != nil {\n\t\t\t\treturn res, err\n\t\t\t}\n\t\t\tres[i].UpdatedAt = updatedTime\n\t\t}\n\n\t\tif cs, ok := thisNodeDetails[\"cloud_server\"].(map[string]interface{}); ok {\n\t\t\tif t, ok := cs[\"created\"].(string); ok && t != \"\" {\n\t\t\t\tcreationTime, err := time.Parse(time.RFC3339, t)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn res, err\n\t\t\t\t}\n\t\t\t\tres[i].CloudServer.CreatedAt = creationTime\n\t\t\t}\n\t\t\tif t, ok := cs[\"updated\"].(string); ok && t != \"\" {\n\t\t\t\tupdatedTime, err := time.Parse(time.RFC3339, t)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn res, err\n\t\t\t\t}\n\t\t\t\tres[i].CloudServer.UpdatedAt = updatedTime\n\t\t\t}\n\t\t\tif cn, ok := cs[\"cloud_network\"].(map[string]interface{}); ok {\n\t\t\t\tif t, ok := cn[\"created\"].(string); ok && t != \"\" {\n\t\t\t\t\tcreationTime, err := time.Parse(time.RFC3339, t)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn res, err\n\t\t\t\t\t}\n\t\t\t\t\tres[i].CloudServer.CloudNetwork.CreatedAt = creationTime\n\t\t\t\t}\n\t\t\t\tif t, ok := cn[\"updated\"].(string); ok && t != \"\" {\n\t\t\t\t\tupdatedTime, err := time.Parse(time.RFC3339, t)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn res, err\n\t\t\t\t\t}\n\t\t\t\t\tres[i].CloudServer.CloudNetwork.UpdatedAt = updatedTime\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res, err\n}", "func (f *FakeInstance) ListIPv4(_ context.Context, _ string, _ *govultr.ListOptions) ([]govultr.IPv4, *govultr.Meta, *http.Response, error) {\n\tpanic(\"implement me\")\n}", "func IPAddresses() (l []net.IP) {\n\tfor _, i := range UpInterfaces() {\n\t\taddrs, _ := i.Addrs()\n\t\tfor _, addr := range addrs {\n\t\t\tip := strings.Split(addr.String(), \"/\")[0] // trim ip mask\n\t\t\tl = append(l, net.ParseIP(ip))\n\t\t}\n\t}\n\n\treturn l\n}", "func (h *HTTPApi) listDatasourceInstance(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tdatasourceInstances := make([]string, 0, len(h.storageNode.Datasources))\n\tfor k := range h.storageNode.Datasources {\n\t\tdatasourceInstances = append(datasourceInstances, k)\n\t}\n\n\t// Now we need to return the results\n\tif bytes, err := json.Marshal(datasourceInstances); err != nil {\n\t\t// TODO: log this better?\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t} else {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(bytes)\n\t}\n}", "func (api *versionAPI) ApisrvList(ctx context.Context, opts *api.ListWatchOptions) ([]*cluster.Version, 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 nil, err\n\t\t}\n\n\t\treturn apicl.ClusterV1().Version().List(context.Background(), opts)\n\t}\n\n\t// List from local cache\n\tctkitObjs, err := api.List(ctx, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar ret []*cluster.Version\n\tfor _, obj := range ctkitObjs {\n\t\tret = append(ret, &obj.Version)\n\t}\n\treturn ret, nil\n}", "func GetAll(ctx *routing.Context) error {\n\tdb := ctx.Get(\"db\").(*gorm.DB)\n\tdata := []models.ImageModel{}\n\tdb.Model(&dbmodels.Image{}).Scan(&data)\n\n\tres := models.NewResponse(true, data, \"OK\")\n\n\treturn ctx.WriteData(res.MustMarshal())\n}", "func (db database) list(w http.ResponseWriter, req *http.Request) {\n\tfor item, price := range db {\n\t\tfmt.Fprintf(w, \"%s: %s\\n\", item, price)\n\t}\n}", "func (db database) list(w http.ResponseWriter, req *http.Request) {\n\tfor item, price := range db {\n\t\tfmt.Fprintf(w, \"%s: %s\\n\", item, price)\n\t}\n}", "func expandConnectionStringIPs(db string) (string, error) {\n\treturn expandConnectionStringIPsDetail(db, net.LookupIP)\n}", "func GetList(tx *sql.Tx) (list []Info, err error) {\n\tmapper := rlt.NewAccountMapper(tx)\n\trows, err := mapper.FindAccountAll()\n\tfor _, row := range rows {\n\t\tinfo := Info{}\n\t\tinfo.ID = row.ID\n\t\tinfo.Domain = row.Domain.String\n\t\tinfo.UserName = row.UserName\n\t\tinfo.DisplayName = row.DisplayName\n\t\tinfo.Email = row.Email\n\t\tlist = append(list, info) //数据写入\n\t}\n\treturn list, err\n}", "func (c *Client) List(ctx context.Context, p *ListPayload) (res *ListResult, err error) {\n\tvar ires interface{}\n\tires, err = c.ListEndpoint(ctx, p)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn ires.(*ListResult), nil\n}", "func (f *Facade) GetPoolIPs(ctx datastore.Context, poolID string) (*PoolIPs, error) {\n\tglog.V(0).Infof(\"Facade.GetPoolIPs: %+v\", poolID)\n\thosts, err := f.FindHostsInPool(ctx, poolID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tglog.V(0).Infof(\"Facade.GetPoolIPs: found hosts %v\", hosts)\n\n\t// save off the static IP addresses\n\thostIPs := make([]host.HostIPResource, 0)\n\tfor _, h := range hosts {\n\t\thostIPs = append(hostIPs, h.IPs...)\n\t}\n\n\t// save off the virtual IP addresses\n\tmyPool, err := f.GetResourcePool(ctx, poolID)\n\tif err != nil {\n\t\tglog.Errorf(\"Unable to load resource pool: %v\", poolID)\n\t\treturn nil, err\n\t} else if myPool == nil {\n\t\tmsg := fmt.Sprintf(\"Pool ID: %v could not be found\", poolID)\n\t\treturn nil, errors.New(msg)\n\t}\n\tvirtualIPs := make([]pool.VirtualIP, 0)\n\tvirtualIPs = append(virtualIPs, myPool.VirtualIPs...)\n\n\treturn &PoolIPs{PoolID: poolID, HostIPs: hostIPs, VirtualIPs: virtualIPs}, nil\n}" ]
[ "0.6849254", "0.6244091", "0.5910938", "0.5899652", "0.57825124", "0.57562876", "0.5694492", "0.5693584", "0.5602305", "0.5589911", "0.55665326", "0.55433226", "0.54862577", "0.54790694", "0.5465517", "0.5461873", "0.5425544", "0.53980386", "0.5375369", "0.5363251", "0.535616", "0.5355867", "0.53534806", "0.533747", "0.5333869", "0.5322646", "0.52814317", "0.5250683", "0.5230115", "0.52283984", "0.5214693", "0.51887286", "0.51866716", "0.5177789", "0.517529", "0.5174123", "0.51614475", "0.51514006", "0.51217294", "0.51084083", "0.50914377", "0.5090993", "0.50900894", "0.50875866", "0.50801235", "0.50750476", "0.506861", "0.5041059", "0.50281036", "0.5024278", "0.5022458", "0.5012719", "0.500679", "0.4995341", "0.49944645", "0.49883357", "0.49782228", "0.49550053", "0.49526128", "0.49469343", "0.49443504", "0.49416986", "0.49351442", "0.49342707", "0.49330866", "0.49266842", "0.49247682", "0.49241447", "0.4924101", "0.49060637", "0.49056357", "0.48907235", "0.48873925", "0.48870233", "0.48852023", "0.48703656", "0.48695984", "0.4868448", "0.4852225", "0.48492283", "0.4847846", "0.48470017", "0.48446658", "0.48373193", "0.48372796", "0.48369545", "0.48338795", "0.48305473", "0.48292556", "0.48160094", "0.4810391", "0.4809181", "0.47939342", "0.4791066", "0.47826722", "0.47826722", "0.47776076", "0.47741973", "0.47736987", "0.4765996" ]
0.61650884
2
GetUserClusterPermList get user cluster permission
func GetUserClusterPermList(user UserInfo, clusterList []string) (map[string]*proto.Permission, error) { permissions := make(map[string]*proto.Permission) cli := &cluster.BCSClusterPerm{} actionIDs := []string{cluster.ClusterView.String(), cluster.ClusterManage.String(), cluster.ClusterDelete.String()} perms, err := cli.GetMultiClusterMultiActionPermission(user.UserID, user.ProjectID, clusterList, actionIDs) if err != nil { return nil, err } for clusterID, perm := range perms { permissions[clusterID] = &proto.Permission{ Policy: perm, } } return permissions, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetUserPermListByProjectAndCluster(user UserInfo, clusterList []string, filterUse bool) (map[string]*proto.Permission, error) {\n\tpermissions := make(map[string]*proto.Permission)\n\n\t// policyCode resourceType clusterList\n\tfor _, clusterID := range clusterList {\n\t\tdefaultPerm := auth.GetInitPerm(true)\n\n\t\tpermissions[clusterID] = &proto.Permission{\n\t\t\tPolicy: defaultPerm,\n\t\t}\n\t}\n\n\treturn permissions, nil\n}", "func GetClusterCreatePerm(user UserInfo) map[string]bool {\n\tpermissions := make(map[string]bool)\n\n\t// attention: v0 permission only support project\n\tpermissions[\"test\"] = true\n\tpermissions[\"prod\"] = true\n\tpermissions[\"create\"] = true\n\n\treturn permissions\n}", "func clusterList() []string {\n\tif c := envy.String(\"DQLITED_CLUSTER\"); c != \"\" {\n\t\treturn strings.Split(c, \",\")\n\t}\n\treturn defaultCluster\n}", "func List(c *client.Client) (*rbacv1.ClusterRoleList, error) {\n\tclusterrolelist, err := c.Clientset.RbacV1().ClusterRoles().List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn clusterrolelist, nil\n}", "func ListClusterUserCredentials(client autorest.Client, urlParameters map[string]interface{}, apiVersion string) containerservice.CredentialResults {\r\n\tqueryParameters := map[string]interface{}{\r\n\t\t\"api-version\": apiVersion,\r\n\t}\r\n\tpreparerDecorators := []autorest.PrepareDecorator{\r\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\r\n\t\tautorest.WithMethod(\"POST\"),\r\n\t\tautorest.WithBaseURL(azure.PublicCloud.ResourceManagerEndpoint),\r\n\t\tautorest.WithPathParameters(\r\n\t\t\t\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{resourceName}/listClusterUserCredential\",\r\n\t\t\turlParameters,\r\n\t\t),\r\n\t\tautorest.WithQueryParameters(queryParameters),\r\n\t}\r\n\r\n\tpreparer := autorest.CreatePreparer(preparerDecorators...)\r\n\treq, err := preparer.Prepare((&http.Request{}).WithContext(context.Background()))\r\n\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\tfmt.Println(req.URL)\r\n\r\n\tresp, err := client.Do(req)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\terr = autorest.Respond(\r\n\t\tresp,\r\n\t\tclient.ByInspecting(),\r\n\t)\r\n\r\n\tcontent, err := ioutil.ReadAll(resp.Body)\r\n\r\n\tvar kubeconfigs containerservice.CredentialResults\r\n\tjson.Unmarshal(content, &kubeconfigs)\r\n\r\n\treturn kubeconfigs\r\n}", "func (p *Permission) CanAccessCluster() (bool, error) {\n\tfor _, pattern := range p.Indices {\n\t\tpattern = strings.Replace(pattern, \"*\", \".*\", -1)\n\t\tmatched, err := regexp.MatchString(pattern, \"*\")\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif matched {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}", "func clusterPermissions(permissions ...auth.Permission) authHandler {\n\treturn func(ctx context.Context, authApi authiface.APIServer, fullMethod string) (string, error) {\n\t\tresp, err := authApi.Authorize(ctx, &auth.AuthorizeRequest{\n\t\t\tResource: &auth.Resource{Type: auth.ResourceType_CLUSTER},\n\t\t\tPermissions: permissions,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn \"\", errors.EnsureStack(err)\n\t\t}\n\n\t\tif resp.Authorized {\n\t\t\treturn \"\", nil\n\t\t}\n\n\t\treturn \"\", &auth.ErrNotAuthorized{\n\t\t\tSubject: resp.Principal,\n\t\t\tResource: &auth.Resource{Type: auth.ResourceType_CLUSTER},\n\t\t\tRequired: permissions,\n\t\t}\n\t}\n}", "func (m *Manager) ListCluster() error {\n\tclusters, err := m.GetClusterList()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch m.logger.GetDisplayMode() {\n\tcase logprinter.DisplayModeJSON:\n\t\tclusterObj := struct {\n\t\t\tClusters []Cluster `json:\"clusters\"`\n\t\t}{\n\t\t\tClusters: clusters,\n\t\t}\n\t\tdata, err := json.Marshal(clusterObj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Println(string(data))\n\tdefault:\n\t\tclusterTable := [][]string{\n\t\t\t// Header\n\t\t\t{\"Name\", \"User\", \"Version\", \"Path\", \"PrivateKey\"},\n\t\t}\n\t\tfor _, v := range clusters {\n\t\t\tclusterTable = append(clusterTable, []string{\n\t\t\t\tv.Name,\n\t\t\t\tv.User,\n\t\t\t\tv.Version,\n\t\t\t\tv.Path,\n\t\t\t\tv.PrivateKey,\n\t\t\t})\n\t\t}\n\t\ttui.PrintTable(clusterTable, true)\n\t}\n\treturn nil\n}", "func listClusters(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {\n\tctx := r.Context()\n\tallowed := permission.Check(t, permission.PermClusterRead)\n\tif !allowed {\n\t\treturn permission.ErrUnauthorized\n\t}\n\tclusters, err := servicemanager.Cluster.List(ctx)\n\tif err != nil {\n\t\tif err == provTypes.ErrNoCluster {\n\t\t\tw.WriteHeader(http.StatusNoContent)\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\tadmin := permission.Check(t, permission.PermClusterAdmin)\n\tif !admin {\n\t\tfor i := range clusters {\n\t\t\tclusters[i].CleanUpSensitive()\n\t\t}\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\treturn json.NewEncoder(w).Encode(clusters)\n}", "func GetClusterPermClient() (*cluster.BCSClusterPerm, error) {\n\tiamClient, err := GetIAMClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cluster.NewBCSClusterPermClient(iamClient), nil\n}", "func (adm Admin) ListClusterInfo(cluster string) (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\t// make sure the cluster is already setup\n\tif ok, err := conn.IsClusterSetup(cluster); !ok || err != nil {\n\t\treturn \"\", ErrClusterNotSetup\n\t}\n\n\tkeys := KeyBuilder{cluster}\n\tisPath := keys.idealStates()\n\tinstancesPath := keys.instances()\n\n\tresources, err := conn.Children(isPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tinstances, err := conn.Children(instancesPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"Existing resources in cluster \" + cluster + \":\\n\")\n\n\tfor _, r := range resources {\n\t\tbuffer.WriteString(\" \" + r + \"\\n\")\n\t}\n\n\tbuffer.WriteString(\"\\nInstances in cluster \" + cluster + \":\\n\")\n\tfor _, i := range instances {\n\t\tbuffer.WriteString(\" \" + i + \"\\n\")\n\t}\n\treturn buffer.String(), nil\n}", "func List() ([]clusterapi.Cluster, error) {\n\tvar clusterList []clusterapi.Cluster\n\terr := utils.BrowseMetadataContent(clusterapi.ClusterMetadataPrefix, func(buf *bytes.Buffer) error {\n\t\tvar c clusterapi.Cluster\n\t\terr := gob.NewDecoder(buf).Decode(&c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tclusterList = append(clusterList, c)\n\t\treturn nil\n\t})\n\treturn clusterList, err\n}", "func loadPerms(uid types.ID) (authority.Permissions, authority.ProjectRoles) {\n\tvar roles []string\n\tvar projectRoles []domain.ProjectRole\n\tdb := persistence.ActiveDataSourceManager.GormDB(context.Background())\n\n\t// system perms\n\tvar systemRoles []string\n\tif err := db.Model(&UserRoleBinding{}).Where(&UserRoleBinding{UserID: uid}).Pluck(\"role_id\", &systemRoles).Error; err != nil {\n\t\tpanic(err)\n\t}\n\n\tif len(systemRoles) > 0 {\n\t\tvar systemPerms []string\n\t\tif err := db.Model(&RolePermissionBinding{}).Where(\"role_id IN (?)\", systemRoles).Pluck(\"permission_id\", &systemPerms).Error; err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\troles = append(roles, systemPerms...)\n\t}\n\n\tif len(systemRoles) > 0 {\n\t\t// system role: all project is visiabble\n\t\tvar projects []domain.Project\n\t\tif err := db.Model(&domain.Project{}).Scan(&projects).Error; err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfor _, project := range projects {\n\t\t\troles = append(roles, fmt.Sprintf(\"%s_%d\", domain.ProjectRoleManager, project.ID))\n\t\t\tprojectRoles = append(projectRoles, domain.ProjectRole{\n\t\t\t\tProjectID: project.ID, ProjectName: project.Name, ProjectIdentifier: project.Identifier, Role: domain.ProjectRoleManager,\n\t\t\t})\n\t\t}\n\t} else {\n\t\tvar gms []domain.ProjectMember\n\t\tvar visiableProjectIds []types.ID\n\t\tif err := db.Model(&domain.ProjectMember{}).Where(&domain.ProjectMember{MemberId: uid}).Scan(&gms).Error; err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tfor _, gm := range gms {\n\t\t\troles = append(roles, fmt.Sprintf(\"%s_%d\", gm.Role, gm.ProjectId))\n\t\t\tprojectRoles = append(projectRoles, domain.ProjectRole{Role: gm.Role, ProjectID: gm.ProjectId})\n\t\t\tvisiableProjectIds = append(visiableProjectIds, gm.ProjectId)\n\t\t}\n\n\t\tm := map[types.ID]domain.Project{}\n\t\tif len(visiableProjectIds) > 0 {\n\t\t\tvar visiableProjects []domain.Project\n\t\t\tif err := db.Model(&domain.Project{}).Where(\"id in (?)\", visiableProjectIds).Scan(&visiableProjects).Error; err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tfor _, project := range visiableProjects {\n\t\t\t\tm[project.ID] = project\n\t\t\t}\n\t\t}\n\t\tfor i := 0; i < len(projectRoles); i++ {\n\t\t\tprojectRole := projectRoles[i]\n\n\t\t\tproject := m[projectRole.ProjectID]\n\t\t\tif (project == domain.Project{}) {\n\t\t\t\tpanic(errors.New(\"project \" + projectRole.ProjectID.String() + \" is not exist\"))\n\t\t\t}\n\n\t\t\tprojectRole.ProjectName = project.Name\n\t\t\tprojectRole.ProjectIdentifier = project.Identifier\n\n\t\t\tprojectRoles[i] = projectRole\n\t\t}\n\t}\n\n\tif roles == nil {\n\t\troles = []string{}\n\t}\n\tif projectRoles == nil {\n\t\tprojectRoles = []domain.ProjectRole{}\n\t}\n\n\treturn roles, projectRoles\n}", "func (w *WhoCan) getClusterRolesFor(action resolvedAction) (clusterRoles, error) {\n\tctx := context.Background()\n\tcrl, err := w.clientRBAC.ClusterRoles().List(ctx, metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcr := make(map[string]struct{}, 10)\n\n\tfor _, item := range crl.Items {\n\t\tif w.policyRuleMatcher.MatchesClusterRole(item, action) {\n\t\t\tif _, ok := cr[item.Name]; !ok {\n\t\t\t\tcr[item.Name] = struct{}{}\n\t\t\t}\n\t\t}\n\t}\n\treturn cr, nil\n}", "func (h *Handler) serveClusterAdmins(w http.ResponseWriter, r *http.Request) {}", "func ExampleConnectedClusterClient_ListClusterUserCredential_listClusterUserCredentialCspExample() {\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\tclientFactory, err := armhybridkubernetes.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewConnectedClusterClient().ListClusterUserCredential(ctx, \"k8sc-rg\", \"testCluster\", armhybridkubernetes.ListClusterUserCredentialProperties{\n\t\tAuthenticationMethod: to.Ptr(armhybridkubernetes.AuthenticationMethodAAD),\n\t\tClientProxy: to.Ptr(false),\n\t}, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.CredentialResults = armhybridkubernetes.CredentialResults{\n\t// \tKubeconfigs: []*armhybridkubernetes.CredentialResult{\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"credentialName1\"),\n\t// \t\t\tValue: []byte(\"YXBpVmVyc2lvbjogdjENCmNsdXN0ZXJzOg0KLSBjbHVzdGVyOg0KICAgIGNlcnRpZmljYXRlLWF1dGhvcml0eS1kYXRhOiBMUzB0TFMxQ1JVZEpUaUJEUlZKVVNVWkpRMEZVUlMwdExTMHRDazFKU1VWNGVrTkRRWEVyWjBGM1NVSkJaMGxSVTJ0dVdsWnZaekp1VmpKVmNYZEtjblZYTTFCSGVrRk9RbWRyY1docmFVYzVkekJDUVZGelJrRkVRVTRLVFZGemQwTlJXVVJXVVZGRVJYZEthbGVsSlEwbHFRVTVDWjJ0eGFHdHBSemwzTUVKQlVVVkdRVUZQUTBGbk9FRk5TVWxEUTJkTFEwRm5SVUUwV1hCNUNsUmtUMVJSU1dNdmVsaERlR3hTZWtVMF\"),\n\t// \t}},\n\t// }\n}", "func (adm Admin) ListClusterInfo(cluster string) (string, error) {\n\t// make sure the cluster is already setup\n\tif ok, err := adm.isClusterSetup(cluster); !ok || err != nil {\n\t\treturn \"\", ErrClusterNotSetup\n\t}\n\n\tbuilder := KeyBuilder{cluster}\n\tisPath := builder.idealStates()\n\tinstancesPath := builder.instances()\n\n\tresources, err := adm.zkClient.Children(isPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tinstances, err := adm.zkClient.Children(instancesPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"Existing resources in cluster \" + cluster + \":\\n\")\n\n\tfor _, r := range resources {\n\t\tbuffer.WriteString(\" \" + r + \"\\n\")\n\t}\n\n\tbuffer.WriteString(\"\\nInstances in cluster \" + cluster + \":\\n\")\n\tfor _, i := range instances {\n\t\tbuffer.WriteString(\" \" + i + \"\\n\")\n\t}\n\treturn buffer.String(), nil\n}", "func (a *HyperflexApiService) GetHyperflexProtectedClusterList(ctx context.Context) ApiGetHyperflexProtectedClusterListRequest {\n\treturn ApiGetHyperflexProtectedClusterListRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func ExampleAppliancesClient_ListClusterUserCredential() {\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 := armresourceconnector.NewAppliancesClient(\"11111111-2222-3333-4444-555555555555\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := client.ListClusterUserCredential(ctx,\n\t\t\"testresourcegroup\",\n\t\t\"appliance01\",\n\t\tnil)\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 (p *Proxy) isClusterAdmin(token string) (bool, error) {\n\tclient, err := p.createTypedClient(token)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tsar := &authv1.SelfSubjectAccessReview{\n\t\tSpec: authv1.SelfSubjectAccessReviewSpec{\n\t\t\tResourceAttributes: &authv1.ResourceAttributes{\n\t\t\t\tNamespace: \"openshift-terminal\",\n\t\t\t\tVerb: \"create\",\n\t\t\t\tResource: \"pods\",\n\t\t\t},\n\t\t},\n\t}\n\tres, err := client.AuthorizationV1().SelfSubjectAccessReviews().Create(context.TODO(), sar, metav1.CreateOptions{})\n\tif err != nil || res == nil {\n\t\treturn false, err\n\t}\n\treturn res.Status.Allowed, nil\n}", "func (m *Group) GetPermissionGrants()([]ResourceSpecificPermissionGrantable) {\n return m.permissionGrants\n}", "func (bc *BaseController) GetPermissionList() (error, []*dream.Permission) {\n\n\tresult, err := dream.GetPermissionList(bc.DB)\n\tif err != nil {\n\t\treturn ServiceErr, nil\n\t}\n\treturn nil, result\n}", "func (m *SharedWithChannelTeamInfo) GetAllowedMembers()([]ConversationMemberable) {\n val, err := m.GetBackingStore().Get(\"allowedMembers\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]ConversationMemberable)\n }\n return nil\n}", "func (n *NameServiceCache) GetUserPermissions(user string, kg fred.KeygroupName) (map[fred.Method]struct{}, error) {\n\treturn n.regularNase.GetUserPermissions(user, kg)\n}", "func (svc ServerlessClusterService) List(ctx context.Context) (*[]models.Cluster, *Response, error) {\n\tvar clusterList []models.Cluster\n\tgraphqlRequest := models.GraphqlRequest{\n\t\tName: \"clusters\",\n\t\tOperation: models.Query,\n\t\tInput: nil,\n\t\tArgs: models.ClusterListInput{\n\t\t\tProductType: models.Starter,\n\t\t},\n\t\tResponse: clusterList,\n\t}\n\treq, err := svc.client.NewRequest(&graphqlRequest)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresp, err := svc.client.Do(ctx, req, &clusterList)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn &clusterList, resp, err\n}", "func (db *SQLiteDB) GetPrivilegedUsers(groupID int64) ([]Permission, error) {\n\trows, err := db.Query(\"SELECT `Permission` FROM Permissions WHERE `GroupID`=?\", groupID)\n\tdefer rows.Close()\n\tprms := make([]Permission, 0)\n\tif err != nil {\n\t\tdb.AddLogEvent(Log{Event: \"GetPrivilegedUsers_ErorExecutingTheQuery\", Message: \"Impossible to get afftected rows\", Error: err.Error()})\n\t\treturn prms, err\n\t}\n\tfor rows.Next() {\n\t\tvar (\n\t\t\tid, userID, groupID, perm int64\n\t\t)\n\t\tif err = rows.Scan(&id, &userID, &groupID, &perm); err != nil {\n\t\t\tdb.AddLogEvent(Log{Event: \"GetPrivilegedUsers_RowQueryFetchResultFailed\", Message: \"Impossible to get data from the row\", Error: err.Error()})\n\t\t} else {\n\t\t\tprms = append(prms, Permission{ID: id, UserID: userID, GroupID: groupID, Permission: perm})\n\t\t}\n\t}\n\tif err == sql.ErrNoRows {\n\t\treturn prms, nil\n\t}\n\tif rows.NextResultSet() {\n\t\tdb.AddLogEvent(Log{Event: \"GetPrivilegedUsers_RowsNotFetched\", Message: \"Some rows in the query were not fetched\"})\n\t} else if err := rows.Err(); err != nil {\n\t\tdb.AddLogEvent(Log{Event: \"GetPrivilegedUsers_UnknowQueryError\", Message: \"An unknown error was thrown\", Error: err.Error()})\n\t}\n\treturn prms, err\n}", "func (s *permStore) List(ctx context.Context, repo string) ([]*core.Collaborator, error) {\n\tvar out []*core.Collaborator\n\terr := s.db.View(func(queryer db.Queryer, binder db.Binder) error {\n\t\tparams := map[string]interface{}{\"repo_uid\": repo}\n\t\tstmt, args, err := binder.BindNamed(queryCollabs, params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trows, err := queryer.Query(stmt, args...)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tout, err = scanCollabRows(rows)\n\t\treturn err\n\t})\n\treturn out, err\n}", "func (App) Permissions() []evo.Permission { return []evo.Permission{} }", "func ExampleConnectedClusterClient_ListClusterUserCredential_listClusterUserCredentialExample() {\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\tclientFactory, err := armhybridkubernetes.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewConnectedClusterClient().ListClusterUserCredential(ctx, \"k8sc-rg\", \"testCluster\", armhybridkubernetes.ListClusterUserCredentialProperties{\n\t\tAuthenticationMethod: to.Ptr(armhybridkubernetes.AuthenticationMethodAAD),\n\t\tClientProxy: to.Ptr(true),\n\t}, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.CredentialResults = armhybridkubernetes.CredentialResults{\n\t// \tHybridConnectionConfig: &armhybridkubernetes.HybridConnectionConfig{\n\t// \t\tExpirationTime: to.Ptr[int64](1631196183),\n\t// \t\tHybridConnectionName: to.Ptr(\"microsoft.kubernetes/connectedclusters/229dc73f7b07196c79a93d4362d9c7fc4ed34df3e95290d27c56cec2dbb82865/1631185383340987904\"),\n\t// \t\tRelay: to.Ptr(\"azgnrelay-ph0-l1\"),\n\t// \t\tToken: to.Ptr(\"SharedAccessSignature 123456789034675890pbduwegiavifkuw647o02423bbhfouseb\"),\n\t// \t},\n\t// \tKubeconfigs: []*armhybridkubernetes.CredentialResult{\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"credentialName1\"),\n\t// \t\t\tValue: []byte(\"YXBpVmVyc2lvbjogdjENCmNsdXN0ZXJzOg0KLSBjbHVzdGVyOg0KICAgIGNlcnRpZmljYXRlLWF1dGhvcml0eS1kYXRhOiBMUzB0TFMxQ1JVZEpUaUJEUlZKVVNVWkpRMEZVUlMwdExTMHRDazFKU1VWNGVrTkRRWEVyWjBGM1NVSkJaMGxSVTJ0dVdsWnZaekp1VmpKVmNYZEtjblZYTTFCSGVrRk9RbWRyY1docmFVYzVkekJDUVZGelJrRkVRVTRLVFZGemQwTlJXVVJXVVZGRVJYZEthbGVsSlEwbHFRVTVDWjJ0eGFHdHBSemwzTUVKQlVVVkdRVUZQUTBGbk9FRk5TVWxEUTJkTFEwRm5SVUUwV1hCNUNsUmtUMVJSU1dNdmVsaERlR3hTZWtVMF\"),\n\t// \t}},\n\t// }\n}", "func (e *BcsDataManager) GetClusterListByProject(ctx context.Context, req *bcsdatamanager.GetClusterListRequest,\n\trsp *bcsdatamanager.GetClusterListResponse) error {\n\tblog.Infof(\"Received GetClusterListByProject.Call request. Project id: %s, dimension:%s, page:%s, size:%s, \"+\n\t\t\"startTime=%s, endTime=%s\",\n\t\treq.GetProject(), req.GetDimension(), req.GetPage(), req.GetSize(), time.Unix(req.GetStartTime(), 0),\n\t\ttime.Unix(req.GetEndTime(), 0))\n\tstart := time.Now()\n\tif req.GetProject() == \"\" && req.GetBusiness() == \"\" && req.GetProjectCode() == \"\" {\n\t\trsp.Message = fmt.Sprintf(\"get cluster list info error, projectId, projectCode or businessID is required\")\n\t\trsp.Code = bcsCommon.AdditionErrorCode + 500\n\t\tblog.Errorf(rsp.Message)\n\t\tprom.ReportAPIRequestMetric(\"GetClusterListByProject\", \"grpc\", prom.StatusErr, start)\n\t\treturn nil\n\t}\n\tif req.GetProject() == \"\" && req.GetBusiness() == \"\" && req.GetProjectCode() != \"\" {\n\t\tproject, err := e.resourceGetter.GetProjectInfo(ctx, \"\", req.GetProjectCode(), nil)\n\t\tif err != nil {\n\t\t\trsp.Message = fmt.Sprintf(\"get project info err:%v\", err)\n\t\t\trsp.Code = bcsCommon.AdditionErrorCode + 500\n\t\t\tblog.Errorf(rsp.Message)\n\t\t\tprom.ReportAPIRequestMetric(\"GetClusterListByProject\", \"grpc\", prom.StatusErr, start)\n\t\t\treturn nil\n\t\t}\n\t\tif project == nil {\n\t\t\trsp.Message = fmt.Sprintf(\"cannot get project info by project code:%s\", req.GetProjectCode())\n\t\t\trsp.Code = bcsCommon.AdditionErrorCode + 500\n\t\t\tblog.Errorf(rsp.Message)\n\t\t\tprom.ReportAPIRequestMetric(\"GetProjectInfo\", \"grpc\", prom.StatusErr, start)\n\t\t\treturn nil\n\t\t}\n\t\treq.Project = project.ProjectID\n\t}\n\tresult, total, err := e.model.GetClusterInfoList(ctx, req)\n\tif err != nil {\n\t\trsp.Message = fmt.Sprintf(\"get cluster list info error: %v\", err)\n\t\trsp.Code = bcsCommon.AdditionErrorCode + 500\n\t\tblog.Errorf(rsp.Message)\n\t\tprom.ReportAPIRequestMetric(\"GetClusterListByProject\", \"grpc\", prom.StatusErr, start)\n\t\treturn nil\n\t}\n\trsp.Data = result\n\trsp.Message = bcsCommon.BcsSuccessStr\n\trsp.Code = bcsCommon.BcsSuccess\n\trsp.Total = uint32(total)\n\tprom.ReportAPIRequestMetric(\"GetClusterListByProject\", \"grpc\", prom.StatusOK, start)\n\treturn nil\n}", "func (p *FileInf) getPermissionsList(u *url.URL) error {\n\tq := u.Query()\n\tq.Set(\"pageSize\", \"100\")\n\tq.Set(\"fields\", \"kind,nextPageToken,permissions\")\n\tu.RawQuery = q.Encode()\n\tr := &RequestParams{\n\t\tMethod: \"GET\",\n\t\tAPIURL: u.String(),\n\t\tData: nil,\n\t\tAccesstoken: p.Accesstoken,\n\t\tDtime: 30,\n\t}\n\tp.reqAndGetRawResponse(r)\n\treturn nil\n}", "func GetAllClusterNode(client redigo.Conn, role string, choose string) ([]string, error) {\n\tret, err := client.Do(\"cluster\", \"nodes\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnodeList := ParseClusterNode(ret.([]byte))\n\tnodeListChoose := ClusterNodeChoose(nodeList, role)\n\n\tresult := make([]string, 0, len(nodeListChoose))\n\tfor _, ele := range nodeListChoose {\n\t\tif choose == \"id\" {\n\t\t\tresult = append(result, ele.Id)\n\t\t} else {\n\t\t\tresult = append(result, ele.Address)\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func random(cluster,n int) []int {\n\treturn rand.Perm(cluster)[:n]\n}", "func ExampleConnectedClusterClient_ListClusterUserCredential() {\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 := armhybridkubernetes.NewConnectedClusterClient(\"1bfbb5d0-917e-4346-9026-1d3b344417f5\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := client.ListClusterUserCredential(ctx,\n\t\t\"k8sc-rg\",\n\t\t\"testCluster\",\n\t\tarmhybridkubernetes.ListClusterUserCredentialProperties{\n\t\t\tAuthenticationMethod: to.Ptr(armhybridkubernetes.AuthenticationMethodAAD),\n\t\t\tClientProxy: to.Ptr(false),\n\t\t},\n\t\tnil)\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 (p *ThriftHiveMetastoreClient) ListPrivileges(ctx context.Context, principal_name string, principal_type PrincipalType, hiveObject *HiveObjectRef) (r []*HiveObjectPrivilege, err error) {\n var _args132 ThriftHiveMetastoreListPrivilegesArgs\n _args132.PrincipalName = principal_name\n _args132.PrincipalType = principal_type\n _args132.HiveObject = hiveObject\n var _result133 ThriftHiveMetastoreListPrivilegesResult\n if err = p.Client_().Call(ctx, \"list_privileges\", &_args132, &_result133); err != nil {\n return\n }\n switch {\n case _result133.O1!= nil:\n return r, _result133.O1\n }\n\n return _result133.GetSuccess(), nil\n}", "func (c starterClusterServiceOp) List(ctx context.Context) (*[]models.Cluster, *Response, error) {\n\tvar clusterList []models.Cluster\n\tgraphqlRequest := models.GraphqlRequest{\n\t\tName: \"clusters\",\n\t\tOperation: models.Query,\n\t\tInput: clusterList,\n\t\tArgs: models.ClusterListInput{\n\t\t\tProductType: models.Starter,\n\t\t},\n\t\tResponse: clusterList,\n\t}\n\treq, err := c.client.NewRequest(&graphqlRequest)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresp, err := c.client.Do(ctx, req, &clusterList)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn &clusterList, resp, err\n}", "func GetAllAdminPermission() (v []AdminPermission, err error) {\n\to := orm.NewOrm()\n\tv = []AdminPermission{}\n\t_, err = o.QueryTable(new(AdminPermission)).RelatedSel().All(&v)\n\tfmt.Println(v)\n\treturn v, err\n}", "func (c *V1) GetPermissions(path string, username *string) (\n\tread, list bool,\n\tpossibleRead, possibleList bool,\n\trealm string, err error) {\n\tif err = c.EnsureInit(); err != nil {\n\t\treturn false, false, false, false, \"\", err\n\t}\n\n\tperms, maxPerms, realm := c.perPathConfigsReader.getPermissions(path, username)\n\treturn perms.read, perms.list, maxPerms.read, maxPerms.list, realm, nil\n}", "func (e *SyncedEnforcer) GetPermissionsForUser(user string) [][]string {\n\te.m.RLock()\n\tdefer e.m.RUnlock()\n\treturn e.Enforcer.GetPermissionsForUser(user)\n}", "func rgwGetGCTaskList(config string, user string) ([]byte, error) {\n\tvar (\n\t\tout []byte\n\t\terr error\n\t)\n\n\tif out, err = exec.Command(radosgwAdminPath, \"-c\", config, \"--user\", user, \"gc\", \"list\", \"--include-all\").Output(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn out, nil\n}", "func (this *managerStruct) Permissions(name string) ([]string, error) {\n\tthis.mutex.RLock()\n\tid := this.getUserId(name)\n\n\t/*\n\t * Check if we have a user with the name provided to us.\n\t */\n\tif id < 0 {\n\t\tthis.mutex.RUnlock()\n\t\treturn nil, fmt.Errorf(\"User '%s' does not exist.\", name)\n\t} else {\n\t\tusers := this.users\n\t\tuser := users[id]\n\t\tpermissions := user.permissions\n\t\tnumPermissions := len(permissions)\n\t\tpermissionsCopy := make([]string, numPermissions)\n\t\tcopy(permissionsCopy, permissions)\n\t\tthis.mutex.RUnlock()\n\t\treturn permissionsCopy, nil\n\t}\n\n}", "func (m *User) GetOauth2PermissionGrants()([]OAuth2PermissionGrantable) {\n return m.oauth2PermissionGrants\n}", "func ExampleConnectedClusterClient_ListClusterUserCredential_listClusterUserCredentialNonAadCspExample() {\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\tclientFactory, err := armhybridkubernetes.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewConnectedClusterClient().ListClusterUserCredential(ctx, \"k8sc-rg\", \"testCluster\", armhybridkubernetes.ListClusterUserCredentialProperties{\n\t\tAuthenticationMethod: to.Ptr(armhybridkubernetes.AuthenticationMethodToken),\n\t\tClientProxy: to.Ptr(false),\n\t}, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.CredentialResults = armhybridkubernetes.CredentialResults{\n\t// \tKubeconfigs: []*armhybridkubernetes.CredentialResult{\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"credentialName1\"),\n\t// \t\t\tValue: []byte(\"YXBpVmVyc2lvbjogdjEKY2x1c3RlcnM6CiAgLSBjbHVzdGVyOgogICAgICBjZXJ0aWZpY2F0ZS1hdXRob3JpdHktZGF0YTogTFMwdExTMUNSVWRKVGlCRFJWSlVTVVpKUTBGVVJTMHRMUzB0Q2sxSlNVaDJWRU5EUW1GWFowRjNTVUpCWjBsVVlYZEJRVUV5VkhWQlRYaEJhVWx5UldsQlFVRkJRVUZFV2tSQlRrSm5hM0ZvYTJsSE9YY3dRa0ZSYzBaQlJFSlFUVkZ6ZDBOUldVUldVVkZIUlhkS1ZsVjZSV1ZOUW5kSFFURlZSVU5vVFZaVVYyeHFZMjA1ZW1JeVdqQkpSVTUyWTI1Q2RtTnRSakJoVnpsMVRWTkJkMGhuV1VSV1VWRkVSWGhrVG1GWFRubGlNMDUyV201UloxVnNUa0pKUmxKTlZYbENSRkZUUVhkTlZFRmxSbmN3ZVUxRVFUUk5hbU40VFdwTmVFNVVXbUZHZHpCNVRWUkJORTFxWTNoTmFrMTRUbFJhWVUxRFdYaEtSRUZwUW1kT1ZrSkJUVTFIZVc5MVlYcG9lbGt5T1hWaWJWWnFaRU0xTUZwWVRqQk1iVVkyWkZoS2JFeHRUblppVkVORFFWTkpkMFJSV1VwTGIxcEphSFpqVGtGUlJVSkNVVUZFWjJkRlVFRkVRME5CVVc5RFoyZEZRa0ZOU0VwVU0wZEtXbWhMTm5KaVVHSm9XRWN6V21SU05HVlhNSGhSVmxVclIwTjVXSEFyY0VwRFNtUjBhbGgyTjNwMFEzTnJRV0ZaZDJobmQyMHpOMGhFVkVWamNFVlFjR1p6TDJSSFdsQktiek5vU0ZOemVGaENUMUJXYUVsVVRHZFBSa1E0YW5BMVlWZG1kVXA0WWsxUFNqZ3dObWxST0VkT1NVdEZURGM1ZDFkMVNWcG5MemhCWTBZeVNEWnJTMDlWVVhJdmVFMWFjVWx1WW5sQk1XVmhPVW8xTmpKbVNVODRUbEp2YWxORVRFUlBWRzFyWTFaYVdHcHlTaTlsYW1wclVVMUhiV0YyT1hreE9EQjJUVkZ5TTBjM2FXZ3Jkell2VFZocGVWWkpLMGxhY3pSaGVXVTJhREo0VDA5VlNYQnRWVTQ0UlhVNWIwY3ZTSGRHV2swemJHWnBkR0ZQZUhsblEydHBNV2R0VFRsd09FcHhNMVIyVVRSbU9YSnBRVWRUVFhaWWVsSlpTa2hOU2toVVRtZFZhV1pZVjFWb1VFWTJWMkZGTWxwbFdVWkdOV1ozU0U5MlVYRnFSa2tyUlZWS1JscE1kekJEUVhkRlFVRmhUME5CTjJ0M1oyZFBNVTFKU1VKQmQxbExTM2RaUWtKQlNGZGxVVWxGUVdkVFFqbEJVMEk0VVVSMlFVaFZRVGxzZVZWTU9VWXpUVU5KVlZaQ1owbE5TbEpYYW5WT1RrVjRhM3AyT1RoTlRIbEJUSHBGTjNoYVQwMUJRVUZHTUV3dlFuTjNRVUZCUWtGTlFWSnFRa1ZCYVVJMFpWSlVTMHhZY1hsM09HazFMeTlyVmtaNWNrTlhZMFZtY0VaV2NGUlZSVFIzYlVNME1rZHhSMkpCU1dkTkswVllkRWhtV0Rrd05WVklZall3Y1hKUlEzUTRibkZhTkUxamRVUjNOMlJaZVhwdGJFc3pja05SUVdSblFtTXpSVTlUTDNWaGNsSlZVM2hZY0hKVlZuVlpVVTR2ZGxZcmEyWmpiMWhQVlhOc04yMDVjMk5QZVdkQlFVRllVWFk0UjNwd1FVRkJSVUYzUWtoTlJWVkRTVVZZYTFwcWMyOUNVamhWZEc5blQwbFhWeXQyVTFOQ2NWcEViRGxIVEVRME1uWXdNR0ZXTkRVMVF6RkJhVVZCZDI1aE4zaDVWRUZJUTBJemNqVTBSSG93WnpKMVJHWktNa2ROUVdod2RuRnJiSGN5YXpka1VrMVdZM2RLZDFsS1MzZFpRa0pCUjBOT2VGVkxRa0p2ZDBkRVFVdENaMmR5UW1kRlJrSlJZMFJCVkVGTFFtZG5ja0puUlVaQ1VXTkVRV3BCSzBKbmEzSkNaMFZGUVZsSk0wWlJZMFZOVkVGMlFtbGpja0puUlVWQldVa3pSbEZwU0RKdldqRm5LemRhUVZsTVNtaFNkVUowV2pWb2FHWlVjbGxKUm1Sb1dXRlBVVmxtUTIxR1FVTkJWMUZEUVZOVmQyZFpZMGREUTNOSFFWRlZSa0ozUlVKQ1NITjNaVlJDVkVKblozSkNaMFZHUWxGamQwRnZXa2hoU0ZJd1kwUnZka3d6WkROa2VUVjBZVmRPZVdJelRuWmFibEYxV1RJNWRFd3pRbkpoVXpsMFl6Sk9kbU51UVhaVVYyeHFZMjA1ZW1JeVdqQktWRWwzVld4T1FrcFVTWGRXUlhoVVNsUkpkMUV3Uld4TmFrRjNUVk0xYW1OdVVYZEpaMWxKUzNkWlFrSlJWVWhOUVVkSFJtMW9NR1JJUVRaTWVUbDJXVE5PZDB4dE1YcGlNazU2WTBNMWFtSXlNSGRJVVZsRVZsSXdUMEpDV1VWR1N6ZFZhQ3M1WkdnNUwxRjFZM0ZKTlVFNVJHc3djMlpzTTFsVFRVRnpSMEV4VldSRWQxRkZRWGRKUlhORVFrSkNaMDVXU0ZKRlJVOXFRVFJuYUhOeFRHMXpOR015VG5aaWJUVnNXVE5SZFdSSFZucGtRelZvWlc1V2VWcFROV3BpTWpKRFIxZHpOR015VG5aaWJUVnNXVE5SZFdSSFZucGtRelZvWlc1V2VWcFROV3BpTWpCM1oySkJSMEV4VldSSWQxTkNjVVJEUW5CVVEwSnZjVU5DYmpaRFFtNUpXazVoU0ZJd1kwUnZka3d5TVhwWk0wcHpURzB4Y0ZrelNuWmpNamx0WkVNMWFtSXlNSFpqUjNSd1RESXhlbGt5T1hsalF6bHFZMjEzZGxSWGJHcGpiVGw2WWpKYU1FcFVTWGRWYkU1Q1NsUkpkMVpGZUZSS1ZFbDNVVEJGYkUxcVFYZE5VelZxWTIxNVIxTXlhREJrU0VFMlRIazVhbU50ZDNWaVYyeHFZMjA1ZW1JeVdqQk1iVTUyWWxNNWQyRXlhM1ppV0U1cVlqTktkMHd5VG5saVF6bE9ZVmRPZVdJelRuWmFibEZzVFdwQ1UxVXdSV3hOYWtKVlZFWk5iRTFxUWtSUlUxVjVUVVJCZUV4dFRubGlSRUpZUW1kT1ZraFRRVVZWUkVKUFRVVkpSME5UYzBkQlVWRkNaMnBqY1VGVVFURk5SRTFIUTBOelIwRlJWVVpDZDBsQ1JtbGtiMlJJVW5kUGFUaDJaRE5rTTB4dE1YQlpNMHAyWXpJNWJXUkROV3BpTWpCMlkwZDBjRXd5TVhwWk1qbDVZME01YW1OSVRYZERRVmxIV2pSRlRVRlJTVUpOUWpoSFFURlZaRWwzVVZsTlFtRkJSa3hXTWtSRVFWSjZjMlZUVVdzeFRYZ3hkM041UzJ0Tk5rRjBhMDFDTUVkQk1WVmtTbEZSVjAxQ1VVZERRM05IUVZGVlJrSjNUVUpDWjJkeVFtZEZSa0pSWTBSQmFrRk9RbWRyY1docmFVYzVkekJDUVZGelJrRkJUME5CWjBWQlJWZHRUVmRzWjJ3NGQzSlRUWHBQTW1Ob1pVbHZhbkZRVjBNd2FVVlVkSGRZYVVreWRqVmtWVkV5ZG01eWMydFVZM1ZzV1ZJNFExSllRemxXY0hWTU5YZDJUbEJaWlVzNWFtRjRhRXhGZW14YUt6aENTaTlhSzA5Q1NsRlBiV0k0VDIxRkwzcEVha1o1WVU5WWIzUXZNMEl3ZG5CcE9FWk1NalZNUkhGbGVuZExSeXN5VHpSVVJWQkhha1pGTmxONVRqWmlVR2d5ZG1Vck4wSTJLemQwVWpWeWVEZEtlU3RVY2pGcE9XdDBkV1p6UVhGWk5HSmtaMmd4Y2xWTGFsSkZVemRLVjNWek9HZDNVWG80YmtkSGMzaEhXbVJuU25oYVpISlJjVlZJUzNFMFlWcDJVVEZtWmtrM1RUbHVXWGhOVFM5VFNURkRlbTkxWkd0NmFHVnFSRXgzYW5vdk5UZHRaR04xYVdZck56TkpUbUZDVG5KRFprRXljemM1T1hwV1lVeDNkbXBMTlhRcmEwOVNSelI0TkZoWVpTdFphelZhV2pWQlkyMUZVa05NWnpSTGJHVkpiRFJJY3pSeGRYSkxhbGMxTjI1SFRYTnhLMHBXVGpBd2FFWXhXR1pETkZCVlpYbFJObFJPTUcxNlVGRXhia2RaZENzcmJVSTFWV053TURkWVRuVnpWR1JoTW05SGF6SlNOak5PVWsxWWIzcHRTbkYxVnlzNGRFVlVMMUJLUzNGUGFrVlNRalJXZHpOQ1IwUnZWRTVYVTNwb1dIbDRTVlp0TVhOT1dUSkJUVlpYYUdOYVkzRXpPVWRYVUc5UVp6RXpSbW80VDFsc2NFRm1SR1o2YURGaWRYWkdVbVpwVFZVME1sbHROa3c1YlROVVMwUjRlVXdyTWxKVmVESlNNbUo1VUZWTVQyVXdSMnd4T1hKelUyWlpjeTlvYjNkb1dWSnNXWEp1T0dKYVJFTkhiRFUzTDFGTWVHcEJXWFJVVWtZdlZFaHZLM1JOYTJSVmFTOWhUV2xVU0hoMlltcGtZeTlsYWxocVVISjRTbUp5UzFCVU1tUkVXRVk0ZG5aRGQzZGFRazAwUjFGWlNGaDViRFV6VTB4cU1VdHJRMjlvVlZKTkwzcDBlVEZpVTJOWWRIcE5aMDFJVmpWUFRYVkthVVZYVVhKV1NpOUhWRzlNVGxsUVNHMWxORXROY21jOUNpMHRMUzB0UlU1RUlFTkZVbFJKUmtsRFFWUkZMUzB0TFMwPQogICAgICBzZXJ2ZXI6IGh0dHBzOi8vYTljNDMzYzMtNjhlMS00NTY2LWI2MzMtODM0NzUyOWYzNjIwLms4c2Nvbm5lY3QudGVzdC5henVyZS5jb20KICAgIG5hbWU6IGNsdXN0ZXIKY29udGV4dHM6CiAgLSBjb250ZXh0OgogICAgICBjbHVzdGVyOiBjbHVzdGVyCiAgICAgIHVzZXI6IGNsdXN0ZXJVc2VyX3Rlc3RfY2x1c3RlcgogICAgbmFtZTogY2x1c3RlcgpjdXJyZW50LWNvbnRleHQ6IGNsdXN0ZXIKa2luZDogQ29uZmlnCnByZWZlcmVuY2VzOiBudWxsCnVzZXJzOgogIC0gbmFtZTogY2x1c3RlclVzZXJfdGVzdF9jbHVzdGVyCiAgICB1c2VyOgogICAgICB0b2tlbjogMmM2NGZyMmQ2MWRhZmZkODY4NGJkYTc3M2Y2YTQ3OGUxZTU4NzlhZTE1ZmRkM2Q1NDU4NGNkNTM1MGM2YWUxMzlhMGI3OTk4YTc2ZjFhOTdlOGI3Y2EwNTJiYjIwZWY0ZjljZTAzN2Q5YTMyM2ZjMTYxZmI0MGI4OTVlOWIwZjM=\"),\n\t// \t}},\n\t// }\n}", "func (d *portworx) GetClusterOpts(n node.Node, options []string) (map[string]string, error) {\n\topts := node.ConnectionOpts{\n\t\tIgnoreError: false,\n\t\tTimeBeforeRetry: defaultRetryInterval,\n\t\tTimeout: defaultTimeout,\n\t}\n\tcmd := fmt.Sprintf(\"%s cluster options list -j json\", d.getPxctlPath(n))\n\tout, err := d.nodeDriver.RunCommand(n, cmd, opts)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get pxctl cluster options on node [%s], Err: %v\", n.Name, err)\n\t}\n\tvar data = map[string]interface{}{}\n\terr = json.Unmarshal([]byte(out), &data)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal pxctl cluster option on node [%s], Err: %v\", n.Name, err)\n\t}\n\tsort.Strings(options)\n\tvar options_map = make(map[string]string)\n\t//Values can be string, array or map\n\tfor key, val := range data {\n\t\tindex := sort.SearchStrings(options, key)\n\t\tif index < len(options) && options[index] == key {\n\t\t\toptions_map[key] = fmt.Sprint(val)\n\t\t}\n\t}\n\t//Make sure required options are available\n\tfor _, option := range options {\n\t\tif _, ok := options_map[option]; !ok {\n\t\t\treturn nil, fmt.Errorf(\"Failed to find option: %v\", option)\n\t\t}\n\t}\n\treturn options_map, nil\n}", "func (*OktetoClusterHelper) List() (map[string]string, error) {\n\treturn nil, ErrNotImplemented\n}", "func (r *V1Alpha1PermissionManagerUser) List() ([]User, error) {\n\t//noinspection GoPreferNilSlice\n\tusers := []User{}\n\n\trawResponse, err := r.kubeclient.Discovery().RESTClient().Get().AbsPath(v1alpha1.ResourceURL).DoRaw(r.context)\n\n\tif err != nil {\n\t\tlog.Print(\"Failed to get users from k8s CRUD api\", err)\n\t\treturn []User{}, err\n\t}\n\n\t// generated from the api-server JSON response, most of the fields are not used but useful as documentation\n\tvar getAllUserResponse v1alpha1.PermissionManagerUserList\n\terr = json.Unmarshal(rawResponse, &getAllUserResponse)\n\n\tif err != nil {\n\t\tlog.Print(\"Failed to decode users from k8s CRUD api\", err)\n\t\treturn []User{}, err\n\t}\n\n\tfor _, v := range getAllUserResponse.Items {\n\t\tusers = append(users, User{Name: v.Spec.Name})\n\t}\n\n\treturn users, nil\n}", "func (a *HyperflexApiService) GetHyperflexClusterProfileList(ctx context.Context) ApiGetHyperflexClusterProfileListRequest {\n\treturn ApiGetHyperflexClusterProfileListRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (core *Plugin) listAdmins(c cmd.Context) (string, slack.PostMessageParameters) {\n\tnoParams := slack.PostMessageParameters{}\n\tmembers := model.Members{}\n\tif err := core.Bot.DAL.GetAdmins(&members); err != nil {\n\t\tlog.WithError(err).Error(\"failed to get admins\")\n\t\treturn \"Failed to get admins\", noParams\n\t}\n\tnames := \"\"\n\tfor _, member := range members {\n\t\tnames += member.Name + \"\\n\"\n\t}\n\treturn names, noParams\n}", "func (api *clusterAPI) List(ctx context.Context, opts *api.ListWatchOptions) ([]*Cluster, error) {\n\tvar objlist []*Cluster\n\tobjs, err := api.ct.List(\"Cluster\", ctx, opts)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, obj := range objs {\n\t\tswitch tp := obj.(type) {\n\t\tcase *Cluster:\n\t\t\teobj := obj.(*Cluster)\n\t\t\tobjlist = append(objlist, eobj)\n\t\tdefault:\n\t\t\tlog.Fatalf(\"Got invalid object type %v while looking for Cluster\", tp)\n\t\t}\n\t}\n\n\treturn objlist, nil\n}", "func (m *RoleDefinition) GetRolePermissions()([]RolePermissionable) {\n return m.rolePermissions\n}", "func (adm Admin) ListClusters() (string, error) {\n\tvar clusters []string\n\n\tchildren, err := adm.zkClient.Children(\"/\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, cluster := range children {\n\t\tif ok, err := adm.isClusterSetup(cluster); ok && err == nil {\n\t\t\tclusters = append(clusters, cluster)\n\t\t}\n\t}\n\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"Existing clusters: \\n\")\n\n\tfor _, cluster := range clusters {\n\t\tbuffer.WriteString(\" \" + cluster + \"\\n\")\n\t}\n\treturn buffer.String(), nil\n}", "func (m *User) GetMemberOf()([]DirectoryObjectable) {\n return m.memberOf\n}", "func (*ListClusterOperationsRequest) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_mdb_greenplum_v1_cluster_service_proto_rawDescGZIP(), []int{13}\n}", "func (m *Manager) GetPermissions(ctx context.Context, params model.RequestParams) (int, interface{}, error) {\n\thookResponse := m.integrationMan.InvokeHook(ctx, params)\n\tif hookResponse.CheckResponse() {\n\t\tif err := hookResponse.Error(); err != nil {\n\t\t\treturn hookResponse.Status(), nil, err\n\t\t}\n\n\t\treturn hookResponse.Status(), hookResponse.Result(), nil\n\t}\n\n\treturn http.StatusOK, []interface{}{map[string]interface{}{\"project\": \"*\", \"resource\": \"*\", \"verb\": \"*\"}}, nil\n}", "func (n *Node) ReadUserPermissions(ctx context.Context, u *userpb.User) (ap provider.ResourcePermissions, err error) {\n\t// check if the current user is the owner\n\to, err := n.Owner()\n\tif err != nil {\n\t\t// TODO check if a parent folder has the owner set?\n\t\tappctx.GetLogger(ctx).Error().Err(err).Interface(\"node\", n).Msg(\"could not determine owner, returning default permissions\")\n\t\treturn NoPermissions(), err\n\t}\n\tif o.OpaqueId == \"\" {\n\t\t// this happens for root nodes in the storage. the extended attributes are set to emptystring to indicate: no owner\n\t\t// TODO what if no owner is set but grants are present?\n\t\treturn NoOwnerPermissions(), nil\n\t}\n\tif utils.UserEqual(u.Id, o) {\n\t\tappctx.GetLogger(ctx).Debug().Interface(\"node\", n).Msg(\"user is owner, returning owner permissions\")\n\t\treturn OwnerPermissions(), nil\n\t}\n\n\tap = provider.ResourcePermissions{}\n\n\t// for an efficient group lookup convert the list of groups to a map\n\t// groups are just strings ... groupnames ... or group ids ??? AAARGH !!!\n\tgroupsMap := make(map[string]bool, len(u.Groups))\n\tfor i := range u.Groups {\n\t\tgroupsMap[u.Groups[i]] = true\n\t}\n\n\tvar g *provider.Grant\n\n\t// we read all grantees from the node\n\tvar grantees []string\n\tif grantees, err = n.ListGrantees(ctx); err != nil {\n\t\tappctx.GetLogger(ctx).Error().Err(err).Interface(\"node\", n).Msg(\"error listing grantees\")\n\t\treturn NoPermissions(), err\n\t}\n\n\t// instead of making n getxattr syscalls we are going to list the acls and filter them here\n\t// we have two options here:\n\t// 1. we can start iterating over the acls / grants on the node or\n\t// 2. we can iterate over the number of groups\n\t// The current implementation tries to be defensive for cases where users have hundreds or thousands of groups, so we iterate over the existing acls.\n\tuserace := xattrs.GrantPrefix + xattrs.UserAcePrefix + u.Id.OpaqueId\n\tuserFound := false\n\tfor i := range grantees {\n\t\tswitch {\n\t\t// we only need to find the user once\n\t\tcase !userFound && grantees[i] == userace:\n\t\t\tg, err = n.ReadGrant(ctx, grantees[i])\n\t\tcase strings.HasPrefix(grantees[i], xattrs.GrantPrefix+xattrs.GroupAcePrefix): // only check group grantees\n\t\t\tgr := strings.TrimPrefix(grantees[i], xattrs.GrantPrefix+xattrs.GroupAcePrefix)\n\t\t\tif groupsMap[gr] {\n\t\t\t\tg, err = n.ReadGrant(ctx, grantees[i])\n\t\t\t} else {\n\t\t\t\t// no need to check attribute\n\t\t\t\tcontinue\n\t\t\t}\n\t\tdefault:\n\t\t\t// no need to check attribute\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch {\n\t\tcase err == nil:\n\t\t\tAddPermissions(&ap, g.GetPermissions())\n\t\tcase isAttrUnset(err):\n\t\t\terr = nil\n\t\t\tappctx.GetLogger(ctx).Error().Interface(\"node\", n).Str(\"grant\", grantees[i]).Interface(\"grantees\", grantees).Msg(\"grant vanished from node after listing\")\n\t\t\t// continue with next segment\n\t\tdefault:\n\t\t\tappctx.GetLogger(ctx).Error().Err(err).Interface(\"node\", n).Str(\"grant\", grantees[i]).Msg(\"error reading permissions\")\n\t\t\t// continue with next segment\n\t\t}\n\t}\n\n\tappctx.GetLogger(ctx).Debug().Interface(\"permissions\", ap).Interface(\"node\", n).Interface(\"user\", u).Msg(\"returning aggregated permissions\")\n\treturn ap, nil\n}", "func (adm Admin) ListClusters() (string, error) {\n\tconn := newConnection(adm.ZkSvr)\n\terr := conn.Connect()\n\tif err != nil {\n\t\tfmt.Println(\"Failed to connect to zookeeper.\")\n\t\treturn \"\", err\n\t}\n\tdefer conn.Disconnect()\n\n\tvar clusters []string\n\n\tchildren, err := conn.Children(\"/\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, cluster := range children {\n\t\tif ok, err := conn.IsClusterSetup(cluster); ok && err == nil {\n\t\t\tclusters = append(clusters, cluster)\n\t\t}\n\t}\n\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"Existing clusters: \\n\")\n\n\tfor _, cluster := range clusters {\n\t\tbuffer.WriteString(\" \" + cluster + \"\\n\")\n\t}\n\treturn buffer.String(), nil\n}", "func (w *WhoCan) getClusterRoleBindings(clusterRoleNames clusterRoles) (clusterRoleBindings []rbac.ClusterRoleBinding, err error) {\n\tctx := context.Background()\n\tlist, err := w.clientRBAC.ClusterRoleBindings().List(ctx, metav1.ListOptions{})\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, roleBinding := range list.Items {\n\t\tif _, ok := clusterRoleNames[roleBinding.RoleRef.Name]; ok {\n\t\t\tclusterRoleBindings = append(clusterRoleBindings, roleBinding)\n\t\t}\n\t}\n\n\treturn\n}", "func ListAllCluster(c echo.Context) error {\n\tcblog.Info(\"call ListAllCluster()\")\n\n\tvar req struct {\n\t\tNameSpace string\n\t\tConnectionName string\n\t}\n\n\tif err := c.Bind(&req); err != nil {\n\t\treturn echo.NewHTTPError(http.StatusInternalServerError, err.Error())\n\t}\n\n\t// To support for Get-Query Param Type API\n\tif req.ConnectionName == \"\" {\n\t\treq.ConnectionName = c.QueryParam(\"ConnectionName\")\n\t}\n\n\t// Call common-runtime API\n\tallResourceList, err := cmrt.ListAllResource(req.ConnectionName, rsCluster)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusInternalServerError, err.Error())\n\t}\n\n\t// To support for Get-Query Param Type API\n\tif req.NameSpace == \"\" {\n\t\treq.NameSpace = c.QueryParam(\"NameSpace\")\n\t}\n\n\t// Resource Name has namespace prefix when from Tumblebug\n\tif req.NameSpace != \"\" {\n\t\tnameSpace := req.NameSpace + \"-\"\n\t\tfor idx, IID := range allResourceList.AllList.MappedList {\n\t\t\tif IID.NameId != \"\" {\n\t\t\t\tallResourceList.AllList.MappedList[idx].NameId = strings.Replace(IID.NameId, nameSpace, \"\", 1)\n\t\t\t}\n\t\t}\n\t\tfor idx, IID := range allResourceList.AllList.OnlySpiderList {\n\t\t\tif IID.NameId != \"\" {\n\t\t\t\tallResourceList.AllList.OnlySpiderList[idx].NameId = strings.Replace(IID.NameId, nameSpace, \"\", 1)\n\t\t\t}\n\t\t}\n\t\tfor idx, IID := range allResourceList.AllList.OnlyCSPList {\n\t\t\tif IID.NameId != \"\" {\n\t\t\t\tallResourceList.AllList.OnlyCSPList[idx].NameId = strings.Replace(IID.NameId, nameSpace, \"\", 1)\n\t\t\t}\n\t\t}\n\t}\n\n\tvar jsonResult struct {\n\t\tConnection string\n\t\tAllResourceList *cmrt.AllResourceList\n\t}\n\tjsonResult.Connection = req.ConnectionName\n\tjsonResult.AllResourceList = &allResourceList\n\n\treturn c.JSON(http.StatusOK, &jsonResult)\n}", "func (m *publicUser) GetUserList(c *gin.Context) (int, interface{}) {\n\tuser := plugins.CurrentPlugin(c, m.config.LoginVersion)\n\tuserList, err := user.GetUserList(c, m.config.ConfigMap)\n\trspBody := metadata.LonginSystemUserListResult{}\n\tif nil != err {\n\t\trspBody.Code = common.CCErrCommHTTPDoRequestFailed\n\t\trspBody.ErrMsg = err.Error()\n\t\trspBody.Result = false\n\t}\n\trspBody.Result = true\n\trspBody.Data = userList\n\treturn 200, rspBody\n}", "func ExampleConnectedClusterClient_ListClusterUserCredential_listClusterUserCredentialNonAadExample() {\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\tclientFactory, err := armhybridkubernetes.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewConnectedClusterClient().ListClusterUserCredential(ctx, \"k8sc-rg\", \"testCluster\", armhybridkubernetes.ListClusterUserCredentialProperties{\n\t\tAuthenticationMethod: to.Ptr(armhybridkubernetes.AuthenticationMethodToken),\n\t\tClientProxy: to.Ptr(true),\n\t}, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.CredentialResults = armhybridkubernetes.CredentialResults{\n\t// \tHybridConnectionConfig: &armhybridkubernetes.HybridConnectionConfig{\n\t// \t\tExpirationTime: to.Ptr[int64](1631196183),\n\t// \t\tHybridConnectionName: to.Ptr(\"microsoft.kubernetes/connectedclusters/229dc73f7b07196c79a93d4362d9c7fc4ed34df3e95290d27c56cec2dbb82865/1631185383340987904\"),\n\t// \t\tRelay: to.Ptr(\"azgnrelay-ph0-l1\"),\n\t// \t\tToken: to.Ptr(\"SharedAccessSignature 123456789034675890pbduwegiavifkuw647o02423bbhfouseb\"),\n\t// \t},\n\t// \tKubeconfigs: []*armhybridkubernetes.CredentialResult{\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"credentialName1\"),\n\t// \t\t\tValue: []byte(\"YXBpVmVyc2lvbjogdjEKY2x1c3RlcnM6CiAgLSBjbHVzdGVyOgogICAgICBjZXJ0aWZpY2F0ZS1hdXRob3JpdHktZGF0YTogTFMwdExTMUNSVWRKVGlCRFJWSlVTVVpKUTBGVVJTMHRMUzB0Q2sxSlNVaDJWRU5EUW1GWFowRjNTVUpCWjBsVVlYZEJRVUV5VkhWQlRYaEJhVWx5UldsQlFVRkJRVUZFV2tSQlRrSm5hM0ZvYTJsSE9YY3dRa0ZSYzBaQlJFSlFUVkZ6ZDBOUldVUldVVkZIUlhkS1ZsVjZSV1ZOUW5kSFFURlZSVU5vVFZaVVYyeHFZMjA1ZW1JeVdqQkpSVTUyWTI1Q2RtTnRSakJoVnpsMVRWTkJkMGhuV1VSV1VWRkVSWGhrVG1GWFRubGlNMDUyV201UloxVnNUa0pKUmxKTlZYbENSRkZUUVhkTlZFRmxSbmN3ZVUxRVFUUk5hbU40VFdwTmVFNVVXbUZHZHpCNVRWUkJORTFxWTNoTmFrMTRUbFJhWVUxRFdYaEtSRUZwUW1kT1ZrSkJUVTFIZVc5MVlYcG9lbGt5T1hWaWJWWnFaRU0xTUZwWVRqQk1iVVkyWkZoS2JFeHRUblppVkVORFFWTkpkMFJSV1VwTGIxcEphSFpqVGtGUlJVSkNVVUZFWjJkRlVFRkVRME5CVVc5RFoyZEZRa0ZOU0VwVU0wZEtXbWhMTm5KaVVHSm9XRWN6V21SU05HVlhNSGhSVmxVclIwTjVXSEFyY0VwRFNtUjBhbGgyTjNwMFEzTnJRV0ZaZDJobmQyMHpOMGhFVkVWamNFVlFjR1p6TDJSSFdsQktiek5vU0ZOemVGaENUMUJXYUVsVVRHZFBSa1E0YW5BMVlWZG1kVXA0WWsxUFNqZ3dObWxST0VkT1NVdEZURGM1ZDFkMVNWcG5MemhCWTBZeVNEWnJTMDlWVVhJdmVFMWFjVWx1WW5sQk1XVmhPVW8xTmpKbVNVODRUbEp2YWxORVRFUlBWRzFyWTFaYVdHcHlTaTlsYW1wclVVMUhiV0YyT1hreE9EQjJUVkZ5TTBjM2FXZ3Jkell2VFZocGVWWkpLMGxhY3pSaGVXVTJhREo0VDA5VlNYQnRWVTQ0UlhVNWIwY3ZTSGRHV2swemJHWnBkR0ZQZUhsblEydHBNV2R0VFRsd09FcHhNMVIyVVRSbU9YSnBRVWRUVFhaWWVsSlpTa2hOU2toVVRtZFZhV1pZVjFWb1VFWTJWMkZGTWxwbFdVWkdOV1ozU0U5MlVYRnFSa2tyUlZWS1JscE1kekJEUVhkRlFVRmhUME5CTjJ0M1oyZFBNVTFKU1VKQmQxbExTM2RaUWtKQlNGZGxVVWxGUVdkVFFqbEJVMEk0VVVSMlFVaFZRVGxzZVZWTU9VWXpUVU5KVlZaQ1owbE5TbEpYYW5WT1RrVjRhM3AyT1RoTlRIbEJUSHBGTjNoYVQwMUJRVUZHTUV3dlFuTjNRVUZCUWtGTlFWSnFRa1ZCYVVJMFpWSlVTMHhZY1hsM09HazFMeTlyVmtaNWNrTlhZMFZtY0VaV2NGUlZSVFIzYlVNME1rZHhSMkpCU1dkTkswVllkRWhtV0Rrd05WVklZall3Y1hKUlEzUTRibkZhTkUxamRVUjNOMlJaZVhwdGJFc3pja05SUVdSblFtTXpSVTlUTDNWaGNsSlZVM2hZY0hKVlZuVlpVVTR2ZGxZcmEyWmpiMWhQVlhOc04yMDVjMk5QZVdkQlFVRllVWFk0UjNwd1FVRkJSVUYzUWtoTlJWVkRTVVZZYTFwcWMyOUNVamhWZEc5blQwbFhWeXQyVTFOQ2NWcEViRGxIVEVRME1uWXdNR0ZXTkRVMVF6RkJhVVZCZDI1aE4zaDVWRUZJUTBJemNqVTBSSG93WnpKMVJHWktNa2ROUVdod2RuRnJiSGN5YXpka1VrMVdZM2RLZDFsS1MzZFpRa0pCUjBOT2VGVkxRa0p2ZDBkRVFVdENaMmR5UW1kRlJrSlJZMFJCVkVGTFFtZG5ja0puUlVaQ1VXTkVRV3BCSzBKbmEzSkNaMFZGUVZsSk0wWlJZMFZOVkVGMlFtbGpja0puUlVWQldVa3pSbEZwU0RKdldqRm5LemRhUVZsTVNtaFNkVUowV2pWb2FHWlVjbGxKUm1Sb1dXRlBVVmxtUTIxR1FVTkJWMUZEUVZOVmQyZFpZMGREUTNOSFFWRlZSa0ozUlVKQ1NITjNaVlJDVkVKblozSkNaMFZHUWxGamQwRnZXa2hoU0ZJd1kwUnZka3d6WkROa2VUVjBZVmRPZVdJelRuWmFibEYxV1RJNWRFd3pRbkpoVXpsMFl6Sk9kbU51UVhaVVYyeHFZMjA1ZW1JeVdqQktWRWwzVld4T1FrcFVTWGRXUlhoVVNsUkpkMUV3Uld4TmFrRjNUVk0xYW1OdVVYZEpaMWxKUzNkWlFrSlJWVWhOUVVkSFJtMW9NR1JJUVRaTWVUbDJXVE5PZDB4dE1YcGlNazU2WTBNMWFtSXlNSGRJVVZsRVZsSXdUMEpDV1VWR1N6ZFZhQ3M1WkdnNUwxRjFZM0ZKTlVFNVJHc3djMlpzTTFsVFRVRnpSMEV4VldSRWQxRkZRWGRKUlhORVFrSkNaMDVXU0ZKRlJVOXFRVFJuYUhOeFRHMXpOR015VG5aaWJUVnNXVE5SZFdSSFZucGtRelZvWlc1V2VWcFROV3BpTWpKRFIxZHpOR015VG5aaWJUVnNXVE5SZFdSSFZucGtRelZvWlc1V2VWcFROV3BpTWpCM1oySkJSMEV4VldSSWQxTkNjVVJEUW5CVVEwSnZjVU5DYmpaRFFtNUpXazVoU0ZJd1kwUnZka3d5TVhwWk0wcHpURzB4Y0ZrelNuWmpNamx0WkVNMWFtSXlNSFpqUjNSd1RESXhlbGt5T1hsalF6bHFZMjEzZGxSWGJHcGpiVGw2WWpKYU1FcFVTWGRWYkU1Q1NsUkpkMVpGZUZSS1ZFbDNVVEJGYkUxcVFYZE5VelZxWTIxNVIxTXlhREJrU0VFMlRIazVhbU50ZDNWaVYyeHFZMjA1ZW1JeVdqQk1iVTUyWWxNNWQyRXlhM1ppV0U1cVlqTktkMHd5VG5saVF6bE9ZVmRPZVdJelRuWmFibEZzVFdwQ1UxVXdSV3hOYWtKVlZFWk5iRTFxUWtSUlUxVjVUVVJCZUV4dFRubGlSRUpZUW1kT1ZraFRRVVZWUkVKUFRVVkpSME5UYzBkQlVWRkNaMnBqY1VGVVFURk5SRTFIUTBOelIwRlJWVVpDZDBsQ1JtbGtiMlJJVW5kUGFUaDJaRE5rTTB4dE1YQlpNMHAyWXpJNWJXUkROV3BpTWpCMlkwZDBjRXd5TVhwWk1qbDVZME01YW1OSVRYZERRVmxIV2pSRlRVRlJTVUpOUWpoSFFURlZaRWwzVVZsTlFtRkJSa3hXTWtSRVFWSjZjMlZUVVdzeFRYZ3hkM041UzJ0Tk5rRjBhMDFDTUVkQk1WVmtTbEZSVjAxQ1VVZERRM05IUVZGVlJrSjNUVUpDWjJkeVFtZEZSa0pSWTBSQmFrRk9RbWRyY1docmFVYzVkekJDUVZGelJrRkJUME5CWjBWQlJWZHRUVmRzWjJ3NGQzSlRUWHBQTW1Ob1pVbHZhbkZRVjBNd2FVVlVkSGRZYVVreWRqVmtWVkV5ZG01eWMydFVZM1ZzV1ZJNFExSllRemxXY0hWTU5YZDJUbEJaWlVzNWFtRjRhRXhGZW14YUt6aENTaTlhSzA5Q1NsRlBiV0k0VDIxRkwzcEVha1o1WVU5WWIzUXZNMEl3ZG5CcE9FWk1NalZNUkhGbGVuZExSeXN5VHpSVVJWQkhha1pGTmxONVRqWmlVR2d5ZG1Vck4wSTJLemQwVWpWeWVEZEtlU3RVY2pGcE9XdDBkV1p6UVhGWk5HSmtaMmd4Y2xWTGFsSkZVemRLVjNWek9HZDNVWG80YmtkSGMzaEhXbVJuU25oYVpISlJjVlZJUzNFMFlWcDJVVEZtWmtrM1RUbHVXWGhOVFM5VFNURkRlbTkxWkd0NmFHVnFSRXgzYW5vdk5UZHRaR04xYVdZck56TkpUbUZDVG5KRFprRXljemM1T1hwV1lVeDNkbXBMTlhRcmEwOVNSelI0TkZoWVpTdFphelZhV2pWQlkyMUZVa05NWnpSTGJHVkpiRFJJY3pSeGRYSkxhbGMxTjI1SFRYTnhLMHBXVGpBd2FFWXhXR1pETkZCVlpYbFJObFJPTUcxNlVGRXhia2RaZENzcmJVSTFWV053TURkWVRuVnpWR1JoTW05SGF6SlNOak5PVWsxWWIzcHRTbkYxVnlzNGRFVlVMMUJLUzNGUGFrVlNRalJXZHpOQ1IwUnZWRTVYVTNwb1dIbDRTVlp0TVhOT1dUSkJUVlpYYUdOYVkzRXpPVWRYVUc5UVp6RXpSbW80VDFsc2NFRm1SR1o2YURGaWRYWkdVbVpwVFZVME1sbHROa3c1YlROVVMwUjRlVXdyTWxKVmVESlNNbUo1VUZWTVQyVXdSMnd4T1hKelUyWlpjeTlvYjNkb1dWSnNXWEp1T0dKYVJFTkhiRFUzTDFGTWVHcEJXWFJVVWtZdlZFaHZLM1JOYTJSVmFTOWhUV2xVU0hoMlltcGtZeTlsYWxocVVISjRTbUp5UzFCVU1tUkVXRVk0ZG5aRGQzZGFRazAwUjFGWlNGaDViRFV6VTB4cU1VdHJRMjlvVlZKTkwzcDBlVEZpVTJOWWRIcE5aMDFJVmpWUFRYVkthVVZYVVhKV1NpOUhWRzlNVGxsUVNHMWxORXROY21jOUNpMHRMUzB0UlU1RUlFTkZVbFJKUmtsRFFWUkZMUzB0TFMwPQogICAgICBzZXJ2ZXI6IGh0dHBzOi8vYTljNDMzYzMtNjhlMS00NTY2LWI2MzMtODM0NzUyOWYzNjIwLms4c2Nvbm5lY3QudGVzdC5henVyZS5jb20KICAgIG5hbWU6IGNsdXN0ZXIKY29udGV4dHM6CiAgLSBjb250ZXh0OgogICAgICBjbHVzdGVyOiBjbHVzdGVyCiAgICAgIHVzZXI6IGNsdXN0ZXJVc2VyX3Rlc3RfY2x1c3RlcgogICAgbmFtZTogY2x1c3RlcgpjdXJyZW50LWNvbnRleHQ6IGNsdXN0ZXIKa2luZDogQ29uZmlnCnByZWZlcmVuY2VzOiBudWxsCnVzZXJzOgogIC0gbmFtZTogY2x1c3RlclVzZXJfdGVzdF9jbHVzdGVyCiAgICB1c2VyOgogICAgICB0b2tlbjogMmM2NGZyMmQ2MWRhZmZkODY4NGJkYTc3M2Y2YTQ3OGUxZTU4NzlhZTE1ZmRkM2Q1NDU4NGNkNTM1MGM2YWUxMzlhMGI3OTk4YTc2ZjFhOTdlOGI3Y2EwNTJiYjIwZWY0ZjljZTAzN2Q5YTMyM2ZjMTYxZmI0MGI4OTVlOWIwZjM=\"),\n\t// \t}},\n\t// }\n}", "func getAllWorkerClusterServiceAccountSecretTokens(ctx context.Context, clientSetMap map[string]kubernetes.Interface, flags flags) (map[string]corev1.Secret, error) {\n\tallSecrets := map[string]corev1.Secret{}\n\n\tfor _, cluster := range flags.memberClusters {\n\t\tc := clientSetMap[cluster]\n\t\tsas, err := getServiceAccounts(ctx, c, flags.memberClusterNamespace)\n\t\tif err != nil {\n\t\t\treturn nil, xerrors.Errorf(\"failed getting service accounts: %w\", err)\n\t\t}\n\n\t\tfor _, sa := range sas {\n\t\t\tif sa.Name == flags.serviceAccount {\n\t\t\t\ttoken, err := getServiceAccountToken(ctx, c, sa)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, xerrors.Errorf(\"failed getting service account token: %w\", err)\n\t\t\t\t}\n\t\t\t\tallSecrets[cluster] = *token\n\t\t\t}\n\t\t}\n\t}\n\treturn allSecrets, nil\n}", "func GetManegementCluster(version, capiImage, capdImage string) ([]runtime.Object, error) {\n\tcapiObjects, err := GetCAPI(version, capiImage)\n\tif err != nil {\n\t\treturn []runtime.Object{}, err\n\t}\n\n\tnamespaceObj := GetNamespace()\n\tstatefulSet := GetStatefulSet(capdImage)\n\tclusterRole := GetClusterRole()\n\tclusterRoleBinding := GetClusterRoleBinding()\n\n\treturn append(capiObjects,\n\t\t&namespaceObj,\n\t\t&statefulSet,\n\t\t&clusterRole,\n\t\t&clusterRoleBinding,\n\t), nil\n}", "func GetAllPermissions(c *gin.Context) {\r\n\trole := model.Role{}\r\n\tmenus, err := role.GetMenus()\r\n\tif err != nil {\r\n\t\tutils.InternalError(c, nil, \"数据库操作失败\")\r\n\t\treturn\r\n\t}\r\n\tpermissions, err := role.GetPermissions()\r\n\tif err != nil {\r\n\t\tutils.InternalError(c, nil, \"数据库操作失败\")\r\n\t\treturn\r\n\t}\r\n\tutils.Success(c, gin.H{\"menus\": menus, \"permissions\": permissions}, \"权限查询成功\")\r\n}", "func (m *Manager) GetClusterList() ([]Cluster, error) {\n\tnames, err := m.specManager.List()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar clusters = []Cluster{}\n\n\tfor _, name := range names {\n\t\tmetadata, err := m.meta(name)\n\t\tif err != nil && !errors.Is(perrs.Cause(err), meta.ErrValidate) &&\n\t\t\t!errors.Is(perrs.Cause(err), spec.ErrNoTiSparkMaster) {\n\t\t\treturn nil, perrs.Trace(err)\n\t\t}\n\n\t\tbase := metadata.GetBaseMeta()\n\n\t\tclusters = append(clusters, Cluster{\n\t\t\tName: name,\n\t\t\tUser: base.User,\n\t\t\tVersion: base.Version,\n\t\t\tPath: m.specManager.Path(name),\n\t\t\tPrivateKey: m.specManager.Path(name, \"ssh\", \"id_rsa\"),\n\t\t})\n\t}\n\n\treturn clusters, nil\n}", "func (o *os) GetGrantedPermissions() gdnative.PoolStringArray {\n\to.ensureSingleton()\n\t//log.Println(\"Calling _OS.GetGrantedPermissions()\")\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_granted_permissions\")\n\n\t// Call the parent method.\n\t// PoolStringArray\n\tretPtr := gdnative.NewEmptyPoolStringArray()\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.NewPoolStringArrayFromPointer(retPtr)\n\treturn ret\n}", "func (c *Client) GetClusterServiceVersionList() (*olm.ClusterServiceVersionList, error) {\n\tklog.V(4).Infof(\"Fetching list of operators installed in cluster\")\n\tcsvs, err := c.OperatorClient.ClusterServiceVersions(c.Namespace).List(v1.ListOptions{})\n\tif err != nil {\n\t\treturn &olm.ClusterServiceVersionList{}, err\n\t}\n\treturn csvs, nil\n}", "func GetCmdListPermissions(queryRoute string, cdc *codec.Codec) *cobra.Command {\n\treturn &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"list\",\n\t\t// Args: cobra.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tcliCtx := context.NewCLIContext().WithCodec(cdc)\n\n\t\t\tfullQueryRoute := fmt.Sprintf(\"custom/%s/%s\", queryRoute, types.QueryPermissionList)\n\t\t\tres, _, err := cliCtx.QueryWithData(fullQueryRoute, nil)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"could not get query permission list full route is %s - error is %v\\n \", fullQueryRoute, err)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tvar out types.QueryResPermissions\n\t\t\tcdc.MustUnmarshalJSON(res, &out)\n\t\t\treturn cliCtx.PrintOutput(out)\n\t\t},\n\t}\n}", "func List(ctx context.Context, client *v1.ServiceClient, clusterID string) ([]*View, *v1.ResponseResult, error) {\n\turl := strings.Join([]string{client.Endpoint, v1.ResourceURLCluster, clusterID, v1.ResourceURLNodegroup}, \"/\")\n\tresponseResult, err := client.DoRequest(ctx, http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif responseResult.Err != nil {\n\t\treturn nil, responseResult, responseResult.Err\n\t}\n\n\t// Extract nodegroups from the response body.\n\tvar result struct {\n\t\tNodegroups []*View `json:\"nodegroups\"`\n\t}\n\terr = responseResult.ExtractResult(&result)\n\tif err != nil {\n\t\treturn nil, responseResult, err\n\t}\n\n\treturn result.Nodegroups, responseResult, err\n}", "func getMemberClusterApiServerUrls(kubeconfig *clientcmdapi.Config, clusterNames []string) ([]string, error) {\n\tvar urls []string\n\tfor _, name := range clusterNames {\n\t\tif cluster := kubeconfig.Clusters[name]; cluster != nil {\n\t\t\turls = append(urls, cluster.Server)\n\t\t} else {\n\t\t\treturn nil, xerrors.Errorf(\"cluster '%s' not found in kubeconfig\", name)\n\t\t}\n\t}\n\treturn urls, nil\n}", "func (c *config) Perm(u *model.User, owner, name string) (*model.Perm, error) {\n\tclient := c.newClient(u)\n\n\tperms := new(model.Perm)\n\trepo, err := client.FindRepo(owner, name)\n\tif err != nil {\n\t\treturn perms, err\n\t}\n\n\tperm, err := client.GetPermission(repo.FullName)\n\tif err != nil {\n\t\treturn perms, err\n\t}\n\n\tswitch perm.Permission {\n\tcase \"admin\":\n\t\tperms.Admin = true\n\t\tfallthrough\n\tcase \"write\":\n\t\tperms.Push = true\n\t\tfallthrough\n\tdefault:\n\t\tperms.Pull = true\n\t}\n\n\treturn perms, nil\n}", "func (o LookupPermissionsResultOutput) Permissions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v LookupPermissionsResult) []string { return v.Permissions }).(pulumi.StringArrayOutput)\n}", "func (r *Resource) createReadAllClusterRole(ctx context.Context) error {\n\n\tlists, err := r.K8sClient().Discovery().ServerPreferredResources()\n\tif err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\tvar policyRules []rbacv1.PolicyRule\n\t{\n\t\tfor _, list := range lists {\n\t\t\tif len(list.APIResources) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgv, err := schema.ParseGroupVersion(list.GroupVersion)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, resource := range list.APIResources {\n\t\t\t\tif len(resource.Verbs) == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif isRestrictedResource(resource.Name) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tpolicyRule := rbacv1.PolicyRule{\n\t\t\t\t\tAPIGroups: []string{gv.Group},\n\t\t\t\t\tResources: []string{resource.Name},\n\t\t\t\t\tVerbs: []string{\"get\", \"list\", \"watch\"},\n\t\t\t\t}\n\t\t\t\tpolicyRules = append(policyRules, policyRule)\n\t\t\t}\n\t\t}\n\t}\n\n\t// ServerPreferredResources explicitely ignores any resource containing a '/'\n\t// but we require this for enabling pods/logs for customer access to\n\t// kubernetes pod logging. This is appended as a specific rule instead.\n\tpolicyRule := rbacv1.PolicyRule{\n\t\tAPIGroups: []string{\"\"},\n\t\tResources: []string{\"pods/log\"},\n\t\tVerbs: []string{\"get\", \"list\"},\n\t}\n\tpolicyRules = append(policyRules, policyRule)\n\n\treadOnlyClusterRole := &rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: pkgkey.DefaultReadAllPermissionsName,\n\t\t\tLabels: map[string]string{\n\t\t\t\tlabel.ManagedBy: project.Name(),\n\t\t\t\tlabel.DisplayInUserInterface: \"true\",\n\t\t\t},\n\t\t\tAnnotations: map[string]string{\n\t\t\t\tannotation.Notes: \"Grants read-only (get, list, watch) permissions to almost all resource types known on the management cluster, with exception of ConfigMap and Secret.\",\n\t\t\t},\n\t\t},\n\t\tRules: policyRules,\n\t}\n\n\treturn rbac.CreateOrUpdateClusterRole(r, ctx, readOnlyClusterRole)\n}", "func (a *HyperflexApiService) GetHyperflexClusterNetworkPolicyList(ctx context.Context) ApiGetHyperflexClusterNetworkPolicyListRequest {\n\treturn ApiGetHyperflexClusterNetworkPolicyListRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (r *Rabbit) GetUserPermissions(name string) ([]Permission, error) {\n\tbody, err := r.doRequest(\"GET\", \"/api/users/\"+name+\"/permissions\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlist := make([]Permission, 0)\n\terr = json.Unmarshal(body, &list)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn list, nil\n}", "func (e *Enforcer) GetPermissionsForUser(user string) [][]string {\n\treturn e.GetFilteredPolicy(0, user)\n}", "func getFilePerm(fpath string) {\n\n\tfileInfo, err := os.Stat(fpath)\n\n\t// check if there is an error\n\tif err != nil {\n\n\t\t// check if error is file does not exist\n\t\tif os.IsNotExist(err) {\n\t\t\tfmt.Println(\"File does not exist.\")\n\t\t}\n\n\t}\n\n\tmode := fileInfo.Mode()\n\n\tfmt.Println(fileInfo, \"mode is \", mode)\n}", "func (s *Server) getAdminAllowed(c *gin.Context) bool {\n\tobj, ok := c.Get(ctxAdminAllowedKey)\n\n\tadminAllowed := false\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\tadminAllowed, ok = obj.(bool)\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\treturn adminAllowed\n\n}", "func (UserService) GetAllPermissions(uid string) []string {\n\tperms := []string{}\n\tvar path = map[string]bool{}\n\tfor _, perm := range perm.GetAllPermsByUser(uid) {\n\t\tprefix := strings.Split(perm[1], \":\")\n\t\tseg := strings.Split(prefix[0], \"/\")\n\t\tss := \"\"\n\t\tfor _, s := range seg[1:] {\n\t\t\tss += \"/\" + s\n\t\t\tif ok := path[ss]; !ok {\n\t\t\t\tpath[ss] = true\n\t\t\t\tperms = append(perms, ss)\n\t\t\t}\n\t\t}\n\t\tperms = append(perms, perm[1])\n\t}\n\treturn perms\n}", "func (o BucketGrantOutput) Permissions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v BucketGrant) []string { return v.Permissions }).(pulumi.StringArrayOutput)\n}", "func (c *client) GetUserPermission(org, repo, user string) (string, error) {\n\tc.log(\"GetUserPermission\", org, repo, user)\n\n\tvar perm struct {\n\t\tPerm string `json:\"permission\"`\n\t}\n\t_, err := c.request(&request{\n\t\tmethod: http.MethodGet,\n\t\tpath: fmt.Sprintf(\"/repos/%s/%s/collaborators/%s/permission\", org, repo, user),\n\t\torg: org,\n\t\texitCodes: []int{200},\n\t}, &perm)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn perm.Perm, nil\n}", "func (*ListClustersRequest) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_mdb_greenplum_v1_cluster_service_proto_rawDescGZIP(), []int{1}\n}", "func getAccessClusterConfig() (*clusterconfig.ClusterConfig, *AWSCredentials, error) {\n\tclusterConfig := &clusterconfig.ClusterConfig{}\n\tawsCreds := &AWSCredentials{}\n\n\tif flagClusterConfig == \"\" {\n\t\terr := clusterconfig.SetFileDefaults(clusterConfig)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\treadClusterConfigFile(clusterConfig, awsCreds, cachedClusterConfigPath)\n\t} else {\n\t\terr := readClusterConfigFile(clusterConfig, awsCreds, flagClusterConfig)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\terr := setAWSCredentials(awsCreds)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn clusterConfig, awsCreds, nil\n}", "func QueryUserHasDashboardPermssion(dashId int64, userId int64,permission int) int8 {\n\tvar rawJSON []byte\n\terr := db.SQL.QueryRow(\"SELECT permission from dashboard_user_acl WHERE dashboard_id=? and user_id=?\",dashId,userId).Scan(&rawJSON)\n\tif err != nil {\n\t\treturn UserAcl_NoPermissionRules\n\t}\n\t\n\tvar permissions []int\n\tjson.Unmarshal(rawJSON,&permissions)\n\n\tfor _,p := range permissions {\n\t\tif p == permission {\n\t\t\treturn UserAcl_PermissionAllow\n\t\t}\n\t}\n\n\treturn UserAcl_PermissionForbidden\n}", "func (client *Client) ListClusterMembers(request *ListClusterMembersRequest) (response *ListClusterMembersResponse, err error) {\n\tresponse = CreateListClusterMembersResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func (p *Provider) List() ([]string, error) {\n\treturn p.provider.ListClusters()\n}", "func GetPermission(username, projectName string) (string, error) {\n\to := orm.NewOrm()\n\n\tsql := \"select r.role_code from role as r \" +\n\t\t\"inner join project_role as pr on r.role_id = pr.role_id \" +\n\t\t\"inner join user_project_role as ur on pr.pr_id = ur.pr_id \" +\n\t\t\"inner join user as u on u.user_id = ur.user_id \" +\n\t\t\"inner join project p on p.project_id = pr.project_id \" +\n\t\t\"where u.username = ? and p.name = ? and u.deleted = 0 and p.deleted = 0\"\n\n\tvar r []models.Role\n\tn, err := o.Raw(sql, username, projectName).QueryRows(&r)\n\tif err != nil {\n\t\treturn \"\", err\n\t} else if n == 0 {\n\t\treturn \"\", nil\n\t} else {\n\t\treturn r[0].RoleCode, nil\n\t}\n}", "func DetectClusterRole(c *Conf) {\n\tclusterRoleBindings := &rbacv1.ClusterRoleBindingList{}\n\tselector := labels.SelectorFromSet(labels.Set{\n\t\t\"olm.owner.kind\": \"ClusterServiceVersion\",\n\t\t\"olm.owner.namespace\": c.SA.Namespace,\n\t})\n\tutil.KubeList(clusterRoleBindings, &client.ListOptions{\n\t\tLabelSelector: selector,\n\t})\n\tfor i := range clusterRoleBindings.Items {\n\t\tb := &clusterRoleBindings.Items[i]\n\t\tfor j := range b.Subjects {\n\t\t\ts := b.Subjects[j]\n\t\t\tif s.Kind == \"ServiceAccount\" &&\n\t\t\t\ts.Name == c.SA.Name &&\n\t\t\t\ts.Namespace == c.SA.Namespace {\n\t\t\t\tc.ClusterRole.Name = b.RoleRef.Name\n\t\t\t\tc.ClusterRoleBinding.Name = b.Name\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (n *Node) ReadUserPermissions(ctx context.Context, u *userpb.User) (ap provider.ResourcePermissions, accessDenied bool, err error) {\n\t// check if the current user is the owner\n\tif utils.UserEqual(u.Id, n.Owner()) {\n\t\tappctx.GetLogger(ctx).Debug().Str(\"node\", n.ID).Msg(\"user is owner, returning owner permissions\")\n\t\treturn OwnerPermissions(), false, nil\n\t}\n\n\tap = provider.ResourcePermissions{}\n\n\t// for an efficient group lookup convert the list of groups to a map\n\t// groups are just strings ... groupnames ... or group ids ??? AAARGH !!!\n\tgroupsMap := make(map[string]bool, len(u.Groups))\n\tfor i := range u.Groups {\n\t\tgroupsMap[u.Groups[i]] = true\n\t}\n\n\tvar g *provider.Grant\n\n\t// we read all grantees from the node\n\tvar grantees []string\n\tif grantees, err = n.ListGrantees(ctx); err != nil {\n\t\tappctx.GetLogger(ctx).Error().Err(err).Interface(\"node\", n).Msg(\"error listing grantees\")\n\t\treturn NoPermissions(), true, err\n\t}\n\n\t// instead of making n getxattr syscalls we are going to list the acls and filter them here\n\t// we have two options here:\n\t// 1. we can start iterating over the acls / grants on the node or\n\t// 2. we can iterate over the number of groups\n\t// The current implementation tries to be defensive for cases where users have hundreds or thousands of groups, so we iterate over the existing acls.\n\tuserace := prefixes.GrantUserAcePrefix + u.Id.OpaqueId\n\tuserFound := false\n\tfor i := range grantees {\n\t\tswitch {\n\t\t// we only need to find the user once\n\t\tcase !userFound && grantees[i] == userace:\n\t\t\tg, err = n.ReadGrant(ctx, grantees[i])\n\t\tcase strings.HasPrefix(grantees[i], prefixes.GrantGroupAcePrefix): // only check group grantees\n\t\t\tgr := strings.TrimPrefix(grantees[i], prefixes.GrantGroupAcePrefix)\n\t\t\tif groupsMap[gr] {\n\t\t\t\tg, err = n.ReadGrant(ctx, grantees[i])\n\t\t\t} else {\n\t\t\t\t// no need to check attribute\n\t\t\t\tcontinue\n\t\t\t}\n\t\tdefault:\n\t\t\t// no need to check attribute\n\t\t\tcontinue\n\t\t}\n\n\t\tif isGrantExpired(g) {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch {\n\t\tcase err == nil:\n\t\t\t// If all permissions are set to false we have a deny grant\n\t\t\tif grants.PermissionsEqual(g.Permissions, &provider.ResourcePermissions{}) {\n\t\t\t\treturn NoPermissions(), true, nil\n\t\t\t}\n\t\t\tAddPermissions(&ap, g.GetPermissions())\n\t\tcase metadata.IsAttrUnset(err):\n\t\t\tappctx.GetLogger(ctx).Error().Interface(\"node\", n).Str(\"grant\", grantees[i]).Interface(\"grantees\", grantees).Msg(\"grant vanished from node after listing\")\n\t\t\t// continue with next segment\n\t\tdefault:\n\t\t\tappctx.GetLogger(ctx).Error().Err(err).Interface(\"node\", n).Str(\"grant\", grantees[i]).Msg(\"error reading permissions\")\n\t\t\t// continue with next segment\n\t\t}\n\t}\n\n\tappctx.GetLogger(ctx).Debug().Interface(\"permissions\", ap).Interface(\"node\", n).Interface(\"user\", u).Msg(\"returning aggregated permissions\")\n\treturn ap, false, nil\n}", "func List(client *golangsdk.ServiceClient, clusterId string) (r ListResult) {\n\t_, r.Err = client.Get(listURL(client, clusterId), &r.Body, nil)\n\treturn\n}", "func provisionerList(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {\n\tallowed := permission.Check(t, permission.PermClusterRead)\n\tif !allowed {\n\t\treturn permission.ErrUnauthorized\n\t}\n\tprovs, err := provision.Registry()\n\tif err != nil {\n\t\treturn err\n\t}\n\tinfo := make([]provisionerInfo, len(provs))\n\tfor i, p := range provs {\n\t\tinfo[i].Name = p.GetName()\n\t\tif clusterProv, ok := p.(cluster.ClusteredProvisioner); ok {\n\t\t\tinfo[i].ClusterHelp = clusterProv.ClusterHelp()\n\t\t}\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\treturn json.NewEncoder(w).Encode(info)\n}", "func getListOfRoles(filterBy string) []v1.Subject {\n\n\t// creates the in-cluster config\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\t// creates the clientset\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\troleBindings, err := clientset.RbacV1().RoleBindings(\"\").List(metav1.ListOptions{})\n\tif err != nil {\n\t\tfmt.Println(\"Error loading cluster role bindings, reason is \" + err.Error())\n\t}\n\n\tvar prefixRegexp = regexp.MustCompile(`^` + filterBy)\n\tarrRolesFiltered := make([]v1.Subject, 0)\n\n\tfor _, roleBinding := range roleBindings.Items {\n\t\tfor _, subject := range roleBinding.Subjects {\n\t\t\tif prefixRegexp.MatchString(subject.Name) {\n\t\t\t\tarrRolesFiltered = append(arrRolesFiltered, subject)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn arrRolesFiltered\n}", "func (o *ClusterAuthorizationResponse) GetAllowed() bool {\n\tif o == nil {\n\t\tvar ret bool\n\t\treturn ret\n\t}\n\n\treturn o.Allowed\n}", "func main() {\n\tfmt.Printf(\"All perms are - %v\", getPerms(\"abc\"))\n}", "func (api *clusterAPI) ApisrvList(ctx context.Context, opts *api.ListWatchOptions) ([]*cluster.Cluster, 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 nil, err\n\t\t}\n\n\t\treturn apicl.ClusterV1().Cluster().List(context.Background(), opts)\n\t}\n\n\t// List from local cache\n\tctkitObjs, err := api.List(ctx, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar ret []*cluster.Cluster\n\tfor _, obj := range ctkitObjs {\n\t\tret = append(ret, &obj.Cluster)\n\t}\n\treturn ret, nil\n}", "func ajaxPerms(r *http.Request) ([]byte, error) {\n\treturn util.JSON(map[string]interface{}{\"permissions\": user.PermissionInfos()})\n}", "func (e *CachedEnforcer) GetImplicitUsersForPermission(permission ...string) ([]string, error) {\n\treturn e.api.GetImplicitUsersForPermission(permission...)\n}", "func (n *Node) ListGrantees(ctx context.Context) (grantees []string, err error) {\n\tvar attrs []string\n\tif attrs, err = xattr.List(n.InternalPath()); err != nil {\n\t\tappctx.GetLogger(ctx).Error().Err(err).Interface(\"node\", n).Msg(\"error listing attributes\")\n\t\treturn nil, err\n\t}\n\tfor i := range attrs {\n\t\tif strings.HasPrefix(attrs[i], xattrs.GrantPrefix) {\n\t\t\tgrantees = append(grantees, attrs[i])\n\t\t}\n\t}\n\treturn\n}", "func requestCredList(ctx aws.Context, client *ec2metadata.EC2Metadata) ([]string, error) {\n\tresp, err := client.GetMetadataWithContext(ctx, iamSecurityCredsPath)\n\tif err != nil {\n\t\treturn nil, awserr.New(\"EC2RoleRequestError\", \"no EC2 instance role found\", err)\n\t}\n\n\tcredsList := []string{}\n\ts := bufio.NewScanner(strings.NewReader(resp))\n\tfor s.Scan() {\n\t\tcredsList = append(credsList, s.Text())\n\t}\n\n\tif err := s.Err(); err != nil {\n\t\treturn nil, awserr.New(request.ErrCodeSerialization,\n\t\t\t\"failed to read EC2 instance role from metadata service\", err)\n\t}\n\n\treturn credsList, nil\n}", "func (o DiagnosticsOptions) findClusterClients(rawConfig *clientcmdapi.Config) (*rest.Config, kclientset.Interface, *clientcmdapi.Config, error) {\n\tif o.ClientClusterContext != \"\" { // user has specified cluster context to use\n\t\tcontext, exists := rawConfig.Contexts[o.ClientClusterContext]\n\t\tif !exists {\n\t\t\tconfigErr := fmt.Errorf(\"Specified '%s' as cluster-admin context, but it was not found in your client configuration.\", o.ClientClusterContext)\n\t\t\to.Logger().Error(\"CED1003\", configErr.Error())\n\t\t\treturn nil, nil, nil, configErr\n\t\t}\n\t\treturn o.makeClusterClients(rawConfig, o.ClientClusterContext, context)\n\t}\n\tcurrentContext, exists := rawConfig.Contexts[rawConfig.CurrentContext]\n\tif !exists { // config specified cluster admin context that doesn't exist; complain and quit\n\t\tconfigErr := fmt.Errorf(\"Current context '%s' not found in client configuration; will not attempt cluster diagnostics.\", rawConfig.CurrentContext)\n\t\to.Logger().Error(\"CED1004\", configErr.Error())\n\t\treturn nil, nil, nil, configErr\n\t}\n\n\t// check if current context is already cluster admin\n\tconfig, kube, rawAdminConfig, err := o.makeClusterClients(rawConfig, rawConfig.CurrentContext, currentContext)\n\tif err == nil && config != nil {\n\t\treturn config, kube, rawAdminConfig, nil\n\t}\n\n\t// otherwise, for convenience, search for a context with the same server but with the system:admin user\n\tfor name, context := range rawConfig.Contexts {\n\t\tif context.Cluster == currentContext.Cluster && name != rawConfig.CurrentContext && strings.HasPrefix(context.AuthInfo, \"system:admin/\") {\n\t\t\tconfig, kube, rawAdminConfig, err := o.makeClusterClients(rawConfig, name, context)\n\t\t\tif err != nil || config == nil {\n\t\t\t\tbreak // don't try more than one such context, they'll probably fail the same\n\t\t\t}\n\t\t\treturn config, kube, rawAdminConfig, nil\n\t\t}\n\t}\n\treturn nil, nil, nil, nil\n}", "func (c ConfigGlyphSet) graphemeClusterAliases() []GCAlias {\n\tif c.Aliases != \"\" {\n\t\treturn EmojiAliases(c.Aliases)\n\t} else {\n\t\treturn []GCAlias{}\n\t}\n}" ]
[ "0.7636283", "0.71130735", "0.5741309", "0.5673176", "0.56616306", "0.5642498", "0.5625123", "0.55157167", "0.550617", "0.54891", "0.54313993", "0.54297036", "0.53427935", "0.5333762", "0.531025", "0.5310238", "0.529976", "0.5285257", "0.5264322", "0.52617234", "0.52366245", "0.5220556", "0.5216671", "0.520395", "0.51709145", "0.5157403", "0.51481056", "0.51435035", "0.51388055", "0.5136383", "0.5108205", "0.51062846", "0.51057714", "0.5099798", "0.5096735", "0.5092156", "0.50867206", "0.50762355", "0.50752956", "0.5074148", "0.5043999", "0.50384307", "0.50340396", "0.50274944", "0.50244814", "0.50203675", "0.50014865", "0.49831983", "0.49690852", "0.49633446", "0.49613765", "0.4949869", "0.494855", "0.49464333", "0.4937978", "0.4922078", "0.49200138", "0.49109396", "0.4909005", "0.490471", "0.49021998", "0.48980236", "0.4897414", "0.4895017", "0.48934963", "0.48931205", "0.4888877", "0.48832762", "0.4864589", "0.4856168", "0.48540127", "0.48430434", "0.48270738", "0.48230767", "0.4813489", "0.48130766", "0.48127505", "0.48014715", "0.47885993", "0.47883737", "0.47860146", "0.47851434", "0.47846055", "0.47839725", "0.4783571", "0.4778781", "0.47745338", "0.47698122", "0.4768759", "0.47673592", "0.4762374", "0.4759521", "0.47521105", "0.4749288", "0.47477317", "0.47449908", "0.47387064", "0.47347662", "0.47302768", "0.4729752" ]
0.8238796
0
GetUserPermListByProjectAndCluster get user cluster permissions
func GetUserPermListByProjectAndCluster(user UserInfo, clusterList []string, filterUse bool) (map[string]*proto.Permission, error) { permissions := make(map[string]*proto.Permission) // policyCode resourceType clusterList for _, clusterID := range clusterList { defaultPerm := auth.GetInitPerm(true) permissions[clusterID] = &proto.Permission{ Policy: defaultPerm, } } return permissions, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetUserClusterPermList(user UserInfo, clusterList []string) (map[string]*proto.Permission, error) {\n\tpermissions := make(map[string]*proto.Permission)\n\tcli := &cluster.BCSClusterPerm{}\n\n\tactionIDs := []string{cluster.ClusterView.String(), cluster.ClusterManage.String(), cluster.ClusterDelete.String()}\n\tperms, err := cli.GetMultiClusterMultiActionPermission(user.UserID, user.ProjectID, clusterList, actionIDs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor clusterID, perm := range perms {\n\t\tpermissions[clusterID] = &proto.Permission{\n\t\t\tPolicy: perm,\n\t\t}\n\t}\n\n\treturn permissions, nil\n}", "func GetClusterCreatePerm(user UserInfo) map[string]bool {\n\tpermissions := make(map[string]bool)\n\n\t// attention: v0 permission only support project\n\tpermissions[\"test\"] = true\n\tpermissions[\"prod\"] = true\n\tpermissions[\"create\"] = true\n\n\treturn permissions\n}", "func loadPerms(uid types.ID) (authority.Permissions, authority.ProjectRoles) {\n\tvar roles []string\n\tvar projectRoles []domain.ProjectRole\n\tdb := persistence.ActiveDataSourceManager.GormDB(context.Background())\n\n\t// system perms\n\tvar systemRoles []string\n\tif err := db.Model(&UserRoleBinding{}).Where(&UserRoleBinding{UserID: uid}).Pluck(\"role_id\", &systemRoles).Error; err != nil {\n\t\tpanic(err)\n\t}\n\n\tif len(systemRoles) > 0 {\n\t\tvar systemPerms []string\n\t\tif err := db.Model(&RolePermissionBinding{}).Where(\"role_id IN (?)\", systemRoles).Pluck(\"permission_id\", &systemPerms).Error; err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\troles = append(roles, systemPerms...)\n\t}\n\n\tif len(systemRoles) > 0 {\n\t\t// system role: all project is visiabble\n\t\tvar projects []domain.Project\n\t\tif err := db.Model(&domain.Project{}).Scan(&projects).Error; err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfor _, project := range projects {\n\t\t\troles = append(roles, fmt.Sprintf(\"%s_%d\", domain.ProjectRoleManager, project.ID))\n\t\t\tprojectRoles = append(projectRoles, domain.ProjectRole{\n\t\t\t\tProjectID: project.ID, ProjectName: project.Name, ProjectIdentifier: project.Identifier, Role: domain.ProjectRoleManager,\n\t\t\t})\n\t\t}\n\t} else {\n\t\tvar gms []domain.ProjectMember\n\t\tvar visiableProjectIds []types.ID\n\t\tif err := db.Model(&domain.ProjectMember{}).Where(&domain.ProjectMember{MemberId: uid}).Scan(&gms).Error; err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tfor _, gm := range gms {\n\t\t\troles = append(roles, fmt.Sprintf(\"%s_%d\", gm.Role, gm.ProjectId))\n\t\t\tprojectRoles = append(projectRoles, domain.ProjectRole{Role: gm.Role, ProjectID: gm.ProjectId})\n\t\t\tvisiableProjectIds = append(visiableProjectIds, gm.ProjectId)\n\t\t}\n\n\t\tm := map[types.ID]domain.Project{}\n\t\tif len(visiableProjectIds) > 0 {\n\t\t\tvar visiableProjects []domain.Project\n\t\t\tif err := db.Model(&domain.Project{}).Where(\"id in (?)\", visiableProjectIds).Scan(&visiableProjects).Error; err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tfor _, project := range visiableProjects {\n\t\t\t\tm[project.ID] = project\n\t\t\t}\n\t\t}\n\t\tfor i := 0; i < len(projectRoles); i++ {\n\t\t\tprojectRole := projectRoles[i]\n\n\t\t\tproject := m[projectRole.ProjectID]\n\t\t\tif (project == domain.Project{}) {\n\t\t\t\tpanic(errors.New(\"project \" + projectRole.ProjectID.String() + \" is not exist\"))\n\t\t\t}\n\n\t\t\tprojectRole.ProjectName = project.Name\n\t\t\tprojectRole.ProjectIdentifier = project.Identifier\n\n\t\t\tprojectRoles[i] = projectRole\n\t\t}\n\t}\n\n\tif roles == nil {\n\t\troles = []string{}\n\t}\n\tif projectRoles == nil {\n\t\tprojectRoles = []domain.ProjectRole{}\n\t}\n\n\treturn roles, projectRoles\n}", "func (e *BcsDataManager) GetClusterListByProject(ctx context.Context, req *bcsdatamanager.GetClusterListRequest,\n\trsp *bcsdatamanager.GetClusterListResponse) error {\n\tblog.Infof(\"Received GetClusterListByProject.Call request. Project id: %s, dimension:%s, page:%s, size:%s, \"+\n\t\t\"startTime=%s, endTime=%s\",\n\t\treq.GetProject(), req.GetDimension(), req.GetPage(), req.GetSize(), time.Unix(req.GetStartTime(), 0),\n\t\ttime.Unix(req.GetEndTime(), 0))\n\tstart := time.Now()\n\tif req.GetProject() == \"\" && req.GetBusiness() == \"\" && req.GetProjectCode() == \"\" {\n\t\trsp.Message = fmt.Sprintf(\"get cluster list info error, projectId, projectCode or businessID is required\")\n\t\trsp.Code = bcsCommon.AdditionErrorCode + 500\n\t\tblog.Errorf(rsp.Message)\n\t\tprom.ReportAPIRequestMetric(\"GetClusterListByProject\", \"grpc\", prom.StatusErr, start)\n\t\treturn nil\n\t}\n\tif req.GetProject() == \"\" && req.GetBusiness() == \"\" && req.GetProjectCode() != \"\" {\n\t\tproject, err := e.resourceGetter.GetProjectInfo(ctx, \"\", req.GetProjectCode(), nil)\n\t\tif err != nil {\n\t\t\trsp.Message = fmt.Sprintf(\"get project info err:%v\", err)\n\t\t\trsp.Code = bcsCommon.AdditionErrorCode + 500\n\t\t\tblog.Errorf(rsp.Message)\n\t\t\tprom.ReportAPIRequestMetric(\"GetClusterListByProject\", \"grpc\", prom.StatusErr, start)\n\t\t\treturn nil\n\t\t}\n\t\tif project == nil {\n\t\t\trsp.Message = fmt.Sprintf(\"cannot get project info by project code:%s\", req.GetProjectCode())\n\t\t\trsp.Code = bcsCommon.AdditionErrorCode + 500\n\t\t\tblog.Errorf(rsp.Message)\n\t\t\tprom.ReportAPIRequestMetric(\"GetProjectInfo\", \"grpc\", prom.StatusErr, start)\n\t\t\treturn nil\n\t\t}\n\t\treq.Project = project.ProjectID\n\t}\n\tresult, total, err := e.model.GetClusterInfoList(ctx, req)\n\tif err != nil {\n\t\trsp.Message = fmt.Sprintf(\"get cluster list info error: %v\", err)\n\t\trsp.Code = bcsCommon.AdditionErrorCode + 500\n\t\tblog.Errorf(rsp.Message)\n\t\tprom.ReportAPIRequestMetric(\"GetClusterListByProject\", \"grpc\", prom.StatusErr, start)\n\t\treturn nil\n\t}\n\trsp.Data = result\n\trsp.Message = bcsCommon.BcsSuccessStr\n\trsp.Code = bcsCommon.BcsSuccess\n\trsp.Total = uint32(total)\n\tprom.ReportAPIRequestMetric(\"GetClusterListByProject\", \"grpc\", prom.StatusOK, start)\n\treturn nil\n}", "func clusterPermissions(permissions ...auth.Permission) authHandler {\n\treturn func(ctx context.Context, authApi authiface.APIServer, fullMethod string) (string, error) {\n\t\tresp, err := authApi.Authorize(ctx, &auth.AuthorizeRequest{\n\t\t\tResource: &auth.Resource{Type: auth.ResourceType_CLUSTER},\n\t\t\tPermissions: permissions,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn \"\", errors.EnsureStack(err)\n\t\t}\n\n\t\tif resp.Authorized {\n\t\t\treturn \"\", nil\n\t\t}\n\n\t\treturn \"\", &auth.ErrNotAuthorized{\n\t\t\tSubject: resp.Principal,\n\t\t\tResource: &auth.Resource{Type: auth.ResourceType_CLUSTER},\n\t\t\tRequired: permissions,\n\t\t}\n\t}\n}", "func GetClusterPermClient() (*cluster.BCSClusterPerm, error) {\n\tiamClient, err := GetIAMClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cluster.NewBCSClusterPermClient(iamClient), nil\n}", "func ListClusterUserCredentials(client autorest.Client, urlParameters map[string]interface{}, apiVersion string) containerservice.CredentialResults {\r\n\tqueryParameters := map[string]interface{}{\r\n\t\t\"api-version\": apiVersion,\r\n\t}\r\n\tpreparerDecorators := []autorest.PrepareDecorator{\r\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\r\n\t\tautorest.WithMethod(\"POST\"),\r\n\t\tautorest.WithBaseURL(azure.PublicCloud.ResourceManagerEndpoint),\r\n\t\tautorest.WithPathParameters(\r\n\t\t\t\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{resourceName}/listClusterUserCredential\",\r\n\t\t\turlParameters,\r\n\t\t),\r\n\t\tautorest.WithQueryParameters(queryParameters),\r\n\t}\r\n\r\n\tpreparer := autorest.CreatePreparer(preparerDecorators...)\r\n\treq, err := preparer.Prepare((&http.Request{}).WithContext(context.Background()))\r\n\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\tfmt.Println(req.URL)\r\n\r\n\tresp, err := client.Do(req)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\terr = autorest.Respond(\r\n\t\tresp,\r\n\t\tclient.ByInspecting(),\r\n\t)\r\n\r\n\tcontent, err := ioutil.ReadAll(resp.Body)\r\n\r\n\tvar kubeconfigs containerservice.CredentialResults\r\n\tjson.Unmarshal(content, &kubeconfigs)\r\n\r\n\treturn kubeconfigs\r\n}", "func (w *WhoCan) getClusterRolesFor(action resolvedAction) (clusterRoles, error) {\n\tctx := context.Background()\n\tcrl, err := w.clientRBAC.ClusterRoles().List(ctx, metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcr := make(map[string]struct{}, 10)\n\n\tfor _, item := range crl.Items {\n\t\tif w.policyRuleMatcher.MatchesClusterRole(item, action) {\n\t\t\tif _, ok := cr[item.Name]; !ok {\n\t\t\t\tcr[item.Name] = struct{}{}\n\t\t\t}\n\t\t}\n\t}\n\treturn cr, nil\n}", "func (n *NameServiceCache) GetUserPermissions(user string, kg fred.KeygroupName) (map[fred.Method]struct{}, error) {\n\treturn n.regularNase.GetUserPermissions(user, kg)\n}", "func GetPermission(username, projectName string) (string, error) {\n\to := orm.NewOrm()\n\n\tsql := \"select r.role_code from role as r \" +\n\t\t\"inner join project_role as pr on r.role_id = pr.role_id \" +\n\t\t\"inner join user_project_role as ur on pr.pr_id = ur.pr_id \" +\n\t\t\"inner join user as u on u.user_id = ur.user_id \" +\n\t\t\"inner join project p on p.project_id = pr.project_id \" +\n\t\t\"where u.username = ? and p.name = ? and u.deleted = 0 and p.deleted = 0\"\n\n\tvar r []models.Role\n\tn, err := o.Raw(sql, username, projectName).QueryRows(&r)\n\tif err != nil {\n\t\treturn \"\", err\n\t} else if n == 0 {\n\t\treturn \"\", nil\n\t} else {\n\t\treturn r[0].RoleCode, nil\n\t}\n}", "func (p *Permission) CanAccessCluster() (bool, error) {\n\tfor _, pattern := range p.Indices {\n\t\tpattern = strings.Replace(pattern, \"*\", \".*\", -1)\n\t\tmatched, err := regexp.MatchString(pattern, \"*\")\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif matched {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}", "func (c *ClusterTx) GetProjectUsedBy(project Project) ([]string, error) {\n\tinstances, err := c.GetInstanceURIs(InstanceFilter{Project: &project.Name})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\timages, err := c.GetImageURIs(ImageFilter{Project: &project.Name})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprofiles, err := c.GetProfileURIs(ProfileFilter{Project: &project.Name})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvolumes, err := c.GetStorageVolumeURIs(project.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnetworks, err := c.GetNetworkURIs(project.ID, project.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnetworkACLs, err := c.GetNetworkACLURIs(project.ID, project.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tusedBy := instances\n\tusedBy = append(usedBy, images...)\n\tusedBy = append(usedBy, profiles...)\n\tusedBy = append(usedBy, volumes...)\n\tusedBy = append(usedBy, networks...)\n\tusedBy = append(usedBy, networkACLs...)\n\n\treturn usedBy, nil\n}", "func GetPermission(username, projectName string) (string, error) {\n\to := GetOrmer()\n\n\tsql := `select r.role_code from role as r\n\t\tinner join project_member as pm on r.role_id = pm.role\n\t\tinner join user as u on u.user_id = pm.user_id\n\t\tinner join project p on p.project_id = pm.project_id\n\t\twhere u.username = ? and p.name = ? and u.deleted = 0 and p.deleted = 0`\n\n\tvar r []models.Role\n\tn, err := o.Raw(sql, username, projectName).QueryRows(&r)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif n == 0 {\n\t\treturn \"\", nil\n\t}\n\n\treturn r[0].RoleCode, nil\n}", "func (c *client) GetUserPermission(org, repo, user string) (string, error) {\n\tc.log(\"GetUserPermission\", org, repo, user)\n\n\tvar perm struct {\n\t\tPerm string `json:\"permission\"`\n\t}\n\t_, err := c.request(&request{\n\t\tmethod: http.MethodGet,\n\t\tpath: fmt.Sprintf(\"/repos/%s/%s/collaborators/%s/permission\", org, repo, user),\n\t\torg: org,\n\t\texitCodes: []int{200},\n\t}, &perm)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn perm.Perm, nil\n}", "func GetClusters(config core.Configuration, clusterID *string, localQuotaUsageOnly bool, withSubcapacities bool, dbi db.Interface, filter Filter) ([]*limes.ClusterReport, error) {\n\t//first query: collect project usage data in these clusters\n\tclusters := make(clusters)\n\tqueryStr, joinArgs := filter.PrepareQuery(clusterReportQuery1)\n\twhereStr, whereArgs := db.BuildSimpleWhereClause(makeClusterFilter(\"d\", clusterID), len(joinArgs))\n\terr := db.ForeachRow(db.DB, fmt.Sprintf(queryStr, whereStr), append(joinArgs, whereArgs...), func(rows *sql.Rows) error {\n\t\tvar (\n\t\t\tclusterID string\n\t\t\tserviceType *string\n\t\t\tresourceName *string\n\t\t\tprojectsQuota *uint64\n\t\t\tusage *uint64\n\t\t\tburstUsage *uint64\n\t\t\tminScrapedAt *util.Time\n\t\t\tmaxScrapedAt *util.Time\n\t\t)\n\t\terr := rows.Scan(&clusterID, &serviceType, &resourceName,\n\t\t\t&projectsQuota, &usage, &burstUsage,\n\t\t\t&minScrapedAt, &maxScrapedAt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t_, service, resource := clusters.Find(config, clusterID, serviceType, resourceName)\n\n\t\tclusterConfig, exists := config.Clusters[clusterID]\n\t\tclusterCanBurst := exists && clusterConfig.Config.Bursting.MaxMultiplier > 0\n\n\t\tif service != nil {\n\t\t\tif maxScrapedAt != nil {\n\t\t\t\tval := time.Time(*maxScrapedAt).Unix()\n\t\t\t\tservice.MaxScrapedAt = &val\n\t\t\t}\n\t\t\tif minScrapedAt != nil {\n\t\t\t\tval := time.Time(*minScrapedAt).Unix()\n\t\t\t\tservice.MinScrapedAt = &val\n\t\t\t}\n\t\t}\n\n\t\tif resource != nil {\n\t\t\tif projectsQuota != nil && resource.ExternallyManaged {\n\t\t\t\tresource.DomainsQuota = *projectsQuota\n\t\t\t}\n\t\t\tif usage != nil {\n\t\t\t\tresource.Usage = *usage\n\t\t\t}\n\t\t\tif clusterCanBurst && burstUsage != nil {\n\t\t\t\tresource.BurstUsage = *burstUsage\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//second query: collect domain quota data in these clusters\n\tqueryStr, joinArgs = filter.PrepareQuery(clusterReportQuery2)\n\twhereStr, whereArgs = db.BuildSimpleWhereClause(makeClusterFilter(\"d\", clusterID), len(joinArgs))\n\terr = db.ForeachRow(db.DB, fmt.Sprintf(queryStr, whereStr), append(joinArgs, whereArgs...), func(rows *sql.Rows) error {\n\t\tvar (\n\t\t\tclusterID string\n\t\t\tserviceType *string\n\t\t\tresourceName *string\n\t\t\tquota *uint64\n\t\t)\n\t\terr := rows.Scan(&clusterID, &serviceType, &resourceName, &quota)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t_, _, resource := clusters.Find(config, clusterID, serviceType, resourceName)\n\n\t\tif resource != nil && quota != nil && !resource.ExternallyManaged {\n\t\t\tresource.DomainsQuota = *quota\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//third query: collect capacity data for these clusters\n\tqueryStr, joinArgs = filter.PrepareQuery(clusterReportQuery3)\n\tif !withSubcapacities {\n\t\tqueryStr = strings.Replace(queryStr, \"cr.subcapacities\", \"''\", 1)\n\t}\n\twhereStr, whereArgs = db.BuildSimpleWhereClause(makeClusterFilter(\"cs\", clusterID), len(joinArgs))\n\terr = db.ForeachRow(db.DB, fmt.Sprintf(queryStr, whereStr), append(joinArgs, whereArgs...), func(rows *sql.Rows) error {\n\t\tvar (\n\t\t\tclusterID string\n\t\t\tserviceType string\n\t\t\tresourceName *string\n\t\t\trawCapacity *uint64\n\t\t\tcomment *string\n\t\t\tsubcapacities *string\n\t\t\tscrapedAt util.Time\n\t\t)\n\t\terr := rows.Scan(&clusterID, &serviceType, &resourceName, &rawCapacity, &comment, &subcapacities, &scrapedAt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcluster, _, resource := clusters.Find(config, clusterID, &serviceType, resourceName)\n\n\t\tif resource != nil {\n\t\t\tovercommitFactor := config.Clusters[clusterID].BehaviorForResource(serviceType, *resourceName).OvercommitFactor\n\t\t\tif overcommitFactor == 0 {\n\t\t\t\tresource.Capacity = rawCapacity\n\t\t\t} else {\n\t\t\t\tresource.RawCapacity = rawCapacity\n\t\t\t\tcapacity := uint64(float64(*rawCapacity) * overcommitFactor)\n\t\t\t\tresource.Capacity = &capacity\n\t\t\t}\n\t\t\tif comment != nil {\n\t\t\t\tresource.Comment = *comment\n\t\t\t}\n\t\t\tif subcapacities != nil && *subcapacities != \"\" {\n\t\t\t\tresource.Subcapacities = limes.JSONString(*subcapacities)\n\t\t\t}\n\t\t}\n\n\t\tif cluster != nil {\n\t\t\tscrapedAtUnix := time.Time(scrapedAt).Unix()\n\t\t\tif cluster.MaxScrapedAt == nil || *cluster.MaxScrapedAt < scrapedAtUnix {\n\t\t\t\tcluster.MaxScrapedAt = &scrapedAtUnix\n\t\t\t}\n\t\t\tif cluster.MinScrapedAt == nil || *cluster.MinScrapedAt > scrapedAtUnix {\n\t\t\t\tcluster.MinScrapedAt = &scrapedAtUnix\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//enumerate shared services\n\tisSharedService := make(map[string]bool)\n\tfor clusterID := range clusters {\n\t\tclusterConfig, exists := config.Clusters[clusterID]\n\t\tif exists {\n\t\t\tfor serviceType, shared := range clusterConfig.IsServiceShared {\n\t\t\t\tif shared {\n\t\t\t\t\tisSharedService[serviceType] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(isSharedService) > 0 {\n\n\t\tif !localQuotaUsageOnly {\n\n\t\t\t//fourth query: aggregate domain quota for shared services\n\t\t\tsharedQuotaSums := make(map[string]map[string]uint64)\n\n\t\t\tsharedServiceTypes := make([]string, 0, len(isSharedService))\n\t\t\tfor serviceType := range isSharedService {\n\t\t\t\tsharedServiceTypes = append(sharedServiceTypes, serviceType)\n\t\t\t}\n\t\t\twhereStr, queryArgs := db.BuildSimpleWhereClause(map[string]interface{}{\"ds.type\": sharedServiceTypes}, 0)\n\t\t\terr = db.ForeachRow(db.DB, fmt.Sprintf(clusterReportQuery4, whereStr), queryArgs, func(rows *sql.Rows) error {\n\t\t\t\tvar (\n\t\t\t\t\tserviceType string\n\t\t\t\t\tresourceName string\n\t\t\t\t\tquota uint64\n\t\t\t\t)\n\t\t\t\terr := rows.Scan(&serviceType, &resourceName, &quota)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif sharedQuotaSums[serviceType] == nil {\n\t\t\t\t\tsharedQuotaSums[serviceType] = make(map[string]uint64)\n\t\t\t\t}\n\t\t\t\tsharedQuotaSums[serviceType][resourceName] = quota\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t//fifth query: aggregate project quota for shared services\n\t\t\twhereStr, queryArgs = db.BuildSimpleWhereClause(map[string]interface{}{\"ps.type\": sharedServiceTypes}, 0)\n\t\t\tsharedUsageSums := make(map[string]map[string]uint64)\n\t\t\terr = db.ForeachRow(db.DB, fmt.Sprintf(clusterReportQuery5, whereStr), queryArgs, func(rows *sql.Rows) error {\n\t\t\t\tvar (\n\t\t\t\t\tserviceType string\n\t\t\t\t\tresourceName string\n\t\t\t\t\tusage uint64\n\t\t\t\t)\n\t\t\t\terr := rows.Scan(&serviceType, &resourceName, &usage)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif sharedUsageSums[serviceType] == nil {\n\t\t\t\t\tsharedUsageSums[serviceType] = make(map[string]uint64)\n\t\t\t\t}\n\t\t\t\tsharedUsageSums[serviceType][resourceName] = usage\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tfor _, cluster := range clusters {\n\t\t\t\tisSharedService := make(map[string]bool)\n\t\t\t\tfor serviceType, shared := range config.Clusters[cluster.ID].IsServiceShared {\n\t\t\t\t\t//NOTE: cluster config is guaranteed to exist due to earlier validation\n\t\t\t\t\tif shared {\n\t\t\t\t\t\tisSharedService[serviceType] = true\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor _, service := range cluster.Services {\n\t\t\t\t\tif isSharedService[service.Type] && sharedQuotaSums[service.Type] != nil {\n\t\t\t\t\t\tfor _, resource := range service.Resources {\n\t\t\t\t\t\t\tquota, exists := sharedQuotaSums[service.Type][resource.Name]\n\t\t\t\t\t\t\tif exists {\n\t\t\t\t\t\t\t\tresource.DomainsQuota = quota\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tusage, exists := sharedUsageSums[service.Type][resource.Name]\n\t\t\t\t\t\t\tif exists {\n\t\t\t\t\t\t\t\tresource.Usage = usage\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}\n\n\t\t//third query again, but this time to collect shared capacities\n\t\tqueryStr, joinArgs = filter.PrepareQuery(clusterReportQuery3)\n\t\tif !withSubcapacities {\n\t\t\tqueryStr = strings.Replace(queryStr, \"cr.subcapacities\", \"''\", 1)\n\t\t}\n\t\tfilter := map[string]interface{}{\"cs.cluster_id\": \"shared\"}\n\t\twhereStr, whereArgs = db.BuildSimpleWhereClause(filter, len(joinArgs))\n\t\terr = db.ForeachRow(db.DB, fmt.Sprintf(queryStr, whereStr), append(joinArgs, whereArgs...), func(rows *sql.Rows) error {\n\t\t\tvar (\n\t\t\t\tsharedClusterID string\n\t\t\t\tserviceType string\n\t\t\t\tresourceName *string\n\t\t\t\trawCapacity *uint64\n\t\t\t\tcomment *string\n\t\t\t\tsubcapacities *string\n\t\t\t\tscrapedAt util.Time\n\t\t\t)\n\t\t\terr := rows.Scan(&sharedClusterID, &serviceType, &resourceName, &rawCapacity, &comment, &subcapacities, &scrapedAt)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfor _, cluster := range clusters {\n\t\t\t\tif !config.Clusters[cluster.ID].IsServiceShared[serviceType] {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t_, _, resource := clusters.Find(config, cluster.ID, &serviceType, resourceName)\n\n\t\t\t\tif resource != nil {\n\t\t\t\t\tovercommitFactor := config.Clusters[cluster.ID].BehaviorForResource(serviceType, *resourceName).OvercommitFactor\n\t\t\t\t\tif overcommitFactor == 0 {\n\t\t\t\t\t\tresource.Capacity = rawCapacity\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresource.RawCapacity = rawCapacity\n\t\t\t\t\t\tcapacity := uint64(float64(*rawCapacity) * overcommitFactor)\n\t\t\t\t\t\tresource.Capacity = &capacity\n\t\t\t\t\t}\n\t\t\t\t\tif comment != nil {\n\t\t\t\t\t\tresource.Comment = *comment\n\t\t\t\t\t}\n\t\t\t\t\tif subcapacities != nil && *subcapacities != \"\" {\n\t\t\t\t\t\tresource.Subcapacities = limes.JSONString(*subcapacities)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tscrapedAtUnix := time.Time(scrapedAt).Unix()\n\t\t\t\tif cluster.MaxScrapedAt == nil || *cluster.MaxScrapedAt < scrapedAtUnix {\n\t\t\t\t\tcluster.MaxScrapedAt = &scrapedAtUnix\n\t\t\t\t}\n\t\t\t\tif cluster.MinScrapedAt == nil || *cluster.MinScrapedAt > scrapedAtUnix {\n\t\t\t\t\tcluster.MinScrapedAt = &scrapedAtUnix\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t}\n\n\t//flatten result (with stable order to keep the tests happy)\n\tids := make([]string, 0, len(clusters))\n\tfor id := range clusters {\n\t\tids = append(ids, id)\n\t}\n\tsort.Strings(ids)\n\tresult := make([]*limes.ClusterReport, len(clusters))\n\tfor idx, id := range ids {\n\t\tresult[idx] = clusters[id]\n\t}\n\n\treturn result, nil\n}", "func List(c *client.Client) (*rbacv1.ClusterRoleList, error) {\n\tclusterrolelist, err := c.Clientset.RbacV1().ClusterRoles().List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn clusterrolelist, nil\n}", "func (e *SyncedEnforcer) GetPermissionsForUser(user string) [][]string {\n\te.m.RLock()\n\tdefer e.m.RUnlock()\n\treturn e.Enforcer.GetPermissionsForUser(user)\n}", "func (o DiagnosticsOptions) findClusterClients(rawConfig *clientcmdapi.Config) (*rest.Config, kclientset.Interface, *clientcmdapi.Config, error) {\n\tif o.ClientClusterContext != \"\" { // user has specified cluster context to use\n\t\tcontext, exists := rawConfig.Contexts[o.ClientClusterContext]\n\t\tif !exists {\n\t\t\tconfigErr := fmt.Errorf(\"Specified '%s' as cluster-admin context, but it was not found in your client configuration.\", o.ClientClusterContext)\n\t\t\to.Logger().Error(\"CED1003\", configErr.Error())\n\t\t\treturn nil, nil, nil, configErr\n\t\t}\n\t\treturn o.makeClusterClients(rawConfig, o.ClientClusterContext, context)\n\t}\n\tcurrentContext, exists := rawConfig.Contexts[rawConfig.CurrentContext]\n\tif !exists { // config specified cluster admin context that doesn't exist; complain and quit\n\t\tconfigErr := fmt.Errorf(\"Current context '%s' not found in client configuration; will not attempt cluster diagnostics.\", rawConfig.CurrentContext)\n\t\to.Logger().Error(\"CED1004\", configErr.Error())\n\t\treturn nil, nil, nil, configErr\n\t}\n\n\t// check if current context is already cluster admin\n\tconfig, kube, rawAdminConfig, err := o.makeClusterClients(rawConfig, rawConfig.CurrentContext, currentContext)\n\tif err == nil && config != nil {\n\t\treturn config, kube, rawAdminConfig, nil\n\t}\n\n\t// otherwise, for convenience, search for a context with the same server but with the system:admin user\n\tfor name, context := range rawConfig.Contexts {\n\t\tif context.Cluster == currentContext.Cluster && name != rawConfig.CurrentContext && strings.HasPrefix(context.AuthInfo, \"system:admin/\") {\n\t\t\tconfig, kube, rawAdminConfig, err := o.makeClusterClients(rawConfig, name, context)\n\t\t\tif err != nil || config == nil {\n\t\t\t\tbreak // don't try more than one such context, they'll probably fail the same\n\t\t\t}\n\t\t\treturn config, kube, rawAdminConfig, nil\n\t\t}\n\t}\n\treturn nil, nil, nil, nil\n}", "func (n *Node) ReadUserPermissions(ctx context.Context, u *userpb.User) (ap provider.ResourcePermissions, err error) {\n\t// check if the current user is the owner\n\to, err := n.Owner()\n\tif err != nil {\n\t\t// TODO check if a parent folder has the owner set?\n\t\tappctx.GetLogger(ctx).Error().Err(err).Interface(\"node\", n).Msg(\"could not determine owner, returning default permissions\")\n\t\treturn NoPermissions(), err\n\t}\n\tif o.OpaqueId == \"\" {\n\t\t// this happens for root nodes in the storage. the extended attributes are set to emptystring to indicate: no owner\n\t\t// TODO what if no owner is set but grants are present?\n\t\treturn NoOwnerPermissions(), nil\n\t}\n\tif utils.UserEqual(u.Id, o) {\n\t\tappctx.GetLogger(ctx).Debug().Interface(\"node\", n).Msg(\"user is owner, returning owner permissions\")\n\t\treturn OwnerPermissions(), nil\n\t}\n\n\tap = provider.ResourcePermissions{}\n\n\t// for an efficient group lookup convert the list of groups to a map\n\t// groups are just strings ... groupnames ... or group ids ??? AAARGH !!!\n\tgroupsMap := make(map[string]bool, len(u.Groups))\n\tfor i := range u.Groups {\n\t\tgroupsMap[u.Groups[i]] = true\n\t}\n\n\tvar g *provider.Grant\n\n\t// we read all grantees from the node\n\tvar grantees []string\n\tif grantees, err = n.ListGrantees(ctx); err != nil {\n\t\tappctx.GetLogger(ctx).Error().Err(err).Interface(\"node\", n).Msg(\"error listing grantees\")\n\t\treturn NoPermissions(), err\n\t}\n\n\t// instead of making n getxattr syscalls we are going to list the acls and filter them here\n\t// we have two options here:\n\t// 1. we can start iterating over the acls / grants on the node or\n\t// 2. we can iterate over the number of groups\n\t// The current implementation tries to be defensive for cases where users have hundreds or thousands of groups, so we iterate over the existing acls.\n\tuserace := xattrs.GrantPrefix + xattrs.UserAcePrefix + u.Id.OpaqueId\n\tuserFound := false\n\tfor i := range grantees {\n\t\tswitch {\n\t\t// we only need to find the user once\n\t\tcase !userFound && grantees[i] == userace:\n\t\t\tg, err = n.ReadGrant(ctx, grantees[i])\n\t\tcase strings.HasPrefix(grantees[i], xattrs.GrantPrefix+xattrs.GroupAcePrefix): // only check group grantees\n\t\t\tgr := strings.TrimPrefix(grantees[i], xattrs.GrantPrefix+xattrs.GroupAcePrefix)\n\t\t\tif groupsMap[gr] {\n\t\t\t\tg, err = n.ReadGrant(ctx, grantees[i])\n\t\t\t} else {\n\t\t\t\t// no need to check attribute\n\t\t\t\tcontinue\n\t\t\t}\n\t\tdefault:\n\t\t\t// no need to check attribute\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch {\n\t\tcase err == nil:\n\t\t\tAddPermissions(&ap, g.GetPermissions())\n\t\tcase isAttrUnset(err):\n\t\t\terr = nil\n\t\t\tappctx.GetLogger(ctx).Error().Interface(\"node\", n).Str(\"grant\", grantees[i]).Interface(\"grantees\", grantees).Msg(\"grant vanished from node after listing\")\n\t\t\t// continue with next segment\n\t\tdefault:\n\t\t\tappctx.GetLogger(ctx).Error().Err(err).Interface(\"node\", n).Str(\"grant\", grantees[i]).Msg(\"error reading permissions\")\n\t\t\t// continue with next segment\n\t\t}\n\t}\n\n\tappctx.GetLogger(ctx).Debug().Interface(\"permissions\", ap).Interface(\"node\", n).Interface(\"user\", u).Msg(\"returning aggregated permissions\")\n\treturn ap, nil\n}", "func (c *V1) GetPermissions(path string, username *string) (\n\tread, list bool,\n\tpossibleRead, possibleList bool,\n\trealm string, err error) {\n\tif err = c.EnsureInit(); err != nil {\n\t\treturn false, false, false, false, \"\", err\n\t}\n\n\tperms, maxPerms, realm := c.perPathConfigsReader.getPermissions(path, username)\n\treturn perms.read, perms.list, maxPerms.read, maxPerms.list, realm, nil\n}", "func (db *SQLiteDB) GetPrivilegedUsers(groupID int64) ([]Permission, error) {\n\trows, err := db.Query(\"SELECT `Permission` FROM Permissions WHERE `GroupID`=?\", groupID)\n\tdefer rows.Close()\n\tprms := make([]Permission, 0)\n\tif err != nil {\n\t\tdb.AddLogEvent(Log{Event: \"GetPrivilegedUsers_ErorExecutingTheQuery\", Message: \"Impossible to get afftected rows\", Error: err.Error()})\n\t\treturn prms, err\n\t}\n\tfor rows.Next() {\n\t\tvar (\n\t\t\tid, userID, groupID, perm int64\n\t\t)\n\t\tif err = rows.Scan(&id, &userID, &groupID, &perm); err != nil {\n\t\t\tdb.AddLogEvent(Log{Event: \"GetPrivilegedUsers_RowQueryFetchResultFailed\", Message: \"Impossible to get data from the row\", Error: err.Error()})\n\t\t} else {\n\t\t\tprms = append(prms, Permission{ID: id, UserID: userID, GroupID: groupID, Permission: perm})\n\t\t}\n\t}\n\tif err == sql.ErrNoRows {\n\t\treturn prms, nil\n\t}\n\tif rows.NextResultSet() {\n\t\tdb.AddLogEvent(Log{Event: \"GetPrivilegedUsers_RowsNotFetched\", Message: \"Some rows in the query were not fetched\"})\n\t} else if err := rows.Err(); err != nil {\n\t\tdb.AddLogEvent(Log{Event: \"GetPrivilegedUsers_UnknowQueryError\", Message: \"An unknown error was thrown\", Error: err.Error()})\n\t}\n\treturn prms, err\n}", "func getAccessClusterConfig() (*clusterconfig.ClusterConfig, *AWSCredentials, error) {\n\tclusterConfig := &clusterconfig.ClusterConfig{}\n\tawsCreds := &AWSCredentials{}\n\n\tif flagClusterConfig == \"\" {\n\t\terr := clusterconfig.SetFileDefaults(clusterConfig)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\treadClusterConfigFile(clusterConfig, awsCreds, cachedClusterConfigPath)\n\t} else {\n\t\terr := readClusterConfigFile(clusterConfig, awsCreds, flagClusterConfig)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\terr := setAWSCredentials(awsCreds)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn clusterConfig, awsCreds, nil\n}", "func (p *Proxy) isClusterAdmin(token string) (bool, error) {\n\tclient, err := p.createTypedClient(token)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tsar := &authv1.SelfSubjectAccessReview{\n\t\tSpec: authv1.SelfSubjectAccessReviewSpec{\n\t\t\tResourceAttributes: &authv1.ResourceAttributes{\n\t\t\t\tNamespace: \"openshift-terminal\",\n\t\t\t\tVerb: \"create\",\n\t\t\t\tResource: \"pods\",\n\t\t\t},\n\t\t},\n\t}\n\tres, err := client.AuthorizationV1().SelfSubjectAccessReviews().Create(context.TODO(), sar, metav1.CreateOptions{})\n\tif err != nil || res == nil {\n\t\treturn false, err\n\t}\n\treturn res.Status.Allowed, nil\n}", "func (h *Handler) serveClusterAdmins(w http.ResponseWriter, r *http.Request) {}", "func (m *Group) GetPermissionGrants()([]ResourceSpecificPermissionGrantable) {\n return m.permissionGrants\n}", "func (n *Node) ReadUserPermissions(ctx context.Context, u *userpb.User) (ap provider.ResourcePermissions, accessDenied bool, err error) {\n\t// check if the current user is the owner\n\tif utils.UserEqual(u.Id, n.Owner()) {\n\t\tappctx.GetLogger(ctx).Debug().Str(\"node\", n.ID).Msg(\"user is owner, returning owner permissions\")\n\t\treturn OwnerPermissions(), false, nil\n\t}\n\n\tap = provider.ResourcePermissions{}\n\n\t// for an efficient group lookup convert the list of groups to a map\n\t// groups are just strings ... groupnames ... or group ids ??? AAARGH !!!\n\tgroupsMap := make(map[string]bool, len(u.Groups))\n\tfor i := range u.Groups {\n\t\tgroupsMap[u.Groups[i]] = true\n\t}\n\n\tvar g *provider.Grant\n\n\t// we read all grantees from the node\n\tvar grantees []string\n\tif grantees, err = n.ListGrantees(ctx); err != nil {\n\t\tappctx.GetLogger(ctx).Error().Err(err).Interface(\"node\", n).Msg(\"error listing grantees\")\n\t\treturn NoPermissions(), true, err\n\t}\n\n\t// instead of making n getxattr syscalls we are going to list the acls and filter them here\n\t// we have two options here:\n\t// 1. we can start iterating over the acls / grants on the node or\n\t// 2. we can iterate over the number of groups\n\t// The current implementation tries to be defensive for cases where users have hundreds or thousands of groups, so we iterate over the existing acls.\n\tuserace := prefixes.GrantUserAcePrefix + u.Id.OpaqueId\n\tuserFound := false\n\tfor i := range grantees {\n\t\tswitch {\n\t\t// we only need to find the user once\n\t\tcase !userFound && grantees[i] == userace:\n\t\t\tg, err = n.ReadGrant(ctx, grantees[i])\n\t\tcase strings.HasPrefix(grantees[i], prefixes.GrantGroupAcePrefix): // only check group grantees\n\t\t\tgr := strings.TrimPrefix(grantees[i], prefixes.GrantGroupAcePrefix)\n\t\t\tif groupsMap[gr] {\n\t\t\t\tg, err = n.ReadGrant(ctx, grantees[i])\n\t\t\t} else {\n\t\t\t\t// no need to check attribute\n\t\t\t\tcontinue\n\t\t\t}\n\t\tdefault:\n\t\t\t// no need to check attribute\n\t\t\tcontinue\n\t\t}\n\n\t\tif isGrantExpired(g) {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch {\n\t\tcase err == nil:\n\t\t\t// If all permissions are set to false we have a deny grant\n\t\t\tif grants.PermissionsEqual(g.Permissions, &provider.ResourcePermissions{}) {\n\t\t\t\treturn NoPermissions(), true, nil\n\t\t\t}\n\t\t\tAddPermissions(&ap, g.GetPermissions())\n\t\tcase metadata.IsAttrUnset(err):\n\t\t\tappctx.GetLogger(ctx).Error().Interface(\"node\", n).Str(\"grant\", grantees[i]).Interface(\"grantees\", grantees).Msg(\"grant vanished from node after listing\")\n\t\t\t// continue with next segment\n\t\tdefault:\n\t\t\tappctx.GetLogger(ctx).Error().Err(err).Interface(\"node\", n).Str(\"grant\", grantees[i]).Msg(\"error reading permissions\")\n\t\t\t// continue with next segment\n\t\t}\n\t}\n\n\tappctx.GetLogger(ctx).Debug().Interface(\"permissions\", ap).Interface(\"node\", n).Interface(\"user\", u).Msg(\"returning aggregated permissions\")\n\treturn ap, false, nil\n}", "func clusterList() []string {\n\tif c := envy.String(\"DQLITED_CLUSTER\"); c != \"\" {\n\t\treturn strings.Split(c, \",\")\n\t}\n\treturn defaultCluster\n}", "func GetManegementCluster(version, capiImage, capdImage string) ([]runtime.Object, error) {\n\tcapiObjects, err := GetCAPI(version, capiImage)\n\tif err != nil {\n\t\treturn []runtime.Object{}, err\n\t}\n\n\tnamespaceObj := GetNamespace()\n\tstatefulSet := GetStatefulSet(capdImage)\n\tclusterRole := GetClusterRole()\n\tclusterRoleBinding := GetClusterRoleBinding()\n\n\treturn append(capiObjects,\n\t\t&namespaceObj,\n\t\t&statefulSet,\n\t\t&clusterRole,\n\t\t&clusterRoleBinding,\n\t), nil\n}", "func ExampleAppliancesClient_ListClusterUserCredential() {\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 := armresourceconnector.NewAppliancesClient(\"11111111-2222-3333-4444-555555555555\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := client.ListClusterUserCredential(ctx,\n\t\t\"testresourcegroup\",\n\t\t\"appliance01\",\n\t\tnil)\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 (m *Manager) GetPermissions(ctx context.Context, params model.RequestParams) (int, interface{}, error) {\n\thookResponse := m.integrationMan.InvokeHook(ctx, params)\n\tif hookResponse.CheckResponse() {\n\t\tif err := hookResponse.Error(); err != nil {\n\t\t\treturn hookResponse.Status(), nil, err\n\t\t}\n\n\t\treturn hookResponse.Status(), hookResponse.Result(), nil\n\t}\n\n\treturn http.StatusOK, []interface{}{map[string]interface{}{\"project\": \"*\", \"resource\": \"*\", \"verb\": \"*\"}}, nil\n}", "func listClusters(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {\n\tctx := r.Context()\n\tallowed := permission.Check(t, permission.PermClusterRead)\n\tif !allowed {\n\t\treturn permission.ErrUnauthorized\n\t}\n\tclusters, err := servicemanager.Cluster.List(ctx)\n\tif err != nil {\n\t\tif err == provTypes.ErrNoCluster {\n\t\t\tw.WriteHeader(http.StatusNoContent)\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\tadmin := permission.Check(t, permission.PermClusterAdmin)\n\tif !admin {\n\t\tfor i := range clusters {\n\t\t\tclusters[i].CleanUpSensitive()\n\t\t}\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\treturn json.NewEncoder(w).Encode(clusters)\n}", "func GetAllClusterNode(client redigo.Conn, role string, choose string) ([]string, error) {\n\tret, err := client.Do(\"cluster\", \"nodes\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnodeList := ParseClusterNode(ret.([]byte))\n\tnodeListChoose := ClusterNodeChoose(nodeList, role)\n\n\tresult := make([]string, 0, len(nodeListChoose))\n\tfor _, ele := range nodeListChoose {\n\t\tif choose == \"id\" {\n\t\t\tresult = append(result, ele.Id)\n\t\t} else {\n\t\t\tresult = append(result, ele.Address)\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func (w *WhoCan) getClusterRoleBindings(clusterRoleNames clusterRoles) (clusterRoleBindings []rbac.ClusterRoleBinding, err error) {\n\tctx := context.Background()\n\tlist, err := w.clientRBAC.ClusterRoleBindings().List(ctx, metav1.ListOptions{})\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, roleBinding := range list.Items {\n\t\tif _, ok := clusterRoleNames[roleBinding.RoleRef.Name]; ok {\n\t\t\tclusterRoleBindings = append(clusterRoleBindings, roleBinding)\n\t\t}\n\t}\n\n\treturn\n}", "func (c *ClusterStatusManager) getClusterPods(clusterName, namespace string, clusterLabels map[string]string) (*corev1.PodList, error) {\n\tpods := &corev1.PodList{\n\t\tTypeMeta: resource.GetPodTypeMeta(),\n\t}\n\n\tlabelSelector := map[string]string{\n\t\t\"cluster\": clusterName,\n\t\t\"type\": \"cassandra-node\",\n\t\t\"state\": \"serving\",\n\t}\n\n\tif appName, ok := clusterLabels[\"app\"]; ok {\n\t\tlabelSelector[\"app\"] = appName\n\t}\n\n\tlistOpts := &metav1.ListOptions{\n\t\tLabelSelector: labels.SelectorFromSet(labelSelector).String(),\n\t}\n\n\terr := c.listerUpdater.List(namespace, pods, sdk.WithListOptions(listOpts))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not list pods for cluster %s: %s\", clusterName, err)\n\t}\n\n\treturn pods, nil\n}", "func (m *Manager) ListCluster() error {\n\tclusters, err := m.GetClusterList()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch m.logger.GetDisplayMode() {\n\tcase logprinter.DisplayModeJSON:\n\t\tclusterObj := struct {\n\t\t\tClusters []Cluster `json:\"clusters\"`\n\t\t}{\n\t\t\tClusters: clusters,\n\t\t}\n\t\tdata, err := json.Marshal(clusterObj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Println(string(data))\n\tdefault:\n\t\tclusterTable := [][]string{\n\t\t\t// Header\n\t\t\t{\"Name\", \"User\", \"Version\", \"Path\", \"PrivateKey\"},\n\t\t}\n\t\tfor _, v := range clusters {\n\t\t\tclusterTable = append(clusterTable, []string{\n\t\t\t\tv.Name,\n\t\t\t\tv.User,\n\t\t\t\tv.Version,\n\t\t\t\tv.Path,\n\t\t\t\tv.PrivateKey,\n\t\t\t})\n\t\t}\n\t\ttui.PrintTable(clusterTable, true)\n\t}\n\treturn nil\n}", "func (adm Admin) ListClusterInfo(cluster string) (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\t// make sure the cluster is already setup\n\tif ok, err := conn.IsClusterSetup(cluster); !ok || err != nil {\n\t\treturn \"\", ErrClusterNotSetup\n\t}\n\n\tkeys := KeyBuilder{cluster}\n\tisPath := keys.idealStates()\n\tinstancesPath := keys.instances()\n\n\tresources, err := conn.Children(isPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tinstances, err := conn.Children(instancesPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"Existing resources in cluster \" + cluster + \":\\n\")\n\n\tfor _, r := range resources {\n\t\tbuffer.WriteString(\" \" + r + \"\\n\")\n\t}\n\n\tbuffer.WriteString(\"\\nInstances in cluster \" + cluster + \":\\n\")\n\tfor _, i := range instances {\n\t\tbuffer.WriteString(\" \" + i + \"\\n\")\n\t}\n\treturn buffer.String(), nil\n}", "func (d *portworx) GetClusterOpts(n node.Node, options []string) (map[string]string, error) {\n\topts := node.ConnectionOpts{\n\t\tIgnoreError: false,\n\t\tTimeBeforeRetry: defaultRetryInterval,\n\t\tTimeout: defaultTimeout,\n\t}\n\tcmd := fmt.Sprintf(\"%s cluster options list -j json\", d.getPxctlPath(n))\n\tout, err := d.nodeDriver.RunCommand(n, cmd, opts)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get pxctl cluster options on node [%s], Err: %v\", n.Name, err)\n\t}\n\tvar data = map[string]interface{}{}\n\terr = json.Unmarshal([]byte(out), &data)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal pxctl cluster option on node [%s], Err: %v\", n.Name, err)\n\t}\n\tsort.Strings(options)\n\tvar options_map = make(map[string]string)\n\t//Values can be string, array or map\n\tfor key, val := range data {\n\t\tindex := sort.SearchStrings(options, key)\n\t\tif index < len(options) && options[index] == key {\n\t\t\toptions_map[key] = fmt.Sprint(val)\n\t\t}\n\t}\n\t//Make sure required options are available\n\tfor _, option := range options {\n\t\tif _, ok := options_map[option]; !ok {\n\t\t\treturn nil, fmt.Errorf(\"Failed to find option: %v\", option)\n\t\t}\n\t}\n\treturn options_map, nil\n}", "func ClusterPolicyToSelectableFields(clusterPolicy *authorizationapi.ClusterPolicy) labels.Set {\n\treturn labels.Set{\n\t\t\"metadata.name\": clusterPolicy.Name,\n\t}\n}", "func (cli *Service) GetRolePri(req *restful.Request, resp *restful.Response) {\n\n\tlanguage := util.GetActionLanguage(req)\n\townerID := util.GetOwnerID(req.Request.Header)\n\tdefErr := cli.Core.CCErr.CreateDefaultCCErrorIf(language)\n\tctx := util.GetDBContext(context.Background(), req.Request.Header)\n\tdb := cli.Instance.Clone()\n\n\tdefer req.Request.Body.Close()\n\tpathParams := req.PathParameters()\n\tobjID := pathParams[\"bk_obj_id\"]\n\tpropertyID := pathParams[\"bk_property_id\"]\n\tcond := make(map[string]interface{})\n\tcond[common.BKObjIDField] = objID\n\tcond[common.BKPropertyIDField] = propertyID\n\tvar result map[string]interface{}\n\tcond = util.SetModOwner(cond, ownerID)\n\n\tcnt, err := db.Table(common.BKTableNamePrivilege).Find(cond).Count(ctx)\n\tif nil != err {\n\t\tblog.Error(\"get user group privi error :%v\", err)\n\t\tresp.WriteError(http.StatusBadRequest, &meta.RespError{Msg: defErr.New(common.CCErrObjectDBOpErrno, err.Error())})\n\t\treturn\n\t}\n\tif 0 == cnt { // TODO:\n\t\tblog.V(3).Infof(\"failed to find the cnt\")\n\t\tinfo := make(map[string]interface{})\n\t\tresp.WriteEntity(meta.Response{BaseResp: meta.SuccessBaseResp, Data: info})\n\t\treturn\n\t}\n\n\terr = db.Table(common.BKTableNamePrivilege).Find(cond).One(ctx, &result)\n\tif nil != err {\n\t\tblog.Error(\"get role pri field error :%v\", err)\n\t\tresp.WriteError(http.StatusBadRequest, &meta.RespError{Msg: defErr.New(common.CCErrCommDBSelectFailed, err.Error())})\n\t\treturn\n\n\t}\n\tprivilege, ok := result[\"privilege\"]\n\tif !ok {\n\t\tblog.Errorf(\"not privilege, the origin data is %#v\", result)\n\t\tinfo := make(map[string]interface{})\n\t\tresp.WriteEntity(meta.Response{BaseResp: meta.SuccessBaseResp, Data: info})\n\t\treturn\n\n\t}\n\tresp.WriteEntity(meta.Response{BaseResp: meta.SuccessBaseResp, Data: privilege})\n}", "func (p *ProjectProvider) List(options *provider.ProjectListOptions) ([]*kubermaticapiv1.Project, error) {\n\tif options == nil {\n\t\toptions = &provider.ProjectListOptions{}\n\t}\n\tprojects := &kubermaticapiv1.ProjectList{}\n\tif err := p.clientPrivileged.List(context.Background(), projects); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar ret []*kubermaticapiv1.Project\n\tfor _, project := range projects.Items {\n\t\tif len(options.ProjectName) > 0 && project.Spec.Name != options.ProjectName {\n\t\t\tcontinue\n\t\t}\n\t\tif len(options.OwnerUID) > 0 {\n\t\t\towners := project.GetOwnerReferences()\n\t\t\tfor _, owner := range owners {\n\t\t\t\tif owner.UID == options.OwnerUID {\n\t\t\t\t\tret = append(ret, project.DeepCopy())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tret = append(ret, project.DeepCopy())\n\t}\n\n\t// Filter out restricted labels\n\tfor i, project := range ret {\n\t\tproject.Labels = label.FilterLabels(label.ClusterResourceType, project.Labels)\n\t\tret[i] = project\n\t}\n\n\treturn ret, nil\n}", "func (c *ClientImpl) ListProject(ctx context.Context, hcpHostURL string) ([]hcpModels.Tenant, error) {\n\tspan, _ := opentracing.StartSpanFromContext(ctx, \"List HCP Projects\")\n\tdefer span.Finish()\n\n\tsession, err := c.getSession(ctx, hcpHostURL, hcpUserName, hcpPassword)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstatus = Failure\n\tmonitor := metrics.StartExternalCall(externalSvcName, \"List Projects from HCP\")\n\tdefer func() { monitor.RecordWithStatus(status) }()\n\n\tresp, err := mlopsHttp.ExecuteHTTPRequest(\n\t\tctx,\n\t\tc.client,\n\t\thcpHostURL+projectPathV1,\n\t\thttp.MethodGet,\n\t\tmap[string]string{sessionHeader: session},\n\t\tbytes.NewReader(nil),\n\t)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"while fetching projects from MLOps controller platform.\")\n\t}\n\n\tstatus = Success\n\n\terr = c.deleteSession(ctx, hcpHostURL, session)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar tenants hcpModels.ListTenants\n\t_, parseRespErr := common.ParseResponse(resp, &tenants)\n\tif parseRespErr != nil {\n\t\tlog.Errorf(\"Failed to fetch projects from HCP: %v\", parseRespErr)\n\t\treturn nil, errors.Wrapf(parseRespErr, \"Failed to fetch projects from HCP\")\n\t}\n\n\t// filter only ML projects\n\tvar mlProjects []hcpModels.Tenant\n\tfor _, tenant := range tenants.Embedded.Tenants {\n\t\tif tenant.Features.MlProject {\n\t\t\tmlProjects = append(mlProjects, tenant)\n\t\t}\n\t}\n\treturn mlProjects, nil\n}", "func grantUserPerms(host string, adminToken string, user ssUser, projectKey string) (err error) {\n\t//scan left out, only those with access to the admin token can run analysis?\n\t// \"scan\",\n\tnecessaryPermissions := []string{\"codeviewer\", \"user\"}\n\n\terrChan := make(chan error, len(necessaryPermissions))\n\n\trequestOnePerm := func(permission string, errChan chan<- error) {\n\t\tgrantPermForm := url.Values{}\n\t\tgrantPermForm.Set(\"login\", user.login)\n\t\tgrantPermForm.Set(\"permission\", permission)\n\t\tgrantPermForm.Set(\"projectKey\", projectKey)\n\n\t\treq, err := http.NewRequest(\"POST\", host+\"/api/permissions/add_user\", strings.NewReader(grantPermForm.Encode()))\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\t\treq.SetBasicAuth(adminToken, \"\")\n\t\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\n\t\tcreateResp, err := http.DefaultClient.Do(req)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\n\t\tcreateResp.Body.Close()\n\t\tif createResp.StatusCode != 204 {\n\t\t\terrChan <- errors.New(fmt.Sprint(\"Failed to grant \", user.login, \"permission. Received status code \", string(createResp.StatusCode)))\n\t\t\treturn\n\t\t}\n\t\terrChan <- nil\n\t}\n\n\tfor _, onePerm := range necessaryPermissions {\n\t\tgo requestOnePerm(onePerm, errChan)\n\t}\n\n\tfor range necessaryPermissions {\n\t\tif err = <-errChan; err != nil {\n\t\t\tprintWrapper(err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func ExampleConnectedClusterClient_ListClusterUserCredential_listClusterUserCredentialCspExample() {\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\tclientFactory, err := armhybridkubernetes.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewConnectedClusterClient().ListClusterUserCredential(ctx, \"k8sc-rg\", \"testCluster\", armhybridkubernetes.ListClusterUserCredentialProperties{\n\t\tAuthenticationMethod: to.Ptr(armhybridkubernetes.AuthenticationMethodAAD),\n\t\tClientProxy: to.Ptr(false),\n\t}, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.CredentialResults = armhybridkubernetes.CredentialResults{\n\t// \tKubeconfigs: []*armhybridkubernetes.CredentialResult{\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"credentialName1\"),\n\t// \t\t\tValue: []byte(\"YXBpVmVyc2lvbjogdjENCmNsdXN0ZXJzOg0KLSBjbHVzdGVyOg0KICAgIGNlcnRpZmljYXRlLWF1dGhvcml0eS1kYXRhOiBMUzB0TFMxQ1JVZEpUaUJEUlZKVVNVWkpRMEZVUlMwdExTMHRDazFKU1VWNGVrTkRRWEVyWjBGM1NVSkJaMGxSVTJ0dVdsWnZaekp1VmpKVmNYZEtjblZYTTFCSGVrRk9RbWRyY1docmFVYzVkekJDUVZGelJrRkVRVTRLVFZGemQwTlJXVVJXVVZGRVJYZEthbGVsSlEwbHFRVTVDWjJ0eGFHdHBSemwzTUVKQlVVVkdRVUZQUTBGbk9FRk5TVWxEUTJkTFEwRm5SVUUwV1hCNUNsUmtUMVJSU1dNdmVsaERlR3hTZWtVMF\"),\n\t// \t}},\n\t// }\n}", "func List() ([]clusterapi.Cluster, error) {\n\tvar clusterList []clusterapi.Cluster\n\terr := utils.BrowseMetadataContent(clusterapi.ClusterMetadataPrefix, func(buf *bytes.Buffer) error {\n\t\tvar c clusterapi.Cluster\n\t\terr := gob.NewDecoder(buf).Decode(&c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tclusterList = append(clusterList, c)\n\t\treturn nil\n\t})\n\treturn clusterList, err\n}", "func GetAccessLevels(perm *pconfig.Permissions, u *users.User, d *users.Device, queryUserID int64, ispublic, isself bool) (usr *pconfig.AccessLevel, dev *pconfig.AccessLevel) {\n\tuserRole := GetUserRole(perm, u)\n\tdeviceRole := GetDeviceRole(perm, d)\n\n\t// Now let's find out which access levels to return\n\tvar userAccess string\n\tvar deviceAccess string\n\tif isself {\n\t\tuserAccess = userRole.SelfAccessLevel\n\t\tdeviceAccess = deviceRole.SelfAccessLevel\n\t} else if queryUserID == u.UserID {\n\t\tuserAccess = userRole.UserAccessLevel\n\t\tdeviceAccess = deviceRole.UserAccessLevel\n\t} else if ispublic {\n\t\tuserAccess = userRole.PublicAccessLevel\n\t\tdeviceAccess = deviceRole.PublicAccessLevel\n\t} else {\n\t\tuserAccess = userRole.PrivateAccessLevel\n\t\tdeviceAccess = deviceRole.PrivateAccessLevel\n\t}\n\n\t// Now find these access levels. Note that we give a fatal error if they are not found, since\n\t// validation of configuration ensures that all levels that are mapped do indeed exist. If the\n\t// access levels are not found, it threfore means that there is some form of corruption, and we crash\n\tua, err := perm.GetAccessLevel(userAccess)\n\tif err != nil {\n\t\tlog.Fatalf(\"User Role '%s': %s\", u.Role, err.Error())\n\t}\n\tda, err := perm.GetAccessLevel(deviceAccess)\n\tif err != nil {\n\t\tlog.Fatalf(\"Device Role '%s': %s\", d.Role, err.Error())\n\t}\n\n\treturn ua, da\n}", "func Permisos(perm int64) structs_lwh.Permisos {\n\tuserPerm := perm / 100\n\n\tgroupPerm := (perm - userPerm*100) / 10\n\n\totherPerm := perm - userPerm*100\n\n\tvar permisos structs_lwh.Permisos\n\t//Permisos Usuarios\n\t//------------------------------------------------------------------------------------------\n\tif userPerm%2 == 1 {\n\t\tpermisos.Permiso[0].Exec = true\n\t} else if userPerm%2 == 0 {\n\t\tpermisos.Permiso[0].Exec = false\n\t}\n\n\tif (userPerm/2)%2 == 1 {\n\t\tpermisos.Permiso[0].Write = true\n\t} else if (userPerm/2)%2 == 0 {\n\t\tpermisos.Permiso[0].Write = false\n\t}\n\n\tif ((userPerm/2)/2)%2 == 1 {\n\t\tpermisos.Permiso[0].Read = true\n\t} else if ((userPerm/2)/2)%2 == 0 {\n\t\tpermisos.Permiso[0].Read = false\n\t}\n\t//-----------------------------------------------------------------------------------------------\n\n\tif groupPerm%2 == 1 {\n\t\tpermisos.Permiso[1].Exec = true\n\t} else if groupPerm%2 == 0 {\n\t\tpermisos.Permiso[1].Exec = false\n\t}\n\n\tif (groupPerm/2)%2 == 1 {\n\t\tpermisos.Permiso[1].Write = true\n\t} else if (groupPerm/2)%2 == 0 {\n\t\tpermisos.Permiso[1].Write = false\n\t}\n\n\tif ((groupPerm/2)/2)%2 == 1 {\n\t\tpermisos.Permiso[1].Read = true\n\t} else if ((groupPerm/2)/2)%2 == 0 {\n\t\tpermisos.Permiso[1].Read = false\n\t}\n\t//------------------------------------------------------------------------------------------------\n\n\tif otherPerm%2 == 1 {\n\t\tpermisos.Permiso[2].Exec = true\n\t} else if otherPerm%2 == 0 {\n\t\tpermisos.Permiso[2].Exec = true\n\t}\n\n\tif (otherPerm/2)%2 == 1 {\n\t\tpermisos.Permiso[2].Write = true\n\t} else if (otherPerm/2)%2 == 0 {\n\t\tpermisos.Permiso[2].Write = false\n\t}\n\n\tif ((otherPerm/2)/2)%2 == 1 {\n\t\tpermisos.Permiso[2].Read = true\n\t} else if ((otherPerm/2)/2)%2 == 0 {\n\t\tpermisos.Permiso[2].Read = false\n\t}\n\treturn permisos\n}", "func (r *Resource) createReadAllClusterRole(ctx context.Context) error {\n\n\tlists, err := r.K8sClient().Discovery().ServerPreferredResources()\n\tif err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\tvar policyRules []rbacv1.PolicyRule\n\t{\n\t\tfor _, list := range lists {\n\t\t\tif len(list.APIResources) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgv, err := schema.ParseGroupVersion(list.GroupVersion)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, resource := range list.APIResources {\n\t\t\t\tif len(resource.Verbs) == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif isRestrictedResource(resource.Name) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tpolicyRule := rbacv1.PolicyRule{\n\t\t\t\t\tAPIGroups: []string{gv.Group},\n\t\t\t\t\tResources: []string{resource.Name},\n\t\t\t\t\tVerbs: []string{\"get\", \"list\", \"watch\"},\n\t\t\t\t}\n\t\t\t\tpolicyRules = append(policyRules, policyRule)\n\t\t\t}\n\t\t}\n\t}\n\n\t// ServerPreferredResources explicitely ignores any resource containing a '/'\n\t// but we require this for enabling pods/logs for customer access to\n\t// kubernetes pod logging. This is appended as a specific rule instead.\n\tpolicyRule := rbacv1.PolicyRule{\n\t\tAPIGroups: []string{\"\"},\n\t\tResources: []string{\"pods/log\"},\n\t\tVerbs: []string{\"get\", \"list\"},\n\t}\n\tpolicyRules = append(policyRules, policyRule)\n\n\treadOnlyClusterRole := &rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: pkgkey.DefaultReadAllPermissionsName,\n\t\t\tLabels: map[string]string{\n\t\t\t\tlabel.ManagedBy: project.Name(),\n\t\t\t\tlabel.DisplayInUserInterface: \"true\",\n\t\t\t},\n\t\t\tAnnotations: map[string]string{\n\t\t\t\tannotation.Notes: \"Grants read-only (get, list, watch) permissions to almost all resource types known on the management cluster, with exception of ConfigMap and Secret.\",\n\t\t\t},\n\t\t},\n\t\tRules: policyRules,\n\t}\n\n\treturn rbac.CreateOrUpdateClusterRole(r, ctx, readOnlyClusterRole)\n}", "func QueryUserHasDashboardPermssion(dashId int64, userId int64,permission int) int8 {\n\tvar rawJSON []byte\n\terr := db.SQL.QueryRow(\"SELECT permission from dashboard_user_acl WHERE dashboard_id=? and user_id=?\",dashId,userId).Scan(&rawJSON)\n\tif err != nil {\n\t\treturn UserAcl_NoPermissionRules\n\t}\n\t\n\tvar permissions []int\n\tjson.Unmarshal(rawJSON,&permissions)\n\n\tfor _,p := range permissions {\n\t\tif p == permission {\n\t\t\treturn UserAcl_PermissionAllow\n\t\t}\n\t}\n\n\treturn UserAcl_PermissionForbidden\n}", "func GetRoleInfo(rid int64, s *PermMaps) {\n\tfound := -1\n\tidx := -1\n\n\t// try to find the requested index\n\t// lib.Ulog(\"len(Authz.Roles)=%d\\n\", len(Authz.Roles))\n\t// lib.Ulog(\"GetRoleInfo - looking for rid=%d\\n\", rid)\n\tfor i := 0; i < len(Authz.Roles); i++ {\n\t\t// lib.Ulog(\"Authz.Roles[%d] = %+v\\n\", i, Authz.Roles[i])\n\t\tif rid == Authz.Roles[i].RID {\n\t\t\tfound = i\n\t\t\tidx = i\n\t\t\ts.Urole.Name = Authz.Roles[i].Name\n\t\t\ts.Urole.RID = rid\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif found < 0 {\n\t\tidx = 0\n\t\tlib.Ulog(\"Did not find rid == %d, all permissions set to read-only\\n\", rid)\n\t}\n\n\tr := Authz.Roles[idx]\n\ts.Pp = make(map[string]int64)\n\ts.Pco = make(map[string]int64)\n\ts.Pcl = make(map[string]int64)\n\ts.Ppr = make(map[string]int64)\n\n\tfor i := 0; i < len(r.Perms); i++ {\n\t\tvar f FieldPerm\n\t\tf.Elem = r.Perms[i].Elem\n\t\tf.Field = r.Perms[i].Field\n\t\tif found < 0 {\n\t\t\tf.Perm = PERMVIEW\n\t\t} else {\n\t\t\tf.Perm = r.Perms[i].Perm\n\t\t}\n\t\ts.Urole.Perms = append(s.Urole.Perms, f)\n\n\t\t// fast access maps:\n\t\tswitch f.Elem {\n\t\tcase ELEMPERSON:\n\t\t\ts.Pp[f.Field] = f.Perm\n\t\tcase ELEMCOMPANY:\n\t\t\ts.Pco[f.Field] = f.Perm\n\t\tcase ELEMCLASS:\n\t\t\ts.Pcl[f.Field] = f.Perm\n\t\tcase ELEMPBSVC:\n\t\t\ts.Ppr[f.Field] = f.Perm\n\t\t}\n\t}\n}", "func newVserverUserAccess(cluster *config.Cluster) (vserverUserAccess, error) {\n\tvua := make(vserverUserAccess)\n\tfor _, vs := range cluster.Vservers {\n\t\tfor _, ag := range vs.AccessGrants {\n\t\t\tif !ag.IsGroup {\n\t\t\t\tvua.grantAccess(vs.Name, ag.Grantee, ag.Key())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgroup, ok := cluster.AccessGroups[ag.Grantee]\n\t\t\tif !ok {\n\t\t\t\tlog.Warningf(\"vserver %v references non-existent access group %q, ignoring\", vs.Name, ag.Grantee)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, username := range group.Members {\n\t\t\t\tvua.grantAccess(vs.Name, username, ag.Key())\n\t\t\t}\n\t\t}\n\t}\n\treturn vua, nil\n}", "func (m *User) GetOauth2PermissionGrants()([]OAuth2PermissionGrantable) {\n return m.oauth2PermissionGrants\n}", "func GetAllPermissions(c *gin.Context) {\r\n\trole := model.Role{}\r\n\tmenus, err := role.GetMenus()\r\n\tif err != nil {\r\n\t\tutils.InternalError(c, nil, \"数据库操作失败\")\r\n\t\treturn\r\n\t}\r\n\tpermissions, err := role.GetPermissions()\r\n\tif err != nil {\r\n\t\tutils.InternalError(c, nil, \"数据库操作失败\")\r\n\t\treturn\r\n\t}\r\n\tutils.Success(c, gin.H{\"menus\": menus, \"permissions\": permissions}, \"权限查询成功\")\r\n}", "func DetectClusterRole(c *Conf) {\n\tclusterRoleBindings := &rbacv1.ClusterRoleBindingList{}\n\tselector := labels.SelectorFromSet(labels.Set{\n\t\t\"olm.owner.kind\": \"ClusterServiceVersion\",\n\t\t\"olm.owner.namespace\": c.SA.Namespace,\n\t})\n\tutil.KubeList(clusterRoleBindings, &client.ListOptions{\n\t\tLabelSelector: selector,\n\t})\n\tfor i := range clusterRoleBindings.Items {\n\t\tb := &clusterRoleBindings.Items[i]\n\t\tfor j := range b.Subjects {\n\t\t\ts := b.Subjects[j]\n\t\t\tif s.Kind == \"ServiceAccount\" &&\n\t\t\t\ts.Name == c.SA.Name &&\n\t\t\t\ts.Namespace == c.SA.Namespace {\n\t\t\t\tc.ClusterRole.Name = b.RoleRef.Name\n\t\t\t\tc.ClusterRoleBinding.Name = b.Name\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *Client) ListClustersForProject(projectID string) ([]models.Cluster, error) {\n\treq, err := c.newRequest(\"GET\", projectPath+\"/\"+projectID+clustersSubPath, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := make([]models.Cluster, 0)\n\n\tresp, err := c.do(req, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// StatusCodes 401 and 403 mean empty response and should be treated as such\n\tif resp.StatusCode == 401 || resp.StatusCode == 403 {\n\t\treturn nil, nil\n\t}\n\n\tif resp.StatusCode >= 299 {\n\t\treturn nil, errors.New(\"Got non-2xx return code: \" + strconv.Itoa(resp.StatusCode))\n\t}\n\n\treturn result, nil\n}", "func (c *ClientIMPL) GetCluster(ctx context.Context) (resp Cluster, err error) {\n\tvar systemList []Cluster\n\tcluster := Cluster{}\n\tqp := c.APIClient().QueryParamsWithFields(&cluster)\n\n\tmajorMinorVersion, err := c.GetSoftwareMajorMinorVersion(ctx)\n\tif err != nil {\n\t\tlog.Errorf(\"Couldn't find the array version %s\", err.Error())\n\t} else {\n\t\tif majorMinorVersion >= 3.0 {\n\t\t\tqp.Select(\"nvm_subsystem_nqn\")\n\t\t}\n\t}\n\t_, err = c.APIClient().Query(\n\t\tctx,\n\t\tRequestConfig{\n\t\t\tMethod: \"GET\",\n\t\t\tEndpoint: clusterURL,\n\t\t\tQueryParams: qp,\n\t\t},\n\t\t&systemList)\n\terr = WrapErr(err)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\treturn systemList[0], err\n}", "func (a *HyperflexApiService) GetHyperflexProtectedClusterList(ctx context.Context) ApiGetHyperflexProtectedClusterListRequest {\n\treturn ApiGetHyperflexProtectedClusterListRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (c *config) Perm(u *model.User, owner, name string) (*model.Perm, error) {\n\tclient := c.newClient(u)\n\n\tperms := new(model.Perm)\n\trepo, err := client.FindRepo(owner, name)\n\tif err != nil {\n\t\treturn perms, err\n\t}\n\n\tperm, err := client.GetPermission(repo.FullName)\n\tif err != nil {\n\t\treturn perms, err\n\t}\n\n\tswitch perm.Permission {\n\tcase \"admin\":\n\t\tperms.Admin = true\n\t\tfallthrough\n\tcase \"write\":\n\t\tperms.Push = true\n\t\tfallthrough\n\tdefault:\n\t\tperms.Pull = true\n\t}\n\n\treturn perms, nil\n}", "func NewGetClusterForbidden() *GetClusterForbidden {\n\n\treturn &GetClusterForbidden{}\n}", "func GetClusterCredentialsInfo(cm *kuberlogicv1.KuberLogicService) (username, passwordField, secretName string, err error) {\n\top, err := GetCluster(cm)\n\tif err != nil {\n\t\treturn\n\t}\n\tdetails := op.GetInternalDetails()\n\tsecretName, passwordField = details.GetDefaultConnectionPassword()\n\tusername = details.GetDefaultConnectionUser()\n\treturn\n}", "func (this *managerStruct) Permissions(name string) ([]string, error) {\n\tthis.mutex.RLock()\n\tid := this.getUserId(name)\n\n\t/*\n\t * Check if we have a user with the name provided to us.\n\t */\n\tif id < 0 {\n\t\tthis.mutex.RUnlock()\n\t\treturn nil, fmt.Errorf(\"User '%s' does not exist.\", name)\n\t} else {\n\t\tusers := this.users\n\t\tuser := users[id]\n\t\tpermissions := user.permissions\n\t\tnumPermissions := len(permissions)\n\t\tpermissionsCopy := make([]string, numPermissions)\n\t\tcopy(permissionsCopy, permissions)\n\t\tthis.mutex.RUnlock()\n\t\treturn permissionsCopy, nil\n\t}\n\n}", "func (e *Enforcer) GetPermissionsForUser(user string) [][]string {\n\treturn e.GetFilteredPolicy(0, user)\n}", "func (s *Server) getCollaborative(request *restful.Request, response *restful.Response) {\n\t// Authorize\n\tif !s.auth(request, response) {\n\t\treturn\n\t}\n\t// Get user id\n\tuserId := request.PathParameter(\"user-id\")\n\ts.getList(cache.CollaborativeItems, userId, request, response)\n}", "func (s *Server) getCollaborative(request *restful.Request, response *restful.Response) {\n\t// Authorize\n\tif !s.auth(request, response) {\n\t\treturn\n\t}\n\t// Get user id\n\tuserId := request.PathParameter(\"user-id\")\n\ts.getList(cache.CollaborativeItems, userId, request, response)\n}", "func (adm Admin) ListClusterInfo(cluster string) (string, error) {\n\t// make sure the cluster is already setup\n\tif ok, err := adm.isClusterSetup(cluster); !ok || err != nil {\n\t\treturn \"\", ErrClusterNotSetup\n\t}\n\n\tbuilder := KeyBuilder{cluster}\n\tisPath := builder.idealStates()\n\tinstancesPath := builder.instances()\n\n\tresources, err := adm.zkClient.Children(isPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tinstances, err := adm.zkClient.Children(instancesPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"Existing resources in cluster \" + cluster + \":\\n\")\n\n\tfor _, r := range resources {\n\t\tbuffer.WriteString(\" \" + r + \"\\n\")\n\t}\n\n\tbuffer.WriteString(\"\\nInstances in cluster \" + cluster + \":\\n\")\n\tfor _, i := range instances {\n\t\tbuffer.WriteString(\" \" + i + \"\\n\")\n\t}\n\treturn buffer.String(), nil\n}", "func (c *client) TeamPerm(u *model.User, org string) (*model.Perm, error) {\n\treturn nil, nil\n}", "func ListAllCluster(c echo.Context) error {\n\tcblog.Info(\"call ListAllCluster()\")\n\n\tvar req struct {\n\t\tNameSpace string\n\t\tConnectionName string\n\t}\n\n\tif err := c.Bind(&req); err != nil {\n\t\treturn echo.NewHTTPError(http.StatusInternalServerError, err.Error())\n\t}\n\n\t// To support for Get-Query Param Type API\n\tif req.ConnectionName == \"\" {\n\t\treq.ConnectionName = c.QueryParam(\"ConnectionName\")\n\t}\n\n\t// Call common-runtime API\n\tallResourceList, err := cmrt.ListAllResource(req.ConnectionName, rsCluster)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusInternalServerError, err.Error())\n\t}\n\n\t// To support for Get-Query Param Type API\n\tif req.NameSpace == \"\" {\n\t\treq.NameSpace = c.QueryParam(\"NameSpace\")\n\t}\n\n\t// Resource Name has namespace prefix when from Tumblebug\n\tif req.NameSpace != \"\" {\n\t\tnameSpace := req.NameSpace + \"-\"\n\t\tfor idx, IID := range allResourceList.AllList.MappedList {\n\t\t\tif IID.NameId != \"\" {\n\t\t\t\tallResourceList.AllList.MappedList[idx].NameId = strings.Replace(IID.NameId, nameSpace, \"\", 1)\n\t\t\t}\n\t\t}\n\t\tfor idx, IID := range allResourceList.AllList.OnlySpiderList {\n\t\t\tif IID.NameId != \"\" {\n\t\t\t\tallResourceList.AllList.OnlySpiderList[idx].NameId = strings.Replace(IID.NameId, nameSpace, \"\", 1)\n\t\t\t}\n\t\t}\n\t\tfor idx, IID := range allResourceList.AllList.OnlyCSPList {\n\t\t\tif IID.NameId != \"\" {\n\t\t\t\tallResourceList.AllList.OnlyCSPList[idx].NameId = strings.Replace(IID.NameId, nameSpace, \"\", 1)\n\t\t\t}\n\t\t}\n\t}\n\n\tvar jsonResult struct {\n\t\tConnection string\n\t\tAllResourceList *cmrt.AllResourceList\n\t}\n\tjsonResult.Connection = req.ConnectionName\n\tjsonResult.AllResourceList = &allResourceList\n\n\treturn c.JSON(http.StatusOK, &jsonResult)\n}", "func ExampleConnectedClusterClient_ListClusterUserCredential_listClusterUserCredentialExample() {\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\tclientFactory, err := armhybridkubernetes.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewConnectedClusterClient().ListClusterUserCredential(ctx, \"k8sc-rg\", \"testCluster\", armhybridkubernetes.ListClusterUserCredentialProperties{\n\t\tAuthenticationMethod: to.Ptr(armhybridkubernetes.AuthenticationMethodAAD),\n\t\tClientProxy: to.Ptr(true),\n\t}, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.CredentialResults = armhybridkubernetes.CredentialResults{\n\t// \tHybridConnectionConfig: &armhybridkubernetes.HybridConnectionConfig{\n\t// \t\tExpirationTime: to.Ptr[int64](1631196183),\n\t// \t\tHybridConnectionName: to.Ptr(\"microsoft.kubernetes/connectedclusters/229dc73f7b07196c79a93d4362d9c7fc4ed34df3e95290d27c56cec2dbb82865/1631185383340987904\"),\n\t// \t\tRelay: to.Ptr(\"azgnrelay-ph0-l1\"),\n\t// \t\tToken: to.Ptr(\"SharedAccessSignature 123456789034675890pbduwegiavifkuw647o02423bbhfouseb\"),\n\t// \t},\n\t// \tKubeconfigs: []*armhybridkubernetes.CredentialResult{\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"credentialName1\"),\n\t// \t\t\tValue: []byte(\"YXBpVmVyc2lvbjogdjENCmNsdXN0ZXJzOg0KLSBjbHVzdGVyOg0KICAgIGNlcnRpZmljYXRlLWF1dGhvcml0eS1kYXRhOiBMUzB0TFMxQ1JVZEpUaUJEUlZKVVNVWkpRMEZVUlMwdExTMHRDazFKU1VWNGVrTkRRWEVyWjBGM1NVSkJaMGxSVTJ0dVdsWnZaekp1VmpKVmNYZEtjblZYTTFCSGVrRk9RbWRyY1docmFVYzVkekJDUVZGelJrRkVRVTRLVFZGemQwTlJXVVJXVVZGRVJYZEthbGVsSlEwbHFRVTVDWjJ0eGFHdHBSemwzTUVKQlVVVkdRVUZQUTBGbk9FRk5TVWxEUTJkTFEwRm5SVUUwV1hCNUNsUmtUMVJSU1dNdmVsaERlR3hTZWtVMF\"),\n\t// \t}},\n\t// }\n}", "func (adm Admin) GetConfig(cluster string, scope string, keys []string) map[string]interface{} {\n\tconn := newConnection(adm.ZkSvr)\n\terr := conn.Connect()\n\tif err != nil {\n\t\treturn nil\n\t}\n\tdefer conn.Disconnect()\n\n\tresult := make(map[string]interface{})\n\n\tswitch scope {\n\tcase \"CLUSTER\":\n\t\tkb := KeyBuilder{cluster}\n\t\tpath := kb.clusterConfig()\n\n\t\tfor _, k := range keys {\n\t\t\tresult[k] = conn.GetSimpleFieldValueByKey(path, k)\n\t\t}\n\tcase \"CONSTRAINT\":\n\tcase \"PARTICIPANT\":\n\tcase \"PARTITION\":\n\tcase \"RESOURCE\":\n\t}\n\n\treturn result\n}", "func List(ctx context.Context, client *v1.ServiceClient, clusterID string) ([]*View, *v1.ResponseResult, error) {\n\turl := strings.Join([]string{client.Endpoint, v1.ResourceURLCluster, clusterID, v1.ResourceURLNodegroup}, \"/\")\n\tresponseResult, err := client.DoRequest(ctx, http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif responseResult.Err != nil {\n\t\treturn nil, responseResult, responseResult.Err\n\t}\n\n\t// Extract nodegroups from the response body.\n\tvar result struct {\n\t\tNodegroups []*View `json:\"nodegroups\"`\n\t}\n\terr = responseResult.ExtractResult(&result)\n\tif err != nil {\n\t\treturn nil, responseResult, err\n\t}\n\n\treturn result.Nodegroups, responseResult, err\n}", "func AuthClusterResourceCreatorPerm(ctx context.Context, clusterID, clusterName, user string) {\n\ttaskID := cloudprovider.GetTaskIDFromContext(ctx)\n\n\terr := auth.IAMClient.AuthResourceCreatorPerm(ctx, iam.ResourceCreator{\n\t\tResourceType: string(iam.SysCluster),\n\t\tResourceID: clusterID,\n\t\tResourceName: clusterName,\n\t\tCreator: user,\n\t}, nil)\n\tif err != nil {\n\t\tblog.Errorf(\"AuthClusterResourceCreatorPerm[%s] resource[%s:%s] failed: %v\",\n\t\t\ttaskID, clusterID, clusterName, user)\n\t\treturn\n\t}\n\n\tblog.Infof(\"AuthClusterResourceCreatorPerm[%s] resource[%s:%s] successful\",\n\t\ttaskID, clusterID, clusterName, user)\n}", "func (o DiagnosticsOptions) makeClusterClients(rawConfig *clientcmdapi.Config, contextName string, context *clientcmdapi.Context) (*rest.Config, kclientset.Interface, *clientcmdapi.Config, error) {\n\t// create a config for making openshift clients\n\tconfig, err := o.Factory.ToRESTConfig()\n\tif err != nil {\n\t\to.Logger().Debug(\"CED1006\", fmt.Sprintf(\"Error creating client config for context '%s':\\n%v\", contextName, err))\n\t\treturn nil, nil, nil, nil\n\t}\n\n\t// create a kube client\n\tkubeClient, err := kclientset.NewForConfig(config)\n\tif err != nil {\n\t\to.Logger().Debug(\"CED1006\", fmt.Sprintf(\"Error creating kube client for context '%s':\\n%v\", contextName, err))\n\t\treturn nil, nil, nil, nil\n\t}\n\n\to.Logger().Debug(\"CED1005\", fmt.Sprintf(\"Checking if context is cluster-admin: '%s'\", contextName))\n\tsubjectAccessReview := &authorization.SelfSubjectAccessReview{\n\t\tSpec: authorization.SelfSubjectAccessReviewSpec{\n\t\t\tResourceAttributes: &authorization.ResourceAttributes{\n\t\t\t\t// if you can do everything, you're the cluster admin.\n\t\t\t\tVerb: \"*\",\n\t\t\t\tGroup: \"*\",\n\t\t\t\tResource: \"*\",\n\t\t\t},\n\t\t},\n\t}\n\tresp, err := kubeClient.Authorization().SelfSubjectAccessReviews().Create(subjectAccessReview)\n\tif err != nil && regexp.MustCompile(`User \"[\\w:]+\" cannot create \\w+ at the cluster scope`).MatchString(err.Error()) {\n\t\to.Logger().Debug(\"CED1007\", fmt.Sprintf(\"Context '%s' does not have cluster-admin access:\\n%v\", contextName, err))\n\t\treturn nil, nil, nil, nil\n\t}\n\tif err != nil {\n\t\to.Logger().Error(\"CED1008\", fmt.Sprintf(\"Unknown error testing cluster-admin access for context '%s':\\n%v\", contextName, err))\n\t\treturn nil, nil, nil, err\n\t}\n\tif !resp.Status.Allowed {\n\t\to.Logger().Debug(\"CED1010\", fmt.Sprintf(\"Context does not have cluster-admin access: '%s'\", contextName))\n\t\treturn nil, nil, nil, nil\n\t}\n\n\to.Logger().Info(\"CED1009\", fmt.Sprintf(\"Using context for cluster-admin access: '%s'\", contextName))\n\tadminConfig := rawConfig.DeepCopy()\n\tadminConfig.CurrentContext = contextName\n\tif err := clientcmdapi.MinifyConfig(adminConfig); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tif err := clientcmdapi.FlattenConfig(adminConfig); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\treturn config, kubeClient, adminConfig, nil\n}", "func (App) Permissions() []evo.Permission { return []evo.Permission{} }", "func (k *KubeadmBootstrapper) GetClusterLogsTo(follow bool, out io.Writer) error {\n\tvar flags []string\n\tif follow {\n\t\tflags = append(flags, \"-f\")\n\t}\n\tlogsCommand := fmt.Sprintf(\"sudo journalctl %s -u kubelet\", strings.Join(flags, \" \"))\n\n\tif follow {\n\t\tif err := k.c.CombinedOutputTo(logsCommand, out); err != nil {\n\t\t\treturn errors.Wrap(err, \"getting cluster logs\")\n\t\t}\n\t} else {\n\n\t\tlogs, err := k.c.CombinedOutput(logsCommand)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"getting cluster logs\")\n\t\t}\n\t\tfmt.Fprint(out, logs)\n\t}\n\treturn nil\n}", "func getMemberClusterApiServerUrls(kubeconfig *clientcmdapi.Config, clusterNames []string) ([]string, error) {\n\tvar urls []string\n\tfor _, name := range clusterNames {\n\t\tif cluster := kubeconfig.Clusters[name]; cluster != nil {\n\t\t\turls = append(urls, cluster.Server)\n\t\t} else {\n\t\t\treturn nil, xerrors.Errorf(\"cluster '%s' not found in kubeconfig\", name)\n\t\t}\n\t}\n\treturn urls, nil\n}", "func rgwGetGCTaskList(config string, user string) ([]byte, error) {\n\tvar (\n\t\tout []byte\n\t\terr error\n\t)\n\n\tif out, err = exec.Command(radosgwAdminPath, \"-c\", config, \"--user\", user, \"gc\", \"list\", \"--include-all\").Output(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn out, nil\n}", "func (s *permStore) List(ctx context.Context, repo string) ([]*core.Collaborator, error) {\n\tvar out []*core.Collaborator\n\terr := s.db.View(func(queryer db.Queryer, binder db.Binder) error {\n\t\tparams := map[string]interface{}{\"repo_uid\": repo}\n\t\tstmt, args, err := binder.BindNamed(queryCollabs, params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trows, err := queryer.Query(stmt, args...)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tout, err = scanCollabRows(rows)\n\t\treturn err\n\t})\n\treturn out, err\n}", "func (a *HyperflexApiService) GetHyperflexClusterProfileList(ctx context.Context) ApiGetHyperflexClusterProfileListRequest {\n\treturn ApiGetHyperflexClusterProfileListRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (t *Translator) filterForCluster() string {\n\tprojectFilter := fmt.Sprintf(\"resource.labels.project_id = %q\", t.config.Project)\n\tclusterFilter := fmt.Sprintf(\"resource.labels.cluster_name = %q\", t.config.Cluster)\n\tlocationFilter := fmt.Sprintf(\"resource.labels.location = %q\", t.config.Location)\n\treturn fmt.Sprintf(\"%s AND %s AND %s\", projectFilter, clusterFilter, locationFilter)\n}", "func (n *Node) PermissionSet(ctx context.Context) provider.ResourcePermissions {\n\tu, ok := ctxpkg.ContextGetUser(ctx)\n\tif !ok {\n\t\tappctx.GetLogger(ctx).Debug().Interface(\"node\", n).Msg(\"no user in context, returning default permissions\")\n\t\treturn NoPermissions()\n\t}\n\tif o, _ := n.Owner(); utils.UserEqual(u.Id, o) {\n\t\treturn OwnerPermissions()\n\t}\n\t// read the permissions for the current user from the acls of the current node\n\tif np, err := n.ReadUserPermissions(ctx, u); err == nil {\n\t\treturn np\n\t}\n\treturn NoPermissions()\n}", "func ExampleConnectedClusterClient_ListClusterUserCredential_listClusterUserCredentialNonAadCspExample() {\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\tclientFactory, err := armhybridkubernetes.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewConnectedClusterClient().ListClusterUserCredential(ctx, \"k8sc-rg\", \"testCluster\", armhybridkubernetes.ListClusterUserCredentialProperties{\n\t\tAuthenticationMethod: to.Ptr(armhybridkubernetes.AuthenticationMethodToken),\n\t\tClientProxy: to.Ptr(false),\n\t}, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.CredentialResults = armhybridkubernetes.CredentialResults{\n\t// \tKubeconfigs: []*armhybridkubernetes.CredentialResult{\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"credentialName1\"),\n\t// \t\t\tValue: []byte(\"YXBpVmVyc2lvbjogdjEKY2x1c3RlcnM6CiAgLSBjbHVzdGVyOgogICAgICBjZXJ0aWZpY2F0ZS1hdXRob3JpdHktZGF0YTogTFMwdExTMUNSVWRKVGlCRFJWSlVTVVpKUTBGVVJTMHRMUzB0Q2sxSlNVaDJWRU5EUW1GWFowRjNTVUpCWjBsVVlYZEJRVUV5VkhWQlRYaEJhVWx5UldsQlFVRkJRVUZFV2tSQlRrSm5hM0ZvYTJsSE9YY3dRa0ZSYzBaQlJFSlFUVkZ6ZDBOUldVUldVVkZIUlhkS1ZsVjZSV1ZOUW5kSFFURlZSVU5vVFZaVVYyeHFZMjA1ZW1JeVdqQkpSVTUyWTI1Q2RtTnRSakJoVnpsMVRWTkJkMGhuV1VSV1VWRkVSWGhrVG1GWFRubGlNMDUyV201UloxVnNUa0pKUmxKTlZYbENSRkZUUVhkTlZFRmxSbmN3ZVUxRVFUUk5hbU40VFdwTmVFNVVXbUZHZHpCNVRWUkJORTFxWTNoTmFrMTRUbFJhWVUxRFdYaEtSRUZwUW1kT1ZrSkJUVTFIZVc5MVlYcG9lbGt5T1hWaWJWWnFaRU0xTUZwWVRqQk1iVVkyWkZoS2JFeHRUblppVkVORFFWTkpkMFJSV1VwTGIxcEphSFpqVGtGUlJVSkNVVUZFWjJkRlVFRkVRME5CVVc5RFoyZEZRa0ZOU0VwVU0wZEtXbWhMTm5KaVVHSm9XRWN6V21SU05HVlhNSGhSVmxVclIwTjVXSEFyY0VwRFNtUjBhbGgyTjNwMFEzTnJRV0ZaZDJobmQyMHpOMGhFVkVWamNFVlFjR1p6TDJSSFdsQktiek5vU0ZOemVGaENUMUJXYUVsVVRHZFBSa1E0YW5BMVlWZG1kVXA0WWsxUFNqZ3dObWxST0VkT1NVdEZURGM1ZDFkMVNWcG5MemhCWTBZeVNEWnJTMDlWVVhJdmVFMWFjVWx1WW5sQk1XVmhPVW8xTmpKbVNVODRUbEp2YWxORVRFUlBWRzFyWTFaYVdHcHlTaTlsYW1wclVVMUhiV0YyT1hreE9EQjJUVkZ5TTBjM2FXZ3Jkell2VFZocGVWWkpLMGxhY3pSaGVXVTJhREo0VDA5VlNYQnRWVTQ0UlhVNWIwY3ZTSGRHV2swemJHWnBkR0ZQZUhsblEydHBNV2R0VFRsd09FcHhNMVIyVVRSbU9YSnBRVWRUVFhaWWVsSlpTa2hOU2toVVRtZFZhV1pZVjFWb1VFWTJWMkZGTWxwbFdVWkdOV1ozU0U5MlVYRnFSa2tyUlZWS1JscE1kekJEUVhkRlFVRmhUME5CTjJ0M1oyZFBNVTFKU1VKQmQxbExTM2RaUWtKQlNGZGxVVWxGUVdkVFFqbEJVMEk0VVVSMlFVaFZRVGxzZVZWTU9VWXpUVU5KVlZaQ1owbE5TbEpYYW5WT1RrVjRhM3AyT1RoTlRIbEJUSHBGTjNoYVQwMUJRVUZHTUV3dlFuTjNRVUZCUWtGTlFWSnFRa1ZCYVVJMFpWSlVTMHhZY1hsM09HazFMeTlyVmtaNWNrTlhZMFZtY0VaV2NGUlZSVFIzYlVNME1rZHhSMkpCU1dkTkswVllkRWhtV0Rrd05WVklZall3Y1hKUlEzUTRibkZhTkUxamRVUjNOMlJaZVhwdGJFc3pja05SUVdSblFtTXpSVTlUTDNWaGNsSlZVM2hZY0hKVlZuVlpVVTR2ZGxZcmEyWmpiMWhQVlhOc04yMDVjMk5QZVdkQlFVRllVWFk0UjNwd1FVRkJSVUYzUWtoTlJWVkRTVVZZYTFwcWMyOUNVamhWZEc5blQwbFhWeXQyVTFOQ2NWcEViRGxIVEVRME1uWXdNR0ZXTkRVMVF6RkJhVVZCZDI1aE4zaDVWRUZJUTBJemNqVTBSSG93WnpKMVJHWktNa2ROUVdod2RuRnJiSGN5YXpka1VrMVdZM2RLZDFsS1MzZFpRa0pCUjBOT2VGVkxRa0p2ZDBkRVFVdENaMmR5UW1kRlJrSlJZMFJCVkVGTFFtZG5ja0puUlVaQ1VXTkVRV3BCSzBKbmEzSkNaMFZGUVZsSk0wWlJZMFZOVkVGMlFtbGpja0puUlVWQldVa3pSbEZwU0RKdldqRm5LemRhUVZsTVNtaFNkVUowV2pWb2FHWlVjbGxKUm1Sb1dXRlBVVmxtUTIxR1FVTkJWMUZEUVZOVmQyZFpZMGREUTNOSFFWRlZSa0ozUlVKQ1NITjNaVlJDVkVKblozSkNaMFZHUWxGamQwRnZXa2hoU0ZJd1kwUnZka3d6WkROa2VUVjBZVmRPZVdJelRuWmFibEYxV1RJNWRFd3pRbkpoVXpsMFl6Sk9kbU51UVhaVVYyeHFZMjA1ZW1JeVdqQktWRWwzVld4T1FrcFVTWGRXUlhoVVNsUkpkMUV3Uld4TmFrRjNUVk0xYW1OdVVYZEpaMWxKUzNkWlFrSlJWVWhOUVVkSFJtMW9NR1JJUVRaTWVUbDJXVE5PZDB4dE1YcGlNazU2WTBNMWFtSXlNSGRJVVZsRVZsSXdUMEpDV1VWR1N6ZFZhQ3M1WkdnNUwxRjFZM0ZKTlVFNVJHc3djMlpzTTFsVFRVRnpSMEV4VldSRWQxRkZRWGRKUlhORVFrSkNaMDVXU0ZKRlJVOXFRVFJuYUhOeFRHMXpOR015VG5aaWJUVnNXVE5SZFdSSFZucGtRelZvWlc1V2VWcFROV3BpTWpKRFIxZHpOR015VG5aaWJUVnNXVE5SZFdSSFZucGtRelZvWlc1V2VWcFROV3BpTWpCM1oySkJSMEV4VldSSWQxTkNjVVJEUW5CVVEwSnZjVU5DYmpaRFFtNUpXazVoU0ZJd1kwUnZka3d5TVhwWk0wcHpURzB4Y0ZrelNuWmpNamx0WkVNMWFtSXlNSFpqUjNSd1RESXhlbGt5T1hsalF6bHFZMjEzZGxSWGJHcGpiVGw2WWpKYU1FcFVTWGRWYkU1Q1NsUkpkMVpGZUZSS1ZFbDNVVEJGYkUxcVFYZE5VelZxWTIxNVIxTXlhREJrU0VFMlRIazVhbU50ZDNWaVYyeHFZMjA1ZW1JeVdqQk1iVTUyWWxNNWQyRXlhM1ppV0U1cVlqTktkMHd5VG5saVF6bE9ZVmRPZVdJelRuWmFibEZzVFdwQ1UxVXdSV3hOYWtKVlZFWk5iRTFxUWtSUlUxVjVUVVJCZUV4dFRubGlSRUpZUW1kT1ZraFRRVVZWUkVKUFRVVkpSME5UYzBkQlVWRkNaMnBqY1VGVVFURk5SRTFIUTBOelIwRlJWVVpDZDBsQ1JtbGtiMlJJVW5kUGFUaDJaRE5rTTB4dE1YQlpNMHAyWXpJNWJXUkROV3BpTWpCMlkwZDBjRXd5TVhwWk1qbDVZME01YW1OSVRYZERRVmxIV2pSRlRVRlJTVUpOUWpoSFFURlZaRWwzVVZsTlFtRkJSa3hXTWtSRVFWSjZjMlZUVVdzeFRYZ3hkM041UzJ0Tk5rRjBhMDFDTUVkQk1WVmtTbEZSVjAxQ1VVZERRM05IUVZGVlJrSjNUVUpDWjJkeVFtZEZSa0pSWTBSQmFrRk9RbWRyY1docmFVYzVkekJDUVZGelJrRkJUME5CWjBWQlJWZHRUVmRzWjJ3NGQzSlRUWHBQTW1Ob1pVbHZhbkZRVjBNd2FVVlVkSGRZYVVreWRqVmtWVkV5ZG01eWMydFVZM1ZzV1ZJNFExSllRemxXY0hWTU5YZDJUbEJaWlVzNWFtRjRhRXhGZW14YUt6aENTaTlhSzA5Q1NsRlBiV0k0VDIxRkwzcEVha1o1WVU5WWIzUXZNMEl3ZG5CcE9FWk1NalZNUkhGbGVuZExSeXN5VHpSVVJWQkhha1pGTmxONVRqWmlVR2d5ZG1Vck4wSTJLemQwVWpWeWVEZEtlU3RVY2pGcE9XdDBkV1p6UVhGWk5HSmtaMmd4Y2xWTGFsSkZVemRLVjNWek9HZDNVWG80YmtkSGMzaEhXbVJuU25oYVpISlJjVlZJUzNFMFlWcDJVVEZtWmtrM1RUbHVXWGhOVFM5VFNURkRlbTkxWkd0NmFHVnFSRXgzYW5vdk5UZHRaR04xYVdZck56TkpUbUZDVG5KRFprRXljemM1T1hwV1lVeDNkbXBMTlhRcmEwOVNSelI0TkZoWVpTdFphelZhV2pWQlkyMUZVa05NWnpSTGJHVkpiRFJJY3pSeGRYSkxhbGMxTjI1SFRYTnhLMHBXVGpBd2FFWXhXR1pETkZCVlpYbFJObFJPTUcxNlVGRXhia2RaZENzcmJVSTFWV053TURkWVRuVnpWR1JoTW05SGF6SlNOak5PVWsxWWIzcHRTbkYxVnlzNGRFVlVMMUJLUzNGUGFrVlNRalJXZHpOQ1IwUnZWRTVYVTNwb1dIbDRTVlp0TVhOT1dUSkJUVlpYYUdOYVkzRXpPVWRYVUc5UVp6RXpSbW80VDFsc2NFRm1SR1o2YURGaWRYWkdVbVpwVFZVME1sbHROa3c1YlROVVMwUjRlVXdyTWxKVmVESlNNbUo1VUZWTVQyVXdSMnd4T1hKelUyWlpjeTlvYjNkb1dWSnNXWEp1T0dKYVJFTkhiRFUzTDFGTWVHcEJXWFJVVWtZdlZFaHZLM1JOYTJSVmFTOWhUV2xVU0hoMlltcGtZeTlsYWxocVVISjRTbUp5UzFCVU1tUkVXRVk0ZG5aRGQzZGFRazAwUjFGWlNGaDViRFV6VTB4cU1VdHJRMjlvVlZKTkwzcDBlVEZpVTJOWWRIcE5aMDFJVmpWUFRYVkthVVZYVVhKV1NpOUhWRzlNVGxsUVNHMWxORXROY21jOUNpMHRMUzB0UlU1RUlFTkZVbFJKUmtsRFFWUkZMUzB0TFMwPQogICAgICBzZXJ2ZXI6IGh0dHBzOi8vYTljNDMzYzMtNjhlMS00NTY2LWI2MzMtODM0NzUyOWYzNjIwLms4c2Nvbm5lY3QudGVzdC5henVyZS5jb20KICAgIG5hbWU6IGNsdXN0ZXIKY29udGV4dHM6CiAgLSBjb250ZXh0OgogICAgICBjbHVzdGVyOiBjbHVzdGVyCiAgICAgIHVzZXI6IGNsdXN0ZXJVc2VyX3Rlc3RfY2x1c3RlcgogICAgbmFtZTogY2x1c3RlcgpjdXJyZW50LWNvbnRleHQ6IGNsdXN0ZXIKa2luZDogQ29uZmlnCnByZWZlcmVuY2VzOiBudWxsCnVzZXJzOgogIC0gbmFtZTogY2x1c3RlclVzZXJfdGVzdF9jbHVzdGVyCiAgICB1c2VyOgogICAgICB0b2tlbjogMmM2NGZyMmQ2MWRhZmZkODY4NGJkYTc3M2Y2YTQ3OGUxZTU4NzlhZTE1ZmRkM2Q1NDU4NGNkNTM1MGM2YWUxMzlhMGI3OTk4YTc2ZjFhOTdlOGI3Y2EwNTJiYjIwZWY0ZjljZTAzN2Q5YTMyM2ZjMTYxZmI0MGI4OTVlOWIwZjM=\"),\n\t// \t}},\n\t// }\n}", "func UserHasPermission(r *http.Request, project string) bool {\n\tval := r.Context().Value(request.CtxAccess)\n\tif val == nil {\n\t\treturn false\n\t}\n\n\tua := val.(*UserAccess)\n\tif ua.Admin {\n\t\treturn true\n\t}\n\n\treturn shared.StringInSlice(project, ua.Projects)\n}", "func (p *v1Provider) GetCluster(w http.ResponseWriter, r *http.Request) {\n\thttpapi.IdentifyEndpoint(r, \"/v1/clusters/current\")\n\ttoken := p.CheckToken(r)\n\tif !token.Require(w, \"cluster:show_basic\") {\n\t\treturn\n\t}\n\tshowBasic := !token.Check(\"cluster:show\")\n\n\tfilter := reports.ReadFilter(r, p.Cluster.GetServiceTypesForArea)\n\tif showBasic {\n\t\tfilter.IsSubcapacityAllowed = func(serviceType, resourceName string) bool {\n\t\t\ttoken.Context.Request[\"service\"] = serviceType\n\t\t\ttoken.Context.Request[\"resource\"] = resourceName\n\t\t\treturn token.Check(\"cluster:show_subcapacity\")\n\t\t}\n\t}\n\n\tcluster, err := reports.GetClusterResources(p.Cluster, p.DB, filter)\n\tif respondwith.ErrorText(w, err) {\n\t\treturn\n\t}\n\trespondwith.JSON(w, 200, map[string]interface{}{\"cluster\": cluster})\n}", "func GetPlayerPermissions(handler *potoq.Handler) (ps PermSet) {\n\tGlobalPermLock.Lock()\n\tdefer GlobalPermLock.Unlock()\n\n\tps = make(PermSet)\n\tps.Apply(Groups[\"default\"], \"\", true)\n\tps.Apply(Users[strings.ToLower(handler.Nickname)], \"\", true)\n\treturn\n}", "func GetProjectPermClient() (*project.BCSProjectPerm, error) {\n\tiamClient, err := GetIAMClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn project.NewBCSProjectPermClient(iamClient), nil\n}", "func (e *CachedEnforcer) GetImplicitUsersForPermission(permission ...string) ([]string, error) {\n\treturn e.api.GetImplicitUsersForPermission(permission...)\n}", "func (c *SiteReplicationSys) GetClusterInfo(ctx context.Context) (info madmin.SiteReplicationInfo, err error) {\n\tc.RLock()\n\tdefer c.RUnlock()\n\tif !c.enabled {\n\t\treturn info, nil\n\t}\n\n\tinfo.Enabled = true\n\tinfo.Name = c.state.Name\n\tinfo.Sites = make([]madmin.PeerInfo, 0, len(c.state.Peers))\n\tfor _, peer := range c.state.Peers {\n\t\tinfo.Sites = append(info.Sites, peer)\n\t}\n\tsort.SliceStable(info.Sites, func(i, j int) bool {\n\t\treturn info.Sites[i].Name < info.Sites[j].Name\n\t})\n\n\tinfo.ServiceAccountAccessKey = c.state.ServiceAccountAccessKey\n\treturn info, nil\n}", "func (p *FileInf) getPermissionsList(u *url.URL) error {\n\tq := u.Query()\n\tq.Set(\"pageSize\", \"100\")\n\tq.Set(\"fields\", \"kind,nextPageToken,permissions\")\n\tu.RawQuery = q.Encode()\n\tr := &RequestParams{\n\t\tMethod: \"GET\",\n\t\tAPIURL: u.String(),\n\t\tData: nil,\n\t\tAccesstoken: p.Accesstoken,\n\t\tDtime: 30,\n\t}\n\tp.reqAndGetRawResponse(r)\n\treturn nil\n}", "func ExampleConnectedClusterClient_ListClusterUserCredential() {\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 := armhybridkubernetes.NewConnectedClusterClient(\"1bfbb5d0-917e-4346-9026-1d3b344417f5\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := client.ListClusterUserCredential(ctx,\n\t\t\"k8sc-rg\",\n\t\t\"testCluster\",\n\t\tarmhybridkubernetes.ListClusterUserCredentialProperties{\n\t\t\tAuthenticationMethod: to.Ptr(armhybridkubernetes.AuthenticationMethodAAD),\n\t\t\tClientProxy: to.Ptr(false),\n\t\t},\n\t\tnil)\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 getLeafClusterCAs(ctx context.Context, srv *Server, domainName string, validateRequest *ValidateTrustedClusterRequest) ([]types.CertAuthority, error) {\n\tcertTypes, err := getCATypesForLeaf(validateRequest)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tcaCerts := make([]types.CertAuthority, 0, len(certTypes))\n\n\tfor _, caType := range certTypes {\n\t\tcertAuthority, err := srv.GetCertAuthority(\n\t\t\tctx,\n\t\t\ttypes.CertAuthID{Type: caType, DomainName: domainName},\n\t\t\tfalse)\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\tcaCerts = append(caCerts, certAuthority)\n\t}\n\n\treturn caCerts, nil\n}", "func getClusterData(c kclientset.Interface, config map[string]string) map[string]string {\n\tnewConfig := make(map[string]string)\n\tfor k, v := range config {\n\t\tif k == \"routerIP\" {\n\t\t\t// TODO sjug: make localhost func\n\t\t\t//v = localhost(f)\n\t\t\tv = \"127.0.0.1\"\n\t\t} else if k == \"targetHost\" {\n\t\t\t// getEndpointsWithLabel will not return single string\n\t\t\tv = concatenateIP(getEndpointsWithLabel(c, config[\"match\"]))\n\t\t}\n\t\tnewConfig[k] = v\n\t}\n\treturn newConfig\n}", "func (m *SharedWithChannelTeamInfo) GetAllowedMembers()([]ConversationMemberable) {\n val, err := m.GetBackingStore().Get(\"allowedMembers\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]ConversationMemberable)\n }\n return nil\n}", "func (n *Node) PermissionSet(ctx context.Context) (provider.ResourcePermissions, bool) {\n\tu, ok := ctxpkg.ContextGetUser(ctx)\n\tif !ok {\n\t\tappctx.GetLogger(ctx).Debug().Interface(\"node\", n).Msg(\"no user in context, returning default permissions\")\n\t\treturn NoPermissions(), false\n\t}\n\tif utils.UserEqual(u.Id, n.SpaceRoot.Owner()) {\n\t\treturn OwnerPermissions(), false\n\t}\n\t// read the permissions for the current user from the acls of the current node\n\tif np, accessDenied, err := n.ReadUserPermissions(ctx, u); err == nil {\n\t\treturn np, accessDenied\n\t}\n\t// be defensive, we could have access via another grant\n\treturn NoPermissions(), true\n}", "func getNodes(clusterType ...string) ([]string, error) {\n hostNames := []string{}\n tabletServersFuture := make(chan helpers.TabletServersFuture)\n go helpers.GetTabletServersFuture(helpers.HOST, tabletServersFuture)\n tabletServersResponse := <-tabletServersFuture\n if tabletServersResponse.Error != nil {\n return hostNames, tabletServersResponse.Error\n }\n\n if len(clusterType) == 0 {\n // to get hostnames, get all second level keys and only keep if\n // net.SpliHostPort succeeds.\n for _, obj := range tabletServersResponse.Tablets {\n for hostport := range obj {\n host, _, err := net.SplitHostPort(hostport)\n if err == nil {\n hostNames = append(hostNames, host)\n }\n }\n }\n } else {\n clusterConfigFuture := make(chan helpers.ClusterConfigFuture)\n go helpers.GetClusterConfigFuture(helpers.HOST, clusterConfigFuture)\n clusterConfigResponse := <-clusterConfigFuture\n if clusterConfigResponse.Error != nil {\n return hostNames, clusterConfigResponse.Error\n }\n replicationInfo := clusterConfigResponse.ClusterConfig.ReplicationInfo\n if clusterType[0] == \"READ_REPLICA\" {\n readReplicas := replicationInfo.ReadReplicas\n if len(readReplicas) == 0 {\n return hostNames, errors.New(\"no Read Replica nodes present\")\n }\n readReplicaUuid := readReplicas[0].PlacementUuid\n for hostport := range tabletServersResponse.Tablets[readReplicaUuid] {\n host, _, err := net.SplitHostPort(hostport)\n if err == nil {\n hostNames = append(hostNames, host)\n }\n }\n } else if clusterType[0] == \"PRIMARY\" {\n primaryUuid := replicationInfo.LiveReplicas.PlacementUuid\n for hostport := range tabletServersResponse.Tablets[primaryUuid] {\n host, _, err := net.SplitHostPort(hostport)\n if err == nil {\n hostNames = append(hostNames, host)\n }\n }\n }\n }\n return hostNames, nil\n}", "func random(cluster,n int) []int {\n\treturn rand.Perm(cluster)[:n]\n}", "func GetUserConfigs(db Database, groups map[int]bool, withPriviledge bool) map[string]duser.UserAccess {\n\tusers := make(map[string]duser.UserAccess)\n\tstored, err := db.FetchAllRecords(pconst.DbConfig, pconst.TbAccess)\n\tif err != nil || stored == nil {\n\t\treturn users\n\t}\n\tfor _, val := range stored {\n\t\tusr, err := duser.ToUserAccess(val)\n\t\tif err != nil || usr == nil {\n\t\t\tcontinue\n\t\t}\n\t\tvar addUser bool\n\t\tif withPriviledge && usr.Priviledge != \"user\" {\n\t\t\taddUser = true\n\t\t} else {\n\t\t\taddUser = false\n\t\t\tfor _, gr := range usr.AccessGroups {\n\t\t\t\tif _, ok := groups[gr]; ok {\n\t\t\t\t\taddUser = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif addUser {\n\t\t\tusers[usr.UserHash] = *usr\n\t\t}\n\t}\n\treturn users\n}", "func ExampleConnectedClusterClient_ListClusterUserCredential_listClusterUserCredentialNonAadExample() {\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\tclientFactory, err := armhybridkubernetes.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewConnectedClusterClient().ListClusterUserCredential(ctx, \"k8sc-rg\", \"testCluster\", armhybridkubernetes.ListClusterUserCredentialProperties{\n\t\tAuthenticationMethod: to.Ptr(armhybridkubernetes.AuthenticationMethodToken),\n\t\tClientProxy: to.Ptr(true),\n\t}, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.CredentialResults = armhybridkubernetes.CredentialResults{\n\t// \tHybridConnectionConfig: &armhybridkubernetes.HybridConnectionConfig{\n\t// \t\tExpirationTime: to.Ptr[int64](1631196183),\n\t// \t\tHybridConnectionName: to.Ptr(\"microsoft.kubernetes/connectedclusters/229dc73f7b07196c79a93d4362d9c7fc4ed34df3e95290d27c56cec2dbb82865/1631185383340987904\"),\n\t// \t\tRelay: to.Ptr(\"azgnrelay-ph0-l1\"),\n\t// \t\tToken: to.Ptr(\"SharedAccessSignature 123456789034675890pbduwegiavifkuw647o02423bbhfouseb\"),\n\t// \t},\n\t// \tKubeconfigs: []*armhybridkubernetes.CredentialResult{\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"credentialName1\"),\n\t// \t\t\tValue: []byte(\"YXBpVmVyc2lvbjogdjEKY2x1c3RlcnM6CiAgLSBjbHVzdGVyOgogICAgICBjZXJ0aWZpY2F0ZS1hdXRob3JpdHktZGF0YTogTFMwdExTMUNSVWRKVGlCRFJWSlVTVVpKUTBGVVJTMHRMUzB0Q2sxSlNVaDJWRU5EUW1GWFowRjNTVUpCWjBsVVlYZEJRVUV5VkhWQlRYaEJhVWx5UldsQlFVRkJRVUZFV2tSQlRrSm5hM0ZvYTJsSE9YY3dRa0ZSYzBaQlJFSlFUVkZ6ZDBOUldVUldVVkZIUlhkS1ZsVjZSV1ZOUW5kSFFURlZSVU5vVFZaVVYyeHFZMjA1ZW1JeVdqQkpSVTUyWTI1Q2RtTnRSakJoVnpsMVRWTkJkMGhuV1VSV1VWRkVSWGhrVG1GWFRubGlNMDUyV201UloxVnNUa0pKUmxKTlZYbENSRkZUUVhkTlZFRmxSbmN3ZVUxRVFUUk5hbU40VFdwTmVFNVVXbUZHZHpCNVRWUkJORTFxWTNoTmFrMTRUbFJhWVUxRFdYaEtSRUZwUW1kT1ZrSkJUVTFIZVc5MVlYcG9lbGt5T1hWaWJWWnFaRU0xTUZwWVRqQk1iVVkyWkZoS2JFeHRUblppVkVORFFWTkpkMFJSV1VwTGIxcEphSFpqVGtGUlJVSkNVVUZFWjJkRlVFRkVRME5CVVc5RFoyZEZRa0ZOU0VwVU0wZEtXbWhMTm5KaVVHSm9XRWN6V21SU05HVlhNSGhSVmxVclIwTjVXSEFyY0VwRFNtUjBhbGgyTjNwMFEzTnJRV0ZaZDJobmQyMHpOMGhFVkVWamNFVlFjR1p6TDJSSFdsQktiek5vU0ZOemVGaENUMUJXYUVsVVRHZFBSa1E0YW5BMVlWZG1kVXA0WWsxUFNqZ3dObWxST0VkT1NVdEZURGM1ZDFkMVNWcG5MemhCWTBZeVNEWnJTMDlWVVhJdmVFMWFjVWx1WW5sQk1XVmhPVW8xTmpKbVNVODRUbEp2YWxORVRFUlBWRzFyWTFaYVdHcHlTaTlsYW1wclVVMUhiV0YyT1hreE9EQjJUVkZ5TTBjM2FXZ3Jkell2VFZocGVWWkpLMGxhY3pSaGVXVTJhREo0VDA5VlNYQnRWVTQ0UlhVNWIwY3ZTSGRHV2swemJHWnBkR0ZQZUhsblEydHBNV2R0VFRsd09FcHhNMVIyVVRSbU9YSnBRVWRUVFhaWWVsSlpTa2hOU2toVVRtZFZhV1pZVjFWb1VFWTJWMkZGTWxwbFdVWkdOV1ozU0U5MlVYRnFSa2tyUlZWS1JscE1kekJEUVhkRlFVRmhUME5CTjJ0M1oyZFBNVTFKU1VKQmQxbExTM2RaUWtKQlNGZGxVVWxGUVdkVFFqbEJVMEk0VVVSMlFVaFZRVGxzZVZWTU9VWXpUVU5KVlZaQ1owbE5TbEpYYW5WT1RrVjRhM3AyT1RoTlRIbEJUSHBGTjNoYVQwMUJRVUZHTUV3dlFuTjNRVUZCUWtGTlFWSnFRa1ZCYVVJMFpWSlVTMHhZY1hsM09HazFMeTlyVmtaNWNrTlhZMFZtY0VaV2NGUlZSVFIzYlVNME1rZHhSMkpCU1dkTkswVllkRWhtV0Rrd05WVklZall3Y1hKUlEzUTRibkZhTkUxamRVUjNOMlJaZVhwdGJFc3pja05SUVdSblFtTXpSVTlUTDNWaGNsSlZVM2hZY0hKVlZuVlpVVTR2ZGxZcmEyWmpiMWhQVlhOc04yMDVjMk5QZVdkQlFVRllVWFk0UjNwd1FVRkJSVUYzUWtoTlJWVkRTVVZZYTFwcWMyOUNVamhWZEc5blQwbFhWeXQyVTFOQ2NWcEViRGxIVEVRME1uWXdNR0ZXTkRVMVF6RkJhVVZCZDI1aE4zaDVWRUZJUTBJemNqVTBSSG93WnpKMVJHWktNa2ROUVdod2RuRnJiSGN5YXpka1VrMVdZM2RLZDFsS1MzZFpRa0pCUjBOT2VGVkxRa0p2ZDBkRVFVdENaMmR5UW1kRlJrSlJZMFJCVkVGTFFtZG5ja0puUlVaQ1VXTkVRV3BCSzBKbmEzSkNaMFZGUVZsSk0wWlJZMFZOVkVGMlFtbGpja0puUlVWQldVa3pSbEZwU0RKdldqRm5LemRhUVZsTVNtaFNkVUowV2pWb2FHWlVjbGxKUm1Sb1dXRlBVVmxtUTIxR1FVTkJWMUZEUVZOVmQyZFpZMGREUTNOSFFWRlZSa0ozUlVKQ1NITjNaVlJDVkVKblozSkNaMFZHUWxGamQwRnZXa2hoU0ZJd1kwUnZka3d6WkROa2VUVjBZVmRPZVdJelRuWmFibEYxV1RJNWRFd3pRbkpoVXpsMFl6Sk9kbU51UVhaVVYyeHFZMjA1ZW1JeVdqQktWRWwzVld4T1FrcFVTWGRXUlhoVVNsUkpkMUV3Uld4TmFrRjNUVk0xYW1OdVVYZEpaMWxKUzNkWlFrSlJWVWhOUVVkSFJtMW9NR1JJUVRaTWVUbDJXVE5PZDB4dE1YcGlNazU2WTBNMWFtSXlNSGRJVVZsRVZsSXdUMEpDV1VWR1N6ZFZhQ3M1WkdnNUwxRjFZM0ZKTlVFNVJHc3djMlpzTTFsVFRVRnpSMEV4VldSRWQxRkZRWGRKUlhORVFrSkNaMDVXU0ZKRlJVOXFRVFJuYUhOeFRHMXpOR015VG5aaWJUVnNXVE5SZFdSSFZucGtRelZvWlc1V2VWcFROV3BpTWpKRFIxZHpOR015VG5aaWJUVnNXVE5SZFdSSFZucGtRelZvWlc1V2VWcFROV3BpTWpCM1oySkJSMEV4VldSSWQxTkNjVVJEUW5CVVEwSnZjVU5DYmpaRFFtNUpXazVoU0ZJd1kwUnZka3d5TVhwWk0wcHpURzB4Y0ZrelNuWmpNamx0WkVNMWFtSXlNSFpqUjNSd1RESXhlbGt5T1hsalF6bHFZMjEzZGxSWGJHcGpiVGw2WWpKYU1FcFVTWGRWYkU1Q1NsUkpkMVpGZUZSS1ZFbDNVVEJGYkUxcVFYZE5VelZxWTIxNVIxTXlhREJrU0VFMlRIazVhbU50ZDNWaVYyeHFZMjA1ZW1JeVdqQk1iVTUyWWxNNWQyRXlhM1ppV0U1cVlqTktkMHd5VG5saVF6bE9ZVmRPZVdJelRuWmFibEZzVFdwQ1UxVXdSV3hOYWtKVlZFWk5iRTFxUWtSUlUxVjVUVVJCZUV4dFRubGlSRUpZUW1kT1ZraFRRVVZWUkVKUFRVVkpSME5UYzBkQlVWRkNaMnBqY1VGVVFURk5SRTFIUTBOelIwRlJWVVpDZDBsQ1JtbGtiMlJJVW5kUGFUaDJaRE5rTTB4dE1YQlpNMHAyWXpJNWJXUkROV3BpTWpCMlkwZDBjRXd5TVhwWk1qbDVZME01YW1OSVRYZERRVmxIV2pSRlRVRlJTVUpOUWpoSFFURlZaRWwzVVZsTlFtRkJSa3hXTWtSRVFWSjZjMlZUVVdzeFRYZ3hkM041UzJ0Tk5rRjBhMDFDTUVkQk1WVmtTbEZSVjAxQ1VVZERRM05IUVZGVlJrSjNUVUpDWjJkeVFtZEZSa0pSWTBSQmFrRk9RbWRyY1docmFVYzVkekJDUVZGelJrRkJUME5CWjBWQlJWZHRUVmRzWjJ3NGQzSlRUWHBQTW1Ob1pVbHZhbkZRVjBNd2FVVlVkSGRZYVVreWRqVmtWVkV5ZG01eWMydFVZM1ZzV1ZJNFExSllRemxXY0hWTU5YZDJUbEJaWlVzNWFtRjRhRXhGZW14YUt6aENTaTlhSzA5Q1NsRlBiV0k0VDIxRkwzcEVha1o1WVU5WWIzUXZNMEl3ZG5CcE9FWk1NalZNUkhGbGVuZExSeXN5VHpSVVJWQkhha1pGTmxONVRqWmlVR2d5ZG1Vck4wSTJLemQwVWpWeWVEZEtlU3RVY2pGcE9XdDBkV1p6UVhGWk5HSmtaMmd4Y2xWTGFsSkZVemRLVjNWek9HZDNVWG80YmtkSGMzaEhXbVJuU25oYVpISlJjVlZJUzNFMFlWcDJVVEZtWmtrM1RUbHVXWGhOVFM5VFNURkRlbTkxWkd0NmFHVnFSRXgzYW5vdk5UZHRaR04xYVdZck56TkpUbUZDVG5KRFprRXljemM1T1hwV1lVeDNkbXBMTlhRcmEwOVNSelI0TkZoWVpTdFphelZhV2pWQlkyMUZVa05NWnpSTGJHVkpiRFJJY3pSeGRYSkxhbGMxTjI1SFRYTnhLMHBXVGpBd2FFWXhXR1pETkZCVlpYbFJObFJPTUcxNlVGRXhia2RaZENzcmJVSTFWV053TURkWVRuVnpWR1JoTW05SGF6SlNOak5PVWsxWWIzcHRTbkYxVnlzNGRFVlVMMUJLUzNGUGFrVlNRalJXZHpOQ1IwUnZWRTVYVTNwb1dIbDRTVlp0TVhOT1dUSkJUVlpYYUdOYVkzRXpPVWRYVUc5UVp6RXpSbW80VDFsc2NFRm1SR1o2YURGaWRYWkdVbVpwVFZVME1sbHROa3c1YlROVVMwUjRlVXdyTWxKVmVESlNNbUo1VUZWTVQyVXdSMnd4T1hKelUyWlpjeTlvYjNkb1dWSnNXWEp1T0dKYVJFTkhiRFUzTDFGTWVHcEJXWFJVVWtZdlZFaHZLM1JOYTJSVmFTOWhUV2xVU0hoMlltcGtZeTlsYWxocVVISjRTbUp5UzFCVU1tUkVXRVk0ZG5aRGQzZGFRazAwUjFGWlNGaDViRFV6VTB4cU1VdHJRMjlvVlZKTkwzcDBlVEZpVTJOWWRIcE5aMDFJVmpWUFRYVkthVVZYVVhKV1NpOUhWRzlNVGxsUVNHMWxORXROY21jOUNpMHRMUzB0UlU1RUlFTkZVbFJKUmtsRFFWUkZMUzB0TFMwPQogICAgICBzZXJ2ZXI6IGh0dHBzOi8vYTljNDMzYzMtNjhlMS00NTY2LWI2MzMtODM0NzUyOWYzNjIwLms4c2Nvbm5lY3QudGVzdC5henVyZS5jb20KICAgIG5hbWU6IGNsdXN0ZXIKY29udGV4dHM6CiAgLSBjb250ZXh0OgogICAgICBjbHVzdGVyOiBjbHVzdGVyCiAgICAgIHVzZXI6IGNsdXN0ZXJVc2VyX3Rlc3RfY2x1c3RlcgogICAgbmFtZTogY2x1c3RlcgpjdXJyZW50LWNvbnRleHQ6IGNsdXN0ZXIKa2luZDogQ29uZmlnCnByZWZlcmVuY2VzOiBudWxsCnVzZXJzOgogIC0gbmFtZTogY2x1c3RlclVzZXJfdGVzdF9jbHVzdGVyCiAgICB1c2VyOgogICAgICB0b2tlbjogMmM2NGZyMmQ2MWRhZmZkODY4NGJkYTc3M2Y2YTQ3OGUxZTU4NzlhZTE1ZmRkM2Q1NDU4NGNkNTM1MGM2YWUxMzlhMGI3OTk4YTc2ZjFhOTdlOGI3Y2EwNTJiYjIwZWY0ZjljZTAzN2Q5YTMyM2ZjMTYxZmI0MGI4OTVlOWIwZjM=\"),\n\t// \t}},\n\t// }\n}", "func (pa *PermAccess) GetPerms(opt *dauth.PermFind) <-chan dlib.Result {\n\tch := make(chan dlib.Result, 256)\n\n\tgo func() {\n\t\tdefer close(ch)\n\t\trows, err := pa.DBS.Query(`\n\t\t\tSELECT\n\t\t\t\tp.id,\n\t\t\t\tp.service,\n\t\t\t\tp.name\n\t\t\tFROM get_perms($1, $2, $3) AS p`,\n\t\t\topt.ID,\n\t\t\topt.Service,\n\t\t\topt.Name)\n\t\tif err != nil {\n\t\t\tch <- dlib.Result{Err: err}\n\t\t\treturn\n\t\t}\n\n\t\tdefer rows.Close()\n\t\tfor rows.Next() {\n\t\t\tr := dauth.PermRow{}\n\t\t\tif err := rows.Scan(\n\t\t\t\t&r.ID,\n\t\t\t\t&r.Service,\n\t\t\t\t&r.Name,\n\t\t\t); err != nil {\n\t\t\t\tch <- dlib.Result{Err: err}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tv := r.ToPerm()\n\t\t\tch <- dlib.Result{Val: v, Num: 1}\n\t\t}\n\t}()\n\n\treturn ch\n}", "func (s *Service) convertPermissions(perms []client.Permission) (map[string][]Privilege, error) {\n\tprivileges := make(map[string][]Privilege, len(perms))\n\tfor _, perm := range perms {\n\t\tswitch perm {\n\t\tcase client.NoPermissions:\n\t\tcase client.APIPermission:\n\t\t\tprivileges[rootResource] = []Privilege{AllPrivileges}\n\t\t\t// Subtractive permission, only add it if something else doesn't already exist.\n\t\t\tif _, ok := privileges[writeResource]; !ok {\n\t\t\t\tprivileges[writeResource] = []Privilege{NoPrivileges}\n\t\t\t}\n\t\t\t// Do not give config API access unless specificaly granted\n\t\t\tif _, ok := privileges[configResource]; !ok {\n\t\t\t\tprivileges[configResource] = []Privilege{NoPrivileges}\n\t\t\t}\n\t\tcase client.ConfigAPIPermission:\n\t\t\tprivileges[pingResource] = []Privilege{AllPrivileges}\n\t\t\tprivileges[configResource] = []Privilege{AllPrivileges}\n\t\tcase client.WritePointsPermission:\n\t\t\tprivileges[pingResource] = []Privilege{AllPrivileges}\n\t\t\tprivileges[writeResource] = []Privilege{AllPrivileges}\n\t\tcase client.AllPermissions:\n\t\t\tprivileges[rootResource] = []Privilege{AllPrivileges}\n\t\t\tprivileges[configResource] = []Privilege{AllPrivileges}\n\t\t\tprivileges[writeResource] = []Privilege{AllPrivileges}\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown permission %v\", perm)\n\t\t}\n\t}\n\treturn privileges, nil\n}", "func GetProjectList(client *rancher.Client, clusterID string) (*management.ProjectCollection, error) {\n\tvar projectsList *management.ProjectCollection\n\n\tprojectsList, err := client.Management.Project.List(&types.ListOpts{\n\t\tFilters: map[string]interface{}{\n\t\t\t\"clusterId\": clusterID,\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn projectsList, err\n\t}\n\n\treturn projectsList, nil\n}", "func (api *clusterAPI) List(ctx context.Context, opts *api.ListWatchOptions) ([]*Cluster, error) {\n\tvar objlist []*Cluster\n\tobjs, err := api.ct.List(\"Cluster\", ctx, opts)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, obj := range objs {\n\t\tswitch tp := obj.(type) {\n\t\tcase *Cluster:\n\t\t\teobj := obj.(*Cluster)\n\t\t\tobjlist = append(objlist, eobj)\n\t\tdefault:\n\t\t\tlog.Fatalf(\"Got invalid object type %v while looking for Cluster\", tp)\n\t\t}\n\t}\n\n\treturn objlist, nil\n}" ]
[ "0.76727074", "0.7316964", "0.6054277", "0.604634", "0.5853511", "0.57059836", "0.56702274", "0.5662144", "0.5530473", "0.5488563", "0.5409145", "0.53811985", "0.53752625", "0.5248118", "0.5241422", "0.5221002", "0.5150384", "0.5136137", "0.5131411", "0.5123411", "0.5080903", "0.5060815", "0.50602615", "0.5036475", "0.500792", "0.50050956", "0.50029224", "0.49983263", "0.4974142", "0.49592337", "0.4954411", "0.49466032", "0.4943259", "0.49406344", "0.49316937", "0.49297416", "0.49241185", "0.48885438", "0.4880009", "0.4879833", "0.48756936", "0.48746133", "0.48672932", "0.4861408", "0.48569703", "0.4851396", "0.4827284", "0.48201415", "0.48197928", "0.4817471", "0.4816812", "0.48097453", "0.4809182", "0.48087177", "0.4807468", "0.4801691", "0.47981223", "0.47927004", "0.47910485", "0.47904524", "0.4787868", "0.4786769", "0.4786769", "0.4780909", "0.47778943", "0.47674322", "0.4765799", "0.4762371", "0.47617838", "0.47607327", "0.47536078", "0.47497776", "0.4742827", "0.47202462", "0.471189", "0.47068903", "0.47048932", "0.47012332", "0.469495", "0.46905246", "0.46897194", "0.4688709", "0.46799567", "0.46789286", "0.46728185", "0.46693876", "0.46656275", "0.4665283", "0.4655382", "0.46540552", "0.46533886", "0.46440533", "0.46404886", "0.46385273", "0.46382397", "0.46368772", "0.4624904", "0.46182272", "0.46180767", "0.46151805" ]
0.8364669
0
GetClusterCreatePerm get cluster create permission by user
func GetClusterCreatePerm(user UserInfo) map[string]bool { permissions := make(map[string]bool) // attention: v0 permission only support project permissions["test"] = true permissions["prod"] = true permissions["create"] = true return permissions }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetUserPermListByProjectAndCluster(user UserInfo, clusterList []string, filterUse bool) (map[string]*proto.Permission, error) {\n\tpermissions := make(map[string]*proto.Permission)\n\n\t// policyCode resourceType clusterList\n\tfor _, clusterID := range clusterList {\n\t\tdefaultPerm := auth.GetInitPerm(true)\n\n\t\tpermissions[clusterID] = &proto.Permission{\n\t\t\tPolicy: defaultPerm,\n\t\t}\n\t}\n\n\treturn permissions, nil\n}", "func GetUserClusterPermList(user UserInfo, clusterList []string) (map[string]*proto.Permission, error) {\n\tpermissions := make(map[string]*proto.Permission)\n\tcli := &cluster.BCSClusterPerm{}\n\n\tactionIDs := []string{cluster.ClusterView.String(), cluster.ClusterManage.String(), cluster.ClusterDelete.String()}\n\tperms, err := cli.GetMultiClusterMultiActionPermission(user.UserID, user.ProjectID, clusterList, actionIDs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor clusterID, perm := range perms {\n\t\tpermissions[clusterID] = &proto.Permission{\n\t\t\tPolicy: perm,\n\t\t}\n\t}\n\n\treturn permissions, nil\n}", "func AuthClusterResourceCreatorPerm(ctx context.Context, clusterID, clusterName, user string) {\n\ttaskID := cloudprovider.GetTaskIDFromContext(ctx)\n\n\terr := auth.IAMClient.AuthResourceCreatorPerm(ctx, iam.ResourceCreator{\n\t\tResourceType: string(iam.SysCluster),\n\t\tResourceID: clusterID,\n\t\tResourceName: clusterName,\n\t\tCreator: user,\n\t}, nil)\n\tif err != nil {\n\t\tblog.Errorf(\"AuthClusterResourceCreatorPerm[%s] resource[%s:%s] failed: %v\",\n\t\t\ttaskID, clusterID, clusterName, user)\n\t\treturn\n\t}\n\n\tblog.Infof(\"AuthClusterResourceCreatorPerm[%s] resource[%s:%s] successful\",\n\t\ttaskID, clusterID, clusterName, user)\n}", "func (p *Proxy) isClusterAdmin(token string) (bool, error) {\n\tclient, err := p.createTypedClient(token)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tsar := &authv1.SelfSubjectAccessReview{\n\t\tSpec: authv1.SelfSubjectAccessReviewSpec{\n\t\t\tResourceAttributes: &authv1.ResourceAttributes{\n\t\t\t\tNamespace: \"openshift-terminal\",\n\t\t\t\tVerb: \"create\",\n\t\t\t\tResource: \"pods\",\n\t\t\t},\n\t\t},\n\t}\n\tres, err := client.AuthorizationV1().SelfSubjectAccessReviews().Create(context.TODO(), sar, metav1.CreateOptions{})\n\tif err != nil || res == nil {\n\t\treturn false, err\n\t}\n\treturn res.Status.Allowed, nil\n}", "func (q *QueryResolver) CreateCluster(ctx context.Context) (*ClusterInfoResolver, error) {\n\treturn nil, errors.New(\"Deprecated. Please use `px deploy`\")\n}", "func CreateCluster(name string, cloudCred string, kubeconfigPath string, orgID string) {\n\n\tStep(fmt.Sprintf(\"Create cluster [%s] in org [%s]\", name, orgID), func() {\n\t\tbackupDriver := Inst().Backup\n\t\tkubeconfigRaw, err := ioutil.ReadFile(kubeconfigPath)\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to read kubeconfig file from location [%s]. Error:[%v]\",\n\t\t\t\tkubeconfigPath, err))\n\n\t\tclusterCreateReq := &api.ClusterCreateRequest{\n\t\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\t\tName: name,\n\t\t\t\tOrgId: orgID,\n\t\t\t},\n\t\t\tKubeconfig: base64.StdEncoding.EncodeToString(kubeconfigRaw),\n\t\t\tCloudCredential: cloudCred,\n\t\t}\n\t\t//ctx, err := backup.GetPxCentralAdminCtx()\n\t\tctx, err := backup.GetAdminCtxFromSecret()\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to fetch px-central-admin ctx: [%v]\",\n\t\t\t\terr))\n\t\t_, err = backupDriver.CreateCluster(ctx, clusterCreateReq)\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to create cluster [%s] in org [%s]. Error : [%v]\",\n\t\t\t\tname, orgID, err))\n\t})\n}", "func CreateCreateClusterRequest() (request *CreateClusterRequest) {\n\trequest = &CreateClusterRequest{\n\t\tRoaRequest: &requests.RoaRequest{},\n\t}\n\trequest.InitWithApiInfo(\"CS\", \"2015-12-15\", \"CreateCluster\", \"/clusters\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateDescribeClusterServiceConfigForAdminRequest() (request *DescribeClusterServiceConfigForAdminRequest) {\n\trequest = &DescribeClusterServiceConfigForAdminRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Emr\", \"2016-04-08\", \"DescribeClusterServiceConfigForAdmin\", \"emr\", \"openAPI\")\n\treturn\n}", "func (h *Handler) serveCreateClusterAdmin(w http.ResponseWriter, r *http.Request) {}", "func CreateCluster(t *testing.T, f *framework.Framework, ctx *framework.TestCtx, z *api.ZookeeperCluster) (*api.ZookeeperCluster, error) {\n\tt.Logf(\"creating zookeeper cluster: %s\", z.Name)\n\terr := f.Client.Create(goctx.TODO(), z, &framework.CleanupOptions{TestContext: ctx, Timeout: CleanupTimeout, RetryInterval: CleanupRetryInterval})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create CR: %v\", err)\n\t}\n\n\tzk := &api.ZookeeperCluster{}\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Namespace: z.Namespace, Name: z.Name}, zk)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to obtain created CR: %v\", err)\n\t}\n\tt.Logf(\"created zookeeper cluster: %s\", zk.Name)\n\treturn z, nil\n}", "func createTeleportCluster(t *testing.T, opts ...testOptionsFunc) *helpers.TeleInstance {\n\tt.Helper()\n\tvar options testOptions\n\tfor _, opt := range opts {\n\t\topt(&options)\n\t}\n\n\tcfg := newInstanceConfig(t)\n\tfor _, optFn := range options.instanceConfigFuncs {\n\t\toptFn(&cfg)\n\t}\n\tteleport := helpers.NewInstance(t, cfg)\n\n\t// Create a new user with the role created above.\n\tteleport.AddUserWithRole(username, options.userRoles...)\n\n\ttconf := newTeleportConfig(t)\n\tfor _, optFn := range options.serviceConfigFuncs {\n\t\toptFn(tconf)\n\t}\n\t// Create a new teleport instance with the auth server.\n\terr := teleport.CreateEx(t, nil, tconf)\n\trequire.NoError(t, err)\n\t// Start the teleport instance and wait for it to be ready.\n\terr = teleport.Start()\n\trequire.NoError(t, err)\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, teleport.StopAll())\n\t})\n\treturn teleport\n}", "func (client *Client) CreateCluster(request *CreateClusterRequest) (response *CreateClusterResponse, err error) {\n\tresponse = CreateCreateClusterResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func GetClusterPermClient() (*cluster.BCSClusterPerm, error) {\n\tiamClient, err := GetIAMClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cluster.NewBCSClusterPermClient(iamClient), nil\n}", "func GenerateCreateClusterInput(cr *svcapitypes.Cluster) *svcsdk.CreateClusterInput {\n\tres := &svcsdk.CreateClusterInput{}\n\n\tif cr.Spec.ForProvider.CapacityProviders != nil {\n\t\tf0 := []*string{}\n\t\tfor _, f0iter := range cr.Spec.ForProvider.CapacityProviders {\n\t\t\tvar f0elem string\n\t\t\tf0elem = *f0iter\n\t\t\tf0 = append(f0, &f0elem)\n\t\t}\n\t\tres.SetCapacityProviders(f0)\n\t}\n\tif cr.Spec.ForProvider.ClusterName != nil {\n\t\tres.SetClusterName(*cr.Spec.ForProvider.ClusterName)\n\t}\n\tif cr.Spec.ForProvider.Configuration != nil {\n\t\tf2 := &svcsdk.ClusterConfiguration{}\n\t\tif cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration != nil {\n\t\t\tf2f0 := &svcsdk.ExecuteCommandConfiguration{}\n\t\t\tif cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.KMSKeyID != nil {\n\t\t\t\tf2f0.SetKmsKeyId(*cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.KMSKeyID)\n\t\t\t}\n\t\t\tif cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.LogConfiguration != nil {\n\t\t\t\tf2f0f1 := &svcsdk.ExecuteCommandLogConfiguration{}\n\t\t\t\tif cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.LogConfiguration.CloudWatchEncryptionEnabled != nil {\n\t\t\t\t\tf2f0f1.SetCloudWatchEncryptionEnabled(*cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.LogConfiguration.CloudWatchEncryptionEnabled)\n\t\t\t\t}\n\t\t\t\tif cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.LogConfiguration.CloudWatchLogGroupName != nil {\n\t\t\t\t\tf2f0f1.SetCloudWatchLogGroupName(*cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.LogConfiguration.CloudWatchLogGroupName)\n\t\t\t\t}\n\t\t\t\tif cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.LogConfiguration.S3BucketName != nil {\n\t\t\t\t\tf2f0f1.SetS3BucketName(*cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.LogConfiguration.S3BucketName)\n\t\t\t\t}\n\t\t\t\tif cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.LogConfiguration.S3EncryptionEnabled != nil {\n\t\t\t\t\tf2f0f1.SetS3EncryptionEnabled(*cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.LogConfiguration.S3EncryptionEnabled)\n\t\t\t\t}\n\t\t\t\tif cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.LogConfiguration.S3KeyPrefix != nil {\n\t\t\t\t\tf2f0f1.SetS3KeyPrefix(*cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.LogConfiguration.S3KeyPrefix)\n\t\t\t\t}\n\t\t\t\tf2f0.SetLogConfiguration(f2f0f1)\n\t\t\t}\n\t\t\tif cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.Logging != nil {\n\t\t\t\tf2f0.SetLogging(*cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.Logging)\n\t\t\t}\n\t\t\tf2.SetExecuteCommandConfiguration(f2f0)\n\t\t}\n\t\tres.SetConfiguration(f2)\n\t}\n\tif cr.Spec.ForProvider.DefaultCapacityProviderStrategy != nil {\n\t\tf3 := []*svcsdk.CapacityProviderStrategyItem{}\n\t\tfor _, f3iter := range cr.Spec.ForProvider.DefaultCapacityProviderStrategy {\n\t\t\tf3elem := &svcsdk.CapacityProviderStrategyItem{}\n\t\t\tif f3iter.Base != nil {\n\t\t\t\tf3elem.SetBase(*f3iter.Base)\n\t\t\t}\n\t\t\tif f3iter.CapacityProvider != nil {\n\t\t\t\tf3elem.SetCapacityProvider(*f3iter.CapacityProvider)\n\t\t\t}\n\t\t\tif f3iter.Weight != nil {\n\t\t\t\tf3elem.SetWeight(*f3iter.Weight)\n\t\t\t}\n\t\t\tf3 = append(f3, f3elem)\n\t\t}\n\t\tres.SetDefaultCapacityProviderStrategy(f3)\n\t}\n\tif cr.Spec.ForProvider.Settings != nil {\n\t\tf4 := []*svcsdk.ClusterSetting{}\n\t\tfor _, f4iter := range cr.Spec.ForProvider.Settings {\n\t\t\tf4elem := &svcsdk.ClusterSetting{}\n\t\t\tif f4iter.Name != nil {\n\t\t\t\tf4elem.SetName(*f4iter.Name)\n\t\t\t}\n\t\t\tif f4iter.Value != nil {\n\t\t\t\tf4elem.SetValue(*f4iter.Value)\n\t\t\t}\n\t\t\tf4 = append(f4, f4elem)\n\t\t}\n\t\tres.SetSettings(f4)\n\t}\n\tif cr.Spec.ForProvider.Tags != nil {\n\t\tf5 := []*svcsdk.Tag{}\n\t\tfor _, f5iter := range cr.Spec.ForProvider.Tags {\n\t\t\tf5elem := &svcsdk.Tag{}\n\t\t\tif f5iter.Key != nil {\n\t\t\t\tf5elem.SetKey(*f5iter.Key)\n\t\t\t}\n\t\t\tif f5iter.Value != nil {\n\t\t\t\tf5elem.SetValue(*f5iter.Value)\n\t\t\t}\n\t\t\tf5 = append(f5, f5elem)\n\t\t}\n\t\tres.SetTags(f5)\n\t}\n\n\treturn res\n}", "func createCluster(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {\n\tctx := r.Context()\n\tallowed := permission.Check(t, permission.PermClusterCreate)\n\tif !allowed {\n\t\treturn permission.ErrUnauthorized\n\t}\n\n\terr = deprecateFormContentType(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar provCluster provTypes.Cluster\n\terr = ParseJSON(r, &provCluster)\n\tif err != nil {\n\t\treturn err\n\t}\n\tevt, err := event.New(&event.Opts{\n\t\tTarget: event.Target{Type: event.TargetTypeCluster, Value: provCluster.Name},\n\t\tKind: permission.PermClusterCreate,\n\t\tOwner: t,\n\t\tRemoteAddr: r.RemoteAddr,\n\t\tCustomData: event.FormToCustomData(InputFields(r)),\n\t\tAllowed: event.Allowed(permission.PermClusterReadEvents),\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() { evt.Done(err) }()\n\t_, err = servicemanager.Cluster.FindByName(ctx, provCluster.Name)\n\tif err == nil {\n\t\treturn &tsuruErrors.HTTP{\n\t\t\tCode: http.StatusConflict,\n\t\t\tMessage: \"cluster already exists\",\n\t\t}\n\t}\n\tfor _, poolName := range provCluster.Pools {\n\t\t_, err = pool.GetPoolByName(ctx, poolName)\n\t\tif err != nil {\n\t\t\tif err == pool.ErrPoolNotFound {\n\t\t\t\treturn &tsuruErrors.HTTP{\n\t\t\t\t\tCode: http.StatusNotFound,\n\t\t\t\t\tMessage: err.Error(),\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n\tstreamResponse := strings.HasPrefix(r.Header.Get(\"Accept\"), \"application/x-json-stream\")\n\tif streamResponse {\n\t\tw.Header().Set(\"Content-Type\", \"application/x-json-stream\")\n\t\tkeepAliveWriter := tsuruIo.NewKeepAliveWriter(w, 30*time.Second, \"\")\n\t\tdefer keepAliveWriter.Stop()\n\t\twriter := &tsuruIo.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)}\n\t\tevt.SetLogWriter(writer)\n\t}\n\tprovCluster.Writer = evt\n\terr = servicemanager.Cluster.Create(ctx, provCluster)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\treturn nil\n}", "func CreateCluster(request *restful.Request, response *restful.Response) {\n\tstart := time.Now()\n\n\tform := CreateClusterForm{}\n\t_ = request.ReadEntity(&form)\n\n\terr := utils.Validate.Struct(&form)\n\tif err != nil {\n\t\tmetrics.ReportRequestAPIMetrics(\"CreateCluster\", request.Request.Method, metrics.ErrStatus, start)\n\t\t_ = response.WriteHeaderAndEntity(400, utils.FormatValidationError(err))\n\t\treturn\n\t}\n\n\tuser := auth.GetUser(request)\n\tcluster := &models.BcsCluster{\n\t\tID: form.ClusterID,\n\t\tCreatorId: user.ID,\n\t}\n\tswitch form.ClusterType {\n\tcase \"k8s\":\n\t\tcluster.ClusterType = BcsK8sCluster\n\tcase \"mesos\":\n\t\tcluster.ClusterType = BcsMesosCluster\n\tcase \"tke\":\n\t\tcluster.ClusterType = BcsTkeCluster\n\t\tif form.TkeClusterID == \"\" || form.TkeClusterRegion == \"\" {\n\t\t\tmetrics.ReportRequestAPIMetrics(\"CreateCluster\", request.Request.Method, metrics.ErrStatus, start)\n\t\t\tblog.Warnf(\"create tke cluster failed, empty tke clusterid or region\")\n\t\t\tmessage := fmt.Sprintf(\"errcode: %d, create tke cluster failed, empty tke clusterid or region\", common.BcsErrApiBadRequest)\n\t\t\tutils.WriteClientError(response, common.BcsErrApiBadRequest, message)\n\t\t\treturn\n\t\t}\n\t\tcluster.TkeClusterId = form.TkeClusterID\n\t\tcluster.TkeClusterRegion = form.TkeClusterRegion\n\tdefault:\n\t\tmetrics.ReportRequestAPIMetrics(\"CreateCluster\", request.Request.Method, metrics.ErrStatus, start)\n\t\tblog.Warnf(\"create failed, cluster type invalid\")\n\t\tmessage := fmt.Sprintf(\"errcode: %d, create failed, cluster type invalid\", common.BcsErrApiBadRequest)\n\t\tutils.WriteClientError(response, common.BcsErrApiBadRequest, message)\n\t\treturn\n\t}\n\n\tclusterInDb := sqlstore.GetCluster(cluster.ID)\n\tif clusterInDb != nil {\n\t\tmetrics.ReportRequestAPIMetrics(\"CreateCluster\", request.Request.Method, metrics.ErrStatus, start)\n\t\tblog.Warnf(\"create cluster failed, cluster [%s] already exist\", cluster.ID)\n\t\tmessage := fmt.Sprintf(\"errcode: %d, create cluster failed, cluster [%s] already exist\", common.BcsErrApiBadRequest, cluster.ID)\n\t\tutils.WriteClientError(response, common.BcsErrApiBadRequest, message)\n\t\treturn\n\t}\n\n\terr = sqlstore.CreateCluster(cluster)\n\tif err != nil {\n\t\tmetrics.ReportRequestAPIMetrics(\"CreateCluster\", request.Request.Method, metrics.ErrStatus, start)\n\t\tblog.Errorf(\"failed to create cluster [%s]: %s\", cluster.ID, err.Error())\n\t\tmessage := fmt.Sprintf(\"errcode: %d, create cluster [%s] failed, error: %s\", common.BcsErrApiInternalDbError, cluster.ID, err.Error())\n\t\tutils.WriteServerError(response, common.BcsErrApiInternalDbError, message)\n\t\treturn\n\t}\n\n\tdata := utils.CreateResponseData(nil, \"success\", *cluster)\n\t_, _ = response.Write([]byte(data))\n\n\tmetrics.ReportRequestAPIMetrics(\"CreateCluster\", request.Request.Method, metrics.SucStatus, start)\n}", "func createPrivilegedServiceAccount(ctx context.Context, log *logrus.Entry, name, cluster, usersAccount string, kubeActions adminactions.KubeActions) (func() error, error, error) {\n\tserviceAcc := newServiceAccount(name, cluster)\n\tclusterRole := newClusterRole(usersAccount, cluster)\n\tcrb := newClusterRoleBinding(name, cluster)\n\tscc := newSecurityContextConstraint(name, cluster, usersAccount)\n\n\t// cleanup is created here incase an error occurs while creating permissions\n\tcleanup := func() error {\n\t\tlog.Infof(\"Deleting service account %s now\", serviceAcc.GetName())\n\t\terr := kubeActions.KubeDelete(ctx, serviceAcc.GetKind(), serviceAcc.GetNamespace(), serviceAcc.GetName(), true, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Infof(\"Deleting security context contstraint %s now\", scc.GetName())\n\t\terr = kubeActions.KubeDelete(ctx, scc.GetKind(), scc.GetNamespace(), scc.GetName(), true, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Infof(\"Deleting cluster role %s now\", clusterRole.GetName())\n\t\terr = kubeActions.KubeDelete(ctx, clusterRole.GetKind(), clusterRole.GetNamespace(), clusterRole.GetName(), true, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Infof(\"Deleting cluster role binding %s now\", crb.GetName())\n\t\terr = kubeActions.KubeDelete(ctx, crb.GetKind(), crb.GetNamespace(), crb.GetName(), true, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tlog.Infof(\"Creating Service Account %s now\", serviceAcc.GetName())\n\terr := kubeActions.KubeCreateOrUpdate(ctx, serviceAcc)\n\tif err != nil {\n\t\treturn nil, err, cleanup()\n\t}\n\n\tlog.Infof(\"Creating Cluster Role %s now\", clusterRole.GetName())\n\terr = kubeActions.KubeCreateOrUpdate(ctx, clusterRole)\n\tif err != nil {\n\t\treturn nil, err, cleanup()\n\t}\n\n\tlog.Infof(\"Creating Cluster Role Binding %s now\", crb.GetName())\n\terr = kubeActions.KubeCreateOrUpdate(ctx, crb)\n\tif err != nil {\n\t\treturn nil, err, cleanup()\n\t}\n\n\tlog.Infof(\"Creating Security Context Constraint %s now\", name)\n\terr = kubeActions.KubeCreateOrUpdate(ctx, scc)\n\tif err != nil {\n\t\treturn nil, err, cleanup()\n\t}\n\n\treturn cleanup, nil, nil\n}", "func CreateClusterRole(cr, namespace, name, app, description string, rules []rbacv1.PolicyRule) *rbacv1.ClusterRole {\n\tlabels := map[string]string{\n\t\t\"app\": app,\n\t\t\"deployedby\": \"aqua-operator\",\n\t\t\"aquasecoperator_cr\": cr,\n\t}\n\tannotations := map[string]string{\n\t\t\"description\": description,\n\t\t\"openshift.io/description\": \"A user who can search and scan images from an OpenShift integrated registry.\",\n\t}\n\tcrole := &rbacv1.ClusterRole{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"rbac.authorization.k8s.io/v1\",\n\t\t\tKind: \"ClusterRole\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t\tAnnotations: annotations,\n\t\t},\n\t\tRules: rules,\n\t}\n\n\treturn crole\n}", "func CreateModifyClusterServiceConfigForAdminRequest() (request *ModifyClusterServiceConfigForAdminRequest) {\n\trequest = &ModifyClusterServiceConfigForAdminRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Emr\", \"2016-04-08\", \"ModifyClusterServiceConfigForAdmin\", \"emr\", \"openAPI\")\n\treturn\n}", "func (s *ClusterListener) Create(inctx context.Context, in *protocol.ClusterCreateRequest) (_ *protocol.ClusterResponse, err error) {\n\tdefer fail.OnExitConvertToGRPCStatus(inctx, &err)\n\tdefer fail.OnExitWrapError(inctx, &err, \"cannot create cluster\")\n\n\tif s == nil {\n\t\treturn nil, fail.InvalidInstanceError()\n\t}\n\tif in == nil {\n\t\treturn nil, fail.InvalidParameterCannotBeNilError(\"in\")\n\t}\n\tif inctx == nil {\n\t\treturn nil, fail.InvalidParameterCannotBeNilError(\"inctx\")\n\t}\n\n\tname := in.GetName()\n\tjob, xerr := PrepareJob(inctx, in.GetTenantId(), fmt.Sprintf(\"/cluster/%s/create\", name))\n\tif xerr != nil {\n\t\treturn nil, xerr\n\t}\n\tdefer job.Close()\n\n\tctx := job.Context()\n\n\tcfg, xerr := job.Service().GetConfigurationOptions(ctx)\n\tif xerr != nil {\n\t\treturn nil, xerr\n\t}\n\n\tin.OperatorUsername = cfg.GetString(\"OperatorUsername\")\n\treq, xerr := converters.ClusterRequestFromProtocolToAbstract(in)\n\tif xerr != nil {\n\t\treturn nil, xerr\n\t}\n\n\tif req.Tenant == \"\" {\n\t\treq.Tenant = job.Tenant()\n\t}\n\n\thandler := handlers.NewClusterHandler(job)\n\tinstance, xerr := handler.Create(*req)\n\tif xerr != nil {\n\t\treturn nil, xerr\n\t}\n\n\treturn instance.ToProtocol(ctx)\n}", "func (client *ManagedClustersClient) listClusterAdminCredentialsCreateRequest(ctx context.Context, resourceGroupName string, resourceName string, options *ManagedClustersClientListClusterAdminCredentialsOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{resourceName}/listClusterAdminCredential\"\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\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 resourceName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceName}\", url.PathEscape(resourceName))\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\", \"2020-11-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (a ClustersAPI) Create(cluster httpmodels.CreateReq) (httpmodels.CreateResp, error) {\n\tvar createResp httpmodels.CreateResp\n\n\tresp, err := a.Client.performQuery(http.MethodPost, \"/clusters/create\", cluster, nil)\n\tif err != nil {\n\t\treturn createResp, err\n\t}\n\n\terr = json.Unmarshal(resp, &createResp)\n\treturn createResp, err\n}", "func (client *ManagedClustersClient) listClusterUserCredentialsCreateRequest(ctx context.Context, resourceGroupName string, resourceName string, options *ManagedClustersClientListClusterUserCredentialsOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{resourceName}/listClusterUserCredential\"\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\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 resourceName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceName}\", url.PathEscape(resourceName))\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\", \"2020-11-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func Create(rw *RequestWrapper) (*clm.GKECluster, error) {\n\tgkeOps, err := rw.acquire()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif rw.Request.SaveMetaData {\n\t\t// At this point we should have a cluster ready to run test. Need to save\n\t\t// metadata so that following flow can understand the context of cluster, as\n\t\t// well as for Prow usage later\n\t\twriteMetaData(gkeOps.Cluster, gkeOps.Project)\n\t}\n\n\t// set up kube config points to cluster\n\tclusterAuthCmd := fmt.Sprintf(\n\t\t\"gcloud beta container clusters get-credentials %s --region %s --project %s\",\n\t\tgkeOps.Cluster.Name, gkeOps.Cluster.Location, gkeOps.Project)\n\tif out, err := cmd.RunCommand(clusterAuthCmd); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed connecting to cluster: %q, %w\", out, err)\n\t}\n\tif out, err := cmd.RunCommand(\"gcloud config set project \" + gkeOps.Project); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed setting project: %q, %w\", out, err)\n\t}\n\n\treturn gkeOps, nil\n}", "func (e *ECS) CreateCluster(req *CreateClusterReq) (resp *CreateClusterResp, err error) {\n\tif req == nil {\n\t\treturn nil, fmt.Errorf(\"The req params cannot be nil\")\n\t}\n\n\tparams := makeParams(\"CreateCluster\")\n\tparams[\"clusterName\"] = req.ClusterName\n\n\tresp = new(CreateClusterResp)\n\tif err := e.query(params, resp); err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}", "func (client *CassandraClustersClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *CassandraClustersClientListByResourceGroupOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters\"\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\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\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-03-15-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (r *Resource) createReadAllClusterRole(ctx context.Context) error {\n\n\tlists, err := r.K8sClient().Discovery().ServerPreferredResources()\n\tif err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\tvar policyRules []rbacv1.PolicyRule\n\t{\n\t\tfor _, list := range lists {\n\t\t\tif len(list.APIResources) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgv, err := schema.ParseGroupVersion(list.GroupVersion)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, resource := range list.APIResources {\n\t\t\t\tif len(resource.Verbs) == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif isRestrictedResource(resource.Name) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tpolicyRule := rbacv1.PolicyRule{\n\t\t\t\t\tAPIGroups: []string{gv.Group},\n\t\t\t\t\tResources: []string{resource.Name},\n\t\t\t\t\tVerbs: []string{\"get\", \"list\", \"watch\"},\n\t\t\t\t}\n\t\t\t\tpolicyRules = append(policyRules, policyRule)\n\t\t\t}\n\t\t}\n\t}\n\n\t// ServerPreferredResources explicitely ignores any resource containing a '/'\n\t// but we require this for enabling pods/logs for customer access to\n\t// kubernetes pod logging. This is appended as a specific rule instead.\n\tpolicyRule := rbacv1.PolicyRule{\n\t\tAPIGroups: []string{\"\"},\n\t\tResources: []string{\"pods/log\"},\n\t\tVerbs: []string{\"get\", \"list\"},\n\t}\n\tpolicyRules = append(policyRules, policyRule)\n\n\treadOnlyClusterRole := &rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: pkgkey.DefaultReadAllPermissionsName,\n\t\t\tLabels: map[string]string{\n\t\t\t\tlabel.ManagedBy: project.Name(),\n\t\t\t\tlabel.DisplayInUserInterface: \"true\",\n\t\t\t},\n\t\t\tAnnotations: map[string]string{\n\t\t\t\tannotation.Notes: \"Grants read-only (get, list, watch) permissions to almost all resource types known on the management cluster, with exception of ConfigMap and Secret.\",\n\t\t\t},\n\t\t},\n\t\tRules: policyRules,\n\t}\n\n\treturn rbac.CreateOrUpdateClusterRole(r, ctx, readOnlyClusterRole)\n}", "func CreateClusterRole(\n\tk8sClient *kubernetes.Clientset,\n\tappName string,\n\tclusterRoleName string,\n\trules []PolicyRule,\n) error {\n\n\tlabels := map[string]string{\n\t\t\"app\": appName,\n\t}\n\n\trbacRules, err := generateRbacRules(rules)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%v\", err)\n\t}\n\n\tclusterRole := rbacv1.ClusterRole{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"rbac.authorization.k8s.io/v1\",\n\t\t\tKind: \"ClusterRole\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: clusterRoleName,\n\t\t\tLabels: labels,\n\t\t},\n\t\tRules: rbacRules,\n\t}\n\n\tclient := k8sClient.RbacV1().ClusterRoles()\n\t_, err = client.Create(&clusterRole)\n\tif err != nil {\n\t\tif !apierr.IsAlreadyExists(err) {\n\t\t\treturn fmt.Errorf(\"Failed to create ClusterRole %q: %v\", clusterRoleName, err)\n\t\t}\n\t\t_, err = client.Update(&clusterRole)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to update ClusterRole %q: %v\", clusterRoleName, err)\n\t\t}\n\t\tfmt.Printf(\"ClusterRole %q updated\\n\", clusterRoleName)\n\t} else {\n\t\tfmt.Printf(\"ClusterRole %q created\\n\", clusterRoleName)\n\t}\n\treturn nil\n}", "func EncodeClusterCreateRequest(m map[string]interface{}) map[string]interface{} {\n\treq := make(map[string]interface{})\n\t// Create requests involving a master version have to be sent under the \"initialMasterVersion\" key.\n\tif val, ok := m[\"currentMasterVersion\"]; ok {\n\t\tm[\"initialClusterVersion\"] = val\n\t\tdelete(m, \"currentMasterVersion\")\n\t}\n\n\tdcl.PutMapEntry(req, []string{\"cluster\"}, m)\n\treturn req\n}", "func (svc ServerlessClusterService) Create(ctx context.Context,\n\tinput *models.CreateServerlessClusterInput) (*models.Cluster, *Response, error) {\n\tvar cluster models.Cluster\n\tvar graphqlRequest = models.GraphqlRequest{\n\t\tOperation: models.Mutation,\n\t\tName: \"createServerlessCluster\",\n\t\tInput: *input,\n\t\tArgs: nil,\n\t\tResponse: cluster,\n\t}\n\treq, err := svc.client.NewRequest(&graphqlRequest)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresp, err := svc.client.Do(ctx, req, &cluster)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn &cluster, resp, nil\n}", "func CreateCreateClusterWithHostPoolRequest() (request *CreateClusterWithHostPoolRequest) {\n\trequest = &CreateClusterWithHostPoolRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Emr\", \"2016-04-08\", \"CreateClusterWithHostPool\", \"emr\", \"openAPI\")\n\treturn\n}", "func createClusterServer(opts *NodeOptions) *clusterServer {\n\treturn &clusterServer{workers: sync.Map{}, opts: opts}\n}", "func NewCmdCreateCluster() *cobra.Command {\n\to := NewCreateClusterOptions()\n\tcmd := &cobra.Command{\n\t\tUse: \"cluster\",\n\t\tShort: \"Create a Kubernetes or KubeSphere cluster\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tutil.CheckErr(o.Complete(cmd, args))\n\t\t\tutil.CheckErr(o.Validate(cmd, args))\n\t\t\tutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.CommonOptions.AddCommonFlag(cmd)\n\to.AddFlags(cmd)\n\n\tif err := completionSetting(cmd); err != nil {\n\t\tpanic(fmt.Sprintf(\"Got error with the completion setting\"))\n\t}\n\treturn cmd\n}", "func (client *ClustersClient) getCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, options *ClustersGetOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/clusters/{clusterName}\"\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\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 clusterName == \"\" {\n\t\treturn nil, errors.New(\"parameter clusterName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{clusterName}\", url.PathEscape(clusterName))\n\treq, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-06-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func CreateClusterRole(name string) *rbacv1.ClusterRole {\n\treturn &rbacv1.ClusterRole{\n\t\tTypeMeta: genTypeMeta(gvk.ClusterRole),\n\t\tObjectMeta: genObjectMeta(name, false),\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\t{\n\t\t\t\tAPIGroups: []string{\n\t\t\t\t\t\"stable.example.com\",\n\t\t\t\t},\n\t\t\t\tResources: []string{\n\t\t\t\t\t\"crontabs\",\n\t\t\t\t},\n\t\t\t\tVerbs: []string{\n\t\t\t\t\t\"get\",\n\t\t\t\t\t\"list\",\n\t\t\t\t\t\"watch\",\n\t\t\t\t\t\"create\",\n\t\t\t\t\t\"update\",\n\t\t\t\t\t\"patch\",\n\t\t\t\t\t\"delete\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func (cbo *CBO) createClusterOperator() (*osconfigv1.ClusterOperator, error) {\n defaultCO := cbo.defaultClusterOperator()\n\n co, err := cbo.osClient.ConfigV1().ClusterOperators().Create(defaultCO)\n if err != nil {\n return nil, err\n }\n\n co.Status = defaultCO.Status\n\n return cbo.osClient.ConfigV1().ClusterOperators().UpdateStatus(co)\n}", "func (client *CassandraClustersClient) getCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, options *CassandraClustersClientGetOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}\"\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\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 clusterName == \"\" {\n\t\treturn nil, errors.New(\"parameter clusterName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{clusterName}\", url.PathEscape(clusterName))\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-03-15-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func computeClusterExists(validationCtx *validationContext, computeCluster string, fldPath *field.Path, checkPrivileges bool) field.ErrorList {\n\tif computeCluster == \"\" {\n\t\treturn field.ErrorList{field.Required(fldPath, \"must specify the cluster\")}\n\t}\n\n\tctx, cancel := context.WithTimeout(context.TODO(), 60*time.Second)\n\tdefer cancel()\n\n\tcomputeClusterMo, err := validationCtx.Finder.ClusterComputeResource(ctx, computeCluster)\n\tif err != nil {\n\t\treturn field.ErrorList{field.Invalid(fldPath, computeCluster, err.Error())}\n\t}\n\n\tif checkPrivileges {\n\t\tpermissionGroup := permissions[permissionCluster]\n\t\terr = comparePrivileges(ctx, validationCtx, computeClusterMo.Reference(), permissionGroup)\n\n\t\tif err != nil {\n\t\t\treturn field.ErrorList{field.InternalError(fldPath, err)}\n\t\t}\n\t}\n\n\treturn field.ErrorList{}\n}", "func CreateCluster(data []int) Cluster {\n\treturn Cluster{\n\t\tindices: append([]int(nil), data...),\n\t}\n}", "func GetOrCreateClusterRole(log logrus.FieldLogger, client *kubernetes.Clientset, name string, rules []rbacv1.PolicyRule) (*rbacv1.ClusterRole, error) {\n\tfieldSelector := fields.SelectorFromSet(fields.Set{\"metadata.name\": name})\n\n\tctx := context.Background()\n\n\tclusterRoles, err := client.RbacV1().ClusterRoles().List(ctx, metav1.ListOptions{FieldSelector: fieldSelector.String()})\n\tif err != nil {\n\t\tlog.Errorf(\"querying cluster roles failed: %s\", err.Error())\n\t\treturn nil, err\n\t}\n\n\tif len(clusterRoles.Items) > 1 {\n\t\tlog.Errorf(\"duplicate cluster role with name %q found\", name)\n\t\treturn nil, fmt.Errorf(\"duplicate cluster role with name %q found\", name)\n\t}\n\n\tif len(clusterRoles.Items) == 1 {\n\t\tlog.Infof(\"cluster role %q already exists\", name)\n\t\treturn &clusterRoles.Items[0], nil\n\t}\n\n\tclusterRole, err := client.RbacV1().ClusterRoles().Create(\n\t\tctx,\n\t\t&rbacv1.ClusterRole{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: name,\n\t\t\t},\n\t\t\tRules: rules,\n\t\t},\n\t\tmetav1.CreateOptions{},\n\t)\n\tif err != nil {\n\t\tlog.Errorf(\"creating cluster role %q failed: %s\", name, err.Error())\n\t\treturn nil, err\n\t}\n\n\tlog.Infof(\"cluster role %q created\", name)\n\n\treturn clusterRole, nil\n}", "func CreateCreateClusterResponse() (response *CreateClusterResponse) {\n\tresponse = &CreateClusterResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (s *Session) CreateClusterModule(ctx context.Context) (string, error) {\n\tlog.Info(\"Creating clusterModule\")\n\n\trestClient := s.Client.RestClient()\n\tmoduleId, err := cluster.NewManager(restClient).CreateModule(ctx, s.cluster)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tlog.Info(\"Created clusterModule\", \"moduleId\", moduleId)\n\treturn moduleId, nil\n}", "func (client *ApiECSClient) CreateCluster(clusterName string) (string, error) {\n\tsvcRequest := svc.NewCreateClusterRequest()\n\tsvcRequest.SetClusterName(&clusterName)\n\n\tsvcClient, err := client.serviceClient()\n\tif err != nil {\n\t\tlog.Error(\"Unable to get service client for frontend\", \"err\", err)\n\t\treturn \"\", err\n\t}\n\n\tresp, err := svcClient.CreateCluster(svcRequest)\n\tif err != nil {\n\t\tlog.Crit(\"Could not register\", \"err\", err)\n\t\treturn \"\", err\n\t}\n\tlog.Info(\"Created a cluster!\", \"clusterName\", clusterName)\n\treturn *resp.Cluster().ClusterArn(), nil\n\n}", "func (s *BasePlSqlParserListener) EnterCreate_cluster(ctx *Create_clusterContext) {}", "func (*CreateClusterRequest) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_mdb_greenplum_v1_cluster_service_proto_rawDescGZIP(), []int{3}\n}", "func (client *ClustersClient) getCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, options *ClustersClientGetOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/serverGroupsv2/{clusterName}\"\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\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 clusterName == \"\" {\n\t\treturn nil, errors.New(\"parameter clusterName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{clusterName}\", url.PathEscape(clusterName))\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\", \"2022-11-08\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (k Kind) CreateCluster() error {\n\tcmd := kindCommand(\"kind create cluster --config /etc/kind/config.yml\")\n\tif err := cmd.Run(); err != nil {\n\t\treturn err\n\t}\n\n\tcmd = kindCommand(\"patch-kubeconfig.sh\")\n\tif err := cmd.Run(); err != nil {\n\t\treturn err\n\t}\n\n\t// This command is necessary to fix the coredns loop detected when using user-defined docker network.\n\t// In that case /etc/resolv.conf use 127.0.0.11 as DNS and CoreDNS thinks it is talking to itself which is wrong.\n\t// This IP is the docker internal DNS so it is safe to disable the loop check.\n\tcmd = kindCommand(\"sh -c 'kubectl -n kube-system get configmap/coredns -o yaml | grep -v loop | kubectl replace -f -'\")\n\terr := cmd.Run()\n\n\treturn err\n}", "func (c starterClusterServiceOp) Create(ctx context.Context, input *models.CreateStarterClusterInput) (*models.Cluster, *Response, error) {\n\tvar cluster models.Cluster\n\tvar graphqlRequest = models.GraphqlRequest{\n\t\tName: \"createStarterCluster\",\n\t\tOperation: models.Mutation,\n\t\tInput: *input,\n\t\tArgs: nil,\n\t\tResponse: cluster,\n\t}\n\treq, err := c.client.NewRequest(&graphqlRequest)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresp, err := c.client.Do(ctx, req, &cluster)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn &cluster, resp, err\n}", "func CreateListClusterMembersRequest() (request *ListClusterMembersRequest) {\n\trequest = &ListClusterMembersRequest{\n\t\tRoaRequest: &requests.RoaRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Edas\", \"2017-08-01\", \"ListClusterMembers\", \"/pop/v5/resource/cluster_member_list\", \"Edas\", \"openAPI\")\n\trequest.Method = requests.GET\n\treturn\n}", "func (client *ClustersClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *ClustersListByResourceGroupOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/clusters\"\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 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.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-06-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (a *Client) CreateCluster(params *CreateClusterParams, authInfo runtime.ClientAuthInfoWriter) (*CreateClusterCreated, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewCreateClusterParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"CreateCluster\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/api/v1/clusters\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &CreateClusterReader{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.(*CreateClusterCreated), nil\n\n}", "func (st *GlusterStorage) createCluster(h *heketiclient.Client) (*heketiapi.ClusterInfoResponse, error) {\n\tvar err error\n\tvar hcluster *heketiapi.ClusterInfoResponse\n\n\t// Wait maximum of one minute\n\tfor count := 0; count < max_loops; count++ {\n\t\thcluster, err = h.ClusterCreate()\n\t\tif err != nil {\n\t\t\ttime.Sleep(max_wait)\n\t\t} else {\n\t\t\treturn hcluster, nil\n\t\t}\n\t}\n\n\treturn nil, err\n}", "func (cluster *Cluster) ValidateCreate() error {\n\tklog.Info(\"validate create\", \"name\", cluster.Name)\n\treturn nil\n}", "func Create(ctx context.Context, client *v1.ServiceClient, clusterID string, opts *CreateOpts) (*v1.ResponseResult, error) {\n\tcreateNodegroupOpts := struct {\n\t\tNodegroup *CreateOpts `json:\"nodegroup\"`\n\t}{\n\t\tNodegroup: opts,\n\t}\n\trequestBody, err := json.Marshal(createNodegroupOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\turl := strings.Join([]string{client.Endpoint, v1.ResourceURLCluster, clusterID, v1.ResourceURLNodegroup}, \"/\")\n\tresponseResult, err := client.DoRequest(ctx, http.MethodPost, url, bytes.NewReader(requestBody))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif responseResult.Err != nil {\n\t\terr = responseResult.Err\n\t}\n\n\treturn responseResult, err\n}", "func (c *client) CreateCluster(settings CreateClusterSettings) error {\n\tk3sImage, err := getK3sImage(settings.KubernetesVersion)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmdArgs := []string{\n\t\t\"cluster\", \"create\", c.clusterName,\n\t\t\"--kubeconfig-update-default\",\n\t\t\"--timeout\", fmt.Sprintf(\"%ds\", int(c.userTimeout.Seconds())),\n\t\t\"--agents\", fmt.Sprintf(\"%d\", settings.Workers),\n\t\t\"--image\", k3sImage,\n\t}\n\n\tcmdArgs = append(cmdArgs, getCreateClusterArgs(settings)...)\n\n\tcmdArgs = append(cmdArgs, constructArgs(\"--port\", settings.PortMapping)...)\n\t//add further k3d args which are not offered by the Kyma CLI flags\n\tcmdArgs = append(cmdArgs, settings.Args...)\n\n\t_, err = c.runCmd(cmdArgs...)\n\treturn err\n}", "func CreateModifyDBClusterMigrationRequest() (request *ModifyDBClusterMigrationRequest) {\n\trequest = &ModifyDBClusterMigrationRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"polardb\", \"2017-08-01\", \"ModifyDBClusterMigration\", \"polardb\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (client *ClustersClient) createCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, parameters Cluster, options *ClustersClientBeginCreateOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/serverGroupsv2/{clusterName}\"\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\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 clusterName == \"\" {\n\t\treturn nil, errors.New(\"parameter clusterName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{clusterName}\", url.PathEscape(clusterName))\n\treq, err := runtime.NewRequest(ctx, http.MethodPut, 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-11-08\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, runtime.MarshalAsJSON(req, parameters)\n}", "func CreateGetClusterMetricsRequest() (request *GetClusterMetricsRequest) {\n\trequest = &GetClusterMetricsRequest{\n\t\tRoaRequest: &requests.RoaRequest{},\n\t}\n\trequest.InitWithApiInfo(\"foas\", \"2018-11-11\", \"GetClusterMetrics\", \"/api/v2/clusters/[clusterId]/metrics\", \"foas\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCluster(c *cli.Context) error {\n\n\t// On Error delete the cluster. If there createCluster() encounter any error,\n\t// call this function to remove all resources allocated for the cluster so far\n\t// so that they don't linger around.\n\tdeleteCluster := func() {\n\t\tlog.Println(\"ERROR: Cluster creation failed, rolling back...\")\n\t\tif err := DeleteCluster(c); err != nil {\n\t\t\tlog.Printf(\"Error: Failed to delete cluster %s\", c.String(\"name\"))\n\t\t}\n\t}\n\n\t// validate --wait flag\n\tif c.IsSet(\"wait\") && c.Int(\"wait\") < 0 {\n\t\tlog.Fatalf(\"Negative value for '--wait' not allowed (set '%d')\", c.Int(\"wait\"))\n\t}\n\n\t/**********************\n\t *\t\t\t\t\t\t\t\t\t\t*\n\t *\t\tCONFIGURATION\t\t*\n\t * vvvvvvvvvvvvvvvvvv *\n\t **********************/\n\n\t/*\n\t * --name, -n\n\t * Name of the cluster\n\t */\n\n\t// ensure that it's a valid hostname, because it will be part of container names\n\tif err := CheckClusterName(c.String(\"name\")); err != nil {\n\t\treturn err\n\t}\n\n\t// check if the cluster name is already taken\n\tif cluster, err := getClusters(false, c.String(\"name\")); err != nil {\n\t\treturn err\n\t} else if len(cluster) != 0 {\n\t\t// A cluster exists with the same name. Return with an error.\n\t\treturn fmt.Errorf(\" Cluster %s already exists\", c.String(\"name\"))\n\t}\n\n\t/*\n\t * --image, -i\n\t * The k3s image used for the k3d node containers\n\t */\n\t// define image\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\n\t/*\n\t * Cluster network\n\t * For proper communication, all k3d node containers have to be in the same docker network\n\t */\n\t// create cluster network\n\tnetworkID, err := createClusterNetwork(c.String(\"name\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"Created cluster network with ID %s\", networkID)\n\n\t/*\n\t * --env, -e\n\t * Environment variables that will be passed into the k3d node containers\n\t */\n\t// environment variables\n\tenv := []string{\"K3S_KUBECONFIG_OUTPUT=/output/kubeconfig.yaml\"}\n\tenv = append(env, c.StringSlice(\"env\")...)\n\tenv = append(env, fmt.Sprintf(\"K3S_CLUSTER_SECRET=%s\", GenerateRandomString(20)))\n\n\t/*\n\t * --label, -l\n\t * Docker container labels that will be added to the k3d node containers\n\t */\n\t// labels\n\tlabelmap, err := mapNodesToLabelSpecs(c.StringSlice(\"label\"), GetAllContainerNames(c.String(\"name\"), DefaultServerCount, c.Int(\"workers\")))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t/*\n\t * Arguments passed on to the k3s server and agent, will be filled later\n\t */\n\tk3AgentArgs := []string{}\n\tk3sServerArgs := []string{}\n\n\t/*\n\t * --api-port, -a\n\t * The port that will be used by the k3s API-Server\n\t * It will be mapped to localhost or to another hist interface, if specified\n\t * If another host is chosen, we also add a tls-san argument for the server to allow connections\n\t */\n\tapiPort, err := parseAPIPort(c.String(\"api-port\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tk3sServerArgs = append(k3sServerArgs, \"--https-listen-port\", apiPort.Port)\n\n\t// When the 'host' is not provided by --api-port, try to fill it using Docker Machine's IP address.\n\tif apiPort.Host == \"\" {\n\t\tapiPort.Host, err = getDockerMachineIp()\n\t\t// IP address is the same as the host\n\t\tapiPort.HostIP = apiPort.Host\n\t\t// In case of error, Log a warning message, and continue on. Since it more likely caused by a miss configured\n\t\t// DOCKER_MACHINE_NAME environment variable.\n\t\tif err != nil {\n\t\t\tlog.Warning(\"Failed to get docker machine IP address, ignoring the DOCKER_MACHINE_NAME environment variable setting.\")\n\t\t}\n\t}\n\n\t// Add TLS SAN for non default host name\n\tif apiPort.Host != \"\" {\n\t\tlog.Printf(\"Add TLS SAN for %s\", apiPort.Host)\n\t\tk3sServerArgs = append(k3sServerArgs, \"--tls-san\", apiPort.Host)\n\t}\n\n\t/*\n\t * --server-arg, -x\n\t * Add user-supplied arguments for the k3s server\n\t */\n\tif c.IsSet(\"server-arg\") || c.IsSet(\"x\") {\n\t\tk3sServerArgs = append(k3sServerArgs, c.StringSlice(\"server-arg\")...)\n\t}\n\n\t/*\n\t * --agent-arg\n\t * Add user-supplied arguments for the k3s agent\n\t */\n\tif c.IsSet(\"agent-arg\") {\n\t\tif c.Int(\"workers\") < 1 {\n\t\t\tlog.Warnln(\"--agent-arg supplied, but --workers is 0, so no agents will be created\")\n\t\t}\n\t\tk3AgentArgs = append(k3AgentArgs, c.StringSlice(\"agent-arg\")...)\n\t}\n\n\t/*\n\t * --port, -p, --publish, --add-port\n\t * List of ports, that should be mapped from some or all k3d node containers to the host system (or other interface)\n\t */\n\t// new port map\n\tportmap, err := mapNodesToPortSpecs(c.StringSlice(\"port\"), GetAllContainerNames(c.String(\"name\"), DefaultServerCount, c.Int(\"workers\")))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t/*\n\t * Image Volume\n\t * A docker volume that will be shared by every k3d node container in the cluster.\n\t * This volume will be used for the `import-image` command.\n\t * On it, all node containers can access the image tarball.\n\t */\n\t// create a docker volume for sharing image tarballs with the cluster\n\timageVolume, err := createImageVolume(c.String(\"name\"))\n\tlog.Println(\"Created docker volume \", imageVolume.Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t/*\n\t * --volume, -v\n\t * List of volumes: host directory mounts for some or all k3d node containers in the cluster\n\t */\n\tvolumes := c.StringSlice(\"volume\")\n\n\tvolumesSpec, err := NewVolumes(volumes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvolumesSpec.DefaultVolumes = append(volumesSpec.DefaultVolumes, fmt.Sprintf(\"%s:/images\", imageVolume.Name))\n\n\t/*\n\t * --registry-file\n\t * check if there is a registries file\n\t */\n\tregistriesFile := \"\"\n\tif c.IsSet(\"registries-file\") {\n\t\tregistriesFile = c.String(\"registries-file\")\n\t\tif !fileExists(registriesFile) {\n\t\t\tlog.Fatalf(\"registries-file %q does not exists\", registriesFile)\n\t\t}\n\t} else {\n\t\tregistriesFile, err = getGlobalRegistriesConfFilename()\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tif !fileExists(registriesFile) {\n\t\t\t// if the default registries file does not exists, go ahead but do not try to load it\n\t\t\tregistriesFile = \"\"\n\t\t}\n\t}\n\n\t/*\n\t * clusterSpec\n\t * Defines, with which specifications, the cluster and the nodes inside should be created\n\t */\n\tclusterSpec := &ClusterSpec{\n\t\tAgentArgs: k3AgentArgs,\n\t\tAPIPort: *apiPort,\n\t\tAutoRestart: c.Bool(\"auto-restart\"),\n\t\tClusterName: c.String(\"name\"),\n\t\tEnv: env,\n\t\tNodeToLabelSpecMap: labelmap,\n\t\tImage: image,\n\t\tNodeToPortSpecMap: portmap,\n\t\tPortAutoOffset: c.Int(\"port-auto-offset\"),\n\t\tRegistriesFile: registriesFile,\n\t\tRegistryEnabled: c.Bool(\"enable-registry\"),\n\t\tRegistryCacheEnabled: c.Bool(\"enable-registry-cache\"),\n\t\tRegistryName: c.String(\"registry-name\"),\n\t\tRegistryPort: c.Int(\"registry-port\"),\n\t\tRegistryVolume: c.String(\"registry-volume\"),\n\t\tServerArgs: k3sServerArgs,\n\t\tVolumes: volumesSpec,\n\t}\n\n\t/******************\n\t *\t\t\t\t\t\t\t\t*\n\t *\t\tCREATION\t\t*\n\t * vvvvvvvvvvvvvv\t*\n\t ******************/\n\n\tlog.Printf(\"Creating cluster [%s]\", c.String(\"name\"))\n\n\t/*\n\t * Cluster Directory\n\t */\n\t// create the directory where we will put the kubeconfig file by default (when running `k3d get-config`)\n\tcreateClusterDir(c.String(\"name\"))\n\n\t/* (1)\n\t * Registry (optional)\n\t * Create the (optional) registry container\n\t */\n\tvar registryNameExists *dnsNameCheck\n\tif clusterSpec.RegistryEnabled {\n\t\tregistryNameExists = newAsyncNameExists(clusterSpec.RegistryName, 1*time.Second)\n\t\tif _, err = createRegistry(*clusterSpec); err != nil {\n\t\t\tdeleteCluster()\n\t\t\treturn err\n\t\t}\n\t}\n\n\t/* (2)\n\t * Server\n\t * Create the server node container\n\t */\n\tserverContainerID, err := createServer(clusterSpec)\n\tif err != nil {\n\t\tdeleteCluster()\n\t\treturn err\n\t}\n\n\t/* (2.1)\n\t * Wait\n\t * Wait for k3s server to be done initializing, if wanted\n\t */\n\t// We're simply scanning the container logs for a line that tells us that everything's up and running\n\t// TODO: also wait for worker nodes\n\tif c.IsSet(\"wait\") {\n\t\tif err := waitForContainerLogMessage(serverContainerID, \"Wrote kubeconfig\", c.Int(\"wait\")); err != nil {\n\t\t\tdeleteCluster()\n\t\t\treturn fmt.Errorf(\"ERROR: failed while waiting for server to come up\\n%+v\", err)\n\t\t}\n\t}\n\n\t/* (3)\n\t * Workers\n\t * Create the worker node containers\n\t */\n\t// TODO: do this concurrently in different goroutines\n\tif c.Int(\"workers\") > 0 {\n\t\tlog.Printf(\"Booting %s workers for cluster %s\", strconv.Itoa(c.Int(\"workers\")), c.String(\"name\"))\n\t\tfor i := 0; i < c.Int(\"workers\"); i++ {\n\t\t\tworkerID, err := createWorker(clusterSpec, i)\n\t\t\tif err != nil {\n\t\t\t\tdeleteCluster()\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlog.Printf(\"Created worker with ID %s\\n\", workerID)\n\t\t}\n\t}\n\n\t/* (4)\n\t * Done\n\t * Finished creating resources.\n\t */\n\tlog.Printf(\"SUCCESS: created cluster [%s]\", c.String(\"name\"))\n\n\tif clusterSpec.RegistryEnabled {\n\t\tlog.Printf(\"A local registry has been started as %s:%d\", clusterSpec.RegistryName, clusterSpec.RegistryPort)\n\n\t\texists, err := registryNameExists.Exists()\n\t\tif !exists || err != nil {\n\t\t\tlog.Printf(\"Make sure you have an alias in your /etc/hosts file like '127.0.0.1 %s'\", clusterSpec.RegistryName)\n\t\t}\n\t}\n\n\tlog.Printf(`You can now use the cluster with:\n\nexport KUBECONFIG=\"$(%s get-kubeconfig --name='%s')\"\nkubectl cluster-info`, os.Args[0], c.String(\"name\"))\n\n\treturn nil\n}", "func (a *ClustersApiService) CreateCluster(ctx _context.Context, space string) ApiCreateClusterRequest {\n\treturn ApiCreateClusterRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tspace: space,\n\t}\n}", "func (client *ManagedClustersClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *ManagedClustersClientListByResourceGroupOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters\"\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\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\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\", \"2020-11-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func CreateCluster(c *gin.Context) {\n\n\tbanzaiUtils.LogInfo(banzaiConstants.TagCreateCluster, \"Cluster creation is stared\")\n\tbanzaiUtils.LogInfo(banzaiConstants.TagCreateCluster, \"Bind json into CreateClusterRequest struct\")\n\n\t// bind request body to struct\n\tvar createClusterBaseRequest banzaiTypes.CreateClusterRequest\n\tif err := c.BindJSON(&createClusterBaseRequest); err != nil {\n\t\t// bind failed\n\t\tbanzaiUtils.LogError(banzaiConstants.TagCreateCluster, \"Required field is empty: \"+err.Error())\n\t\tcloud.SetResponseBodyJson(c, http.StatusBadRequest, gin.H{\n\t\t\tcloud.JsonKeyStatus: http.StatusBadRequest,\n\t\t\tcloud.JsonKeyMessage: \"Required field is empty\",\n\t\t\tcloud.JsonKeyError: err,\n\t\t})\n\t\treturn\n\t} else {\n\t\tbanzaiUtils.LogInfo(banzaiConstants.TagCreateCluster, \"Bind succeeded\")\n\t}\n\n\tbanzaiUtils.LogInfo(banzaiConstants.TagCreateCluster, \"Searching entry with name:\", createClusterBaseRequest.Name)\n\tvar savedCluster banzaiSimpleTypes.ClusterSimple\n\n\tdatabase.Query(\"SELECT * FROM \"+banzaiSimpleTypes.ClusterSimple.TableName(savedCluster)+\" WHERE name = ?;\",\n\t\tcreateClusterBaseRequest.Name,\n\t\t&savedCluster)\n\n\tif savedCluster.ID != 0 {\n\t\t// duplicated entry\n\t\tmsg := \"Duplicate entry '\" + savedCluster.Name + \"' for key 'name'\"\n\t\tbanzaiUtils.LogError(banzaiConstants.TagCreateCluster, msg)\n\t\tcloud.SetResponseBodyJson(c, http.StatusBadRequest, gin.H{\n\t\t\tcloud.JsonKeyStatus: http.StatusBadRequest,\n\t\t\tcloud.JsonKeyMessage: msg,\n\t\t})\n\t\treturn\n\t}\n\n\tbanzaiUtils.LogInfo(banzaiConstants.TagCreateCluster, \"No entity with this name exists. The creation is possible.\")\n\n\tcloudType := createClusterBaseRequest.Cloud\n\tbanzaiUtils.LogInfo(banzaiConstants.TagCreateCluster, \"Cloud type is \", cloudType)\n\n\tswitch cloudType {\n\tcase banzaiConstants.Amazon:\n\t\t// validate and create Amazon cluster\n\t\tawsData := createClusterBaseRequest.Properties.CreateClusterAmazon\n\t\tif isValid, err := awsData.Validate(); isValid && len(err) == 0 {\n\t\t\tbanzaiUtils.LogInfo(banzaiConstants.TagCreateCluster, \"Validation is OK\")\n\t\t\tif isOk, createdCluster := cloud.CreateClusterAmazon(&createClusterBaseRequest, c); isOk {\n\t\t\t\t// update prometheus config..\n\t\t\t\tgo updatePrometheusWithRetryConf(createdCluster)\n\t\t\t}\n\t\t} else {\n\t\t\t// not valid request\n\t\t\tcloud.SetResponseBodyJson(c, http.StatusBadRequest, gin.H{\n\t\t\t\tcloud.JsonKeyStatus: http.StatusBadRequest,\n\t\t\t\tcloud.JsonKeyMessage: err,\n\t\t\t})\n\t\t}\n\tcase banzaiConstants.Azure:\n\t\t// validate and create Azure cluster\n\t\taksData := createClusterBaseRequest.Properties.CreateClusterAzure\n\t\tif isValid, err := aksData.Validate(); isValid && len(err) == 0 {\n\t\t\tif cloud.CreateClusterAzure(&createClusterBaseRequest, c) {\n\t\t\t\t// update prometheus config..\n\t\t\t\tupdatePrometheus()\n\t\t\t}\n\t\t} else {\n\t\t\t// not valid request\n\t\t\tcloud.SetResponseBodyJson(c, http.StatusBadRequest, gin.H{\n\t\t\t\tcloud.JsonKeyStatus: http.StatusBadRequest,\n\t\t\t\tcloud.JsonKeyMessage: err,\n\t\t\t})\n\t\t}\n\tdefault:\n\t\t// wrong cloud type\n\t\tcloud.SendNotSupportedCloudResponse(c, banzaiConstants.TagCreateCluster)\n\t}\n\n}", "func clusterPermissions(permissions ...auth.Permission) authHandler {\n\treturn func(ctx context.Context, authApi authiface.APIServer, fullMethod string) (string, error) {\n\t\tresp, err := authApi.Authorize(ctx, &auth.AuthorizeRequest{\n\t\t\tResource: &auth.Resource{Type: auth.ResourceType_CLUSTER},\n\t\t\tPermissions: permissions,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn \"\", errors.EnsureStack(err)\n\t\t}\n\n\t\tif resp.Authorized {\n\t\t\treturn \"\", nil\n\t\t}\n\n\t\treturn \"\", &auth.ErrNotAuthorized{\n\t\t\tSubject: resp.Principal,\n\t\t\tResource: &auth.Resource{Type: auth.ResourceType_CLUSTER},\n\t\t\tRequired: permissions,\n\t\t}\n\t}\n}", "func (ctrler CtrlDefReactor) OnClusterCreate(obj *Cluster) error {\n\tlog.Info(\"OnClusterCreate is not implemented\")\n\treturn nil\n}", "func (r *Resource) createWriteClientCertsClusterRole(ctx context.Context) error {\n\tpolicyRule := rbacv1.PolicyRule{\n\t\tAPIGroups: []string{\n\t\t\t\"core.giantswarm.io\",\n\t\t},\n\t\tResources: []string{\n\t\t\t\"certconfigs\",\n\t\t},\n\t\tVerbs: []string{\"*\"},\n\t}\n\n\tclusterRole := &rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: pkgkey.WriteClientCertsPermissionsName,\n\t\t\tLabels: map[string]string{\n\t\t\t\tlabel.ManagedBy: project.Name(),\n\t\t\t\tlabel.DisplayInUserInterface: \"true\",\n\t\t\t},\n\t\t\tAnnotations: map[string]string{\n\t\t\t\tannotation.Notes: \"Grants full permissions on certconfigs.core.giantswarm.io resources.\",\n\t\t\t},\n\t\t},\n\t\tRules: []rbacv1.PolicyRule{policyRule},\n\t}\n\n\treturn rbac.CreateOrUpdateClusterRole(r, ctx, clusterRole)\n}", "func (r *ApplicationSetReconciler) createInCluster(ctx context.Context, applicationSet argov1alpha1.ApplicationSet, desiredApplications []argov1alpha1.Application) error {\n\n\tvar createApps []argov1alpha1.Application\n\tcurrent, err := r.getCurrentApplications(ctx, applicationSet)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting current applications: %w\", err)\n\t}\n\n\tm := make(map[string]bool) // Will holds the app names that are current in the cluster\n\n\tfor _, app := range current {\n\t\tm[app.Name] = true\n\t}\n\n\t// filter applications that are not in m[string]bool (new to the cluster)\n\tfor _, app := range desiredApplications {\n\t\t_, exists := m[app.Name]\n\n\t\tif !exists {\n\t\t\tcreateApps = append(createApps, app)\n\t\t}\n\t}\n\n\treturn r.createOrUpdateInCluster(ctx, applicationSet, createApps)\n}", "func (client *ManagedClustersClient) listClusterMonitoringUserCredentialsCreateRequest(ctx context.Context, resourceGroupName string, resourceName string, options *ManagedClustersClientListClusterMonitoringUserCredentialsOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{resourceName}/listClusterMonitoringUserCredential\"\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\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 resourceName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceName}\", url.PathEscape(resourceName))\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\", \"2020-11-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (c *Client) CreateGlobalCluster(ctx context.Context, params *CreateGlobalClusterInput, optFns ...func(*Options)) (*CreateGlobalClusterOutput, error) {\n\tif params == nil {\n\t\tparams = &CreateGlobalClusterInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"CreateGlobalCluster\", params, optFns, c.addOperationCreateGlobalClusterMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*CreateGlobalClusterOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (opts CreateOpts) ToClusterCreateMap() (map[string]interface{}, error) {\n\treturn gophercloud.BuildRequestBody(opts, \"\")\n}", "func createCentralClusterServiceAccountAndRoles(ctx context.Context, c kubernetes.Interface, f flags) error {\n\t// central cluster always uses Roles. Never Cluster Roles.\n\treturn createServiceAccountAndRoles(ctx, c, f.serviceAccount, f.centralClusterNamespace, f.clusterScoped, centralCluster)\n}", "func (o DiagnosticsOptions) makeClusterClients(rawConfig *clientcmdapi.Config, contextName string, context *clientcmdapi.Context) (*rest.Config, kclientset.Interface, *clientcmdapi.Config, error) {\n\t// create a config for making openshift clients\n\tconfig, err := o.Factory.ToRESTConfig()\n\tif err != nil {\n\t\to.Logger().Debug(\"CED1006\", fmt.Sprintf(\"Error creating client config for context '%s':\\n%v\", contextName, err))\n\t\treturn nil, nil, nil, nil\n\t}\n\n\t// create a kube client\n\tkubeClient, err := kclientset.NewForConfig(config)\n\tif err != nil {\n\t\to.Logger().Debug(\"CED1006\", fmt.Sprintf(\"Error creating kube client for context '%s':\\n%v\", contextName, err))\n\t\treturn nil, nil, nil, nil\n\t}\n\n\to.Logger().Debug(\"CED1005\", fmt.Sprintf(\"Checking if context is cluster-admin: '%s'\", contextName))\n\tsubjectAccessReview := &authorization.SelfSubjectAccessReview{\n\t\tSpec: authorization.SelfSubjectAccessReviewSpec{\n\t\t\tResourceAttributes: &authorization.ResourceAttributes{\n\t\t\t\t// if you can do everything, you're the cluster admin.\n\t\t\t\tVerb: \"*\",\n\t\t\t\tGroup: \"*\",\n\t\t\t\tResource: \"*\",\n\t\t\t},\n\t\t},\n\t}\n\tresp, err := kubeClient.Authorization().SelfSubjectAccessReviews().Create(subjectAccessReview)\n\tif err != nil && regexp.MustCompile(`User \"[\\w:]+\" cannot create \\w+ at the cluster scope`).MatchString(err.Error()) {\n\t\to.Logger().Debug(\"CED1007\", fmt.Sprintf(\"Context '%s' does not have cluster-admin access:\\n%v\", contextName, err))\n\t\treturn nil, nil, nil, nil\n\t}\n\tif err != nil {\n\t\to.Logger().Error(\"CED1008\", fmt.Sprintf(\"Unknown error testing cluster-admin access for context '%s':\\n%v\", contextName, err))\n\t\treturn nil, nil, nil, err\n\t}\n\tif !resp.Status.Allowed {\n\t\to.Logger().Debug(\"CED1010\", fmt.Sprintf(\"Context does not have cluster-admin access: '%s'\", contextName))\n\t\treturn nil, nil, nil, nil\n\t}\n\n\to.Logger().Info(\"CED1009\", fmt.Sprintf(\"Using context for cluster-admin access: '%s'\", contextName))\n\tadminConfig := rawConfig.DeepCopy()\n\tadminConfig.CurrentContext = contextName\n\tif err := clientcmdapi.MinifyConfig(adminConfig); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tif err := clientcmdapi.FlattenConfig(adminConfig); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\treturn config, kubeClient, adminConfig, nil\n}", "func createCluster(\n\tctx context.Context,\n\tc *cli.Context,\n\tcfgHelper *cmdutils.ConfigHelper,\n\thost host.Host,\n\tpubsub *pubsub.PubSub,\n\tdht *dual.DHT,\n\tstore ds.Datastore,\n\traftStaging bool,\n) (*ipfscluster.Cluster, error) {\n\n\tcfgs := cfgHelper.Configs()\n\tcfgMgr := cfgHelper.Manager()\n\tcfgBytes, err := cfgMgr.ToDisplayJSON()\n\tcheckErr(\"getting configuration string\", err)\n\tlogger.Debugf(\"Configuration:\\n%s\\n\", cfgBytes)\n\n\tctx, err = tag.New(ctx, tag.Upsert(observations.HostKey, host.ID().Pretty()))\n\tcheckErr(\"tag context with host id\", err)\n\n\terr = observations.SetupMetrics(cfgs.Metrics)\n\tcheckErr(\"setting up Metrics\", err)\n\n\ttracer, err := observations.SetupTracing(cfgs.Tracing)\n\tcheckErr(\"setting up Tracing\", err)\n\n\tvar apis []ipfscluster.API\n\tif cfgMgr.IsLoadedFromJSON(config.API, cfgs.Restapi.ConfigKey()) {\n\t\tvar api *rest.API\n\t\t// Do NOT enable default Libp2p API endpoint on CRDT\n\t\t// clusters. Collaborative clusters are likely to share the\n\t\t// secret with untrusted peers, thus the API would be open for\n\t\t// anyone.\n\t\tif cfgHelper.GetConsensus() == cfgs.Raft.ConfigKey() {\n\t\t\tapi, err = rest.NewAPIWithHost(ctx, cfgs.Restapi, host)\n\t\t} else {\n\t\t\tapi, err = rest.NewAPI(ctx, cfgs.Restapi)\n\t\t}\n\t\tcheckErr(\"creating REST API component\", err)\n\t\tapis = append(apis, api)\n\n\t}\n\n\tif cfgMgr.IsLoadedFromJSON(config.API, cfgs.Pinsvcapi.ConfigKey()) {\n\t\tpinsvcapi, err := pinsvcapi.NewAPI(ctx, cfgs.Pinsvcapi)\n\t\tcheckErr(\"creating Pinning Service API component\", err)\n\n\t\tapis = append(apis, pinsvcapi)\n\t}\n\n\tif cfgMgr.IsLoadedFromJSON(config.API, cfgs.Ipfsproxy.ConfigKey()) {\n\t\tproxy, err := ipfsproxy.New(cfgs.Ipfsproxy)\n\t\tcheckErr(\"creating IPFS Proxy component\", err)\n\n\t\tapis = append(apis, proxy)\n\t}\n\n\tconnector, err := ipfshttp.NewConnector(cfgs.Ipfshttp)\n\tcheckErr(\"creating IPFS Connector component\", err)\n\n\tvar informers []ipfscluster.Informer\n\tif cfgMgr.IsLoadedFromJSON(config.Informer, cfgs.DiskInf.ConfigKey()) {\n\t\tdiskInf, err := disk.NewInformer(cfgs.DiskInf)\n\t\tcheckErr(\"creating disk informer\", err)\n\t\tinformers = append(informers, diskInf)\n\t}\n\tif cfgMgr.IsLoadedFromJSON(config.Informer, cfgs.TagsInf.ConfigKey()) {\n\t\ttagsInf, err := tags.New(cfgs.TagsInf)\n\t\tcheckErr(\"creating numpin informer\", err)\n\t\tinformers = append(informers, tagsInf)\n\t}\n\n\tif cfgMgr.IsLoadedFromJSON(config.Informer, cfgs.PinQueueInf.ConfigKey()) {\n\t\tpinQueueInf, err := pinqueue.New(cfgs.PinQueueInf)\n\t\tcheckErr(\"creating pinqueue informer\", err)\n\t\tinformers = append(informers, pinQueueInf)\n\t}\n\n\t// For legacy compatibility we need to make the allocator\n\t// automatically compatible with informers that have been loaded. For\n\t// simplicity we assume that anyone that does not specify an allocator\n\t// configuration (legacy configs), will be using \"freespace\"\n\tif !cfgMgr.IsLoadedFromJSON(config.Allocator, cfgs.BalancedAlloc.ConfigKey()) {\n\t\tcfgs.BalancedAlloc.AllocateBy = []string{\"freespace\"}\n\t}\n\talloc, err := balanced.New(cfgs.BalancedAlloc)\n\tcheckErr(\"creating allocator\", err)\n\n\tcons, err := setupConsensus(\n\t\tcfgHelper,\n\t\thost,\n\t\tdht,\n\t\tpubsub,\n\t\tstore,\n\t\traftStaging,\n\t)\n\tif err != nil {\n\t\tstore.Close()\n\t\tcheckErr(\"setting up Consensus\", err)\n\t}\n\n\tvar peersF func(context.Context) ([]peer.ID, error)\n\tif cfgHelper.GetConsensus() == cfgs.Raft.ConfigKey() {\n\t\tpeersF = cons.Peers\n\t}\n\n\ttracker := stateless.New(cfgs.Statelesstracker, host.ID(), cfgs.Cluster.Peername, cons.State)\n\tlogger.Debug(\"stateless pintracker loaded\")\n\n\tmon, err := pubsubmon.New(ctx, cfgs.Pubsubmon, pubsub, peersF)\n\tif err != nil {\n\t\tstore.Close()\n\t\tcheckErr(\"setting up PeerMonitor\", err)\n\t}\n\n\treturn ipfscluster.NewCluster(\n\t\tctx,\n\t\thost,\n\t\tdht,\n\t\tcfgs.Cluster,\n\t\tstore,\n\t\tcons,\n\t\tapis,\n\t\tconnector,\n\t\ttracker,\n\t\tmon,\n\t\talloc,\n\t\tinformers,\n\t\ttracer,\n\t)\n}", "func newGetClusterNodeCmd(out io.Writer) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"node\",\n\t\tShort: \"Get Cluster Nodes\",\n\t\tLong: `Get Cluster Nodes`,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tc7nclient.InitClient(&clientConfig, &clientPlatformConfig)\n\t\t\terror := c7nclient.Client.CheckIsLogin()\n\t\t\tif error != nil {\n\t\t\t\tfmt.Println(error)\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr, userInfo := c7nclient.Client.QuerySelf(cmd.OutOrStdout())\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr = c7nclient.Client.SetOrganization(cmd.OutOrStdout(), userInfo.ID)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr = c7nclient.Client.SetProject(cmd.OutOrStdout(), userInfo.ID)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr, pro := c7nclient.Client.GetProject(cmd.OutOrStdout(), userInfo.ID, proCode)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr, cluster := c7nclient.Client.GetCluster(cmd.OutOrStdout(), pro.ID, clusterCode)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tc7nclient.Client.ListClusterNode(cmd.OutOrStdout(), pro.ID, cluster.ID)\n\t\t},\n\t}\n\n\tcmd.Flags().StringVarP(&clusterCode, \"clusterCode\", \"c\", \"\", \"cluster code\")\n\tcmd.MarkFlagRequired(\"clusterCode\")\n\n\treturn cmd\n}", "func (fgsc *FakeGKESDKClient) create(project, location string, rb *container.CreateClusterRequest) (*container.Operation, error) {\n\tparent := fmt.Sprintf(\"projects/%s/locations/%s\", project, location)\n\tname := rb.Cluster.Name\n\tif cls, ok := fgsc.clusters[parent]; ok {\n\t\tfor _, cl := range cls {\n\t\t\tif cl.Name == name {\n\t\t\t\treturn nil, errors.New(\"cluster already exist\")\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfgsc.clusters[parent] = make([]*container.Cluster, 0)\n\t}\n\tcluster := &container.Cluster{\n\t\tName: name,\n\t\tLocation: location,\n\t\tStatus: \"RUNNING\",\n\t}\n\n\tfgsc.clusters[parent] = append(fgsc.clusters[parent], cluster)\n\treturn fgsc.newOp(), nil\n}", "func CreateK3SRKE2Cluster(client *rancher.Client, rke2Cluster *apisV1.Cluster) (*v1.SteveAPIObject, error) {\n\tcluster, err := client.Steve.SteveType(ProvisioningSteveResouceType).Create(rke2Cluster)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = kwait.Poll(500*time.Millisecond, 2*time.Minute, func() (done bool, err error) {\n\t\tclient, err = client.ReLogin()\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\t_, err = client.Steve.SteveType(ProvisioningSteveResouceType).ByID(cluster.ID)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t} else {\n\t\t\treturn true, nil\n\t\t}\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.Session.RegisterCleanupFunc(func() error {\n\t\tadminClient, err := rancher.NewClient(client.RancherConfig.AdminToken, client.Session)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tprovKubeClient, err := adminClient.GetKubeAPIProvisioningClient()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\twatchInterface, err := provKubeClient.Clusters(cluster.ObjectMeta.Namespace).Watch(context.TODO(), metav1.ListOptions{\n\t\t\tFieldSelector: \"metadata.name=\" + cluster.ObjectMeta.Name,\n\t\t\tTimeoutSeconds: &defaults.WatchTimeoutSeconds,\n\t\t})\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tclient, err = client.ReLogin()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = client.Steve.SteveType(ProvisioningSteveResouceType).Delete(cluster)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn wait.WatchWait(watchInterface, func(event watch.Event) (ready bool, err error) {\n\t\t\tcluster := event.Object.(*apisV1.Cluster)\n\t\t\tif event.Type == watch.Error {\n\t\t\t\treturn false, fmt.Errorf(\"there was an error deleting cluster\")\n\t\t\t} else if event.Type == watch.Deleted {\n\t\t\t\treturn true, nil\n\t\t\t} else if cluster == nil {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\treturn false, nil\n\t\t})\n\t})\n\n\treturn cluster, nil\n}", "func NewCreateCmd(globalFlags *flags.GlobalFlags) *cobra.Command {\n\tcmd := &CreateCmd{\n\t\tGlobalFlags: globalFlags,\n\t\tlog: log.GetInstance(),\n\t}\n\n\tcobraCmd := &cobra.Command{\n\t\tUse: \"create\",\n\t\tShort: \"Create a new virtual cluster\",\n\t\tLong: `\n#######################################################\n################### vcluster create ###################\n#######################################################\nCreates a new virtual cluster\n\nExample:\nvcluster create test --namespace test\n#######################################################\n\t`,\n\t\tArgs: cobra.ExactArgs(1),\n\t\tRunE: func(cobraCmd *cobra.Command, args []string) error {\n\t\t\t// Check for newer version\n\t\t\tupgrade.PrintNewerVersionWarning()\n\n\t\t\treturn cmd.Run(cobraCmd, args)\n\t\t},\n\t}\n\n\tcobraCmd.Flags().StringVar(&cmd.ChartVersion, \"chart-version\", upgrade.GetVersion(), \"The virtual cluster chart version to use\")\n\tcobraCmd.Flags().StringVar(&cmd.ChartName, \"chart-name\", \"vcluster\", \"The virtual cluster chart name to use\")\n\tcobraCmd.Flags().StringVar(&cmd.ChartRepo, \"chart-repo\", \"https://charts.loft.sh\", \"The virtual cluster chart repo to use\")\n\tcobraCmd.Flags().StringVar(&cmd.ReleaseValues, \"release-values\", \"\", \"Path where to load the virtual cluster helm release values from\")\n\tcobraCmd.Flags().StringVar(&cmd.K3SImage, \"k3s-image\", \"\", \"If specified, use this k3s image version\")\n\tcobraCmd.Flags().StringSliceVarP(&cmd.ExtraValues, \"extra-values\", \"f\", []string{}, \"Path where to load extra helm values from\")\n\tcobraCmd.Flags().BoolVar(&cmd.CreateNamespace, \"create-namespace\", true, \"If true the namespace will be created if it does not exist\")\n\tcobraCmd.Flags().BoolVar(&cmd.DisableIngressSync, \"disable-ingress-sync\", false, \"If true the virtual cluster will not sync any ingresses\")\n\tcobraCmd.Flags().BoolVar(&cmd.CreateClusterRole, \"create-cluster-role\", false, \"If true a cluster role will be created to access nodes, storageclasses and priorityclasses\")\n\tcobraCmd.Flags().BoolVar(&cmd.Expose, \"expose\", false, \"If true will create a load balancer service to expose the vcluster endpoint\")\n\tcobraCmd.Flags().BoolVar(&cmd.Connect, \"connect\", false, \"If true will run vcluster connect directly after the vcluster was created\")\n\treturn cobraCmd\n}", "func NewGetClusterForbidden() *GetClusterForbidden {\n\n\treturn &GetClusterForbidden{}\n}", "func (p *Provider) Create(name string, options ...CreateOption) error {\n\t// apply options\n\topts := &internalcreate.ClusterOptions{}\n\tfor _, o := range options {\n\t\tif err := o.apply(opts); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn internalcreate.Cluster(p.logger, p.ic(name), opts)\n}", "func (a *ClustersApiService) CreateClusterExecute(r ApiCreateClusterRequest) (CreateClusterResponse, *_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 CreateClusterResponse\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"ClustersApiService.CreateCluster\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/spaces/{space}/clusters\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"space\"+\"}\", _neturl.PathEscape(parameterToString(r.space, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.createCluster == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"createCluster is required and must be specified\")\n\t}\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\"}\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 = r.createCluster\n\treq, err := a.client.prepareRequest(r.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(req)\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\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\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\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 createServiceAccountsAndRoles(ctx context.Context, clientMap map[string]kubernetes.Interface, f flags) error {\n\tfmt.Printf(\"creating central cluster roles in cluster: %s\\n\", f.centralCluster)\n\tc := clientMap[f.centralCluster]\n\tif err := createCentralClusterServiceAccountAndRoles(ctx, c, f); err != nil {\n\t\treturn err\n\t}\n\tif f.createServiceAccountSecrets {\n\t\tif err := createServiceAccountTokenSecret(ctx, c, f.centralClusterNamespace, f.serviceAccount); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor _, memberCluster := range f.memberClusters {\n\t\tif memberCluster == f.centralCluster {\n\t\t\tfmt.Printf(\"skipping creation of member roles in cluster (it is also the central cluster): %s\\n\", memberCluster)\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"creating member roles in cluster: %s\\n\", memberCluster)\n\t\tc := clientMap[memberCluster]\n\t\tif err := createMemberServiceAccountAndRoles(ctx, c, f); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif f.createServiceAccountSecrets {\n\t\t\tif err := createServiceAccountTokenSecret(ctx, c, f.memberClusterNamespace, f.serviceAccount); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func CreateCluster(ctx context.Context, clusterClient containerservice.ManagedClustersClient, parameters ClusterParameters) (status string, err error) {\n\tresourceGroupName := parameters.Name + \"-group\"\n\n\t// create map of containerservice.ManagedClusterAgentPoolProfile from parameters.AgentPools\n\tagentPoolProfiles := make([]containerservice.ManagedClusterAgentPoolProfile, len(parameters.AgentPools))\n\tfor i := range parameters.AgentPools {\n\t\tvar vmSize containerservice.VMSizeTypes\n\n\t\t// get list of available VM size types\n\t\tvmSizeTypes := containerservice.PossibleVMSizeTypesValues()\n\t\tfor j := range vmSizeTypes {\n\t\t\t// convert the vmSizeTypes to a string\n\t\t\ttypeAsStr := string(vmSizeTypes[j])\n\t\t\t// compare input type against available vm size types\n\t\t\tif parameters.AgentPools[i].Type == typeAsStr {\n\t\t\t\tvmSize = vmSizeTypes[j]\n\t\t\t}\n\t\t}\n\t\tif vmSize == \"\" {\n\t\t\treturn \"\", fmt.Errorf(\"invalid VM Size selected\")\n\t\t}\n\n\t\tagentPoolProfiles[i] = containerservice.ManagedClusterAgentPoolProfile{\n\t\t\tName: parameters.AgentPools[i].Name,\n\t\t\tCount: parameters.AgentPools[i].Count,\n\t\t\tVMSize: vmSize,\n\t\t}\n\t}\n\n\tfuture, err := clusterClient.CreateOrUpdate(\n\t\tctx,\n\t\tresourceGroupName,\n\t\tparameters.Name,\n\t\tcontainerservice.ManagedCluster{\n\t\t\tName: &parameters.Name,\n\t\t\tLocation: &parameters.Location,\n\t\t\tManagedClusterProperties: &containerservice.ManagedClusterProperties{\n\t\t\t\tDNSPrefix: &parameters.Name,\n\t\t\t\tKubernetesVersion: &parameters.KubernetesVersion,\n\t\t\t\tAgentPoolProfiles: &agentPoolProfiles,\n\t\t\t\tServicePrincipalProfile: &containerservice.ManagedClusterServicePrincipalProfile{\n\t\t\t\t\tClientID: to.StringPtr(parameters.ClientID),\n\t\t\t\t\tSecret: to.StringPtr(parameters.ClientSecret),\n\t\t\t\t},\n\t\t\t},\n\t\t\tTags: parameters.Tags,\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"cannot create aks cluster: %v\", err)\n\t}\n\n\tstatus = future.Status()\n\tif status != \"Creating\" {\n\t\treturn \"\", fmt.Errorf(\"cannot create cluster: %v\", status)\n\t}\n\n\treturn status, nil\n}", "func (mcr *MiddlewareClusterRepo) Create(middlewareCluster metadata.MiddlewareCluster) (metadata.MiddlewareCluster, error) {\n\tsql := `insert into t_meta_middleware_cluster_info(cluster_name, owner_id, env_id) values(?, ?, ?);`\n\tlog.Debugf(\"metadata MiddlewareClusterRepo.Create() insert sql: %s\", sql)\n\t// execute\n\t_, err := mcr.Execute(sql,\n\t\tmiddlewareCluster.(*MiddlewareClusterInfo).ClusterName,\n\t\tmiddlewareCluster.(*MiddlewareClusterInfo).OwnerID,\n\t\tmiddlewareCluster.(*MiddlewareClusterInfo).EnvID,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// get id\n\tid, err := mcr.GetID(middlewareCluster.GetClusterName(), middlewareCluster.GetEnvID())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// get entity\n\treturn mcr.GetByID(id)\n}", "func Create(c *client.Client, cr *Instance) error {\n\n\trole := &rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.Name,\n\t\t\tLabels: map[string]string{\n\t\t\t\tcr.LabelKey: cr.LabelValue,\n\t\t\t},\n\t\t},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\t{\n\t\t\t\tAPIGroups: cr.APIGroups,\n\t\t\t\tResources: cr.Resources,\n\t\t\t\tVerbs: cr.Verbs,\n\t\t\t\tResourceNames: cr.ResourcesNames,\n\t\t\t},\n\t\t},\n\t}\n\n\t_, err := c.Clientset.RbacV1().ClusterRoles().Create(\n\t\tcontext.TODO(),\n\t\trole,\n\t\tmetav1.CreateOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (*ProjectGrantUserGrantCreate) Descriptor() ([]byte, []int) {\n\treturn file_management_proto_rawDescGZIP(), []int{133}\n}", "func CreateClusterRole(client kubeclient.Interface, clusterRoleObj *rbacv1.ClusterRole) (*rbacv1.ClusterRole, error) {\n\tcreatedObj, err := client.RbacV1().ClusterRoles().Create(context.TODO(), clusterRoleObj, metav1.CreateOptions{})\n\tif err != nil {\n\t\tif apierrors.IsAlreadyExists(err) {\n\t\t\treturn clusterRoleObj, nil\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn createdObj, nil\n}", "func Create(req clusterapi.Request) (clusterapi.ClusterAPI, error) {\n\t// Validates parameters\n\tif req.Name == \"\" {\n\t\treturn nil, fmt.Errorf(\"Invalid parameter req.Name: can't be empty\")\n\t}\n\tif req.CIDR == \"\" {\n\t\treturn nil, fmt.Errorf(\"Invalid parameter req.CIDR: can't be empty\")\n\t}\n\n\t// We need at first the Metadata container to be present\n\terr := utils.CreateMetadataContainer()\n\tif err != nil {\n\t\tfmt.Printf(\"failed to create Object Container: %s\\n\", err.Error())\n\t}\n\n\tvar network *pb.Network\n\tvar instance clusterapi.ClusterAPI\n\n\tlog.Printf(\"Creating infrastructure for cluster '%s'\", req.Name)\n\n\ttenant, err := utils.GetCurrentTenant()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Creates network\n\tlog.Printf(\"Creating Network 'net-%s'\", req.Name)\n\treq.Name = strings.ToLower(req.Name)\n\tnetwork, err = utils.CreateNetwork(\"net-\"+req.Name, req.CIDR)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to create Network '%s': %s\", req.Name, err.Error())\n\t\treturn nil, err\n\t}\n\n\tswitch req.Flavor {\n\tcase Flavor.DCOS:\n\t\treq.NetworkID = network.ID\n\t\treq.Tenant = tenant\n\t\tinstance, err = dcos.NewCluster(req)\n\t\tif err != nil {\n\t\t\t//utils.DeleteNetwork(network.ID)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tlog.Printf(\"Cluster '%s' created and initialized successfully\", req.Name)\n\treturn instance, nil\n}", "func CreateClusterServiceAccountCredentials(clientset kubernetes.Interface, duration metav1.Duration) (token []byte, caPEM []byte, err error) {\n\ttoken, caPEM, err = getOrCreateSA(clientset, duration)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"get or create SA: %w\", err)\n\t}\n\n\treturn token, caPEM, nil\n}", "func (client *ManagedClustersClient) getCreateRequest(ctx context.Context, resourceGroupName string, resourceName string, options *ManagedClustersClientGetOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{resourceName}\"\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\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 resourceName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceName}\", url.PathEscape(resourceName))\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\", \"2020-11-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func Create(c *golangsdk.ServiceClient, opts CreateOptsBuilder, cluster_id string) (r CreateResult) {\n\tb, err := opts.ToAddonCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\treqOpt := &golangsdk.RequestOpts{OkCodes: []int{201}}\n\t_, r.Err = c.Post(rootURL(c, cluster_id), b, &r.Body, reqOpt)\n\treturn\n}", "func (a *HyperflexApiService) CreateHyperflexClusterNetworkPolicy(ctx context.Context) ApiCreateHyperflexClusterNetworkPolicyRequest {\n\treturn ApiCreateHyperflexClusterNetworkPolicyRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func CreateZKCluster(t *testing.T, k8client client.Client, z *zkapi.ZookeeperCluster) (*zkapi.ZookeeperCluster, error) {\n\tlog.Printf(\"creating zookeeper cluster: %s\", z.Name)\n\terr := k8client.Create(goctx.TODO(), z)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create CR: %v\", err)\n\t}\n\n\tzookeeper := &zkapi.ZookeeperCluster{}\n\terr = k8client.Get(goctx.TODO(), types.NamespacedName{Namespace: z.Namespace, Name: z.Name}, zookeeper)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to obtain created CR: %v\", err)\n\t}\n\tlog.Printf(\"created zookeeper cluster: %s\", z.Name)\n\treturn zookeeper, nil\n}", "func newCluster() *cobra.Command {\n\tvar cluster *[]string\n\n\tcmd := &cobra.Command{\n\t\tUse: \"cluster\",\n\t\tShort: \"display cluster nodes.\",\n\t\tArgs: cobra.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tclient, err := getLeader(*cluster)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"can't connect to cluster leader\")\n\t\t\t}\n\t\t\tdefer client.Close()\n\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\t\t\tdefer cancel()\n\n\t\t\tvar leader *dqclient.NodeInfo\n\t\t\tvar nodes []dqclient.NodeInfo\n\t\t\tif leader, err = client.Leader(ctx); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"can't get leader\")\n\t\t\t}\n\n\t\t\tif nodes, err = client.Cluster(ctx); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"can't get cluster\")\n\t\t\t}\n\n\t\t\tfmt.Printf(\"ID \\tLeader \\tAddress\\n\")\n\t\t\tfor _, node := range nodes {\n\t\t\t\tfmt.Printf(\"%d \\t%v \\t%s\\n\", node.ID, node.ID == leader.ID, node.Address)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tflags := cmd.Flags()\n\tcluster = flags.StringSliceP(\"cluster\", \"c\", defaultCluster, \"addresses of existing cluster nodes\")\n\n\treturn cmd\n}", "func nodesToCreate(clusterName string, flags *CreateOptions) []nodeSpec {\n\tvar desiredNodes []nodeSpec\n\n\t// prepare nodes explicitly\n\tfor n := 0; n < flags.controlPlanes; n++ {\n\t\trole := constants.ControlPlaneNodeRoleValue\n\t\tdesiredNode := nodeSpec{\n\t\t\tName: fmt.Sprintf(\"%s-%s-%d\", clusterName, role, n+1),\n\t\t\tRole: role,\n\t\t}\n\t\tdesiredNodes = append(desiredNodes, desiredNode)\n\t}\n\tfor n := 0; n < flags.workers; n++ {\n\t\trole := constants.WorkerNodeRoleValue\n\t\tdesiredNode := nodeSpec{\n\t\t\tName: fmt.Sprintf(\"%s-%s-%d\", clusterName, role, n+1),\n\t\t\tRole: role,\n\t\t}\n\t\tdesiredNodes = append(desiredNodes, desiredNode)\n\t}\n\n\t// add an external load balancer if explicitly requested or if there are multiple control planes\n\tif flags.externalLoadBalancer || flags.controlPlanes > 1 {\n\t\trole := constants.ExternalLoadBalancerNodeRoleValue\n\t\tdesiredNodes = append(desiredNodes, nodeSpec{\n\t\t\tName: fmt.Sprintf(\"%s-lb\", clusterName),\n\t\t\tRole: role,\n\t\t})\n\t}\n\n\treturn desiredNodes\n}", "func campaignsCreateAccess(ctx context.Context) error {\n\t// On Sourcegraph.com nobody can create campaigns/patchsets/changesets\n\tif envvar.SourcegraphDotComMode() {\n\t\treturn ErrCampaignsDotCom\n\t}\n\n\t// Only site-admins can create campaigns/patchsets/changesets\n\treturn backend.CheckCurrentUserIsSiteAdmin(ctx)\n}", "func (o GetClustersClusterOutput) CreateTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetClustersCluster) string { return v.CreateTime }).(pulumi.StringOutput)\n}", "func (s *Server) CreateCluster(cluster *api.Cluster) (*api.Cluster, error) {\n\tinstance, err := s.doCreateCluster(convertAPIToRegions(cluster.Regions), convertAPIToStores(cluster.Stores))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn convertClusterToAPI(instance), nil\n}", "func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToClusterCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\tvar result *http.Response\n\tresult, r.Err = client.Post(createURL(client), b, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{201},\n\t})\n\n\tif r.Err == nil {\n\t\tr.Header = result.Header\n\t}\n\n\treturn\n}", "func GetPermission(username, projectName string) (string, error) {\n\to := orm.NewOrm()\n\n\tsql := \"select r.role_code from role as r \" +\n\t\t\"inner join project_role as pr on r.role_id = pr.role_id \" +\n\t\t\"inner join user_project_role as ur on pr.pr_id = ur.pr_id \" +\n\t\t\"inner join user as u on u.user_id = ur.user_id \" +\n\t\t\"inner join project p on p.project_id = pr.project_id \" +\n\t\t\"where u.username = ? and p.name = ? and u.deleted = 0 and p.deleted = 0\"\n\n\tvar r []models.Role\n\tn, err := o.Raw(sql, username, projectName).QueryRows(&r)\n\tif err != nil {\n\t\treturn \"\", err\n\t} else if n == 0 {\n\t\treturn \"\", nil\n\t} else {\n\t\treturn r[0].RoleCode, nil\n\t}\n}", "func (client *ClustersClient) listCreateRequest(ctx context.Context, options *ClustersListOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/providers/Microsoft.OperationalInsights/clusters\"\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.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-06-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (*UserGrantCreate) Descriptor() ([]byte, []int) {\n\treturn file_management_proto_rawDescGZIP(), []int{127}\n}" ]
[ "0.63714695", "0.6282406", "0.5705621", "0.56503934", "0.56013805", "0.5566028", "0.55602676", "0.5558598", "0.5530747", "0.552794", "0.54925996", "0.54693615", "0.5449176", "0.5403863", "0.5362785", "0.53541005", "0.53517973", "0.5348801", "0.53400254", "0.53187317", "0.5315454", "0.5313493", "0.5300269", "0.52858096", "0.5272991", "0.5250597", "0.5238797", "0.52189744", "0.5201176", "0.5194952", "0.5171213", "0.5153249", "0.51524645", "0.5148842", "0.51467013", "0.51466537", "0.5135542", "0.51346534", "0.51068795", "0.50982815", "0.50940883", "0.5086179", "0.5085136", "0.5078584", "0.50780123", "0.5076888", "0.50742966", "0.5071536", "0.50712585", "0.5068217", "0.50547284", "0.5045174", "0.5027595", "0.50259864", "0.50192034", "0.50138384", "0.49981478", "0.4996621", "0.4992862", "0.49865198", "0.498555", "0.49755397", "0.4964285", "0.49523738", "0.4948695", "0.49472418", "0.49413225", "0.49326965", "0.4931983", "0.49310887", "0.49276796", "0.4924763", "0.49155688", "0.49043256", "0.48929548", "0.48923427", "0.4890448", "0.48803714", "0.48797464", "0.485241", "0.48514715", "0.4848555", "0.4846601", "0.48462942", "0.4840876", "0.48397747", "0.48373935", "0.48325083", "0.48316422", "0.48114532", "0.48114112", "0.4811293", "0.4806254", "0.47943944", "0.4774247", "0.47730178", "0.4771608", "0.47666505", "0.47633767", "0.47566506" ]
0.8883577
0
CheckUseNodesPermForUser check user use nodes permission
func CheckUseNodesPermForUser(businessID string, user string, nodes []string) bool { bizID, err := strconv.Atoi(businessID) if err != nil { errMsg := fmt.Errorf("strconv BusinessID to int failed: %v", err) blog.Errorf(errMsg.Error()) return false } return canUseHosts(bizID, user, nodes) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Command) canAccess(r *http.Request, user *userState) accessResult {\n\tif c.AdminOnly && (c.UserOK || c.GuestOK || c.UntrustedOK) {\n\t\tlogger.Panicf(\"internal error: command cannot have AdminOnly together with any *OK flag\")\n\t}\n\n\tif user != nil && !c.AdminOnly {\n\t\t// Authenticated users do anything not requiring explicit admin.\n\t\treturn accessOK\n\t}\n\n\t// isUser means we have a UID for the request\n\tisUser := false\n\tpid, uid, socket, err := ucrednetGet(r.RemoteAddr)\n\tif err == nil {\n\t\tisUser = true\n\t} else if err != errNoID {\n\t\tlogger.Noticef(\"unexpected error when attempting to get UID: %s\", err)\n\t\treturn accessForbidden\n\t}\n\n\tisUntrusted := (socket == c.d.untrustedSocketPath)\n\n\t_ = pid\n\t_ = uid\n\n\tif isUntrusted {\n\t\tif c.UntrustedOK {\n\t\t\treturn accessOK\n\t\t}\n\t\treturn accessUnauthorized\n\t}\n\n\t// the !AdminOnly check is redundant, but belt-and-suspenders\n\tif r.Method == \"GET\" && !c.AdminOnly {\n\t\t// Guest and user access restricted to GET requests\n\t\tif c.GuestOK {\n\t\t\treturn accessOK\n\t\t}\n\n\t\tif isUser && c.UserOK {\n\t\t\treturn accessOK\n\t\t}\n\t}\n\n\t// Remaining admin checks rely on identifying peer uid\n\tif !isUser {\n\t\treturn accessUnauthorized\n\t}\n\n\tif uid == 0 || sys.UserID(uid) == sysGetuid() {\n\t\t// Superuser and process owner can do anything.\n\t\treturn accessOK\n\t}\n\n\tif c.AdminOnly {\n\t\treturn accessUnauthorized\n\t}\n\n\treturn accessUnauthorized\n}", "func checkPermission(c *gin.Context, enforcer *casbin.Enforcer, d *gorm.DB, user *db.User, roles []string) bool {\n\tr := c.Request\n\tmethod := r.Method\n\tpath := r.URL.Path\n\tusergroup := db.UserGroup{}\n\td.First(&usergroup, user.UserGroupID)\n\tfor _, role := range roles {\n\t\treturn enforcer.Enforce(usergroup.GroupName, role, path, method)\n\t}\n\treturn false\n}", "func checkViewPermission(us user.User, r *http.Request) bool {\n\n\tloggedIn, loggedInMat := loggedIn(r)\n\tif !loggedIn {\n\t\treturn false\n\t}\n\n\trequester, err := user.FromMatrikel(loggedInMat)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tif requester.Matrikel == us.Matrikel || courseconfig.GetConfig().Open_course || requester.IsAuthorized() {\n\t\treturn true\n\t}\n\n\tif us.IsAuthorized() {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func pvSupportsMultiNodeAccess(accessModes []corev1.PersistentVolumeAccessMode) bool {\n\tfor _, accessMode := range accessModes {\n\t\tswitch accessMode {\n\t\tcase corev1.ReadOnlyMany, corev1.ReadWriteMany:\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func validatePrivileges(ctx *sql.Context, a *Analyzer, n sql.Node, scope *plan.Scope, sel RuleSelector) (sql.Node, transform.TreeIdentity, error) {\n\tmysqlDb := a.Catalog.MySQLDb\n\n\tswitch n.(type) {\n\tcase *plan.CreateUser, *plan.DropUser, *plan.RenameUser, *plan.CreateRole, *plan.DropRole,\n\t\t*plan.Grant, *plan.GrantRole, *plan.GrantProxy, *plan.Revoke, *plan.RevokeRole, *plan.RevokeAll, *plan.RevokeProxy:\n\t\tmysqlDb.SetEnabled(true)\n\t}\n\tif !mysqlDb.Enabled() {\n\t\treturn n, transform.SameTree, nil\n\t}\n\n\tclient := ctx.Session.Client()\n\tuser := func() *mysql_db.User {\n\t\trd := mysqlDb.Reader()\n\t\tdefer rd.Close()\n\t\treturn mysqlDb.GetUser(rd, client.User, client.Address, false)\n\t}()\n\tif user == nil {\n\t\treturn nil, transform.SameTree, mysql.NewSQLError(mysql.ERAccessDeniedError, mysql.SSAccessDeniedError, \"Access denied for user '%v'\", ctx.Session.Client().User)\n\t}\n\n\t// TODO: this is incorrect, getTable returns only the first table, there could be others in the tree\n\tif plan.IsDualTable(getTable(n)) {\n\t\treturn n, transform.SameTree, nil\n\t}\n\tif rt := getResolvedTable(n); rt != nil && rt.SqlDatabase.Name() == sql.InformationSchemaDatabaseName {\n\t\treturn n, transform.SameTree, nil\n\t}\n\n\tif !n.CheckPrivileges(ctx, mysqlDb) {\n\t\treturn nil, transform.SameTree, sql.ErrPrivilegeCheckFailed.New(user.UserHostToString(\"'\"))\n\t}\n\treturn n, transform.SameTree, nil\n}", "func (r *Permitter) ViewerCanAdmin(\n\tctx context.Context,\n\tnode interface{},\n) (bool, error) {\n\tviewer, ok := myctx.UserFromContext(ctx)\n\tif !ok {\n\t\terr := &myctx.ErrNotFound{\"viewer\"}\n\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\treturn false, err\n\t}\n\tif viewer.Login.String == Guest {\n\t\treturn false, nil\n\t}\n\tvid := viewer.ID.String\n\tswitch node := node.(type) {\n\tcase data.Activity:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tactivity, err := r.repos.Activity().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &activity.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.Activity:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tactivity, err := r.repos.Activity().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &activity.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.ActivityAsset:\n\t\tactivityID := &node.ActivityID\n\t\tif activityID.Status == pgtype.Undefined {\n\t\t\tactivityAsset, err := r.repos.ActivityAsset().load.Get(ctx, node.AssetID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tactivityID = &activityAsset.ActivityID\n\t\t}\n\t\tactivity, err := r.repos.Activity().load.Get(ctx, activityID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\treturn vid == activity.UserID.String, nil\n\tcase *data.ActivityAsset:\n\t\tactivityID := &node.ActivityID\n\t\tif activityID.Status == pgtype.Undefined {\n\t\t\tactivityAsset, err := r.repos.ActivityAsset().load.Get(ctx, node.AssetID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tactivityID = &activityAsset.ActivityID\n\t\t}\n\t\tactivity, err := r.repos.Activity().load.Get(ctx, activityID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\treturn vid == activity.UserID.String, nil\n\tcase data.Appled:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tappled, err := r.repos.Appled().load.Get(ctx, node.ID.Int)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &appled.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.Appled:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tappled, err := r.repos.Appled().load.Get(ctx, node.ID.Int)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &appled.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.Comment:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tcomment, err := r.repos.Comment().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &comment.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.Comment:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tcomment, err := r.repos.Comment().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &comment.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.CommentDraftBackup:\n\t\tcomment, err := r.repos.Comment().load.Get(ctx, node.CommentID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\tuserID := &comment.UserID\n\t\treturn vid == userID.String, nil\n\tcase *data.CommentDraftBackup:\n\t\tcomment, err := r.repos.Comment().load.Get(ctx, node.CommentID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\tuserID := &comment.UserID\n\t\treturn vid == userID.String, nil\n\tcase data.Course:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tcourse, err := r.repos.Course().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &course.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.Course:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tcourse, err := r.repos.Course().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &course.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.CourseLesson:\n\t\tcourseID := &node.CourseID\n\t\tif courseID.Status == pgtype.Undefined {\n\t\t\tcourseLesson, err := r.repos.CourseLesson().load.Get(ctx, node.LessonID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tcourseID = &courseLesson.CourseID\n\t\t}\n\t\tcourse, err := r.repos.Course().load.Get(ctx, courseID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\treturn vid == course.UserID.String, nil\n\tcase *data.CourseLesson:\n\t\tcourseID := &node.CourseID\n\t\tif courseID.Status == pgtype.Undefined {\n\t\t\tcourseLesson, err := r.repos.CourseLesson().load.Get(ctx, node.LessonID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tcourseID = &courseLesson.CourseID\n\t\t}\n\t\tcourse, err := r.repos.Course().load.Get(ctx, courseID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\treturn vid == course.UserID.String, nil\n\tcase data.Email:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\temail, err := r.repos.Email().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &email.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.Email:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\temail, err := r.repos.Email().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &email.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.Enrolled:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tenrolled, err := r.repos.Enrolled().load.Get(ctx, node.ID.Int)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &enrolled.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.Enrolled:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tenrolled, err := r.repos.Enrolled().load.Get(ctx, node.ID.Int)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &enrolled.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.EVT:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tevt, err := r.repos.EVT().load.Get(ctx, node.EmailID.String, node.Token.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &evt.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.EVT:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tevt, err := r.repos.EVT().load.Get(ctx, node.EmailID.String, node.Token.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &evt.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.Label:\n\t\tlabel, err := r.repos.Label().load.Get(ctx, node.ID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\tstudy, err := r.repos.Study().load.Get(ctx, label.StudyID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\treturn vid == study.UserID.String, nil\n\tcase *data.Label:\n\t\tlabel, err := r.repos.Label().load.Get(ctx, node.ID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\tstudy, err := r.repos.Study().load.Get(ctx, label.StudyID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\treturn vid == study.UserID.String, nil\n\tcase data.Labeled:\n\t\tuserID := mytype.OID{}\n\t\tswitch node.LabelableID.Type {\n\t\tcase \"Comment\":\n\t\t\tcomment, err := r.repos.Comment().load.Get(ctx, node.LabelableID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = comment.UserID\n\t\tcase \"Lesson\":\n\t\t\tlesson, err := r.repos.Lesson().load.Get(ctx, node.LabelableID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = lesson.UserID\n\t\tcase \"UserAsset\":\n\t\t\tlesson, err := r.repos.UserAsset().load.Get(ctx, node.LabelableID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = lesson.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.Labeled:\n\t\tuserID := mytype.OID{}\n\t\tswitch node.LabelableID.Type {\n\t\tcase \"Comment\":\n\t\t\tcomment, err := r.repos.Comment().load.Get(ctx, node.LabelableID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = comment.UserID\n\t\tcase \"Lesson\":\n\t\t\tlesson, err := r.repos.Lesson().load.Get(ctx, node.LabelableID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = lesson.UserID\n\t\tcase \"UserAsset\":\n\t\t\tlesson, err := r.repos.UserAsset().load.Get(ctx, node.LabelableID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = lesson.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.Lesson:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tlesson, err := r.repos.Lesson().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &lesson.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.Lesson:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tlesson, err := r.repos.Lesson().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &lesson.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.LessonDraftBackup:\n\t\tlesson, err := r.repos.Lesson().load.Get(ctx, node.LessonID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\tuserID := &lesson.UserID\n\t\treturn vid == userID.String, nil\n\tcase *data.LessonDraftBackup:\n\t\tlesson, err := r.repos.Lesson().load.Get(ctx, node.LessonID.String)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn false, err\n\t\t}\n\t\tuserID := &lesson.UserID\n\t\treturn vid == userID.String, nil\n\tcase data.Notification:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tnotification, err := r.repos.Notification().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &notification.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.Notification:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tnotification, err := r.repos.Notification().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &notification.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.PRT:\n\t\treturn vid == node.UserID.String, nil\n\tcase *data.PRT:\n\t\treturn vid == node.UserID.String, nil\n\tcase data.Study:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tstudy, err := r.repos.Study().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &study.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.Study:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tstudy, err := r.repos.Study().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &study.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.Topiced:\n\t\tuserID := mytype.OID{}\n\t\tswitch node.TopicableID.Type {\n\t\tcase \"Course\":\n\t\t\tcourse, err := r.repos.Course().load.Get(ctx, node.TopicableID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = course.UserID\n\t\tcase \"Study\":\n\t\t\tstudy, err := r.repos.Study().load.Get(ctx, node.TopicableID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = study.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.Topiced:\n\t\tuserID := mytype.OID{}\n\t\tswitch node.TopicableID.Type {\n\t\tcase \"Course\":\n\t\t\tcourse, err := r.repos.Course().load.Get(ctx, node.TopicableID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = course.UserID\n\t\tcase \"Study\":\n\t\t\tstudy, err := r.repos.Study().load.Get(ctx, node.TopicableID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = study.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase data.User:\n\t\treturn vid == node.ID.String, nil\n\tcase *data.User:\n\t\treturn vid == node.ID.String, nil\n\tcase data.UserAsset:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tuserAsset, err := r.repos.UserAsset().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &userAsset.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tcase *data.UserAsset:\n\t\tuserID := &node.UserID\n\t\tif node.UserID.Status == pgtype.Undefined {\n\t\t\tuserAsset, err := r.repos.UserAsset().load.Get(ctx, node.ID.String)\n\t\t\tif err != nil {\n\t\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tuserID = &userAsset.UserID\n\t\t}\n\t\treturn vid == userID.String, nil\n\tdefault:\n\t\treturn false, nil\n\t}\n\treturn false, nil\n}", "func (p *Provider) checkUser(userId bson.ObjectId, users []models.MachineUser) error {\n\t// check if the incoming user is in the list of permitted user list\n\tfor _, u := range users {\n\t\tif userId == u.Id && (u.Owner || (u.Permanent && u.Approved)) {\n\t\t\treturn nil // ok he/she is good to go!\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"permission denied. user not in the list of permitted users\")\n}", "func changeAccessNodes(ctx isc.Sandbox) dict.Dict {\n\tctx.RequireCallerIsChainOwner()\n\n\tstate := ctx.State()\n\taccessNodeCandidates := governance.AccessNodeCandidatesMap(state)\n\taccessNodes := governance.AccessNodesMap(state)\n\tparamNodeActions := collections.NewMapReadOnly(ctx.Params(), governance.ParamChangeAccessNodesActions)\n\tctx.Log().Debugf(\"changeAccessNodes: actions len: %d\", paramNodeActions.Len())\n\n\tparamNodeActions.Iterate(func(pubKey, actionBin []byte) bool {\n\t\tif len(actionBin) != 1 {\n\t\t\tpanic(errInvalidAction)\n\t\t}\n\t\tswitch governance.ChangeAccessNodeAction(actionBin[0]) {\n\t\tcase governance.ChangeAccessNodeActionRemove:\n\t\t\taccessNodes.DelAt(pubKey)\n\t\tcase governance.ChangeAccessNodeActionAccept:\n\t\t\t// TODO should the list of candidates be checked? we are just adding any pubkey\n\t\t\taccessNodes.SetAt(pubKey, codec.EncodeBool(true))\n\t\t\t// TODO should the node be removed from the list of candidates? // accessNodeCandidates.DelAt(pubKey)\n\t\tcase governance.ChangeAccessNodeActionDrop:\n\t\t\taccessNodes.DelAt(pubKey)\n\t\t\taccessNodeCandidates.DelAt(pubKey)\n\t\tdefault:\n\t\t\tpanic(errInvalidAction)\n\t\t}\n\t\treturn true\n\t})\n\treturn nil\n}", "func isAllowedUser(request admissionctl.Request) bool {\n\tif utils.SliceContains(request.UserInfo.Username, allowedUsers) {\n\t\treturn true\n\t}\n\n\tfor _, group := range sreAdminGroups {\n\t\tif utils.SliceContains(group, request.UserInfo.Groups) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func isAdmin(user string) bool {\n\treturn user == ROOT1 || user == ROOT2\n}", "func checkAdmin() bool {\n\treturn os.Getenv(\"USER\") == \"root\"\n}", "func (n *Node) ReadUserPermissions(ctx context.Context, u *userpb.User) (ap provider.ResourcePermissions, accessDenied bool, err error) {\n\t// check if the current user is the owner\n\tif utils.UserEqual(u.Id, n.Owner()) {\n\t\tappctx.GetLogger(ctx).Debug().Str(\"node\", n.ID).Msg(\"user is owner, returning owner permissions\")\n\t\treturn OwnerPermissions(), false, nil\n\t}\n\n\tap = provider.ResourcePermissions{}\n\n\t// for an efficient group lookup convert the list of groups to a map\n\t// groups are just strings ... groupnames ... or group ids ??? AAARGH !!!\n\tgroupsMap := make(map[string]bool, len(u.Groups))\n\tfor i := range u.Groups {\n\t\tgroupsMap[u.Groups[i]] = true\n\t}\n\n\tvar g *provider.Grant\n\n\t// we read all grantees from the node\n\tvar grantees []string\n\tif grantees, err = n.ListGrantees(ctx); err != nil {\n\t\tappctx.GetLogger(ctx).Error().Err(err).Interface(\"node\", n).Msg(\"error listing grantees\")\n\t\treturn NoPermissions(), true, err\n\t}\n\n\t// instead of making n getxattr syscalls we are going to list the acls and filter them here\n\t// we have two options here:\n\t// 1. we can start iterating over the acls / grants on the node or\n\t// 2. we can iterate over the number of groups\n\t// The current implementation tries to be defensive for cases where users have hundreds or thousands of groups, so we iterate over the existing acls.\n\tuserace := prefixes.GrantUserAcePrefix + u.Id.OpaqueId\n\tuserFound := false\n\tfor i := range grantees {\n\t\tswitch {\n\t\t// we only need to find the user once\n\t\tcase !userFound && grantees[i] == userace:\n\t\t\tg, err = n.ReadGrant(ctx, grantees[i])\n\t\tcase strings.HasPrefix(grantees[i], prefixes.GrantGroupAcePrefix): // only check group grantees\n\t\t\tgr := strings.TrimPrefix(grantees[i], prefixes.GrantGroupAcePrefix)\n\t\t\tif groupsMap[gr] {\n\t\t\t\tg, err = n.ReadGrant(ctx, grantees[i])\n\t\t\t} else {\n\t\t\t\t// no need to check attribute\n\t\t\t\tcontinue\n\t\t\t}\n\t\tdefault:\n\t\t\t// no need to check attribute\n\t\t\tcontinue\n\t\t}\n\n\t\tif isGrantExpired(g) {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch {\n\t\tcase err == nil:\n\t\t\t// If all permissions are set to false we have a deny grant\n\t\t\tif grants.PermissionsEqual(g.Permissions, &provider.ResourcePermissions{}) {\n\t\t\t\treturn NoPermissions(), true, nil\n\t\t\t}\n\t\t\tAddPermissions(&ap, g.GetPermissions())\n\t\tcase metadata.IsAttrUnset(err):\n\t\t\tappctx.GetLogger(ctx).Error().Interface(\"node\", n).Str(\"grant\", grantees[i]).Interface(\"grantees\", grantees).Msg(\"grant vanished from node after listing\")\n\t\t\t// continue with next segment\n\t\tdefault:\n\t\t\tappctx.GetLogger(ctx).Error().Err(err).Interface(\"node\", n).Str(\"grant\", grantees[i]).Msg(\"error reading permissions\")\n\t\t\t// continue with next segment\n\t\t}\n\t}\n\n\tappctx.GetLogger(ctx).Debug().Interface(\"permissions\", ap).Interface(\"node\", n).Interface(\"user\", u).Msg(\"returning aggregated permissions\")\n\treturn ap, false, nil\n}", "func (ctx *TestContext) UserIsAManagerOfTheGroupAndCanWatchItsMembers(user, group string) error {\n\treturn ctx.UserIsAManagerOfTheGroupWith(getParameterString(map[string]string{\n\t\t\"id\": group,\n\t\t\"user_id\": user,\n\t\t\"name\": group,\n\t\t\"can_watch_members\": strTrue,\n\t}))\n}", "func (n *Node) PermissionSet(ctx context.Context) (provider.ResourcePermissions, bool) {\n\tu, ok := ctxpkg.ContextGetUser(ctx)\n\tif !ok {\n\t\tappctx.GetLogger(ctx).Debug().Interface(\"node\", n).Msg(\"no user in context, returning default permissions\")\n\t\treturn NoPermissions(), false\n\t}\n\tif utils.UserEqual(u.Id, n.SpaceRoot.Owner()) {\n\t\treturn OwnerPermissions(), false\n\t}\n\t// read the permissions for the current user from the acls of the current node\n\tif np, accessDenied, err := n.ReadUserPermissions(ctx, u); err == nil {\n\t\treturn np, accessDenied\n\t}\n\t// be defensive, we could have access via another grant\n\treturn NoPermissions(), true\n}", "func (c ClusterNodes) checkStatusOfClusterNodes() {\n\n}", "func (u *User) GetNodes(queryParams ...string) (map[string]interface{}, error) {\n\tlog.info(\"========== GET USER NODES ==========\")\n\turl := buildURL(path[\"users\"], u.UserID, path[\"nodes\"])\n\n\treturn u.do(\"GET\", url, \"\", queryParams)\n}", "func (f *aclFilter) allowNode(node string) bool {\n\tif !f.enforceVersion8 {\n\t\treturn true\n\t}\n\treturn f.authorizer.NodeRead(node)\n}", "func (ca *ComponentAction) CheckUserPermission(ctx context.Context) (bool, error) {\n\tsdk := cputil.SDK(ctx)\n\tisGuest := false\n\tprojectID := cputil.GetInParamByKey(ctx, \"projectId\").(string)\n\tscopeRole, err := bdl.Bdl.ScopeRoleAccess(sdk.Identity.UserID, &apistructs.ScopeRoleAccessRequest{\n\t\tScope: apistructs.Scope{\n\t\t\tType: apistructs.ProjectScope,\n\t\t\tID: projectID,\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tfor _, role := range scopeRole.Roles {\n\t\tif role == \"Guest\" {\n\t\t\tisGuest = true\n\t\t}\n\t}\n\treturn isGuest, nil\n}", "func (n *Node) ReadUserPermissions(ctx context.Context, u *userpb.User) (ap provider.ResourcePermissions, err error) {\n\t// check if the current user is the owner\n\to, err := n.Owner()\n\tif err != nil {\n\t\t// TODO check if a parent folder has the owner set?\n\t\tappctx.GetLogger(ctx).Error().Err(err).Interface(\"node\", n).Msg(\"could not determine owner, returning default permissions\")\n\t\treturn NoPermissions(), err\n\t}\n\tif o.OpaqueId == \"\" {\n\t\t// this happens for root nodes in the storage. the extended attributes are set to emptystring to indicate: no owner\n\t\t// TODO what if no owner is set but grants are present?\n\t\treturn NoOwnerPermissions(), nil\n\t}\n\tif utils.UserEqual(u.Id, o) {\n\t\tappctx.GetLogger(ctx).Debug().Interface(\"node\", n).Msg(\"user is owner, returning owner permissions\")\n\t\treturn OwnerPermissions(), nil\n\t}\n\n\tap = provider.ResourcePermissions{}\n\n\t// for an efficient group lookup convert the list of groups to a map\n\t// groups are just strings ... groupnames ... or group ids ??? AAARGH !!!\n\tgroupsMap := make(map[string]bool, len(u.Groups))\n\tfor i := range u.Groups {\n\t\tgroupsMap[u.Groups[i]] = true\n\t}\n\n\tvar g *provider.Grant\n\n\t// we read all grantees from the node\n\tvar grantees []string\n\tif grantees, err = n.ListGrantees(ctx); err != nil {\n\t\tappctx.GetLogger(ctx).Error().Err(err).Interface(\"node\", n).Msg(\"error listing grantees\")\n\t\treturn NoPermissions(), err\n\t}\n\n\t// instead of making n getxattr syscalls we are going to list the acls and filter them here\n\t// we have two options here:\n\t// 1. we can start iterating over the acls / grants on the node or\n\t// 2. we can iterate over the number of groups\n\t// The current implementation tries to be defensive for cases where users have hundreds or thousands of groups, so we iterate over the existing acls.\n\tuserace := xattrs.GrantPrefix + xattrs.UserAcePrefix + u.Id.OpaqueId\n\tuserFound := false\n\tfor i := range grantees {\n\t\tswitch {\n\t\t// we only need to find the user once\n\t\tcase !userFound && grantees[i] == userace:\n\t\t\tg, err = n.ReadGrant(ctx, grantees[i])\n\t\tcase strings.HasPrefix(grantees[i], xattrs.GrantPrefix+xattrs.GroupAcePrefix): // only check group grantees\n\t\t\tgr := strings.TrimPrefix(grantees[i], xattrs.GrantPrefix+xattrs.GroupAcePrefix)\n\t\t\tif groupsMap[gr] {\n\t\t\t\tg, err = n.ReadGrant(ctx, grantees[i])\n\t\t\t} else {\n\t\t\t\t// no need to check attribute\n\t\t\t\tcontinue\n\t\t\t}\n\t\tdefault:\n\t\t\t// no need to check attribute\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch {\n\t\tcase err == nil:\n\t\t\tAddPermissions(&ap, g.GetPermissions())\n\t\tcase isAttrUnset(err):\n\t\t\terr = nil\n\t\t\tappctx.GetLogger(ctx).Error().Interface(\"node\", n).Str(\"grant\", grantees[i]).Interface(\"grantees\", grantees).Msg(\"grant vanished from node after listing\")\n\t\t\t// continue with next segment\n\t\tdefault:\n\t\t\tappctx.GetLogger(ctx).Error().Err(err).Interface(\"node\", n).Str(\"grant\", grantees[i]).Msg(\"error reading permissions\")\n\t\t\t// continue with next segment\n\t\t}\n\t}\n\n\tappctx.GetLogger(ctx).Debug().Interface(\"permissions\", ap).Interface(\"node\", n).Interface(\"user\", u).Msg(\"returning aggregated permissions\")\n\treturn ap, nil\n}", "func CheckUserDataPerm(pkg string, source, target *core.User, name, value string) (int, os.Error) {\n\tf := func(h interface{}) (int, os.Error) {\n\t\tf, ok := h.(func(string, *core.User, *core.User, string, string) (int, os.Error))\n\t\tif ok && f != nil {\n\t\t\treturn f(pkg, source, target, name, value)\n\t\t}\n\t\treturn 0, nil\n\t}\n\n\tvar prefix = name\n\tvar len int\n\tfor {\n\t\tif v := checkUserData[prefix]; v != nil {\n\t\t\tlen++\n\t\t}\n\n\t\tif v := strings.LastIndex(prefix, \" \"); v != -1 {\n\t\t\tprefix = prefix[:v]\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tlists := make([][]interface{}, 0, len)\n\n\tprefix = name\n\tfor {\n\t\tif v := checkUserData[prefix]; v != nil {\n\t\t\tlists = append(lists, v)\n\t\t}\n\n\t\tif v := strings.LastIndex(prefix, \" \"); v != -1 {\n\t\t\tprefix = prefix[:v]\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn runPermHooksSlice(lists, f, false)\n}", "func AllowBoostrapTokensToGetNodes(client clientset.Interface) error {\n\tfmt.Println(\"[bootstrap-token] Configured RBAC rules to allow Node Bootstrap tokens to get nodes\")\n\n\tif err := apiclient.CreateOrUpdateClusterRole(client, &rbac.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: constants.GetNodesClusterRoleName,\n\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t},\n\t\tRules: []rbac.PolicyRule{\n\t\t\t{\n\t\t\t\tVerbs: []string{\"get\"},\n\t\t\t\tAPIGroups: []string{\"\"},\n\t\t\t\tResources: []string{\"nodes\"},\n\t\t\t},\n\t\t},\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\treturn apiclient.CreateOrUpdateClusterRoleBinding(client, &rbac.ClusterRoleBinding{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: constants.GetNodesClusterRoleName,\n\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t},\n\t\tRoleRef: rbac.RoleRef{\n\t\t\tAPIGroup: rbac.GroupName,\n\t\t\tKind: \"ClusterRole\",\n\t\t\tName: constants.GetNodesClusterRoleName,\n\t\t},\n\t\tSubjects: []rbac.Subject{\n\t\t\t{\n\t\t\t\tKind: rbac.GroupKind,\n\t\t\t\tName: constants.NodeBootstrapTokenAuthGroup,\n\t\t\t},\n\t\t},\n\t})\n}", "func isNodeUnderutilizedCandidate(node nodeInfo) bool {\n\treturn node.config.Enabled &&\n\t\tnode.stats.utilizedCPURatio < node.config.ScaleDownCPURequestRatioLimit &&\n\t\t!node.state.ScaleDownInProgress &&\n\t\t*node.node.Metadata.CreationTimestamp.Seconds < time.Now().Unix()-*minimumNodeAgeSeconds\n}", "func isNodeCapable(pod *v1.Pod, node v1.Node) (bool, []string, error) {\n\tfits := true\n\tfailReasons := []string{}\n\tfor _, predicateKey := range predicatesEvalOrderStore {\n\t\tfit, failures, err := predicatesFuncMap[predicateKey](pod, node)\n\t\tif err != nil {\n\t\t\treturn false, nil, err\n\t\t}\n\t\tfits = fits && fit\n\t\tfailReasons = append(failReasons, failures...)\n\t}\n\treturn fits, failReasons, nil\n}", "func (c *kubernetesClient) GetPreemptibleNodes(ctx context.Context, filters map[string]string) (nodes *v1.NodeList, err error) {\n\n\tlabelSelector := labels.Set{\n\t\t\"cloud.google.com/gke-preemptible\": \"true\",\n\t}\n\n\tfor key, value := range filters {\n\t\tlabelSelector[key] = value\n\t}\n\n\tnodes, err = c.kubeClientset.CoreV1().Nodes().List(ctx, metav1.ListOptions{\n\t\tLabelSelector: labelSelector.String(),\n\t})\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (s *Server) requestAuthorized(c echo.Context, perm, tgtOwner string) error {\n\tclaims := getClaims(c)\n\treqOwner := claims[\"user\"].(string)\n\n\tpset := make(map[string]struct{})\n\tfor _, p := range claims[\"permissions\"].([]interface{}) {\n\t\tpset[strings.ToLower(p.(string))] = struct{}{}\n\t}\n\n\tnet := c.Param(\"id\")\n\n\t// Make checks for the individual nodes of the permissions\n\t// checks below. This still winds up being O(N) and is much\n\t// easier to read than a clever loop.\n\t_, netAny := pset[net+\":*\"]\n\t_, netExact := pset[net+\":\"+perm]\n\t_, netSudo := pset[net+\":sudo\"]\n\t_, anyAny := pset[\"*:*\"]\n\t_, anyExact := pset[\"*:\"+perm]\n\t_, anySudo := pset[\"*:sudo\"]\n\n\thasPerm := netAny || netExact || anyAny || anyExact\n\thasSudo := netAny || anyAny || netSudo || anySudo\n\n\t// Now we can perform the permissions check. If the user has\n\t// any permission on any network, or any on the specific one\n\t// that satisfies the check right away. Failing that we check\n\t// that they have the permission and optionally if they\n\t// require sudo.\n\tif hasPerm && (reqOwner == tgtOwner || hasSudo) {\n\t\treturn nil\n\t}\n\n\t// Anything but the above and the request isn't authorized.\n\treturn errors.New(\"requestor unqualified\")\n}", "func (n *NodeManager) CheckByUUIDEnvID(uuid string, envID int) bool {\n\tvar results int64\n\tn.DB.Model(&OsqueryNode{}).Where(\"uuid = ? AND environment_id = ?\", strings.ToUpper(uuid), envID).Count(&results)\n\treturn (results > 0)\n}", "func (r *Permitter) ViewerCanRead(\n\tctx context.Context,\n\tnode interface{},\n) (bool, error) {\n\tswitch node := node.(type) {\n\tcase data.Comment:\n\t\t// If the comment has not been published, then check if the viewer can admin\n\t\t// the object\n\t\tif node.PublishedAt.Status == pgtype.Undefined || node.PublishedAt.Status == pgtype.Null {\n\t\t\treturn r.ViewerCanAdmin(ctx, node)\n\t\t}\n\tcase *data.Comment:\n\t\t// If the comment has not been published, then check if the viewer can admin\n\t\t// the object\n\t\tif node.PublishedAt.Status == pgtype.Undefined || node.PublishedAt.Status == pgtype.Null {\n\t\t\treturn r.ViewerCanAdmin(ctx, node)\n\t\t}\n\tcase data.CommentDraftBackup:\n\t\treturn r.ViewerCanAdmin(ctx, node)\n\tcase *data.CommentDraftBackup:\n\t\treturn r.ViewerCanAdmin(ctx, node)\n\tcase data.Course:\n\t\t// If the course has not been published, then check if the viewer can admin\n\t\t// the object\n\t\tif node.PublishedAt.Status == pgtype.Undefined || node.PublishedAt.Status == pgtype.Null {\n\t\t\treturn r.ViewerCanAdmin(ctx, node)\n\t\t}\n\tcase *data.Course:\n\t\t// If the course has not been published, then check if the viewer can admin\n\t\t// the object\n\t\tif node.PublishedAt.Status == pgtype.Undefined || node.PublishedAt.Status == pgtype.Null {\n\t\t\treturn r.ViewerCanAdmin(ctx, node)\n\t\t}\n\tcase data.Email:\n\t\t// If the email is not public, then check if the viewer can admin\n\t\tif node.Public.Status == pgtype.Undefined ||\n\t\t\tnode.Public.Status == pgtype.Null ||\n\t\t\t!node.Public.Bool {\n\t\t\treturn r.ViewerCanAdmin(ctx, node)\n\t\t}\n\tcase *data.Email:\n\t\t// If the email is not public, then check if the viewer can admin\n\t\tif node.Public.Status == pgtype.Undefined ||\n\t\t\tnode.Public.Status == pgtype.Null ||\n\t\t\t!node.Public.Bool {\n\t\t\treturn r.ViewerCanAdmin(ctx, node)\n\t\t}\n\tcase data.Lesson:\n\t\t// If the lesson has not been published, then check if the viewer can admin\n\t\t// the object\n\t\tif node.PublishedAt.Status == pgtype.Undefined || node.PublishedAt.Status == pgtype.Null {\n\t\t\treturn r.ViewerCanAdmin(ctx, node)\n\t\t}\n\tcase *data.Lesson:\n\t\t// If the lesson has not been published, then check if the viewer can admin\n\t\t// the object\n\t\tif node.PublishedAt.Status == pgtype.Undefined || node.PublishedAt.Status == pgtype.Null {\n\t\t\treturn r.ViewerCanAdmin(ctx, node)\n\t\t}\n\tcase data.LessonDraftBackup:\n\t\treturn r.ViewerCanAdmin(ctx, node)\n\tcase *data.LessonDraftBackup:\n\t\treturn r.ViewerCanAdmin(ctx, node)\n\tdefault:\n\t\treturn true, nil\n\t}\n\treturn true, nil\n}", "func (m *MgoUserManager) Can(user *auth.User, do string) bool {\n\tfor _, pri := range user.Privilege {\n\t\tif do == pri {\n\t\t\treturn true\n\t\t}\n\t}\n\n\taid := make([]interface{}, 0, len(user.BriefGroups))\n\tfor _, v := range user.BriefGroups {\n\t\taid = append(aid, v.Id)\n\t}\n\n\tgroups, err := m.GroupMngr.FindSomeGroup(aid...)\n\tif err != nil {\n\t\tlog.Println(\"mgoauth: cannot find user group to determine privilege - \", err)\n\t\treturn false\n\t}\n\n\tfor _, v := range groups {\n\t\tfor _, pri := range v.Privilege {\n\t\t\tif do == pri {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}", "func (n *ClusterPolicyController) labelGPUNodes() (bool, int, error) {\n\tctx := n.ctx\n\t// fetch all nodes\n\topts := []client.ListOption{}\n\tlist := &corev1.NodeList{}\n\terr := n.rec.Client.List(ctx, list, opts...)\n\tif err != nil {\n\t\treturn false, 0, fmt.Errorf(\"Unable to list nodes to check labels, err %s\", err.Error())\n\t}\n\n\tclusterHasNFDLabels := false\n\tupdateLabels := false\n\tgpuNodesTotal := 0\n\tfor _, node := range list.Items {\n\t\tnode := node\n\t\t// get node labels\n\t\tlabels := node.GetLabels()\n\t\tif !clusterHasNFDLabels {\n\t\t\tclusterHasNFDLabels = hasNFDLabels(labels)\n\t\t}\n\t\tconfig, err := getWorkloadConfig(labels, n.sandboxEnabled)\n\t\tif err != nil {\n\t\t\tn.rec.Log.Info(\"WARNING: failed to get GPU workload config for node; using default\",\n\t\t\t\t\"NodeName\", node.ObjectMeta.Name, \"SandboxEnabled\", n.sandboxEnabled,\n\t\t\t\t\"Error\", err, \"defaultGPUWorkloadConfig\", defaultGPUWorkloadConfig)\n\t\t}\n\t\tn.rec.Log.Info(\"GPU workload configuration\", \"NodeName\", node.ObjectMeta.Name, \"GpuWorkloadConfig\", config)\n\t\tgpuWorkloadConfig := &gpuWorkloadConfiguration{config, node.ObjectMeta.Name, n.rec.Log}\n\t\tif !hasCommonGPULabel(labels) && hasGPULabels(labels) {\n\t\t\tn.rec.Log.Info(\"Node has GPU(s)\", \"NodeName\", node.ObjectMeta.Name)\n\t\t\t// label the node with common Nvidia GPU label\n\t\t\tn.rec.Log.Info(\"Setting node label\", \"NodeName\", node.ObjectMeta.Name, \"Label\", commonGPULabelKey, \"Value\", commonGPULabelValue)\n\t\t\tlabels[commonGPULabelKey] = commonGPULabelValue\n\t\t\t// update node labels\n\t\t\tnode.SetLabels(labels)\n\t\t\tupdateLabels = true\n\t\t} else if hasCommonGPULabel(labels) && !hasGPULabels(labels) {\n\t\t\t// previously labelled node and no longer has GPU's\n\t\t\t// label node to reset common Nvidia GPU label\n\t\t\tn.rec.Log.Info(\"Node no longer has GPUs\", \"NodeName\", node.ObjectMeta.Name)\n\t\t\tn.rec.Log.Info(\"Setting node label\", \"Label\", commonGPULabelKey, \"Value\", \"false\")\n\t\t\tlabels[commonGPULabelKey] = \"false\"\n\t\t\tn.rec.Log.Info(\"Disabling all operands for node\", \"NodeName\", node.ObjectMeta.Name)\n\t\t\tremoveAllGPUStateLabels(labels)\n\t\t\t// update node labels\n\t\t\tnode.SetLabels(labels)\n\t\t\tupdateLabels = true\n\t\t}\n\n\t\tif hasCommonGPULabel(labels) {\n\t\t\t// If node has GPU, then add state labels as per the workload type\n\t\t\tn.rec.Log.Info(\"Checking GPU state labels on the node\", \"NodeName\", node.ObjectMeta.Name)\n\t\t\tif gpuWorkloadConfig.updateGPUStateLabels(labels) {\n\t\t\t\tn.rec.Log.Info(\"Applying correct GPU state labels to the node\", \"NodeName\", node.ObjectMeta.Name)\n\t\t\t\tnode.SetLabels(labels)\n\t\t\t\tupdateLabels = true\n\t\t\t}\n\t\t\t// Disable MIG on the node explicitly where no MIG config is specified\n\t\t\tif n.singleton.Spec.MIGManager.IsEnabled() && hasMIGCapableGPU(labels) && !hasMIGConfigLabel(labels) {\n\t\t\t\tif n.singleton.Spec.MIGManager.Config != nil && n.singleton.Spec.MIGManager.Config.Default == migConfigDisabledValue {\n\t\t\t\t\tn.rec.Log.Info(\"Setting MIG config label\", \"NodeName\", node.ObjectMeta.Name, \"Label\", migConfigLabelKey, \"Value\", migConfigDisabledValue)\n\t\t\t\t\tlabels[migConfigLabelKey] = migConfigDisabledValue\n\t\t\t\t\tnode.SetLabels(labels)\n\t\t\t\t\tupdateLabels = true\n\t\t\t\t}\n\t\t\t}\n\t\t\t// increment GPU node count\n\t\t\tgpuNodesTotal++\n\n\t\t\t// add GPU node CoreOS version for OCP\n\t\t\tif n.ocpDriverToolkit.requested {\n\t\t\t\trhcosVersion, ok := labels[nfdOSTreeVersionLabelKey]\n\t\t\t\tif ok {\n\t\t\t\t\tn.ocpDriverToolkit.rhcosVersions[rhcosVersion] = true\n\t\t\t\t\tn.rec.Log.V(1).Info(\"GPU node running RHCOS\",\n\t\t\t\t\t\t\"nodeName\", node.ObjectMeta.Name,\n\t\t\t\t\t\t\"RHCOS version\", rhcosVersion,\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\tn.rec.Log.Info(\"node doesn't have the proper NFD RHCOS version label.\",\n\t\t\t\t\t\t\"nodeName\", node.ObjectMeta.Name,\n\t\t\t\t\t\t\"nfdLabel\", nfdOSTreeVersionLabelKey,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// update node with the latest labels\n\t\tif updateLabels {\n\t\t\terr = n.rec.Client.Update(ctx, &node)\n\t\t\tif err != nil {\n\t\t\t\treturn false, 0, fmt.Errorf(\"Unable to label node %s for the GPU Operator deployment, err %s\",\n\t\t\t\t\tnode.ObjectMeta.Name, err.Error())\n\t\t\t}\n\t\t}\n\t} // end node loop\n\n\tn.rec.Log.Info(\"Number of nodes with GPU label\", \"NodeCount\", gpuNodesTotal)\n\tn.operatorMetrics.gpuNodesTotal.Set(float64(gpuNodesTotal))\n\treturn clusterHasNFDLabels, gpuNodesTotal, nil\n}", "func GetClusterCreatePerm(user UserInfo) map[string]bool {\n\tpermissions := make(map[string]bool)\n\n\t// attention: v0 permission only support project\n\tpermissions[\"test\"] = true\n\tpermissions[\"prod\"] = true\n\tpermissions[\"create\"] = true\n\n\treturn permissions\n}", "func IsPermission(err error) bool", "func (ipuc IsPrivilegedUserCheck) Check() (warnings, errorList []error) {\n\terrorList = []error{}\n\n\tresult, err := ipuc.CombinedOutput(\"id -u\")\n\tif err != nil {\n\t\terrorList = append(errorList, err)\n\t\treturn\n\t}\n\tuid, err := strconv.Atoi(strings.TrimSpace(string(result)))\n\tif err != nil {\n\t\terrorList = append(errorList, err)\n\t\treturn\n\t}\n\n\tif uid != 0 {\n\t\terrorList = append(errorList, errors.New(\"user is not running as root\"))\n\t}\n\n\treturn nil, errorList\n}", "func checkPermissions(s *model.SessionContext, methodPermission, userPermission string) bool {\n\t// Blocked permission no access.\n\tif userPermission == utils.BlockPermission {\n\t\tlogutil.Errorf(s, \"RBAC check failed... Permission is set to blocked...\")\n\t\treturn false\n\t}\n\n\t// Lower permission Deny access. \"Read vs Modify\" case\n\tif userPermission == utils.ReadPermission &&\n\t\tmethodPermission == utils.ModifyPermission {\n\t\tlogutil.Errorf(s, \"RBAC check failed...\"+\n\t\t\t\"Method permission - %s & User Permission - %s \", methodPermission, userPermission)\n\t\treturn false\n\t}\n\n\t// Matching permission allow access.\n\t// Higher permission allow access. \"Modify vs Read\" case\n\treturn true\n}", "func (o *CommitteeInfoResponse) GetAccessNodesOk() ([]CommitteeNode, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn o.AccessNodes, true\n}", "func (n *Node) PermissionSet(ctx context.Context) provider.ResourcePermissions {\n\tu, ok := ctxpkg.ContextGetUser(ctx)\n\tif !ok {\n\t\tappctx.GetLogger(ctx).Debug().Interface(\"node\", n).Msg(\"no user in context, returning default permissions\")\n\t\treturn NoPermissions()\n\t}\n\tif o, _ := n.Owner(); utils.UserEqual(u.Id, o) {\n\t\treturn OwnerPermissions()\n\t}\n\t// read the permissions for the current user from the acls of the current node\n\tif np, err := n.ReadUserPermissions(ctx, u); err == nil {\n\t\treturn np\n\t}\n\treturn NoPermissions()\n}", "func pvtShowAdminButton(s *sess.Session) bool {\n\tfor i := 0; i < len(s.PMap.Urole.Perms); i++ {\n\t\tif s.PMap.Urole.Perms[i].Perm&authz.PERMCREATE != 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func compareNodes(got, want *types.Node) bool {\n\tresult := false\n\tif compareMeta(got.Meta.Meta, want.Meta.Meta) &&\n\t\t(got.Online == want.Online) &&\n\t\t(got.Meta.Cluster == want.Meta.Cluster) &&\n\t\t(got.Meta.Token == want.Meta.Token) &&\n\t\t(got.Meta.Region == want.Meta.Region) &&\n\t\t(got.Meta.Provider == want.Meta.Provider) &&\n\t\treflect.DeepEqual(got.Status, want.Status) &&\n\t\treflect.DeepEqual(got.Info, want.Info) &&\n\t\treflect.DeepEqual(got.Roles, want.Roles) &&\n\t\treflect.DeepEqual(got.Network, want.Network) &&\n\t\treflect.DeepEqual(got.Spec, want.Spec) {\n\t\tresult = true\n\t}\n\n\treturn result\n}", "func NodeIsControllable(node *api.Node) bool {\n\tcontrollable := !NodeIsMaster(node)\n\tif !controllable {\n\t\tglog.V(3).Infof(\"Node %s is not controllable.\", node.Name)\n\t}\n\treturn controllable\n}", "func checkPermissions(request *Request) (bool, error) {\n\tif request.MethodName == \"auth\" {\n\t\treturn true, nil\n\t} else {\n\t\tif token, err := model.TokenByValue(request.Token); err == nil{\n\t\t\tif user, err := model.UserById(token.UserId); err == nil{\n\t\t\t\treturn isOperationAllowed(user, request.MethodName), nil\n\t\t\t}\n\t\t} else {\n\t\t\treturn false, err\n\t\t}\n\t\treturn false, nil\n\t}\n}", "func pvtHasAdminScreenAccess(s *sess.Session, el int, perm int) bool {\n\tvar p int\n\tvar ok bool\n\tfor i := 0; i < len(adminScreenFields); i++ {\n\t\tif adminScreenFields[i].Elem == el {\n\t\t\tif (el == authz.ELEMPERSON && adminScreenFields[i].AdminScreen) || (el != authz.ELEMPERSON) {\n\t\t\t\tswitch el {\n\t\t\t\tcase authz.ELEMPERSON:\n\t\t\t\t\tp, ok = s.PMap.Pp[adminScreenFields[i].FieldName] // here's the permission we have\n\t\t\t\tcase authz.ELEMCOMPANY:\n\t\t\t\t\tp, ok = s.PMap.Pco[adminScreenFields[i].FieldName] // here's the permission we have\n\t\t\t\tcase authz.ELEMCLASS:\n\t\t\t\t\tp, ok = s.PMap.Pcl[adminScreenFields[i].FieldName] // here's the permission we have\n\t\t\t\tcase authz.ELEMPBSVC:\n\t\t\t\t\tp, ok = s.PMap.Ppr[adminScreenFields[i].FieldName] // here's the permission we have\n\t\t\t\t}\n\t\t\t\tif ok { // if we have a permission for the field name\n\t\t\t\t\t// fmt.Printf(\"p = 0x%02x\\n\", p)\n\t\t\t\t\tpcheck := p & perm // AND it with the required permission\n\t\t\t\t\tif 0 != pcheck { // if the result is non-zero...\n\t\t\t\t\t\t// fmt.Printf(\"granted\\n\")\n\t\t\t\t\t\treturn true // ... we have the permission to view the screen\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// fmt.Printf(\"not granted\\n\")\n\treturn false\n}", "func (ctl *Ctl) waitForWantedNodes(wantedNodes []string, ignoreWaitTimeOut bool,\n\tcancelCh <-chan struct{}) ([]string, error) {\n\tsecs := ctl.optionsCtl.WaitForMemberNodes\n\tif secs <= 0 {\n\t\tif ignoreWaitTimeOut {\n\t\t\tsecs = 5\n\t\t} else {\n\t\t\tsecs = 30\n\t\t}\n\t}\n\tlog.Printf(\"ctl: waitForWantedNodes, wantedNodes: %+v\", wantedNodes)\n\treturn WaitForWantedNodes(ctl.cfg, wantedNodes, cancelCh, secs, ignoreWaitTimeOut)\n}", "func (dk *DynaKube) FeatureEnableMultipleOsAgentsOnNode() bool {\n\treturn dk.getFeatureFlagRaw(AnnotationFeatureMultipleOsAgentsOnNode) == truePhrase\n}", "func CheckUserData(pkg string, source, target *core.User, name, value string) (bool, os.Error) {\n\tperm, err := CheckUserDataPerm(pkg, source, target, name, value)\n\treturn perm > 0, err\n}", "func isOperationAllowed(user *model.User, operation string) bool {\n\tif groups, err := model.GetGroups(user.Groups); err == nil {\n\t\tfor _, group := range groups {\n\t\t\tfor _, permission := range group.Permissions {\n\t\t\t\tif permission.Value == operation {\n\t\t\t\t\treturn permission.Execute\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func isNodeWithLowUtilization(usage NodeUsage) bool {\n\tfor name, nodeValue := range usage.usage {\n\t\t// usage.lowResourceThreshold[name] < nodeValue\n\t\tif usage.lowResourceThreshold[name].Cmp(*nodeValue) == -1 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func CheckNickPerm(pkg string, u *core.User, nick string) (int, os.Error) {\n\treturn runPermHooks(checkNick, func(h interface{}) (int, os.Error) {\n\t\tif f, ok := h.(func(string, *core.User, string) (int, os.Error)); ok && h != nil {\n\t\t\treturn f(pkg, u, nick)\n\t\t}\n\t\treturn 0, nil\n\t},true)\n}", "func classifyNodes(\n\tnodeUsages []NodeUsage,\n\tlowThresholdFilter, highThresholdFilter func(node *v1.Node, usage NodeUsage) bool,\n) ([]NodeUsage, []NodeUsage) {\n\tlowNodes, highNodes := []NodeUsage{}, []NodeUsage{}\n\n\tfor _, nodeUsage := range nodeUsages {\n\t\tif lowThresholdFilter(nodeUsage.node, nodeUsage) {\n\t\t\tklog.V(2).InfoS(\"Node is underutilized\", \"node\", klog.KObj(nodeUsage.node), \"usage\", nodeUsage.usage, \"usagePercentage\", resourceUsagePercentages(nodeUsage))\n\t\t\tlowNodes = append(lowNodes, nodeUsage)\n\t\t} else if highThresholdFilter(nodeUsage.node, nodeUsage) {\n\t\t\tklog.V(2).InfoS(\"Node is overutilized\", \"node\", klog.KObj(nodeUsage.node), \"usage\", nodeUsage.usage, \"usagePercentage\", resourceUsagePercentages(nodeUsage))\n\t\t\thighNodes = append(highNodes, nodeUsage)\n\t\t} else {\n\t\t\tklog.V(2).InfoS(\"Node is appropriately utilized\", \"node\", klog.KObj(nodeUsage.node), \"usage\", nodeUsage.usage, \"usagePercentage\", resourceUsagePercentages(nodeUsage))\n\t\t}\n\t}\n\n\treturn lowNodes, highNodes\n}", "func (n *NodeManager) CheckByUUIDEnv(uuid, environment string) bool {\n\tvar results int64\n\tn.DB.Model(&OsqueryNode{}).Where(\"uuid = ? AND environment = ?\", strings.ToUpper(uuid), environment).Count(&results)\n\treturn (results > 0)\n}", "func NeedAdminFromCtx(ctx context.Context) bool {\n\tif ctx == nil {\n\t\treturn false\n\t}\n\tval := ctx.Value(constants.ContextNeedAdmin)\n\tif needAdmin, ok := val.(bool); ok {\n\t\treturn needAdmin\n\t}\n\treturn false\n}", "func (gen *Db) NodesForUser(userID string) ([]data.NodeEdge, error) {\n\tvar nodes []data.NodeEdge\n\n\terr := gen.store.View(func(tx *genji.Tx) error {\n\t\t// first find parents of user node\n\t\tedges, err := txEdgeUp(tx, userID, false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(edges) == 0 {\n\t\t\treturn errors.New(\"orphaned user\")\n\t\t}\n\n\t\tfor _, edge := range edges {\n\t\t\trootNode, err := txNode(tx, edge.Up)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\trootNodeEdge := rootNode.ToNodeEdge(data.Edge{})\n\t\t\trootNodeEdge.Hash, err = gen.txCalcHash(tx, rootNode, data.Edge{})\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tnodes = append(nodes, rootNodeEdge)\n\n\t\t\tchildNodes, err := txNodeFindDescendents(tx, rootNode.ID, true, 0)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tnodes = append(nodes, childNodes...)\n\t\t}\n\n\t\treturn nil\n\t})\n\n\treturn data.RemoveDuplicateNodesIDParent(nodes), err\n}", "func IsUserAuthorizedForProjectOrganizationTree(user *auth.User, projectSFID, companySFID string) bool {\n\t// Previously, we checked for user.Admin - admins should be in a separate role\n\t// Previously, we checked for user.Allowed, which is currently not used (future flag that is currently not implemented)\n\treturn user.IsUserAuthorized(auth.ProjectOrganization, projectSFID+\"|\"+companySFID, true)\n}", "func (ctx *TestContext) IAmAManagerOfTheGroupAndCanWatchItsMembers(group string) error {\n\treturn ctx.UserIsAManagerOfTheGroupWith(getParameterString(map[string]string{\n\t\t\"id\": group,\n\t\t\"user_id\": ctx.user,\n\t\t\"name\": group,\n\t\t\"can_watch_members\": strTrue,\n\t}))\n}", "func (cfg *Config) CheckAvailableGPUs(kubeClientset kubernetes.Interface) {\n\tnodes, err := kubeClientset.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{LabelSelector: \"!node-role.kubernetes.io/control-plane,!node-role.kubernetes.io/master\"})\n\tif err != nil {\n\t\tlog.Printf(\"Error getting list of nodes: %v\\n\", err)\n\t}\n\tfor _, node := range nodes.Items {\n\t\tgpu := node.Status.Allocatable[\"nvidia.com/gpu\"]\n\t\tif gpu.Value() > 0 {\n\t\t\tcfg.GPUAvailable = true\n\t\t\treturn\n\t\t}\n\t}\n}", "func (o ClusterOutput) AllowNetAdmin() pulumi.BoolPtrOutput {\n\treturn o.ApplyT(func(v *Cluster) pulumi.BoolPtrOutput { return v.AllowNetAdmin }).(pulumi.BoolPtrOutput)\n}", "func IsUserAuthorizedForProjectTree(user *auth.User, projectSFID string) bool {\n\t// Previously, we checked for user.Admin - admins should be in a separate role\n\t// Previously, we checked for user.Allowed, which is currently not used (future flag that is currently not implemented)\n\treturn user.IsUserAuthorized(auth.Project, projectSFID, true)\n}", "func NetUse(ipAddress string, user string, password string) bool {\n\tresult := true\n\n\tout, err := exec.Command(\"net\", \"use\", `\\\\`+ipAddress, `/user:`+user, password).Output()\n\n\t// c.Stdout = os.Stdout\n\t// err := c.Run()\n\n\tif err != nil {\n\t\t//common.PrnLog(\"Error conectando unidad de red...\"+err.Error(), \"red\", false, false)\n\t\t//os.Exit(0)\n\t\tresult = false\n\t} else {\n\t\t//fmt.Println(\"net use out: \" + string(out))\n\t\tresult = strings.Contains(string(out), \"successfully\") || strings.Contains(string(out), \"correctamente\")\n\t}\n\treturn result\n}", "func reqIsAdmin(r *http.Request) bool {\n\tu, err := GetCurrent(r)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn u.Admin\n}", "func (room *Room) checkUserPermissions(user string) error {\n\tisAdmin, isOnline := false, false\n\tfor _, admin := range room.Admins {\n\t\tif admin == user {\n\t\t\tisAdmin = true\n\t\t}\n\t}\n\tfor _, online := range room.Online {\n\t\tif online == user {\n\t\t\tisOnline = true\n\t\t}\n\t}\n\tif !isAdmin {\n\t\treturn errors.New(\"user is not an admin\")\n\t}\n\tif !isOnline {\n\t\treturn errors.New(\"user is not in the room\")\n\t}\n\treturn nil\n}", "func checkNode(node *v1.Node, kc kubeclient.KubeHttpClientInterface) (float64, error) {\n\tip := repository.ParseNodeIP(node, v1.NodeInternalIP)\n\tcpuFreq, err := kc.GetMachineCpuFrequency(ip)\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\treturn float64(cpuFreq) / util.MegaToKilo, nil\n}", "func (e *RevokeExec) checkDynamicPrivilegeUsage() error {\n\tvar dynamicPrivs []string\n\tfor _, priv := range e.Privs {\n\t\tif priv.Priv == mysql.ExtendedPriv {\n\t\t\tdynamicPrivs = append(dynamicPrivs, strings.ToUpper(priv.Name))\n\t\t}\n\t}\n\tif len(dynamicPrivs) > 0 && e.Level.Level != ast.GrantLevelGlobal {\n\t\treturn exeerrors.ErrIllegalPrivilegeLevel.GenWithStackByArgs(strings.Join(dynamicPrivs, \",\"))\n\t}\n\treturn nil\n}", "func CheckNodeNumLocally(expectNum int) {\n\tcmd := \"sudo -E kubectl get nodes | wc -l\"\n\tresult, err := utils.RunSimpleCmd(cmd)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tnum, err := strconv.Atoi(strings.ReplaceAll(result, \"\\n\", \"\"))\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tgomega.Expect(num).Should(gomega.Equal(expectNum + 1))\n}", "func makeNodeUserIdent(ctx *cli.Context) string {\n\tvar comps []string\n\tif identity := ctx.GlobalString(IdentityFlag.Name); len(identity) > 0 {\n\t\tcomps = append(comps, identity)\n\t}\n\tif ctx.GlobalBool(VMEnableJitFlag.Name) {\n\t\tcomps = append(comps, \"JIT\")\n\t}\n\treturn strings.Join(comps, \"/\")\n}", "func (cc *Context) ProvisionNodes() (nodeList map[string]*nodes.Node, err error) {\n\tnodeList = map[string]*nodes.Node{}\n\n\t// For all the nodes defined in the `kind` config\n\tfor _, configNode := range cc.AllReplicas() {\n\n\t\tcc.Status.Start(fmt.Sprintf(\"[%s] Creating node container 📦\", configNode.Name))\n\t\t// create the node into a container (docker run, but it is paused, see createNode)\n\t\tvar name = fmt.Sprintf(\"%s-%s\", cc.Name(), configNode.Name)\n\t\tvar node *nodes.Node\n\n\t\tswitch configNode.Role {\n\t\tcase config.ExternalLoadBalancerRole:\n\t\t\tnode, err = nodes.CreateExternalLoadBalancerNode(name, configNode.Image, cc.ClusterLabel())\n\t\tcase config.ControlPlaneRole:\n\t\t\tnode, err = nodes.CreateControlPlaneNode(name, configNode.Image, cc.ClusterLabel(), configNode.ExtraMounts)\n\t\tcase config.WorkerRole:\n\t\t\tnode, err = nodes.CreateWorkerNode(name, configNode.Image, cc.ClusterLabel(), configNode.ExtraMounts)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nodeList, err\n\t\t}\n\t\tnodeList[configNode.Name] = node\n\n\t\tcc.Status.Start(fmt.Sprintf(\"[%s] Fixing mounts 🗻\", configNode.Name))\n\t\t// we need to change a few mounts once we have the container\n\t\t// we'd do this ahead of time if we could, but --privileged implies things\n\t\t// that don't seem to be configurable, and we need that flag\n\t\tif err := node.FixMounts(); err != nil {\n\t\t\t// TODO(bentheelder): logging here\n\t\t\treturn nodeList, err\n\t\t}\n\n\t\tcc.Status.Start(fmt.Sprintf(\"[%s] Configuring proxy 🐋\", configNode.Name))\n\t\tif err := node.SetProxy(); err != nil {\n\t\t\t// TODO: logging here\n\t\t\treturn nodeList, errors.Wrapf(err, \"failed to set proxy for %s\", configNode.Name)\n\t\t}\n\n\t\tcc.Status.Start(fmt.Sprintf(\"[%s] Starting systemd 🖥\", configNode.Name))\n\t\t// signal the node container entrypoint to continue booting into systemd\n\t\tif err := node.SignalStart(); err != nil {\n\t\t\t// TODO(bentheelder): logging here\n\t\t\treturn nodeList, err\n\t\t}\n\n\t\tcc.Status.Start(fmt.Sprintf(\"[%s] Waiting for docker to be ready 🐋\", configNode.Name))\n\t\t// wait for docker to be ready\n\t\tif !node.WaitForDocker(time.Now().Add(time.Second * 30)) {\n\t\t\t// TODO(bentheelder): logging here\n\t\t\treturn nodeList, errors.New(\"timed out waiting for docker to be ready on node\")\n\t\t}\n\n\t\t// load the docker image artifacts into the docker daemon\n\t\tcc.Status.Start(fmt.Sprintf(\"[%s] Pre-loading images 🐋\", configNode.Name))\n\t\tnode.LoadImages()\n\n\t}\n\n\treturn nodeList, nil\n}", "func CheckAccess(permissionGroup string, hasRole string, makerChecker bool, requestedMethod string, requestedEndpoint string) (bool, error) {\n\n\tp := authPermissions.Permissions()\n\t// permissionsByte, err := ioutil.ReadFile(\"../permissions.json\")\n\tvar permissions Permissions\n\t// if err != nil {\n\t// \tpanic(err)\n\t// }\n\terr := json.Unmarshal([]byte(p), &permissions)\n\t// fmt.Print(string(permissionsByte))\n\n\tif err != nil {\n\t\tLOGGER.Error(\"Error while parsing JSON\")\n\t\treturn false, errors.New(\"not authorized, no matching permissions\")\n\t}\n\n\tif permissionGroup == \"Jwt\" {\n\n\t\t// endpoints requiring JWT\n\t\t// fmt.Print(\"\\n\\n\" + requestedMethod + \" | jwt endpoints:\\n\")\n\t\tjwtEndp := permissions.Permissions.Jwt.Default.Method[requestedMethod].Endpoint\n\t\tfor key, value := range jwtEndp {\n\t\t\t// fmt.Println(key+\" - Allow: \", value.Role.Allow)\n\t\t\tif hasRole == \"allow\" && value.Role.Allow == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"Permissions Succeeded! \"+key+\" - Allow: \", value.Role.Allow)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif permissionGroup == \"Super_permissions\" && makerChecker == false {\n\n\t\t// super user endpoints\n\t\t// fmt.Print(\"\\n\\n\" + requestedMethod + \" | super user endpoints:\\n\")\n\t\tsuperEndpDef := permissions.Permissions.Super_permissions.Default.Method[requestedMethod].Endpoint\n\t\tfor key, value := range superEndpDef {\n\t\t\t// fmt.Println(key+\" - Admin: \", value.Role.Admin)\n\t\t\t// fmt.Println(key+\" - Manager: \", value.Role.Manager)\n\t\t\tif hasRole == \"admin\" && value.Role.Admin == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Admin: \", value.Role.Admin)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tif hasRole == \"manager\" && value.Role.Manager == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Manager: \", value.Role.Manager)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif permissionGroup == \"Super_permissions\" && makerChecker == true {\n\n\t\t// super user endpoints requiring maker/checker\n\t\t// fmt.Print(\"\\n\\n\" + requestedMethod + \" | super user + maker/checker endpoints:\\n\")\n\t\tsuperEndpMC := permissions.Permissions.Super_permissions.Maker_checker.Method[requestedMethod].Endpoint\n\t\tfor key, value := range superEndpMC {\n\t\t\t// fmt.Println(key+\" - Admin: \", value.Role.Admin)\n\t\t\t// fmt.Println(key+\" - Manager: \", value.Role.Manager)\n\t\t\tif hasRole == \"admin\" && value.Role.Admin == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Admin: \", value.Role.Admin)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tif hasRole == \"manager\" && value.Role.Manager == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Manager: \", value.Role.Manager)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif permissionGroup == \"Participant_permissions\" && makerChecker == false {\n\n\t\t// participant user endpoints\n\t\t// fmt.Print(\"\\n\\n\" + requestedMethod + \" | participant endpoints:\\n\")\n\t\tparticipantEndpDef := permissions.Permissions.Participant_permissions.Default.Method[requestedMethod].Endpoint\n\t\tfor key, value := range participantEndpDef {\n\t\t\t// fmt.Println(key+\" - Admin: \", value.Role.Admin)\n\t\t\t// fmt.Println(key+\" - Manager: \", value.Role.Manager)\n\t\t\tif hasRole == \"admin\" && value.Role.Admin == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Admin: \", value.Role.Admin)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tif hasRole == \"manager\" && value.Role.Manager == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Manager: \", value.Role.Manager)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif permissionGroup == \"Participant_permissions\" && makerChecker == true {\n\n\t\t// participant user endpoints requiring maker/checker\n\t\t// fmt.Print(\"\\n\\n\" + requestedMethod + \" | participant + maker/checker endpoints:\\n\")\n\t\tparticipantEndpMC := permissions.Permissions.Participant_permissions.Maker_checker.Method[requestedMethod].Endpoint\n\t\tfor key, value := range participantEndpMC {\n\t\t\t// fmt.Println(key+\" - Admin: \", value.Role.Admin)\n\t\t\t// fmt.Println(key+\" - Manager: \", value.Role.Manager)\n\t\t\tif hasRole == \"admin\" && value.Role.Admin == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Admin: \", value.Role.Admin)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tif hasRole == \"manager\" && value.Role.Manager == true && authutility.ComparePaths(key, requestedEndpoint) {\n\t\t\t\t// fmt.Println(\"\\nPermissions Succeeded! \"+key+\" - Manager: \", value.Role.Manager)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn false, errors.New(\"not authorized, no matching permissions\")\n\n}", "func checkNode(c *cli.Context) error {\n\n\tmonitoringData := nagiosPlugin.NewMonitoring()\n\n\t// Check global parameters\n\terr := manageGlobalParameters()\n\tif err != nil {\n\t\treturn cli.NewExitError(fmt.Sprintf(\"%v\", err), nagiosPlugin.STATUS_UNKNOWN)\n\t}\n\n\t// Check current parameters\n\tif c.String(\"cluster-name\") == \"\" {\n\t\treturn cli.NewExitError(\"You must set --cluster-name parameter\", nagiosPlugin.STATUS_UNKNOWN)\n\t}\n\tif c.String(\"node-name\") == \"\" {\n\t\treturn cli.NewExitError(\"You must set --node-name parameter\", nagiosPlugin.STATUS_UNKNOWN)\n\t}\n\n\tparams := &OptionnalComputeState{}\n\tif c.String(\"include-alerts\") != \"\" {\n\t\tparams.IncludeAlerts = strings.Split(c.String(\"include-alerts\"), \",\")\n\t}\n\tif c.String(\"exclude-alerts\") != \"\" {\n\t\tparams.ExcludeAlerts = strings.Split(c.String(\"exclude-alerts\"), \",\")\n\t}\n\n\t// Get Ambari connection\n\tambariClient := client.New(ambariUrl+\"/api/v1\", ambariLogin, ambariPassword)\n\tambariClient.DisableVerifySSL()\n\n\t// Check node alertes\n\talerts, err := ambariClient.AlertsInHost(c.String(\"cluster-name\"), c.String(\"node-name\"))\n\tif err != nil {\n\t\tmonitoringData.AddMessage(\"Somethink wrong when try to check node alerts on %s: %v\", c.String(\"node-name\"), err)\n\t\tmonitoringData.SetStatus(nagiosPlugin.STATUS_UNKNOWN)\n\t\tmonitoringData.ToSdtOut()\n\t}\n\n\t// Remove all UNKNOWN alert before to compute them\n\tfilterAlerts := make([]client.Alert, 0, 1)\n\tfor _, alert := range alerts {\n\t\tif alert.AlertInfo.State != \"UNKNOWN\" {\n\t\t\tfilterAlerts = append(filterAlerts, alert)\n\t\t}\n\t}\n\n\tmonitoringData, err = computeState(filterAlerts, monitoringData, params)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmonitoringData.ToSdtOut()\n\treturn nil\n\n}", "func isNodeAboveTargetUtilization(usage NodeUsage) bool {\n\tfor name, nodeValue := range usage.usage {\n\t\t// usage.highResourceThreshold[name] < nodeValue\n\t\tif usage.highResourceThreshold[name].Cmp(*nodeValue) == -1 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func CheckNodeAffinity(pv *v1.PersistentVolume, nodeLabels map[string]string) error {\n\tif pv.Spec.NodeAffinity == nil {\n\t\treturn nil\n\t}\n\n\tif pv.Spec.NodeAffinity.Required != nil {\n\t\tnode := &v1.Node{ObjectMeta: metav1.ObjectMeta{Labels: nodeLabels}}\n\t\tterms := pv.Spec.NodeAffinity.Required\n\t\tif matches, err := corev1.MatchNodeSelectorTerms(node, terms); err != nil {\n\t\t\treturn err\n\t\t} else if !matches {\n\t\t\treturn fmt.Errorf(\"no matching NodeSelectorTerms\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func HasAccess(callerUid, callerGid, fileUid, fileGid uint32, perm uint32, mask uint32) bool {\n\tif callerUid == 0 {\n\t\t// root can do anything.\n\t\treturn true\n\t}\n\tmask = mask & 7\n\tif mask == 0 {\n\t\treturn true\n\t}\n\n\tif callerUid == fileUid {\n\t\tif perm&(mask<<6) != 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\tif callerGid == fileGid {\n\t\tif perm&(mask<<3) != 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\tif perm&mask != 0 {\n\t\treturn true\n\t}\n\n\t// Check other groups.\n\tif perm&(mask<<3) == 0 {\n\t\t// avoid expensive lookup if it's not allowed anyway\n\t\treturn false\n\t}\n\n\tu, err := user.LookupId(strconv.Itoa(int(callerUid)))\n\tif err != nil {\n\t\treturn false\n\t}\n\tgs, err := u.GroupIds()\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tfileGidStr := strconv.Itoa(int(fileGid))\n\tfor _, gidStr := range gs {\n\t\tif gidStr == fileGidStr {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func CanAccess(userId, path string) bool {\n\tpath = filepath.FromSlash(path)\n\n\tuserWorkspace := conf.GetUserWorkspace(userId)\n\tworkspaces := filepath.SplitList(userWorkspace)\n\n\tfor _, workspace := range workspaces {\n\t\tif strings.HasPrefix(path, workspace) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func UseUserPermission() BoolFlag {\n\treturn useUserPermission\n}", "func (n *Node) IsAllowed() bool {\n\tif !n.NodeAllow.Check(n.Nodestr) && n.NodeDeny.Check(n.Nodestr) {\n\t\treturn false\n\t}\n\treturn true\n}", "func (s Service) checkAdminLevel(ctx context.Context, companyID string, requiredLevels ...companyadmin.AdminLevel) bool {\n\tspan := s.tracer.MakeSpan(ctx, \"checkAdminLevel\")\n\tdefer span.Finish()\n\n\tactualLevel, err := s.networkRPC.GetAdminLevel(ctx, companyID)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t\tlog.Println(\"Error: checkAdminLevel:\", err)\n\t\treturn false\n\t}\n\n\tfor _, lvl := range requiredLevels {\n\t\tif lvl == actualLevel {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func GetNodesStatus(cfg *setting.Setting) []bool {\n\tclients := cfg.GetClients()\n\tr := make([]bool, len(clients))\n\tfor i, cl := range clients {\n\t\tr[i] = cl.Alive\n\t}\n\tlog.Println(\"status\", r)\n\treturn r\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 (p *Proxy) isClusterAdmin(token string) (bool, error) {\n\tclient, err := p.createTypedClient(token)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tsar := &authv1.SelfSubjectAccessReview{\n\t\tSpec: authv1.SelfSubjectAccessReviewSpec{\n\t\t\tResourceAttributes: &authv1.ResourceAttributes{\n\t\t\t\tNamespace: \"openshift-terminal\",\n\t\t\t\tVerb: \"create\",\n\t\t\t\tResource: \"pods\",\n\t\t\t},\n\t\t},\n\t}\n\tres, err := client.AuthorizationV1().SelfSubjectAccessReviews().Create(context.TODO(), sar, metav1.CreateOptions{})\n\tif err != nil || res == nil {\n\t\treturn false, err\n\t}\n\treturn res.Status.Allowed, nil\n}", "func RunningInUserNS() bool {\n\tfile, err := os.Open(\"/proc/self/uid_map\")\n\tif err != nil {\n\t\t/*\n\t\t * This kernel-provided file only exists if user namespaces are\n\t\t * supported\n\t\t */\n\t\treturn false\n\t}\n\tdefer file.Close()\n\n\tbuf := bufio.NewReader(file)\n\tl, _, err := buf.ReadLine()\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tline := string(l)\n\tvar a, b, c int64\n\tfmt.Sscanf(line, \"%d %d %d\", &a, &b, &c)\n\t/*\n\t * We assume we are in the initial user namespace if we have a full\n\t * range - 4294967295 uids starting at uid 0.\n\t */\n\tif a == 0 && b == 0 && c == 4294967295 {\n\t\treturn false\n\t}\n\treturn true\n}", "func (*filesystem) AllowUserList() bool {\n\treturn false\n}", "func RunNodeChecks(c *typesv1.Cluster, s ssh.Interface) error {\n\tchecks := newCommonChecks(c.ClusterName, s)\n\tchecks = append(checks, []Checker{}...)\n\n\tfor _, tool := range tools {\n\t\tchecks = append(checks, InPathCheck{Interface: s, executable: tool})\n\t}\n\n\treturn RunChecks(checks)\n}", "func grantUserPerms(host string, adminToken string, user ssUser, projectKey string) (err error) {\n\t//scan left out, only those with access to the admin token can run analysis?\n\t// \"scan\",\n\tnecessaryPermissions := []string{\"codeviewer\", \"user\"}\n\n\terrChan := make(chan error, len(necessaryPermissions))\n\n\trequestOnePerm := func(permission string, errChan chan<- error) {\n\t\tgrantPermForm := url.Values{}\n\t\tgrantPermForm.Set(\"login\", user.login)\n\t\tgrantPermForm.Set(\"permission\", permission)\n\t\tgrantPermForm.Set(\"projectKey\", projectKey)\n\n\t\treq, err := http.NewRequest(\"POST\", host+\"/api/permissions/add_user\", strings.NewReader(grantPermForm.Encode()))\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\t\treq.SetBasicAuth(adminToken, \"\")\n\t\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\n\t\tcreateResp, err := http.DefaultClient.Do(req)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\n\t\tcreateResp.Body.Close()\n\t\tif createResp.StatusCode != 204 {\n\t\t\terrChan <- errors.New(fmt.Sprint(\"Failed to grant \", user.login, \"permission. Received status code \", string(createResp.StatusCode)))\n\t\t\treturn\n\t\t}\n\t\terrChan <- nil\n\t}\n\n\tfor _, onePerm := range necessaryPermissions {\n\t\tgo requestOnePerm(onePerm, errChan)\n\t}\n\n\tfor range necessaryPermissions {\n\t\tif err = <-errChan; err != nil {\n\t\t\tprintWrapper(err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (tc *testContext) testNodeTaint(t *testing.T) {\n\t// windowsTaint is the taint that needs to be applied to the Windows node\n\twindowsTaint := core.Taint{\n\t\tKey: \"os\",\n\t\tValue: \"Windows\",\n\t\tEffect: core.TaintEffectNoSchedule,\n\t}\n\n\tfor _, node := range gc.allNodes() {\n\t\thasTaint := func() bool {\n\t\t\tfor _, taint := range node.Spec.Taints {\n\t\t\t\tif taint.Key == windowsTaint.Key && taint.Value == windowsTaint.Value && taint.Effect == windowsTaint.Effect {\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\tassert.Equal(t, hasTaint, true, \"expected Windows Taint to be present on the Node: %s\", node.GetName())\n\t}\n}", "func isAdmin(res http.ResponseWriter, req *http.Request) bool {\n\tmyUser := getUser(res, req)\n\treturn myUser.Username == \"admin\"\n}", "func (a API) NodeChk() (isNew bool) {\n\tselect {\n\tcase o := <-a.Ch.(chan NodeRes):\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 ensureUserAlterPrivileges(users []string, meta interface{}) error {\n\tdb := meta.(*sql.DB)\n\tfor _, user := range users {\n\t\tuserDescSql := snowflake.User(user).Describe()\n\t\terr := snowflake.Exec(db, userDescSql)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"error altering network policy of user %v\", user)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (_FCToken *FCTokenCallerSession) Nodes(arg0 *big.Int) (string, error) {\n\treturn _FCToken.Contract.Nodes(&_FCToken.CallOpts, arg0)\n}", "func checkAdmin(value int64) bool {\n\tfor _, i := range Config.Admins {\n\t\tif i == value {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func Use(newer string) bool {\n\n\t// try catch\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tmsg := fmt.Sprintf(\"'gnvm use %v' an error has occurred. please check. \\nError: \", newer)\n\t\t\tError(ERROR, msg, err)\n\t\t\tos.Exit(0)\n\t\t}\n\t}()\n\n\t// get true folder, e.g. folder is latest return x.xx.xx\n\tutil.FormatLatVer(&newer, config.GetConfig(config.LATEST_VERSION), true)\n\tif newer == util.UNKNOWN {\n\t\tP(WARING, \"current latest is %v, please usage '%v' first. See '%v'.\\n\", newer, \"gnvm update latest\", \"gnvm help update\")\n\t\treturn false\n\t}\n\n\t// set newerPath and verify newerPath is exist?\n\tnewerPath := rootPath + newer\n\tif _, err := util.GetNodeVer(newerPath); err != nil {\n\t\tP(WARING, \"%v folder is not exist %v, use '%v' get local Node.js version list. See '%v'.\\n\", newer, \"node.exe\", \"gnvm ls\", \"gnvm help ls\")\n\t\treturn false\n\t}\n\n\t// get <root>/node.exe version, when exist, get full version, e.g. x.xx.xx-x86\n\tglobal, err := util.GetNodeVer(rootPath)\n\tif err != nil {\n\t\tP(WARING, \"not found %v Node.js version.\\n\", \"global\")\n\t} else {\n\t\tif bit, err := util.Arch(rootPath); err == nil {\n\t\t\tif bit == \"x86\" && runtime.GOARCH == \"amd64\" {\n\t\t\t\tglobal += \"-\" + bit\n\t\t\t}\n\t\t}\n\t}\n\n\t// check newer is global\n\tif newer == global {\n\t\tP(WARING, \"current Node.js version is %v, not re-use. See '%v'.\\n\", newer, \"gnvm node-version\")\n\t\treturn false\n\t}\n\n\t// set globalPath\n\tglobalPath := rootPath + global\n\n\t// <root>/global is exist? when not exist, create global folder\n\tif !util.IsDirExist(globalPath) {\n\t\tif err := os.Mkdir(globalPath, 0777); err != nil {\n\t\t\tP(ERROR, \"create %v folder Error: %v.\\n\", global, err.Error())\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// backup copy <root>/node.exe to <root>/global/node.exe\n\tif global != \"\" {\n\t\tif err := util.Copy(rootPath, globalPath, util.NODE); err != nil {\n\t\t\tP(ERROR, \"copy %v to %v folder Error: %v.\\n\", rootPath, globalPath, err.Error())\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// copy <root>/newer/node.exe to <root>/node.exe\n\tif err := util.Copy(newerPath, rootPath, util.NODE); err != nil {\n\t\tP(ERROR, \"copy %v to %v folder Error: %v.\\n\", newerPath, rootPath, err.Error())\n\t\treturn false\n\t}\n\n\tP(DEFAULT, \"Set success, global Node.js version is %v.\\n\", newer)\n\n\treturn true\n}", "func (conn *DB) WhereUserHasViewPermissionOnItems(user *User, viewPermission string) *DB {\n\treturn conn.WhereUserHasPermissionOnItems(user, \"view\", viewPermission)\n}", "func nodeIsValidForTopologyAwareHints(node *corev1.Node) bool {\n\treturn !node.Status.Allocatable.Cpu().IsZero() && node.Labels[corev1.LabelTopologyZone] != \"\"\n}", "func (e UserEdges) NodesOrErr() ([]*Node, error) {\n\tif e.loadedTypes[3] {\n\t\treturn e.Nodes, nil\n\t}\n\treturn nil, &NotLoadedError{edge: \"nodes\"}\n}", "func (p *Processor) checkIPOnNode(nodenetwork *cloudv1.NodeNetwork) (bool, error) {\n\tcloudips := &cloudv1.CloudIPList{}\n\tif err := p.kubeClient.List(context.TODO(), cloudips,\n\t\t&client.MatchingLabels{\n\t\t\tconstant.IP_LABEL_KEY_FOR_HOST: nodenetwork.Spec.NodeAddress,\n\t\t\tconstant.IP_LABEL_KEY_FOR_IS_CLUSTER_LAYER: strconv.FormatBool(true),\n\t\t}); err != nil {\n\n\t\tblog.Errorf(\"list cloud ip on node %s failed, err %s\", nodenetwork.Spec.NodeAddress, err.Error())\n\t\treturn true, fmt.Errorf(\"list cloud ip on node %s failed, err %s\", nodenetwork.Spec.NodeAddress, err.Error())\n\t}\n\tif len(cloudips.Items) == 0 {\n\t\treturn false, nil\n\t}\n\tblog.Infof(\"found ips: %+v on node %s\", cloudips.Items, nodenetwork.Spec.NodeAddress)\n\treturn true, nil\n}", "func (Task) IsNode() {}", "func (ls *LocalStorage) filterAllowedNodes(clients map[string]provisioner.API, deploymentName, role string) ([]provisioner.API, error) {\n\t// Find all PVs for given deployment & role\n\tlist, err := ls.deps.KubeCli.CoreV1().PersistentVolumes().List(metav1.ListOptions{\n\t\tLabelSelector: fmt.Sprintf(\"%s=%s,%s=%s\", k8sutil.LabelKeyArangoDeployment, deploymentName, k8sutil.LabelKeyRole, role),\n\t})\n\tif err != nil {\n\t\treturn nil, maskAny(err)\n\t}\n\texcludedNodes := make(map[string]struct{})\n\tfor _, pv := range list.Items {\n\t\tnodeName := pv.GetAnnotations()[nodeNameAnnotation]\n\t\texcludedNodes[nodeName] = struct{}{}\n\t}\n\tresult := make([]provisioner.API, 0, len(clients))\n\tfor nodeName, c := range clients {\n\t\tif _, found := excludedNodes[nodeName]; !found {\n\t\t\tresult = append(result, c)\n\t\t}\n\t}\n\treturn result, nil\n}", "func (o *Object) CheckPermissions(creds *auth.Credentials, req vfs.AccessTypes) bool {\n\tperms := uint16(o.Mode.Permissions())\n\tif o.OwnerUID == creds.EffectiveKUID {\n\t\tperms >>= 6\n\t} else if creds.InGroup(o.OwnerGID) {\n\t\tperms >>= 3\n\t}\n\n\tif uint16(req)&perms == uint16(req) {\n\t\treturn true\n\t}\n\treturn creds.HasCapabilityIn(linux.CAP_IPC_OWNER, o.UserNS)\n}", "func (p *planner) ShowGrants(ctx context.Context, n *tree.ShowGrants) (planNode, error) {\n\tvar params []string\n\tvar initCheck func(context.Context) error\n\n\tconst dbPrivQuery = `SELECT table_catalog AS \"Database\", table_schema as \"Schema\", grantee AS \"User\", privilege_type AS \"Privileges\" ` +\n\t\t`FROM \"\".information_schema.schema_privileges`\n\tconst tablePrivQuery = `SELECT table_catalog as \"Database\", table_schema AS \"Schema\", table_name AS \"Table\", grantee AS \"User\", privilege_type AS \"Privileges\" ` +\n\t\t`FROM \"\".information_schema.table_privileges`\n\n\tvar source bytes.Buffer\n\tvar cond bytes.Buffer\n\tvar orderBy string\n\n\tif n.Targets != nil && n.Targets.Databases != nil {\n\t\t// Get grants of database from information_schema.schema_privileges\n\t\t// if the type of target is database.\n\t\tdbNames := n.Targets.Databases.ToStrings()\n\n\t\tinitCheck = func(ctx context.Context) error {\n\t\t\tfor _, db := range dbNames {\n\t\t\t\tif err := checkDBExists(ctx, p, db); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\tfor _, db := range dbNames {\n\t\t\tparams = append(params, lex.EscapeSQLString(db))\n\t\t}\n\n\t\tfmt.Fprint(&source, dbPrivQuery)\n\t\torderBy = \"1,2,3\"\n\t\tif len(params) == 0 {\n\t\t\t// There are no rows, but we can't simply return emptyNode{} because\n\t\t\t// the result columns must still be defined.\n\t\t\tcond.WriteString(`WHERE false`)\n\t\t} else {\n\t\t\tfmt.Fprintf(&cond, `WHERE \"Database\" IN (%s)`, strings.Join(params, \",\"))\n\t\t}\n\t} else {\n\t\tfmt.Fprint(&source, tablePrivQuery)\n\t\torderBy = \"1,2,3,4\"\n\n\t\tif n.Targets != nil {\n\t\t\t// Get grants of table from information_schema.table_privileges\n\t\t\t// if the type of target is table.\n\t\t\tvar allTables tree.TableNames\n\n\t\t\tfor _, tableTarget := range n.Targets.Tables {\n\t\t\t\ttableGlob, err := tableTarget.NormalizeTablePattern()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tvar tables tree.TableNames\n\t\t\t\t// We avoid the cache so that we can observe the grants taking\n\t\t\t\t// a lease, like other SHOW commands. We also use\n\t\t\t\t// allowAdding=true so we can look at the grants of a table\n\t\t\t\t// added in the same transaction.\n\t\t\t\t//\n\t\t\t\t// TODO(vivek): check if the cache can be used.\n\t\t\t\tp.runWithOptions(resolveFlags{allowAdding: true, skipCache: true}, func() {\n\t\t\t\t\ttables, err = expandTableGlob(ctx, p, tableGlob)\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\tallTables = append(allTables, tables...)\n\t\t\t}\n\n\t\t\tinitCheck = func(ctx context.Context) error { return nil }\n\n\t\t\tfor i := range allTables {\n\t\t\t\tparams = append(params, fmt.Sprintf(\"(%s,%s,%s)\",\n\t\t\t\t\tlex.EscapeSQLString(allTables[i].Catalog()),\n\t\t\t\t\tlex.EscapeSQLString(allTables[i].Schema()),\n\t\t\t\t\tlex.EscapeSQLString(allTables[i].Table())))\n\t\t\t}\n\n\t\t\tif len(params) == 0 {\n\t\t\t\t// The glob pattern has expanded to zero matching tables.\n\t\t\t\t// There are no rows, but we can't simply return emptyNode{} because\n\t\t\t\t// the result columns must still be defined.\n\t\t\t\tcond.WriteString(`WHERE false`)\n\t\t\t} else {\n\t\t\t\tfmt.Fprintf(&cond, `WHERE (\"Database\", \"Schema\", \"Table\") IN (%s)`, strings.Join(params, \",\"))\n\t\t\t}\n\t\t} else {\n\t\t\t// No target: only look at tables and schemas in the current database.\n\t\t\tsource.WriteString(` UNION ALL ` +\n\t\t\t\t`SELECT \"Database\", \"Schema\", NULL::STRING AS \"Table\", \"User\", \"Privileges\" FROM (`)\n\t\t\tsource.WriteString(dbPrivQuery)\n\t\t\tsource.WriteByte(')')\n\t\t\t// If the current database is set, restrict the command to it.\n\t\t\tif p.CurrentDatabase() != \"\" {\n\t\t\t\tfmt.Fprintf(&cond, ` WHERE \"Database\" = %s`, lex.EscapeSQLString(p.CurrentDatabase()))\n\t\t\t} else {\n\t\t\t\tcond.WriteString(`WHERE true`)\n\t\t\t}\n\t\t}\n\t}\n\n\tif n.Grantees != nil {\n\t\tparams = params[:0]\n\t\tfor _, grantee := range n.Grantees.ToStrings() {\n\t\t\tparams = append(params, lex.EscapeSQLString(grantee))\n\t\t}\n\t\tfmt.Fprintf(&cond, ` AND \"User\" IN (%s)`, strings.Join(params, \",\"))\n\t}\n\treturn p.delegateQuery(ctx, \"SHOW GRANTS\",\n\t\tfmt.Sprintf(\"SELECT * FROM (%s) %s ORDER BY %s\", source.String(), cond.String(), orderBy),\n\t\tinitCheck, nil)\n}", "func hasAdmin() (bool, error) {\n\tvar sid *windows.SID\n\n\t// Although this looks scary, it is directly copied from the\n\t// official windows documentation. The Go API for this is a\n\t// direct wrap around the official C++ API.\n\t// See https://docs.microsoft.com/en-us/windows/desktop/api/securitybaseapi/nf-securitybaseapi-checktokenmembership\n\terr := windows.AllocateAndInitializeSid(\n\t\t&windows.SECURITY_NT_AUTHORITY,\n\t\t2,\n\t\twindows.SECURITY_BUILTIN_DOMAIN_RID,\n\t\twindows.DOMAIN_ALIAS_RID_ADMINS,\n\t\t0, 0, 0, 0, 0, 0,\n\t\t&sid)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tdefer func() {\n\t\t_ = windows.FreeSid(sid)\n\t}()\n\n\t// This appears to cast a null pointer so I'm not sure why this\n\t// works, but this guy says it does and it Works for Me™:\n\t// https://github.com/golang/go/issues/28804#issuecomment-438838144\n\ttoken := windows.Token(0)\n\n\tmember, err := token.IsMember(sid)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn token.IsElevated() || member, nil\n}", "func (o *KubernetesNodeGroupProfile) HasNodes() bool {\n\tif o != nil && o.Nodes != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o ClusterNodeGroupOptionsOutput) NodeUserData() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ClusterNodeGroupOptions) *string { return v.NodeUserData }).(pulumi.StringPtrOutput)\n}", "func (u *User) QueryNodes() *NodeQuery {\n\treturn (&UserClient{config: u.config}).QueryNodes(u)\n}", "func (n *NodeManager) CheckByUUID(uuid string) bool {\n\tvar results int64\n\tn.DB.Model(&OsqueryNode{}).Where(\"uuid = ?\", strings.ToUpper(uuid)).Count(&results)\n\treturn (results > 0)\n}", "func DeleteNodeUserInput(errorhandler DeviceErrorHandler, db *bolt.DB,\n\tgetDevice exchange.DeviceHandler,\n\tpatchDevice exchange.PatchDeviceHandler) (bool, []*events.NodeUserInputMessage) {\n\n\t// Check for the device in the local database. If there are errors, they will be written\n\t// to the HTTP response.\n\tpDevice, err := persistence.FindExchangeDevice(db)\n\tif err != nil {\n\t\treturn errorhandler(nil, NewSystemError(fmt.Sprintf(\"Unable to read node object, error %v\", err))), nil\n\t} else if pDevice == nil {\n\t\treturn errorhandler(nil, NewNotFoundError(\"Exchange registration not recorded. Complete account and node registration with an exchange and then record node registration using this API's /node path.\", \"node\")), nil\n\t}\n\n\tuserInput, err := persistence.FindNodeUserInput(db)\n\tif err != nil {\n\t\treturn errorhandler(pDevice, NewSystemError(fmt.Sprintf(\"unable to read node user input object, error %v\", err))), nil\n\t}\n\tif userInput == nil || len(userInput) == 0 {\n\t\tLogDeviceEvent(db, persistence.SEVERITY_INFO, fmt.Sprintf(\"No node user input to detele\"), persistence.EC_NODE_USERINPUT_UPDATED, pDevice)\n\t\treturn false, []*events.NodeUserInputMessage{}\n\t}\n\n\t// delete the node policy from both exchange the local db\n\tif err := exchangesync.DeleteNodeUserInput(pDevice, db, getDevice, patchDevice); err != nil {\n\t\treturn errorhandler(pDevice, NewSystemError(fmt.Sprintf(\"Node user input could not be deleted. %v\", err))), nil\n\t}\n\n\tLogDeviceEvent(db, persistence.SEVERITY_INFO, fmt.Sprintf(\"Deleted all node user input\"), persistence.EC_NODE_USERINPUT_UPDATED, pDevice)\n\n\tchnagedSvcSpecs := new(persistence.ServiceSpecs)\n\tfor _, ui := range userInput {\n\t\tchnagedSvcSpecs.AppendServiceSpec(persistence.ServiceSpec{Url: ui.ServiceUrl, Org: ui.ServiceOrgid})\n\t}\n\tnodeUserInputUpdated := events.NewNodeUserInputMessage(events.UPDATE_NODE_USERINPUT, *chnagedSvcSpecs)\n\treturn false, []*events.NodeUserInputMessage{nodeUserInputUpdated}\n}" ]
[ "0.53122437", "0.5281791", "0.5281775", "0.5256282", "0.5237384", "0.5215866", "0.51346487", "0.5133892", "0.51283", "0.5124426", "0.51170623", "0.510045", "0.5097251", "0.50586534", "0.5048094", "0.5030782", "0.49881282", "0.49571005", "0.49561796", "0.49313322", "0.4897643", "0.48798883", "0.48715687", "0.48708603", "0.48599884", "0.48490843", "0.48270884", "0.4825435", "0.48244783", "0.48199117", "0.481668", "0.4799266", "0.47948265", "0.47939703", "0.4785941", "0.4782467", "0.4770417", "0.47677302", "0.47593546", "0.47479782", "0.47428656", "0.4738338", "0.47323903", "0.47284472", "0.47238326", "0.47231013", "0.47114202", "0.47076744", "0.4705675", "0.4699678", "0.46994406", "0.46985483", "0.4682164", "0.46721682", "0.46696457", "0.46668383", "0.46662113", "0.466136", "0.46607336", "0.46553457", "0.46531984", "0.46523878", "0.46460733", "0.4641731", "0.46178114", "0.4616903", "0.46098027", "0.4605046", "0.46030813", "0.4601656", "0.4594918", "0.45827377", "0.45819137", "0.45752612", "0.45630184", "0.45580855", "0.4556769", "0.45567602", "0.4552176", "0.45312873", "0.45283377", "0.45269006", "0.45179176", "0.45108488", "0.4507653", "0.4500604", "0.4490184", "0.44890696", "0.44837838", "0.44824073", "0.4482119", "0.44795865", "0.447803", "0.44764596", "0.44754088", "0.4475033", "0.44691166", "0.44664288", "0.44656518", "0.44638097" ]
0.8255833
0
importClusterExtraOperation extra operation (sync cluster to passcc)
func importClusterExtraOperation(cluster *proto.Cluster) { // sync cluster/cluster-snap info to pass-cc err := passcc.GetCCClient().CreatePassCCCluster(cluster) if err != nil { blog.Errorf("ImportClusterExtraOperation[%s] CreatePassCCCluster failed: %v", cluster.ClusterID, err) } err = passcc.GetCCClient().CreatePassCCClusterSnapshoot(cluster) if err != nil { blog.Errorf("ImportClusterExtraOperation CreatePassCCClusterSnapshoot[%s] failed: %v", cluster.ClusterID, err) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (h *Handler) importCluster(config *gkev1.GKEClusterConfig) (*gkev1.GKEClusterConfig, error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tcluster, err := GetCluster(ctx, h.secretsCache, &config.Spec)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\tif err := h.createCASecret(config, cluster); err != nil {\n\t\treturn config, err\n\t}\n\n\tconfig.Status.Phase = gkeConfigActivePhase\n\treturn h.gkeCC.UpdateStatus(config)\n}", "func (h *Handler) importCluster(config *eksv1.EKSClusterConfig, awsSVCs *awsServices) (*eksv1.EKSClusterConfig, error) {\n\tif awsSVCs == nil {\n\t\treturn config, fmt.Errorf(\"aws services not initialized\")\n\t}\n\n\tclusterState, err := awsservices.GetClusterState(&awsservices.GetClusterStatusOpts{\n\t\tEKSService: awsSVCs.eks,\n\t\tConfig: config,\n\t})\n\tif err != nil {\n\t\treturn config, err\n\t}\n\n\tif err := h.createCASecret(config, clusterState); err != nil {\n\t\tif !apierrors.IsAlreadyExists(err) {\n\t\t\treturn config, err\n\t\t}\n\t}\n\n\tlaunchTemplatesOutput, err := awsSVCs.ec2.DescribeLaunchTemplates(&ec2.DescribeLaunchTemplatesInput{\n\t\tLaunchTemplateNames: []*string{aws.String(fmt.Sprintf(awsservices.LaunchTemplateNameFormat, config.Spec.DisplayName))},\n\t})\n\tif err == nil && len(launchTemplatesOutput.LaunchTemplates) > 0 {\n\t\tconfig.Status.ManagedLaunchTemplateID = aws.StringValue(launchTemplatesOutput.LaunchTemplates[0].LaunchTemplateId)\n\t}\n\n\tconfig.Status.Subnets = aws.StringValueSlice(clusterState.Cluster.ResourcesVpcConfig.SubnetIds)\n\tconfig.Status.SecurityGroups = aws.StringValueSlice(clusterState.Cluster.ResourcesVpcConfig.SecurityGroupIds)\n\tconfig.Status.Phase = eksConfigActivePhase\n\treturn h.eksCC.UpdateStatus(config)\n}", "func (c *Cluster) Import(ctx context.Context, nodeID int64, it *datapb.ImportTaskRequest) {\n\tc.sessionManager.Import(ctx, nodeID, it)\n}", "func (a *Client) V2ImportCluster(ctx context.Context, params *V2ImportClusterParams) (*V2ImportClusterCreated, error) {\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"v2ImportCluster\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/v2/clusters/import\",\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: &V2ImportClusterReader{formats: a.formats},\n\t\tAuthInfo: a.authInfo,\n\t\tContext: ctx,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*V2ImportClusterCreated), nil\n\n}", "func (s *BasePlSqlParserListener) EnterAlter_cluster(ctx *Alter_clusterContext) {}", "func (s *BasecluListener) EnterCluster(ctx *ClusterContext) {}", "func clusterOperations(adapter federatedtypes.FederatedTypeAdapter, selectedClusters []*federationapi.Cluster, unselectedClusters []*federationapi.Cluster, obj pkgruntime.Object, key string, schedulingInfo *federatedtypes.SchedulingInfo, accessor clusterObjectAccessorFunc) ([]util.FederatedOperation, error) {\n\toperations := make([]util.FederatedOperation, 0)\n\n\tkind := adapter.Kind()\n\tfor _, cluster := range selectedClusters {\n\t\t// The data should not be modified.\n\t\tdesiredObj := adapter.Copy(obj)\n\n\t\tclusterObj, found, err := accessor(cluster.Name)\n\t\tif err != nil {\n\t\t\twrappedErr := fmt.Errorf(\"Failed to get %s %q from cluster %q: %v\", kind, key, cluster.Name, err)\n\t\t\truntime.HandleError(wrappedErr)\n\t\t\treturn nil, wrappedErr\n\t\t}\n\n\t\tshouldCreateIfNeeded := true\n\t\tif adapter.IsSchedulingAdapter() {\n\t\t\tschedulingAdapter, ok := adapter.(federatedtypes.SchedulingAdapter)\n\t\t\tif !ok {\n\t\t\t\terr = fmt.Errorf(\"adapter for kind %s does not properly implement SchedulingAdapter.\", kind)\n\t\t\t\tglog.Fatalf(\"Error: %v\", err)\n\t\t\t}\n\t\t\tvar clusterTypedObj pkgruntime.Object = nil\n\t\t\tif clusterObj != nil {\n\t\t\t\tclusterTypedObj = clusterObj.(pkgruntime.Object)\n\t\t\t}\n\t\t\tdesiredObj, shouldCreateIfNeeded, err = schedulingAdapter.ScheduleObject(cluster, clusterTypedObj, desiredObj, schedulingInfo)\n\t\t\tif err != nil {\n\t\t\t\truntime.HandleError(err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tvar operationType util.FederatedOperationType = \"\"\n\t\tif found {\n\t\t\tclusterObj := clusterObj.(pkgruntime.Object)\n\t\t\tif !adapter.Equivalent(desiredObj, clusterObj) {\n\t\t\t\toperationType = util.OperationTypeUpdate\n\t\t\t}\n\t\t} else if shouldCreateIfNeeded {\n\t\t\toperationType = util.OperationTypeAdd\n\t\t}\n\n\t\tif len(operationType) > 0 {\n\t\t\toperations = append(operations, util.FederatedOperation{\n\t\t\t\tType: operationType,\n\t\t\t\tObj: desiredObj,\n\t\t\t\tClusterName: cluster.Name,\n\t\t\t\tKey: key,\n\t\t\t})\n\t\t}\n\t}\n\n\tfor _, cluster := range unselectedClusters {\n\t\tclusterObj, found, err := accessor(cluster.Name)\n\t\tif err != nil {\n\t\t\twrappedErr := fmt.Errorf(\"Failed to get %s %q from cluster %q: %v\", kind, key, cluster.Name, err)\n\t\t\truntime.HandleError(wrappedErr)\n\t\t\treturn nil, wrappedErr\n\t\t}\n\t\tif found {\n\t\t\toperations = append(operations, util.FederatedOperation{\n\t\t\t\tType: util.OperationTypeDelete,\n\t\t\t\tObj: clusterObj.(pkgruntime.Object),\n\t\t\t\tClusterName: cluster.Name,\n\t\t\t\tKey: key,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn operations, nil\n}", "func (m *Multicluster) initializeCluster(cluster *multicluster.Cluster, kubeController *kubeController, kubeRegistry *Controller,\n\toptions Options, configCluster bool, clusterStopCh <-chan struct{},\n) {\n\tclient := cluster.Client\n\n\tif m.serviceEntryController != nil && features.EnableServiceEntrySelectPods {\n\t\t// Add an instance handler in the kubernetes registry to notify service entry store about pod events\n\t\tkubeRegistry.AppendWorkloadHandler(m.serviceEntryController.WorkloadInstanceHandler)\n\t}\n\tif m.configController != nil && features.EnableAmbientControllers {\n\t\tm.configController.RegisterEventHandler(gvk.AuthorizationPolicy, kubeRegistry.AuthorizationPolicyHandler)\n\t\tm.configController.RegisterEventHandler(gvk.PeerAuthentication, kubeRegistry.PeerAuthenticationHandler)\n\t}\n\n\tif configCluster && m.serviceEntryController != nil && features.EnableEnhancedResourceScoping {\n\t\tkubeRegistry.AppendNamespaceDiscoveryHandlers(m.serviceEntryController.NamespaceDiscoveryHandler)\n\t}\n\n\t// TODO implement deduping in aggregate registry to allow multiple k8s registries to handle WorkloadEntry\n\tif features.EnableK8SServiceSelectWorkloadEntries {\n\t\tif m.serviceEntryController != nil && configCluster {\n\t\t\t// Add an instance handler in the service entry store to notify kubernetes about workload entry events\n\t\t\tm.serviceEntryController.AppendWorkloadHandler(kubeRegistry.WorkloadInstanceHandler)\n\t\t} else if features.WorkloadEntryCrossCluster {\n\t\t\t// TODO only do this for non-remotes, can't guarantee CRDs in remotes (depends on https://github.com/istio/istio/pull/29824)\n\t\t\tconfigStore := createWleConfigStore(client, m.revision, options)\n\t\t\tkubeController.workloadEntryController = serviceentry.NewWorkloadEntryController(\n\t\t\t\tconfigStore, options.XDSUpdater,\n\t\t\t\tserviceentry.WithClusterID(cluster.ID),\n\t\t\t\tserviceentry.WithNetworkIDCb(kubeRegistry.Network))\n\t\t\t// Services can select WorkloadEntry from the same cluster. We only duplicate the Service to configure kube-dns.\n\t\t\tkubeController.workloadEntryController.AppendWorkloadHandler(kubeRegistry.WorkloadInstanceHandler)\n\t\t\t// ServiceEntry selects WorkloadEntry from remote cluster\n\t\t\tkubeController.workloadEntryController.AppendWorkloadHandler(m.serviceEntryController.WorkloadInstanceHandler)\n\t\t\tif features.EnableEnhancedResourceScoping {\n\t\t\t\tkubeRegistry.AppendNamespaceDiscoveryHandlers(kubeController.workloadEntryController.NamespaceDiscoveryHandler)\n\t\t\t}\n\t\t\tm.opts.MeshServiceController.AddRegistryAndRun(kubeController.workloadEntryController, clusterStopCh)\n\t\t\tgo configStore.Run(clusterStopCh)\n\n\t\t}\n\t}\n\n\t// namespacecontroller requires discoverySelectors only if EnableEnhancedResourceScoping feature flag is set.\n\tvar discoveryNamespacesFilter namespace.DiscoveryNamespacesFilter\n\tif features.EnableEnhancedResourceScoping {\n\t\tdiscoveryNamespacesFilter = kubeRegistry.opts.DiscoveryNamespacesFilter\n\t}\n\n\t// run after WorkloadHandler is added\n\tm.opts.MeshServiceController.AddRegistryAndRun(kubeRegistry, clusterStopCh)\n\n\tgo func() {\n\t\tvar shouldLead bool\n\t\tif !configCluster {\n\t\t\tshouldLead = m.checkShouldLead(client, options.SystemNamespace, clusterStopCh)\n\t\t\tlog.Infof(\"should join leader-election for cluster %s: %t\", cluster.ID, shouldLead)\n\t\t}\n\t\tif m.startNsController && (shouldLead || configCluster) {\n\t\t\t// Block server exit on graceful termination of the leader controller.\n\t\t\tm.s.RunComponentAsyncAndWait(\"namespace controller\", func(_ <-chan struct{}) error {\n\t\t\t\tlog.Infof(\"joining leader-election for %s in %s on cluster %s\",\n\t\t\t\t\tleaderelection.NamespaceController, options.SystemNamespace, options.ClusterID)\n\t\t\t\telection := leaderelection.\n\t\t\t\t\tNewLeaderElectionMulticluster(options.SystemNamespace, m.serverID, leaderelection.NamespaceController, m.revision, !configCluster, client).\n\t\t\t\t\tAddRunFunction(func(leaderStop <-chan struct{}) {\n\t\t\t\t\t\tlog.Infof(\"starting namespace controller for cluster %s\", cluster.ID)\n\t\t\t\t\t\tnc := NewNamespaceController(client, m.caBundleWatcher, discoveryNamespacesFilter)\n\t\t\t\t\t\t// Start informers again. This fixes the case where informers for namespace do not start,\n\t\t\t\t\t\t// as we create them only after acquiring the leader lock\n\t\t\t\t\t\t// Note: stop here should be the overall pilot stop, NOT the leader election stop. We are\n\t\t\t\t\t\t// basically lazy loading the informer, if we stop it when we lose the lock we will never\n\t\t\t\t\t\t// recreate it again.\n\t\t\t\t\t\tclient.RunAndWait(clusterStopCh)\n\t\t\t\t\t\tnc.Run(leaderStop)\n\t\t\t\t\t})\n\t\t\t\telection.Run(clusterStopCh)\n\t\t\t\treturn nil\n\t\t\t})\n\t\t}\n\t\t// Set up injection webhook patching for remote clusters we are controlling.\n\t\t// The config cluster has this patching set up elsewhere. We may eventually want to move it here.\n\t\t// We can not use leader election for webhook patching because each revision needs to patch its own\n\t\t// webhook.\n\t\tif shouldLead && !configCluster && m.caBundleWatcher != nil {\n\t\t\t// Patch injection webhook cert\n\t\t\t// This requires RBAC permissions - a low-priv Istiod should not attempt to patch but rely on\n\t\t\t// operator or CI/CD\n\t\t\tif features.InjectionWebhookConfigName != \"\" {\n\t\t\t\tlog.Infof(\"initializing injection webhook cert patcher for cluster %s\", cluster.ID)\n\t\t\t\tpatcher, err := webhooks.NewWebhookCertPatcher(client, m.revision, webhookName, m.caBundleWatcher)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"could not initialize webhook cert patcher: %v\", err)\n\t\t\t\t} else {\n\t\t\t\t\tgo patcher.Run(clusterStopCh)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\t// setting up the serviceexport controller if and only if it is turned on in the meshconfig.\n\tif features.EnableMCSAutoExport {\n\t\tlog.Infof(\"joining leader-election for %s in %s on cluster %s\",\n\t\t\tleaderelection.ServiceExportController, options.SystemNamespace, options.ClusterID)\n\t\t// Block server exit on graceful termination of the leader controller.\n\t\tm.s.RunComponentAsyncAndWait(\"auto serviceexport controller\", func(_ <-chan struct{}) error {\n\t\t\tleaderelection.\n\t\t\t\tNewLeaderElectionMulticluster(options.SystemNamespace, m.serverID, leaderelection.ServiceExportController, m.revision, !configCluster, client).\n\t\t\t\tAddRunFunction(func(leaderStop <-chan struct{}) {\n\t\t\t\t\tserviceExportController := newAutoServiceExportController(autoServiceExportOptions{\n\t\t\t\t\t\tClient: client,\n\t\t\t\t\t\tClusterID: options.ClusterID,\n\t\t\t\t\t\tDomainSuffix: options.DomainSuffix,\n\t\t\t\t\t\tClusterLocal: m.clusterLocal,\n\t\t\t\t\t})\n\t\t\t\t\t// Start informers again. This fixes the case where informers do not start,\n\t\t\t\t\t// as we create them only after acquiring the leader lock\n\t\t\t\t\t// Note: stop here should be the overall pilot stop, NOT the leader election stop. We are\n\t\t\t\t\t// basically lazy loading the informer, if we stop it when we lose the lock we will never\n\t\t\t\t\t// recreate it again.\n\t\t\t\t\tclient.RunAndWait(clusterStopCh)\n\t\t\t\t\tserviceExportController.Run(leaderStop)\n\t\t\t\t}).Run(clusterStopCh)\n\t\t\treturn nil\n\t\t})\n\t}\n}", "func (s *IngestStep) Cluster(schemaFile string, dataset string,\n\trootDataPath string, outputFolder string, hasHeader bool) error {\n\toutputSchemaPath := path.Join(outputFolder, D3MSchemaPathRelative)\n\toutputDataPath := path.Join(outputFolder, D3MDataPathRelative)\n\tsourceFolder := path.Dir(dataset)\n\n\t// copy the source folder to have all the linked files for merging\n\tos.MkdirAll(outputFolder, os.ModePerm)\n\terr := copy.Copy(sourceFolder, outputFolder)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"unable to copy source data\")\n\t}\n\n\t// delete the existing files that will be overwritten\n\tos.Remove(outputSchemaPath)\n\tos.Remove(outputDataPath)\n\n\t// load metadata from original schema\n\tmeta, err := metadata.LoadMetadataFromOriginalSchema(schemaFile)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"unable to load original schema file\")\n\t}\n\tmainDR := meta.GetMainDataResource()\n\n\t// add feature variables\n\tfeatures, err := getClusterVariables(meta, \"_cluster_\")\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"unable to get cluster variables\")\n\t}\n\n\td3mIndexField := getD3MIndexField(mainDR)\n\n\t// open the input file\n\tdataPath := path.Join(rootDataPath, mainDR.ResPath)\n\tlines, err := s.readCSVFile(dataPath, hasHeader)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error reading raw data\")\n\t}\n\n\t// add the cluster data to the raw data\n\tfor _, f := range features {\n\t\tmainDR.Variables = append(mainDR.Variables, f.Variable)\n\n\t\tlines, err = s.appendFeature(sourceFolder, d3mIndexField, false, f, lines)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"error appending clustered data\")\n\t\t}\n\t}\n\n\t// initialize csv writer\n\toutput := &bytes.Buffer{}\n\twriter := csv.NewWriter(output)\n\n\t// output the header\n\theader := make([]string, len(mainDR.Variables))\n\tfor _, v := range mainDR.Variables {\n\t\theader[v.Index] = v.Name\n\t}\n\terr = writer.Write(header)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error storing clustered header\")\n\t}\n\n\tfor _, line := range lines {\n\t\terr = writer.Write(line)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"error storing clustered output\")\n\t\t}\n\t}\n\n\t// output the data with the new feature\n\twriter.Flush()\n\n\terr = util.WriteFileWithDirs(outputDataPath, output.Bytes(), os.ModePerm)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error writing clustered output\")\n\t}\n\n\trelativePath := getRelativePath(path.Dir(outputSchemaPath), outputDataPath)\n\tmainDR.ResPath = relativePath\n\n\t// write the new schema to file\n\terr = metadata.WriteSchema(meta, outputSchemaPath)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"unable to store cluster schema\")\n\t}\n\n\treturn nil\n}", "func (c ClusterNodes) Add() {\n\n}", "func (s *FederationSyncController) clusterOperations(selectedClusters, unselectedClusters []string,\n\ttemplate, override *unstructured.Unstructured, key string) ([]util.FederatedOperation, error) {\n\n\toperations := make([]util.FederatedOperation, 0)\n\n\toverridesMap, err := util.GetOverrides(override)\n\tif err != nil {\n\t\toverrideKind := s.typeConfig.GetOverride().Kind\n\t\treturn nil, fmt.Errorf(\"Error reading cluster overrides for %s %q: %v\", overrideKind, key, err)\n\t}\n\n\tversionMap, err := s.versionManager.Get(template, override)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error retrieving version map: %v\", err)\n\t}\n\n\ttargetKind := s.typeConfig.GetTarget().Kind\n\tfor _, clusterName := range selectedClusters {\n\t\t// TODO(marun) Create the desired object only if needed\n\t\tdesiredObj, err := s.objectForCluster(template, overridesMap[clusterName])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// TODO(marun) Wait until result of add operation has reached\n\t\t// the target store before attempting subsequent operations?\n\t\t// Otherwise the object won't be found but an add operation\n\t\t// will fail with AlreadyExists.\n\t\tclusterObj, found, err := s.informer.GetTargetStore().GetByKey(clusterName, key)\n\t\tif err != nil {\n\t\t\twrappedErr := fmt.Errorf(\"Failed to get %s %q from cluster %q: %v\", targetKind, key, clusterName, err)\n\t\t\truntime.HandleError(wrappedErr)\n\t\t\treturn nil, wrappedErr\n\t\t}\n\n\t\tvar operationType util.FederatedOperationType = \"\"\n\n\t\tif found {\n\t\t\tclusterObj := clusterObj.(*unstructured.Unstructured)\n\n\t\t\t// This controller does not perform updates to namespaces\n\t\t\t// in the host cluster. Such operations need to be\n\t\t\t// performed via the Kube API.\n\t\t\t//\n\t\t\t// The Namespace type is a special case because it is the\n\t\t\t// only container in the Kubernetes API. This controller\n\t\t\t// presumes a separation between the template and target\n\t\t\t// resources, but a namespace in the host cluster is\n\t\t\t// necessarily both template and target.\n\t\t\tif targetKind == util.NamespaceKind && util.IsPrimaryCluster(template, clusterObj) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tdesiredObj, err = s.objectForUpdateOp(desiredObj, clusterObj)\n\t\t\tif err != nil {\n\t\t\t\twrappedErr := fmt.Errorf(\"Failed to determine desired object %s %q for cluster %q: %v\", targetKind, key, clusterName, err)\n\t\t\t\truntime.HandleError(wrappedErr)\n\t\t\t\treturn nil, wrappedErr\n\t\t\t}\n\n\t\t\tversion, ok := versionMap[clusterName]\n\t\t\tif !ok {\n\t\t\t\t// No target version recorded for template+override version\n\t\t\t\toperationType = util.OperationTypeUpdate\n\t\t\t} else {\n\t\t\t\ttargetVersion := s.comparisonHelper.GetVersion(clusterObj)\n\n\t\t\t\t// Check if versions don't match. If they match then check its\n\t\t\t\t// ObjectMeta which only applies to resources where Generation\n\t\t\t\t// is used to track versions because Generation is only updated\n\t\t\t\t// when Spec changes.\n\t\t\t\tif version != targetVersion {\n\t\t\t\t\toperationType = util.OperationTypeUpdate\n\t\t\t\t} else if !s.comparisonHelper.Equivalent(desiredObj, clusterObj) {\n\t\t\t\t\t// TODO(marun) Since only the metadata is compared\n\t\t\t\t\t// in the call to Equivalent(), use the template\n\t\t\t\t\t// to avoid having to worry about overrides.\n\t\t\t\t\toperationType = util.OperationTypeUpdate\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// A namespace in the host cluster will never need to be\n\t\t\t// added since by definition it must already exist.\n\n\t\t\toperationType = util.OperationTypeAdd\n\t\t}\n\n\t\tif len(operationType) > 0 {\n\t\t\toperations = append(operations, util.FederatedOperation{\n\t\t\t\tType: operationType,\n\t\t\t\tObj: desiredObj,\n\t\t\t\tClusterName: clusterName,\n\t\t\t\tKey: key,\n\t\t\t})\n\t\t}\n\t}\n\n\tfor _, clusterName := range unselectedClusters {\n\t\trawClusterObj, found, err := s.informer.GetTargetStore().GetByKey(clusterName, key)\n\t\tif err != nil {\n\t\t\twrappedErr := fmt.Errorf(\"Failed to get %s %q from cluster %q: %v\", targetKind, key, clusterName, err)\n\t\t\truntime.HandleError(wrappedErr)\n\t\t\treturn nil, wrappedErr\n\t\t}\n\t\tif found {\n\t\t\tclusterObj := rawClusterObj.(pkgruntime.Object)\n\t\t\t// This controller does not initiate deletion of namespaces in the host cluster.\n\t\t\tif targetKind == util.NamespaceKind && util.IsPrimaryCluster(template, clusterObj) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\toperations = append(operations, util.FederatedOperation{\n\t\t\t\tType: util.OperationTypeDelete,\n\t\t\t\tObj: clusterObj,\n\t\t\t\tClusterName: clusterName,\n\t\t\t\tKey: key,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn operations, nil\n}", "func (client RoverClusterClient) requestAdditionalNodes(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/roverClusters/{roverClusterId}/actions/requestAdditionalNodes\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response RequestAdditionalNodesResponse\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\tapiReferenceLink := \"https://docs.oracle.com/iaas/api/#/en/rover/20201210/RoverCluster/RequestAdditionalNodes\"\n\t\terr = common.PostProcessServiceError(err, \"RoverCluster\", \"RequestAdditionalNodes\", apiReferenceLink)\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func addMasterClusterReconcilers(ctx context.Context, mgr manager.Manager, discoveryReconcilers reconcilers.DiscoveryReconcilers) error {\n\terr := smh_discovery_controller.\n\t\tNewMeshReconcileLoop(\"meshes\", mgr, reconcile.Options{}).\n\t\tRunMeshReconciler(ctx, discoveryReconcilers)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = smh_discovery_controller.\n\t\tNewMeshWorkloadReconcileLoop(\"mesh-workloads\", mgr, reconcile.Options{}).\n\t\tRunMeshWorkloadReconciler(ctx, discoveryReconcilers)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *operations) InsertUpgradeClusterOperation(operation internal.UpgradeClusterOperation) error {\n\tsession := s.NewWriteSession()\n\tdto, err := s.upgradeClusterOperationToDTO(&operation)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"while converting upgrade cluser operation (id: %s)\", operation.Operation.ID)\n\t}\n\tvar lastErr error\n\t_ = wait.PollImmediate(defaultRetryInterval, defaultRetryTimeout, func() (bool, error) {\n\t\tlastErr = session.InsertOperation(dto)\n\t\tif lastErr != nil {\n\t\t\tlog.Errorf(\"while insert operation: %v\", err)\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn true, nil\n\t})\n\treturn lastErr\n}", "func loadClusterInformationFromStore(ctx context.Context, svc *config.Config, clusterMsg persistence.ClusterMetadataManager, logger log.Logger) error {\n\titer := collection.NewPagingIterator(func(paginationToken []byte) ([]interface{}, []byte, error) {\n\t\trequest := &persistence.ListClusterMetadataRequest{\n\t\t\tPageSize: 100,\n\t\t\tNextPageToken: nil,\n\t\t}\n\t\tresp, err := clusterMsg.ListClusterMetadata(ctx, request)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tvar pageItem []interface{}\n\t\tfor _, metadata := range resp.ClusterMetadata {\n\t\t\tpageItem = append(pageItem, metadata)\n\t\t}\n\t\treturn pageItem, resp.NextPageToken, nil\n\t})\n\n\tfor iter.HasNext() {\n\t\titem, err := iter.Next()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmetadata := item.(*persistence.GetClusterMetadataResponse)\n\t\tshardCount := metadata.HistoryShardCount\n\t\tif shardCount == 0 {\n\t\t\t// This is to add backward compatibility to the svc based cluster connection.\n\t\t\tshardCount = svc.Persistence.NumHistoryShards\n\t\t}\n\t\tnewMetadata := cluster.ClusterInformation{\n\t\t\tEnabled: metadata.IsConnectionEnabled,\n\t\t\tInitialFailoverVersion: metadata.InitialFailoverVersion,\n\t\t\tRPCAddress: metadata.ClusterAddress,\n\t\t\tShardCount: shardCount,\n\t\t\tTags: metadata.Tags,\n\t\t}\n\t\tif staticClusterMetadata, ok := svc.ClusterMetadata.ClusterInformation[metadata.ClusterName]; ok {\n\t\t\tif metadata.ClusterName != svc.ClusterMetadata.CurrentClusterName {\n\t\t\t\tlogger.Warn(\n\t\t\t\t\t\"ClusterInformation in ClusterMetadata svc is deprecated. Please use TCTL tool to configure remote cluster connections\",\n\t\t\t\t\ttag.Key(\"clusterInformation\"),\n\t\t\t\t\ttag.IgnoredValue(staticClusterMetadata),\n\t\t\t\t\ttag.Value(newMetadata))\n\t\t\t} else {\n\t\t\t\tnewMetadata.RPCAddress = staticClusterMetadata.RPCAddress\n\t\t\t\tlogger.Info(fmt.Sprintf(\"Use rpc address %v for cluster %v.\", newMetadata.RPCAddress, metadata.ClusterName))\n\t\t\t}\n\t\t}\n\t\tsvc.ClusterMetadata.ClusterInformation[metadata.ClusterName] = newMetadata\n\t}\n\treturn nil\n}", "func (config *DirectClientConfig) getCluster() (clientcmdapi.Cluster, error) {\n\tclusterInfos := config.config.Clusters\n\tclusterInfoName, required := config.getClusterName()\n\n\tmergedClusterInfo := clientcmdapi.NewCluster()\n\tif config.overrides != nil {\n\t\tmergo.Merge(mergedClusterInfo, config.overrides.ClusterDefaults, mergo.WithOverride)\n\t}\n\tif configClusterInfo, exists := clusterInfos[clusterInfoName]; exists {\n\t\tmergo.Merge(mergedClusterInfo, configClusterInfo, mergo.WithOverride)\n\t} else if required {\n\t\treturn clientcmdapi.Cluster{}, fmt.Errorf(\"cluster %q does not exist\", clusterInfoName)\n\t}\n\tif config.overrides != nil {\n\t\tmergo.Merge(mergedClusterInfo, config.overrides.ClusterInfo, mergo.WithOverride)\n\t}\n\n\t// * An override of --insecure-skip-tls-verify=true and no accompanying CA/CA data should clear already-set CA/CA data\n\t// otherwise, a kubeconfig containing a CA reference would return an error that \"CA and insecure-skip-tls-verify couldn't both be set\".\n\t// * An override of --certificate-authority should also override TLS skip settings and CA data, otherwise existing CA data will take precedence.\n\tif config.overrides != nil {\n\t\tcaLen := len(config.overrides.ClusterInfo.CertificateAuthority)\n\t\tcaDataLen := len(config.overrides.ClusterInfo.CertificateAuthorityData)\n\t\tif config.overrides.ClusterInfo.InsecureSkipTLSVerify || caLen > 0 || caDataLen > 0 {\n\t\t\tmergedClusterInfo.InsecureSkipTLSVerify = config.overrides.ClusterInfo.InsecureSkipTLSVerify\n\t\t\tmergedClusterInfo.CertificateAuthority = config.overrides.ClusterInfo.CertificateAuthority\n\t\t\tmergedClusterInfo.CertificateAuthorityData = config.overrides.ClusterInfo.CertificateAuthorityData\n\t\t}\n\n\t\t// if the --tls-server-name has been set in overrides, use that value.\n\t\t// if the --server has been set in overrides, then use the value of --tls-server-name specified on the CLI too. This gives the property\n\t\t// that setting a --server will effectively clear the KUBECONFIG value of tls-server-name if it is specified on the command line which is\n\t\t// usually correct.\n\t\tif config.overrides.ClusterInfo.TLSServerName != \"\" || config.overrides.ClusterInfo.Server != \"\" {\n\t\t\tmergedClusterInfo.TLSServerName = config.overrides.ClusterInfo.TLSServerName\n\t\t}\n\t}\n\n\treturn *mergedClusterInfo, nil\n}", "func createCluster(\n\tctx context.Context,\n\tc *cli.Context,\n\tcfgHelper *cmdutils.ConfigHelper,\n\thost host.Host,\n\tpubsub *pubsub.PubSub,\n\tdht *dual.DHT,\n\tstore ds.Datastore,\n\traftStaging bool,\n) (*ipfscluster.Cluster, error) {\n\n\tcfgs := cfgHelper.Configs()\n\tcfgMgr := cfgHelper.Manager()\n\tcfgBytes, err := cfgMgr.ToDisplayJSON()\n\tcheckErr(\"getting configuration string\", err)\n\tlogger.Debugf(\"Configuration:\\n%s\\n\", cfgBytes)\n\n\tctx, err = tag.New(ctx, tag.Upsert(observations.HostKey, host.ID().Pretty()))\n\tcheckErr(\"tag context with host id\", err)\n\n\terr = observations.SetupMetrics(cfgs.Metrics)\n\tcheckErr(\"setting up Metrics\", err)\n\n\ttracer, err := observations.SetupTracing(cfgs.Tracing)\n\tcheckErr(\"setting up Tracing\", err)\n\n\tvar apis []ipfscluster.API\n\tif cfgMgr.IsLoadedFromJSON(config.API, cfgs.Restapi.ConfigKey()) {\n\t\tvar api *rest.API\n\t\t// Do NOT enable default Libp2p API endpoint on CRDT\n\t\t// clusters. Collaborative clusters are likely to share the\n\t\t// secret with untrusted peers, thus the API would be open for\n\t\t// anyone.\n\t\tif cfgHelper.GetConsensus() == cfgs.Raft.ConfigKey() {\n\t\t\tapi, err = rest.NewAPIWithHost(ctx, cfgs.Restapi, host)\n\t\t} else {\n\t\t\tapi, err = rest.NewAPI(ctx, cfgs.Restapi)\n\t\t}\n\t\tcheckErr(\"creating REST API component\", err)\n\t\tapis = append(apis, api)\n\n\t}\n\n\tif cfgMgr.IsLoadedFromJSON(config.API, cfgs.Pinsvcapi.ConfigKey()) {\n\t\tpinsvcapi, err := pinsvcapi.NewAPI(ctx, cfgs.Pinsvcapi)\n\t\tcheckErr(\"creating Pinning Service API component\", err)\n\n\t\tapis = append(apis, pinsvcapi)\n\t}\n\n\tif cfgMgr.IsLoadedFromJSON(config.API, cfgs.Ipfsproxy.ConfigKey()) {\n\t\tproxy, err := ipfsproxy.New(cfgs.Ipfsproxy)\n\t\tcheckErr(\"creating IPFS Proxy component\", err)\n\n\t\tapis = append(apis, proxy)\n\t}\n\n\tconnector, err := ipfshttp.NewConnector(cfgs.Ipfshttp)\n\tcheckErr(\"creating IPFS Connector component\", err)\n\n\tvar informers []ipfscluster.Informer\n\tif cfgMgr.IsLoadedFromJSON(config.Informer, cfgs.DiskInf.ConfigKey()) {\n\t\tdiskInf, err := disk.NewInformer(cfgs.DiskInf)\n\t\tcheckErr(\"creating disk informer\", err)\n\t\tinformers = append(informers, diskInf)\n\t}\n\tif cfgMgr.IsLoadedFromJSON(config.Informer, cfgs.TagsInf.ConfigKey()) {\n\t\ttagsInf, err := tags.New(cfgs.TagsInf)\n\t\tcheckErr(\"creating numpin informer\", err)\n\t\tinformers = append(informers, tagsInf)\n\t}\n\n\tif cfgMgr.IsLoadedFromJSON(config.Informer, cfgs.PinQueueInf.ConfigKey()) {\n\t\tpinQueueInf, err := pinqueue.New(cfgs.PinQueueInf)\n\t\tcheckErr(\"creating pinqueue informer\", err)\n\t\tinformers = append(informers, pinQueueInf)\n\t}\n\n\t// For legacy compatibility we need to make the allocator\n\t// automatically compatible with informers that have been loaded. For\n\t// simplicity we assume that anyone that does not specify an allocator\n\t// configuration (legacy configs), will be using \"freespace\"\n\tif !cfgMgr.IsLoadedFromJSON(config.Allocator, cfgs.BalancedAlloc.ConfigKey()) {\n\t\tcfgs.BalancedAlloc.AllocateBy = []string{\"freespace\"}\n\t}\n\talloc, err := balanced.New(cfgs.BalancedAlloc)\n\tcheckErr(\"creating allocator\", err)\n\n\tcons, err := setupConsensus(\n\t\tcfgHelper,\n\t\thost,\n\t\tdht,\n\t\tpubsub,\n\t\tstore,\n\t\traftStaging,\n\t)\n\tif err != nil {\n\t\tstore.Close()\n\t\tcheckErr(\"setting up Consensus\", err)\n\t}\n\n\tvar peersF func(context.Context) ([]peer.ID, error)\n\tif cfgHelper.GetConsensus() == cfgs.Raft.ConfigKey() {\n\t\tpeersF = cons.Peers\n\t}\n\n\ttracker := stateless.New(cfgs.Statelesstracker, host.ID(), cfgs.Cluster.Peername, cons.State)\n\tlogger.Debug(\"stateless pintracker loaded\")\n\n\tmon, err := pubsubmon.New(ctx, cfgs.Pubsubmon, pubsub, peersF)\n\tif err != nil {\n\t\tstore.Close()\n\t\tcheckErr(\"setting up PeerMonitor\", err)\n\t}\n\n\treturn ipfscluster.NewCluster(\n\t\tctx,\n\t\thost,\n\t\tdht,\n\t\tcfgs.Cluster,\n\t\tstore,\n\t\tcons,\n\t\tapis,\n\t\tconnector,\n\t\ttracker,\n\t\tmon,\n\t\talloc,\n\t\tinformers,\n\t\ttracer,\n\t)\n}", "func (cv ClusterVersion) ClusterVersionImpl() {}", "func (s *BasePlSqlParserListener) EnterCreate_cluster(ctx *Create_clusterContext) {}", "func SyncClusterInfoToPassCC(taskID string, cluster *proto.Cluster) {\n\terr := passcc.GetCCClient().CreatePassCCCluster(cluster)\n\tif err != nil {\n\t\tblog.Errorf(\"UpdateCreateClusterDBInfoTask[%s] syncClusterInfoToPassCC CreatePassCCCluster[%s] failed: %v\",\n\t\t\ttaskID, cluster.ClusterID, err)\n\t} else {\n\t\tblog.Infof(\"UpdateCreateClusterDBInfoTask[%s] syncClusterInfoToPassCC CreatePassCCCluster[%s] successful\",\n\t\t\ttaskID, cluster.ClusterID)\n\t}\n\n\terr = passcc.GetCCClient().CreatePassCCClusterSnapshoot(cluster)\n\tif err != nil {\n\t\tblog.Errorf(\"UpdateCreateClusterDBInfoTask[%s] syncClusterInfoToPassCC CreatePassCCClusterSnapshoot[%s] failed: %v\",\n\t\t\ttaskID, cluster.ClusterID, err)\n\t} else {\n\t\tblog.Infof(\"UpdateCreateClusterDBInfoTask[%s] syncClusterInfoToPassCC CreatePassCCClusterSnapshoot[%s] successful\",\n\t\t\ttaskID, cluster.ClusterID)\n\t}\n}", "func (client *Client) ServiceMeshAddClusterWithCallback(request *ServiceMeshAddClusterRequest, callback func(response *ServiceMeshAddClusterResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *ServiceMeshAddClusterResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.ServiceMeshAddCluster(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func AddCapabilityIntoCluster(c client.Client, mapper discoverymapper.DiscoveryMapper, capability string) (string, error) {\n\tss := strings.Split(capability, \"/\")\n\tif len(ss) < 2 {\n\t\treturn \"\", errors.New(\"invalid format for \" + capability + \", please follow format <center>/<name>\")\n\t}\n\trepoName := ss[0]\n\tname := ss[1]\n\tioStreams := cmdutil.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr}\n\tif err := InstallCapability(c, mapper, repoName, name, ioStreams); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"Successfully installed capability %s from %s\", name, repoName), nil\n}", "func (c *HandlerComp) intClusterUpdate(params ops.ClusterUpdateParams, ai *auth.Info, oObj *models.Cluster) (*models.Cluster, error) {\n\tctx := params.HTTPRequest.Context()\n\tvar err error\n\tif ai == nil {\n\t\tai, err = c.GetAuthInfo(params.HTTPRequest)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tvar uP = [centrald.NumActionTypes][]string{\n\t\tcentrald.UpdateRemove: params.Remove,\n\t\tcentrald.UpdateAppend: params.Append,\n\t\tcentrald.UpdateSet: params.Set,\n\t}\n\tua, err := c.MakeStdUpdateArgs(emptyCluster, params.ID, params.Version, uP)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif params.Payload == nil {\n\t\terr = c.eUpdateInvalidMsg(\"missing payload\")\n\t\treturn nil, err\n\t}\n\tif ua.IsModified(\"Name\") && params.Payload.Name == \"\" {\n\t\terr := c.eUpdateInvalidMsg(\"non-empty name is required\")\n\t\treturn nil, err\n\t}\n\tif oObj == nil {\n\t\tc.RLock()\n\t\tdefer c.RUnlock()\n\t\tc.ClusterLock()\n\t\tdefer c.ClusterUnlock()\n\t\toObj, err = c.DS.OpsCluster().Fetch(ctx, params.ID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif ua.IsModified(\"ClusterUsagePolicy\") {\n\t\tif oObj.State != common.ClusterStateDeployable {\n\t\t\terr := c.eUpdateInvalidMsg(\"invalid state\")\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := c.validateClusterUsagePolicy(params.Payload.ClusterUsagePolicy, common.AccountSecretScopeCluster); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif ua.Version == 0 {\n\t\tua.Version = int32(oObj.Meta.Version)\n\t} else if int32(oObj.Meta.Version) != ua.Version {\n\t\terr = centrald.ErrorIDVerNotFound\n\t\treturn nil, err\n\t}\n\tif err = c.app.AuditLog.Ready(); err != nil {\n\t\treturn nil, err\n\t}\n\tif ua.IsModified(\"ClusterVersion\") || ua.IsModified(\"Service\") || ua.IsModified(\"ClusterAttributes\") || ua.IsModified(\"ClusterIdentifier\") || ua.IsModified(\"State\") || ua.IsModified(\"Messages\") {\n\t\tif err = ai.InternalOK(); err != nil {\n\t\t\tc.app.AuditLog.Post(ctx, ai, centrald.ClusterUpdateAction, models.ObjID(params.ID), models.ObjName(oObj.Name), \"\", true, \"Update unauthorized\")\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tif err = ai.CapOK(centrald.CSPDomainManagementCap, models.ObjIDMutable(oObj.AccountID)); err != nil {\n\t\t\tc.app.AuditLog.Post(ctx, ai, centrald.ClusterUpdateAction, models.ObjID(params.ID), models.ObjName(oObj.Name), \"\", true, \"Update unauthorized\")\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif ua.IsModified(\"ClusterIdentifier\") {\n\t\tif !ua.IsModified(\"State\") {\n\t\t\terr := c.eMissingMsg(\"state must be set with clusterIdentifier\")\n\t\t\treturn nil, err\n\t\t}\n\t\t// when transitioning to DEPLOYABLE state ClusterIdentifier must be reset, e.g. set to empty string\n\t\tif params.Payload.State == common.ClusterStateDeployable && params.Payload.ClusterIdentifier != \"\" {\n\t\t\terr := c.eMissingMsg(\"clusterIdentifier must be cleared when transitioning to %s\", common.ClusterStateDeployable)\n\t\t\treturn nil, err\n\t\t}\n\t\t// ClusterIdentifier may be modified (set to non-empty value) only when changing state from DEPLOYABLE to MANAGED\n\t\tif !(oObj.State == common.ClusterStateDeployable && params.Payload.State == common.ClusterStateManaged) {\n\t\t\terr := c.eInvalidState(\"invalid state transition (%s ⇒ %s)\", oObj.State, params.Payload.State)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif ua.IsModified(\"State\") {\n\t\tif !c.validateClusterState(params.Payload.State) {\n\t\t\terr := c.eUpdateInvalidMsg(\"invalid cluster state\")\n\t\t\treturn nil, err\n\t\t}\n\t\t// when transitioning from DEPLOYABLE state to MANAGED ClusterIdentifier is required\n\t\tif oObj.State == common.ClusterStateDeployable && params.Payload.State == common.ClusterStateManaged && (!ua.IsModified(\"ClusterIdentifier\") || params.Payload.ClusterIdentifier == \"\") {\n\t\t\terr := c.eMissingMsg(\"clusterIdentifier must be set when transitioning to %s\", common.ClusterStateManaged)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tdom, err := c.ops.intCspDomainFetch(ctx, ai, string(oObj.CspDomainID))\n\tif err != nil {\n\t\tc.Log.Errorf(\"Cluster[%s]: error looking up CSPDomain[%s]: %s\", oObj.Meta.ID, oObj.CspDomainID, err.Error())\n\t\treturn nil, err\n\t}\n\tdetail := \"\"\n\tif a := ua.FindUpdateAttr(\"AuthorizedAccounts\"); a != nil && a.IsModified() {\n\t\tdetail, err = c.authAccountValidator.validateAuthorizedAccountsUpdate(ctx, ai, centrald.ClusterUpdateAction, params.ID, models.ObjName(oObj.Name), a, oObj.AuthorizedAccounts, params.Payload.AuthorizedAccounts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\t// TBD: validate clusterAttributes by clusterType\n\tobj, err := c.DS.OpsCluster().Update(ctx, ua, params.Payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.clusterApplyInheritedProperties(ctx, ai, obj, dom) // no error possible\n\tif len(detail) > 0 {\n\t\tc.app.AuditLog.Post(ctx, ai, centrald.ClusterUpdateAction, models.ObjID(params.ID), models.ObjName(oObj.Name), \"\", false, fmt.Sprintf(\"Updated authorizedAccounts %s\", detail))\n\t}\n\tc.setDefaultObjectScope(params.HTTPRequest, obj)\n\treturn obj, nil\n}", "func (z *zpoolctl) Import3(ctx context.Context, name, dir, file string, force, n bool) *execute {\n\targs := []string{\"import\"}\n\tswitch {\n\tcase len(dir) > 0:\n\t\targs = append(args, \"-d \"+dir)\n\tcase len(file) > 0:\n\t\targs = append(args, \"-c \"+file)\n\t}\n\tif force {\n\t\targs = append(args, \"-f\")\n\t\tif n {\n\t\t\targs = append(args, \"-n\")\n\t\t}\n\t}\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func (m *InstallManager) provisionCluster() error {\n\n\tm.log.Info(\"running openshift-install create cluster\")\n\n\tif err := m.runOpenShiftInstallCommand(\"create\", \"cluster\"); err != nil {\n\t\tif m.isBootstrapComplete() {\n\t\t\tm.log.WithError(err).Warn(\"provisioning cluster failed after completing bootstrapping, waiting longer for install to complete\")\n\t\t\terr = m.runOpenShiftInstallCommand(\"wait-for\", \"install-complete\")\n\t\t}\n\t\tif err != nil {\n\t\t\tm.log.WithError(err).Error(\"error provisioning cluster\")\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (m *Multicluster) addCluster(cluster *multicluster.Cluster) (*kubeController, *Controller, *Options, bool) {\n\tif m.closing {\n\t\treturn nil, nil, nil, false\n\t}\n\n\tclient := cluster.Client\n\tconfigCluster := m.opts.ClusterID == cluster.ID\n\n\toptions := m.opts\n\toptions.ClusterID = cluster.ID\n\tif !configCluster {\n\t\toptions.SyncTimeout = features.RemoteClusterTimeout\n\t}\n\t// config cluster's DiscoveryNamespacesFilter is shared by both configController and serviceController\n\t// it is initiated in bootstrap initMulticluster function, pass to service controller to update it.\n\t// For other clusters, it should filter by its own cluster's namespace.\n\tif !configCluster {\n\t\toptions.DiscoveryNamespacesFilter = nil\n\t}\n\toptions.ConfigController = m.configController\n\tlog.Infof(\"Initializing Kubernetes service registry %q\", options.ClusterID)\n\toptions.ConfigCluster = configCluster\n\tkubeRegistry := NewController(client, options)\n\tkubeController := &kubeController{\n\t\tController: kubeRegistry,\n\t}\n\tm.remoteKubeControllers[cluster.ID] = kubeController\n\treturn kubeController, kubeRegistry, &options, configCluster\n}", "func ClusterOldAndNewFromRequest(request *webhook.Request) (*v3.Cluster, *v3.Cluster, error) {\n\tvar object runtime.Object\n\tvar err error\n\tif request.Operation != admissionv1.Delete {\n\t\tobject, err = request.DecodeObject()\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t} else {\n\t\tobject = &v3.Cluster{}\n\t}\n\n\tif request.Operation == admissionv1.Create {\n\t\treturn &v3.Cluster{}, object.(*v3.Cluster), nil\n\t}\n\n\toldObject, err := request.DecodeOldObject()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn oldObject.(*v3.Cluster), object.(*v3.Cluster), nil\n}", "func (r *reconciler) AddMulticlusterConfig(newconfig istiomodel.Config) (*ConfigChanges, error) {\n\n\tistioConfigs, svcs, err := model.ConvertBindingsAndExposures2(\n\t\t[]istiomodel.Config{newconfig}, r.clusterInfo, r.store, r.services)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toutAdditions := make([]istiomodel.Config, 0)\n\toutModifications := make([]istiomodel.Config, 0)\n\tfor _, istioConfig := range istioConfigs {\n\t\torig, ok := r.store.Get(istioConfig.Type, istioConfig.Name, getNamespace(istioConfig))\n\t\tif !ok {\n\t\t\toutAdditions = append(outAdditions, istioConfig)\n\t\t} else {\n\t\t\tif !reflect.DeepEqual(istioConfig.Spec, orig.Spec) {\n\t\t\t\toutModifications = append(outModifications, istioConfig)\n\t\t\t}\n\t\t}\n\t}\n\n\torigSvcs := indexServices(r.services, svcIndex)\n\tsvcAdditions := make([]kube_v1.Service, 0)\n\tsvcModifications := make([]kube_v1.Service, 0)\n\tfor _, svc := range svcs {\n\t\torig, ok := origSvcs[svcIndex(svc)]\n\t\tif !ok {\n\t\t\tsvcAdditions = append(svcAdditions, svc)\n\t\t} else {\n\t\t\t// Compare, but don't include generated immutable field ClusterIP in comparison\n\t\t\torigNoIP := orig.Spec\n\t\t\torigNoIP.ClusterIP = \"\"\n\t\t\tif !reflect.DeepEqual(svc.Spec, origNoIP) {\n\t\t\t\t// New version is different in some way besides ClusterIP. Make a new one,\n\t\t\t\t// but use the UID and ClusterIP of the old one so that we survive K8s\n\t\t\t\t// immutability requirement on ClusterIP.\n\t\t\t\tnewSpec := svc.Spec\n\t\t\t\torigSpec := orig.Spec\n\t\t\t\tnewSpec.ClusterIP = origSpec.ClusterIP\n\t\t\t\tsvc.UID = orig.UID\n\t\t\t\tsvcModifications = append(svcModifications, svc)\n\t\t\t}\n\t\t\t// TODO merge Annotations if multiple remote clusters offer service\n\t\t}\n\t}\n\n\treturn &ConfigChanges{\n\t\tAdditions: outAdditions,\n\t\tModifications: outModifications,\n\t\tKubernetes: &KubernetesChanges{\n\t\t\tAdditions: svcAdditions,\n\t\t\tModifications: svcModifications,\n\t\t},\n\t}, nil\n}", "func (c *HandlerComp) intClusterFetch(ctx context.Context, ai *auth.Info, id string) (*models.Cluster, error) {\n\tobj, err := c.DS.OpsCluster().Fetch(ctx, id)\n\tif err == nil {\n\t\tif err = c.clusterFetchFilter(ai, obj); err == nil {\n\t\t\terr = c.clusterApplyInheritedProperties(ctx, ai, obj, nil)\n\t\t}\n\t}\n\treturn obj, err\n}", "func GenerateUpdateClusterInput(cr *svcapitypes.Cluster) *svcsdk.UpdateClusterInput {\n\tres := &svcsdk.UpdateClusterInput{}\n\n\tif cr.Spec.ForProvider.Configuration != nil {\n\t\tf1 := &svcsdk.ClusterConfiguration{}\n\t\tif cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration != nil {\n\t\t\tf1f0 := &svcsdk.ExecuteCommandConfiguration{}\n\t\t\tif cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.KMSKeyID != nil {\n\t\t\t\tf1f0.SetKmsKeyId(*cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.KMSKeyID)\n\t\t\t}\n\t\t\tif cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.LogConfiguration != nil {\n\t\t\t\tf1f0f1 := &svcsdk.ExecuteCommandLogConfiguration{}\n\t\t\t\tif cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.LogConfiguration.CloudWatchEncryptionEnabled != nil {\n\t\t\t\t\tf1f0f1.SetCloudWatchEncryptionEnabled(*cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.LogConfiguration.CloudWatchEncryptionEnabled)\n\t\t\t\t}\n\t\t\t\tif cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.LogConfiguration.CloudWatchLogGroupName != nil {\n\t\t\t\t\tf1f0f1.SetCloudWatchLogGroupName(*cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.LogConfiguration.CloudWatchLogGroupName)\n\t\t\t\t}\n\t\t\t\tif cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.LogConfiguration.S3BucketName != nil {\n\t\t\t\t\tf1f0f1.SetS3BucketName(*cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.LogConfiguration.S3BucketName)\n\t\t\t\t}\n\t\t\t\tif cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.LogConfiguration.S3EncryptionEnabled != nil {\n\t\t\t\t\tf1f0f1.SetS3EncryptionEnabled(*cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.LogConfiguration.S3EncryptionEnabled)\n\t\t\t\t}\n\t\t\t\tif cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.LogConfiguration.S3KeyPrefix != nil {\n\t\t\t\t\tf1f0f1.SetS3KeyPrefix(*cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.LogConfiguration.S3KeyPrefix)\n\t\t\t\t}\n\t\t\t\tf1f0.SetLogConfiguration(f1f0f1)\n\t\t\t}\n\t\t\tif cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.Logging != nil {\n\t\t\t\tf1f0.SetLogging(*cr.Spec.ForProvider.Configuration.ExecuteCommandConfiguration.Logging)\n\t\t\t}\n\t\t\tf1.SetExecuteCommandConfiguration(f1f0)\n\t\t}\n\t\tres.SetConfiguration(f1)\n\t}\n\tif cr.Spec.ForProvider.Settings != nil {\n\t\tf2 := []*svcsdk.ClusterSetting{}\n\t\tfor _, f2iter := range cr.Spec.ForProvider.Settings {\n\t\t\tf2elem := &svcsdk.ClusterSetting{}\n\t\t\tif f2iter.Name != nil {\n\t\t\t\tf2elem.SetName(*f2iter.Name)\n\t\t\t}\n\t\t\tif f2iter.Value != nil {\n\t\t\t\tf2elem.SetValue(*f2iter.Value)\n\t\t\t}\n\t\t\tf2 = append(f2, f2elem)\n\t\t}\n\t\tres.SetSettings(f2)\n\t}\n\n\treturn res\n}", "func (w *worker) reconcileCluster(cluster *chop.ChiCluster) error {\n\tw.a.V(2).M(cluster).S().P()\n\tdefer w.a.V(2).M(cluster).E().P()\n\n\t// Add Cluster's Service\n\tservice := w.creator.CreateServiceCluster(cluster)\n\tif service == nil {\n\t\t// TODO\n\t\t// For somewhat reason Service is not created, this is an error, but not clear what to do about it\n\t\treturn nil\n\t}\n\treturn w.reconcileService(cluster.CHI, service)\n}", "func (c *Controller) OnAdd(add common.Cluster) {\n\tblog.Infof(\"cluster %+v add\", add)\n\t// add new reconciler there is no reconciler for the cluster\n\tif _, ok := c.reconcilerMap[add.ClusterID]; !ok {\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tnewReconciler, err := reconciler.NewReconciler(add, c.storageClient, c.cmdbClient, c.ops.FullSyncInterval)\n\t\tif err != nil {\n\t\t\tblog.Errorf(\"failed, to create new reconciler, err %s\", err.Error())\n\t\t\tcancel()\n\t\t\treturn\n\t\t}\n\t\tblog.Infof(\"add reconciler for cluster %+v\", add)\n\t\tc.reconcilerMap[add.ClusterID] = newReconciler\n\t\tc.cancelFuncMap[add.ClusterID] = cancel\n\t\tgo newReconciler.Run(ctx)\n\t} else {\n\t\tblog.Warnf(\"duplicated add cluster\")\n\t}\n}", "func (w *worker) includeHostIntoClickHouseCluster(host *chop.ChiHost) {\n\toptions := chopmodel.NewClickHouseConfigFilesGeneratorOptions().\n\t\tSetRemoteServersGeneratorOptions(chopmodel.NewRemoteServersGeneratorOptions().\n\t\t\tExcludeReconcileAttributes(\n\t\t\t\tchop.NewChiHostReconcileAttributes().SetAdd(),\n\t\t\t),\n\t\t)\n\t\t// Add host to the cluster config (always) and wait for ClickHouse to pick-up the change\n\t_ = w.reconcileCHIConfigMapCommon(host.GetCHI(), options, true)\n\tif w.waitIncludeHost(host) {\n\t\t_ = w.waitHostInCluster(host)\n\t}\n}", "func disallowUsingLegacyAPIInNewCluster(old, tc *v1alpha1.TidbCluster) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tpath := field.NewPath(\"spec\")\n\tpdSpecified := old.Spec.PD != nil && tc.Spec.PD != nil\n\ttidbSpecified := old.Spec.TiDB != nil && tc.Spec.TiDB != nil\n\ttikvSpecified := old.Spec.TiKV != nil && tc.Spec.TiKV != nil\n\n\tif old.Spec.Version != \"\" && tc.Spec.Version == \"\" {\n\t\tallErrs = append(allErrs, field.Invalid(path.Child(\"version\"), tc.Spec.Version, \"version must not be empty\"))\n\t}\n\tif tidbSpecified && old.Spec.TiDB.BaseImage != \"\" && tc.Spec.TiDB.BaseImage == \"\" {\n\t\tallErrs = append(allErrs, field.Invalid(path.Child(\"tidb.baseImage\"), tc.Spec.TiDB.BaseImage, \"baseImage of TiDB must not be empty\"))\n\t}\n\tif pdSpecified && old.Spec.PD.BaseImage != \"\" && tc.Spec.PD.BaseImage == \"\" {\n\t\tallErrs = append(allErrs, field.Invalid(path.Child(\"pd.baseImage\"), tc.Spec.PD.BaseImage, \"baseImage of PD must not be empty\"))\n\t}\n\tif tikvSpecified && old.Spec.TiKV.BaseImage != \"\" && tc.Spec.TiKV.BaseImage == \"\" {\n\t\tallErrs = append(allErrs, field.Invalid(path.Child(\"tikv.baseImage\"), tc.Spec.TiKV.BaseImage, \"baseImage of TiKV must not be empty\"))\n\t}\n\tif tidbSpecified && old.Spec.TiDB.Config != nil && tc.Spec.TiDB.Config == nil {\n\t\tallErrs = append(allErrs, field.Invalid(path.Child(\"tidb.config\"), tc.Spec.TiDB.Config, \"tidb.config must not be nil\"))\n\t}\n\tif tikvSpecified && old.Spec.TiKV.Config != nil && tc.Spec.TiKV.Config == nil {\n\t\tallErrs = append(allErrs, field.Invalid(path.Child(\"tikv.config\"), tc.Spec.TiKV.Config, \"TiKV.config must not be nil\"))\n\t}\n\tif pdSpecified && old.Spec.PD.Config != nil && tc.Spec.PD.Config == nil {\n\t\tallErrs = append(allErrs, field.Invalid(path.Child(\"pd.config\"), tc.Spec.PD.Config, \"PD.config must not be nil\"))\n\t}\n\treturn allErrs\n}", "func cmdCluster(c *cli.Context, subCmd string) string {\n\troute := \"_cluster/\"\n\turl := c.GlobalString(\"baseurl\")\n\n\tvar arg string\n\tswitch subCmd {\n\tcase \"health\":\n\t\targ = \"health\"\n\tcase \"state\":\n\t\targ = \"state\"\n\tdefault:\n\t\targ = \"\"\n\t}\n\treturn url + route + arg\n}", "func addMultiClusterReconcilers(ctx context.Context, clusterWatcher multicluster.ClusterWatcher, discoveryReconcilers reconcilers.DiscoveryReconcilers) {\n\n\tcore_v1_controller.\n\t\tNewMulticlusterServiceReconcileLoop(\"services\", clusterWatcher).\n\t\tAddMulticlusterServiceReconciler(ctx, discoveryReconcilers)\n\n\tcore_v1_controller.\n\t\tNewMulticlusterPodReconcileLoop(\"pods\", clusterWatcher).\n\t\tAddMulticlusterPodReconciler(ctx, discoveryReconcilers)\n\n\tapps_v1_controller.\n\t\tNewMulticlusterDeploymentReconcileLoop(\"pods\", clusterWatcher).\n\t\tAddMulticlusterDeploymentReconciler(ctx, discoveryReconcilers)\n\n}", "func fetchCluster(c *gin.Context) string {\n\tconst key = \"cluster\"\n\n\tswitch {\n\tcase len(c.Param(key)) > 0:\n\t\treturn c.Param(key)\n\tcase len(c.Query(key)) > 0:\n\t\treturn c.Query(key)\n\tcase len(c.PostForm(key)) > 0:\n\t\treturn c.PostForm(key)\n\tdefault:\n\t\treturn \"\"\n\t}\n}", "func (a *HyperflexApiService) PatchHyperflexClusterExecute(r ApiPatchHyperflexClusterRequest) (*HyperflexCluster, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodPatch\n\t\tlocalVarPostBody interface{}\n\t\tformFiles []formFile\n\t\tlocalVarReturnValue *HyperflexCluster\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"HyperflexApiService.PatchHyperflexCluster\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/hyperflex/Clusters/{Moid}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"Moid\"+\"}\", url.PathEscape(parameterToString(r.moid, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\tif r.hyperflexCluster == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"hyperflexCluster is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\", \"application/json-patch+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\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ifMatch != nil {\n\t\tlocalVarHeaderParams[\"If-Match\"] = parameterToString(*r.ifMatch, \"\")\n\t}\n\t// body params\n\tlocalVarPostBody = r.hyperflexCluster\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\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\tlocalVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody))\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 == 400 {\n\t\t\tvar v Error\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 == 401 {\n\t\t\tvar v Error\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 == 403 {\n\t\t\tvar v Error\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 == 404 {\n\t\t\tvar v Error\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\tvar v Error\n\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\tif err != nil {\n\t\t\tnewErr.error = err.Error()\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tnewErr.model = v\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 (client RoverClusterClient) RequestAdditionalNodes(ctx context.Context, request RequestAdditionalNodesRequest) (response RequestAdditionalNodesResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.DefaultRetryPolicy()\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.requestAdditionalNodes, 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 = RequestAdditionalNodesResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = RequestAdditionalNodesResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(RequestAdditionalNodesResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into RequestAdditionalNodesResponse\")\n\t}\n\treturn\n}", "func (d *Database) ImportClustersForEvent(responses firebase.EventUserResponses, clusters []int, numClusters int) error {\n\t_, err := d.client.TxPipelined(func(pipe redis.Pipeliner) error {\n\t\tfor i, r := range responses.Results {\n\t\t\tpipe.ZAdd(responses.ID, &redis.Z{\n\t\t\t\tScore: float64(clusters[i]),\n\t\t\t\tMember: r.UID,\n\t\t\t})\n\t\t}\n\n\t\tmetaKey := fmt.Sprintf(\"meta:%s\", responses.ID)\n\n\t\t// Set the number of clusters.\n\t\tpipe.HSet(metaKey, \"clusters\", numClusters)\n\n\t\t// Set color metadata information.\n\t\tfor i, c := range colors.GenerateRandomColors(numClusters) {\n\t\t\tpipe.HSet(metaKey, fmt.Sprintf(\"color:%d\", i+1), c)\n\t\t}\n\n\t\treturn nil\n\t})\n\n\treturn err\n}", "func runNomadClusterColocatedTest(t *testing.T, packerBuildName string) {\n\texamplesDir := test_structure.CopyTerraformFolderToTemp(t, REPO_ROOT, CLUSTER_COLOCATED_EXAMPLE_PATH)\n\n\tdefer test_structure.RunTestStage(t, \"teardown\", func() {\n\t\tterraformOptions := test_structure.LoadTerraformOptions(t, examplesDir)\n\t\tterraform.Destroy(t, terraformOptions)\n\n\t\tamiId := test_structure.LoadAmiId(t, examplesDir)\n\t\tawsRegion := test_structure.LoadString(t, examplesDir, SAVED_AWS_REGION)\n\t\taws.DeleteAmi(t, awsRegion, amiId)\n\t})\n\n\ttest_structure.RunTestStage(t, \"setup_ami\", func() {\n\t\tawsRegion := getRandomRegion(t)\n\t\ttest_structure.SaveString(t, examplesDir, SAVED_AWS_REGION, awsRegion)\n\n\t\tuniqueId := random.UniqueId()\n\t\ttest_structure.SaveString(t, examplesDir, SAVED_UNIQUE_ID, uniqueId)\n\n\t\tamiId := buildAmi(t, filepath.Join(examplesDir, \"examples\", \"nomad-consul-ami\", \"nomad-consul.json\"), packerBuildName, awsRegion, uniqueId)\n\t\ttest_structure.SaveAmiId(t, examplesDir, amiId)\n\t})\n\n\ttest_structure.RunTestStage(t, \"deploy\", func() {\n\t\tamiId := test_structure.LoadAmiId(t, examplesDir)\n\t\tawsRegion := test_structure.LoadString(t, examplesDir, SAVED_AWS_REGION)\n\t\tuniqueId := test_structure.LoadString(t, examplesDir, SAVED_UNIQUE_ID)\n\n\t\tterraformOptions := &terraform.Options{\n\t\t\tTerraformDir: examplesDir,\n\t\t\tVars: map[string]interface{}{\n\t\t\t\tCLUSTER_COLOCATED_EXAMPLE_VAR_CLUSTER_NAME: fmt.Sprintf(\"test-%s\", uniqueId),\n\t\t\t\tCLUSTER_COLOCATED_EXAMPLE_VAR_CLUSTER_TAG_VALUE: fmt.Sprintf(\"auto-join-%s\", uniqueId),\n\t\t\t\tCLUSTER_COLOCATED_EXAMPLE_VAR_NUM_SERVERS: DEFAULT_NUM_SERVERS,\n\t\t\t\tCLUSTER_COLOCATED_EXAMPLE_VAR_NUM_CLIENTS: DEFAULT_NUM_CLIENTS,\n\t\t\t\tVAR_AMI_ID: amiId,\n\t\t\t},\n\t\t\tEnvVars: map[string]string{\n\t\t\t\tENV_VAR_AWS_REGION: awsRegion,\n\t\t\t},\n\t\t}\n\t\ttest_structure.SaveTerraformOptions(t, examplesDir, terraformOptions)\n\n\t\tterraform.InitAndApply(t, terraformOptions)\n\t})\n\n\ttest_structure.RunTestStage(t, \"validate\", func() {\n\t\tterraformOptions := test_structure.LoadTerraformOptions(t, examplesDir)\n\t\tawsRegion := test_structure.LoadString(t, examplesDir, SAVED_AWS_REGION)\n\n\t\tcheckNomadClusterIsWorking(t, CLUSTER_COLOCATED_EXAMPLE_OUTPUT_SERVER_ASG_NAME, terraformOptions, awsRegion)\n\t})\n}", "func (adm Admin) AddCluster(cluster string) bool {\n\tconn := newConnection(adm.ZkSvr)\n\terr := conn.Connect()\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer conn.Disconnect()\n\n\tkb := KeyBuilder{cluster}\n\t// c = \"/<cluster>\"\n\tc := kb.cluster()\n\n\t// check if cluster already exists\n\texists, err := conn.Exists(c)\n\tmust(err)\n\tif exists {\n\t\treturn false\n\t}\n\n\tconn.CreateEmptyNode(c)\n\n\t// PROPERTYSTORE is an empty node\n\tpropertyStore := fmt.Sprintf(\"/%s/PROPERTYSTORE\", cluster)\n\tconn.CreateEmptyNode(propertyStore)\n\n\t// STATEMODELDEFS has 6 children\n\tstateModelDefs := fmt.Sprintf(\"/%s/STATEMODELDEFS\", cluster)\n\tconn.CreateEmptyNode(stateModelDefs)\n\tconn.CreateRecordWithData(stateModelDefs+\"/LeaderStandby\", HelixDefaultNodes[\"LeaderStandby\"])\n\tconn.CreateRecordWithData(stateModelDefs+\"/MasterSlave\", HelixDefaultNodes[\"MasterSlave\"])\n\tconn.CreateRecordWithData(stateModelDefs+\"/OnlineOffline\", HelixDefaultNodes[\"OnlineOffline\"])\n\tconn.CreateRecordWithData(stateModelDefs+\"/STORAGE_DEFAULT_SM_SCHEMATA\", HelixDefaultNodes[\"STORAGE_DEFAULT_SM_SCHEMATA\"])\n\tconn.CreateRecordWithData(stateModelDefs+\"/SchedulerTaskQueue\", HelixDefaultNodes[\"SchedulerTaskQueue\"])\n\tconn.CreateRecordWithData(stateModelDefs+\"/Task\", HelixDefaultNodes[\"Task\"])\n\n\t// INSTANCES is initailly an empty node\n\tinstances := fmt.Sprintf(\"/%s/INSTANCES\", cluster)\n\tconn.CreateEmptyNode(instances)\n\n\t// CONFIGS has 3 children: CLUSTER, RESOURCE, PARTICIPANT\n\tconfigs := fmt.Sprintf(\"/%s/CONFIGS\", cluster)\n\tconn.CreateEmptyNode(configs)\n\tconn.CreateEmptyNode(configs + \"/PARTICIPANT\")\n\tconn.CreateEmptyNode(configs + \"/RESOURCE\")\n\tconn.CreateEmptyNode(configs + \"/CLUSTER\")\n\n\tclusterNode := NewRecord(cluster)\n\tconn.CreateRecordWithPath(configs+\"/CLUSTER/\"+cluster, clusterNode)\n\n\t// empty ideal states\n\tidealStates := fmt.Sprintf(\"/%s/IDEALSTATES\", cluster)\n\tconn.CreateEmptyNode(idealStates)\n\n\t// empty external view\n\texternalView := fmt.Sprintf(\"/%s/EXTERNALVIEW\", cluster)\n\tconn.CreateEmptyNode(externalView)\n\n\t// empty live instances\n\tliveInstances := fmt.Sprintf(\"/%s/LIVEINSTANCES\", cluster)\n\tconn.CreateEmptyNode(liveInstances)\n\n\t// CONTROLLER has four childrens: [ERRORS, HISTORY, MESSAGES, STATUSUPDATES]\n\tcontroller := fmt.Sprintf(\"/%s/CONTROLLER\", cluster)\n\tconn.CreateEmptyNode(controller)\n\tconn.CreateEmptyNode(controller + \"/ERRORS\")\n\tconn.CreateEmptyNode(controller + \"/HISTORY\")\n\tconn.CreateEmptyNode(controller + \"/MESSAGES\")\n\tconn.CreateEmptyNode(controller + \"/STATUSUPDATES\")\n\n\treturn true\n}", "func (adm Admin) AddCluster(cluster string, recreateIfExists bool) bool {\n\tkb := &KeyBuilder{cluster}\n\t// c = \"/<cluster>\"\n\tc := kb.cluster()\n\n\t// check if cluster already exists\n\texists, _, err := adm.zkClient.Exists(c)\n\tif err != nil || (exists && !recreateIfExists) {\n\t\treturn false\n\t}\n\n\tif recreateIfExists {\n\t\tif err := adm.zkClient.DeleteTree(c); err != nil {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tadm.zkClient.CreateEmptyNode(c)\n\n\t// PROPERTYSTORE is an empty node\n\tpropertyStore := fmt.Sprintf(\"/%s/PROPERTYSTORE\", cluster)\n\tadm.zkClient.CreateEmptyNode(propertyStore)\n\n\t// STATEMODELDEFS has 6 children\n\tstateModelDefs := fmt.Sprintf(\"/%s/STATEMODELDEFS\", cluster)\n\tadm.zkClient.CreateEmptyNode(stateModelDefs)\n\tadm.zkClient.CreateDataWithPath(\n\t\tstateModelDefs+\"/LeaderStandby\", []byte(_helixDefaultNodes[\"LeaderStandby\"]))\n\tadm.zkClient.CreateDataWithPath(\n\t\tstateModelDefs+\"/MasterSlave\", []byte(_helixDefaultNodes[\"MasterSlave\"]))\n\tadm.zkClient.CreateDataWithPath(\n\t\tstateModelDefs+\"/OnlineOffline\", []byte(_helixDefaultNodes[StateModelNameOnlineOffline]))\n\tadm.zkClient.CreateDataWithPath(\n\t\tstateModelDefs+\"/STORAGE_DEFAULT_SM_SCHEMATA\",\n\t\t[]byte(_helixDefaultNodes[\"STORAGE_DEFAULT_SM_SCHEMATA\"]))\n\tadm.zkClient.CreateDataWithPath(\n\t\tstateModelDefs+\"/SchedulerTaskQueue\", []byte(_helixDefaultNodes[\"SchedulerTaskQueue\"]))\n\tadm.zkClient.CreateDataWithPath(\n\t\tstateModelDefs+\"/Task\", []byte(_helixDefaultNodes[\"Task\"]))\n\n\t// INSTANCES is initailly an empty node\n\tinstances := fmt.Sprintf(\"/%s/INSTANCES\", cluster)\n\tadm.zkClient.CreateEmptyNode(instances)\n\n\t// CONFIGS has 3 children: CLUSTER, RESOURCE, PARTICIPANT\n\tconfigs := fmt.Sprintf(\"/%s/CONFIGS\", cluster)\n\tadm.zkClient.CreateEmptyNode(configs)\n\tadm.zkClient.CreateEmptyNode(configs + \"/PARTICIPANT\")\n\tadm.zkClient.CreateEmptyNode(configs + \"/RESOURCE\")\n\tadm.zkClient.CreateEmptyNode(configs + \"/CLUSTER\")\n\n\tclusterNode := model.NewMsg(cluster)\n\taccessor := newDataAccessor(adm.zkClient, kb)\n\taccessor.createMsg(configs+\"/CLUSTER/\"+cluster, clusterNode)\n\n\t// empty ideal states\n\tidealStates := fmt.Sprintf(\"/%s/IDEALSTATES\", cluster)\n\tadm.zkClient.CreateEmptyNode(idealStates)\n\n\t// empty external view\n\texternalView := fmt.Sprintf(\"/%s/EXTERNALVIEW\", cluster)\n\tadm.zkClient.CreateEmptyNode(externalView)\n\n\t// empty live instances\n\tliveInstances := fmt.Sprintf(\"/%s/LIVEINSTANCES\", cluster)\n\tadm.zkClient.CreateEmptyNode(liveInstances)\n\n\t// CONTROLLER has four childrens: [ERRORS, HISTORY, MESSAGES, STATUSUPDATES]\n\tcontroller := fmt.Sprintf(\"/%s/CONTROLLER\", cluster)\n\tadm.zkClient.CreateEmptyNode(controller)\n\tadm.zkClient.CreateEmptyNode(controller + \"/ERRORS\")\n\tadm.zkClient.CreateEmptyNode(controller + \"/HISTORY\")\n\tadm.zkClient.CreateEmptyNode(controller + \"/MESSAGES\")\n\tadm.zkClient.CreateEmptyNode(controller + \"/STATUSUPDATES\")\n\n\treturn true\n}", "func (s *StressFlag) AddExtraUsage(eu string) {}", "func (m *Multicluster) ClusterAdded(cluster *multicluster.Cluster, clusterStopCh <-chan struct{}) {\n\tm.m.Lock()\n\tkubeController, kubeRegistry, options, configCluster := m.addCluster(cluster)\n\tif kubeController == nil {\n\t\t// m.closing was true, nothing to do.\n\t\tm.m.Unlock()\n\t\treturn\n\t}\n\tm.m.Unlock()\n\t// clusterStopCh is a channel that will be closed when this cluster removed.\n\tm.initializeCluster(cluster, kubeController, kubeRegistry, *options, configCluster, clusterStopCh)\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"clustersync-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource ClusterSync\n\terr = c.Watch(&source.Kind{Type: &hiveinternal.ClusterSync{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func initializeClusterOperator(co *configv1.ClusterOperator) {\n\tco.Status.Versions = []configv1.OperandVersion{\n\t\t{\n\t\t\tName: OperatorVersionName,\n\t\t\tVersion: UnknownVersionValue,\n\t\t},\n\t\t{\n\t\t\tName: CoreDNSVersionName,\n\t\t\tVersion: UnknownVersionValue,\n\t\t},\n\t\t{\n\t\t\tName: OpenshiftCLIVersionName,\n\t\t\tVersion: UnknownVersionValue,\n\t\t},\n\t}\n\tco.Status.Conditions = []configv1.ClusterOperatorStatusCondition{\n\t\t{\n\t\t\tType: configv1.OperatorDegraded,\n\t\t\tStatus: configv1.ConditionUnknown,\n\t\t},\n\t\t{\n\t\t\tType: configv1.OperatorProgressing,\n\t\t\tStatus: configv1.ConditionUnknown,\n\t\t},\n\t\t{\n\t\t\tType: configv1.OperatorAvailable,\n\t\t\tStatus: configv1.ConditionUnknown,\n\t\t},\n\t}\n}", "func (c *Controller) processClusterNew(ecs *ecsv1.KubernetesCluster) error {\n\tdeployMode := ecs.Spec.Cluster.DeployMode\n\n\tvar err error\n\tswitch deployMode {\n\tcase ecsv1.BinaryDeployMode:\n\t\terr = c.sshInstaller.ClusterNew(ecs)\n\tcase ecsv1.ContainerDeployMode:\n\t\terr = c.grpcInstaller.ClusterNew(ecs)\n\t}\n\n\tif err != nil {\n\t\tglog.Errorf(\"install cluster %s failed with %v\", ecs.Name, err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func TestConfigReloadEnableClusterAuthorization(t *testing.T) {\n\tsrvb, srvbOpts, srvbConfig := runReloadServerWithConfig(t, \"./configs/reload/srv_b_1.conf\")\n\tdefer srvb.Shutdown()\n\n\tsrva, srvaOpts, srvaConfig := runReloadServerWithConfig(t, \"./configs/reload/srv_a_1.conf\")\n\tdefer srva.Shutdown()\n\n\tcheckClusterFormed(t, srva, srvb)\n\n\tsrvaAddr := fmt.Sprintf(\"nats://%s:%d\", srvaOpts.Host, srvaOpts.Port)\n\tsrvaConn, err := nats.Connect(srvaAddr)\n\tif err != nil {\n\t\tt.Fatalf(\"Error creating client: %v\", err)\n\t}\n\tdefer srvaConn.Close()\n\tsub, err := srvaConn.SubscribeSync(\"foo\")\n\tif err != nil {\n\t\tt.Fatalf(\"Error subscribing: %v\", err)\n\t}\n\tdefer sub.Unsubscribe()\n\tif err := srvaConn.Flush(); err != nil {\n\t\tt.Fatalf(\"Error flushing: %v\", err)\n\t}\n\n\tsrvbAddr := fmt.Sprintf(\"nats://%s:%d\", srvbOpts.Host, srvbOpts.Port)\n\tsrvbConn, err := nats.Connect(srvbAddr)\n\tif err != nil {\n\t\tt.Fatalf(\"Error creating client: %v\", err)\n\t}\n\tdefer srvbConn.Close()\n\n\tif numRoutes := srvb.NumRoutes(); numRoutes != 1 {\n\t\tt.Fatalf(\"Expected 1 route, got %d\", numRoutes)\n\t}\n\n\t// Ensure messages flow through the cluster as a sanity check.\n\tif err := srvbConn.Publish(\"foo\", []byte(\"hello\")); err != nil {\n\t\tt.Fatalf(\"Error publishing: %v\", err)\n\t}\n\tsrvbConn.Flush()\n\tmsg, err := sub.NextMsg(2 * time.Second)\n\tif err != nil {\n\t\tt.Fatalf(\"Error receiving message: %v\", err)\n\t}\n\tif string(msg.Data) != \"hello\" {\n\t\tt.Fatalf(\"Msg is incorrect.\\nexpected: %+v\\ngot: %+v\", []byte(\"hello\"), msg.Data)\n\t}\n\n\t// Enable route authorization.\n\tchangeCurrentConfigContent(t, srvbConfig, \"./configs/reload/srv_b_2.conf\")\n\tif err := srvb.Reload(); err != nil {\n\t\tt.Fatalf(\"Error reloading config: %v\", err)\n\t}\n\n\tcheckNumRoutes(t, srvb, 0)\n\n\t// Ensure messages no longer flow through the cluster.\n\tfor i := 0; i < 5; i++ {\n\t\tif err := srvbConn.Publish(\"foo\", []byte(\"world\")); err != nil {\n\t\t\tt.Fatalf(\"Error publishing: %v\", err)\n\t\t}\n\t\tsrvbConn.Flush()\n\t}\n\tif _, err := sub.NextMsg(50 * time.Millisecond); err != nats.ErrTimeout {\n\t\tt.Fatalf(\"Expected ErrTimeout, got %v\", err)\n\t}\n\n\t// Reload Server A with correct route credentials.\n\tchangeCurrentConfigContent(t, srvaConfig, \"./configs/reload/srv_a_2.conf\")\n\tif err := srva.Reload(); err != nil {\n\t\tt.Fatalf(\"Error reloading config: %v\", err)\n\t}\n\tcheckClusterFormed(t, srva, srvb)\n\n\tif numRoutes := srvb.NumRoutes(); numRoutes != 1 {\n\t\tt.Fatalf(\"Expected 1 route, got %d\", numRoutes)\n\t}\n\n\t// Ensure messages flow through the cluster now.\n\tif err := srvbConn.Publish(\"foo\", []byte(\"hola\")); err != nil {\n\t\tt.Fatalf(\"Error publishing: %v\", err)\n\t}\n\tsrvbConn.Flush()\n\tmsg, err = sub.NextMsg(2 * time.Second)\n\tif err != nil {\n\t\tt.Fatalf(\"Error receiving message: %v\", err)\n\t}\n\tif string(msg.Data) != \"hola\" {\n\t\tt.Fatalf(\"Msg is incorrect.\\nexpected: %+v\\ngot: %+v\", []byte(\"hola\"), msg.Data)\n\t}\n}", "func (client *Client) ServiceMeshAddClusterWithChan(request *ServiceMeshAddClusterRequest) (<-chan *ServiceMeshAddClusterResponse, <-chan error) {\n\tresponseChan := make(chan *ServiceMeshAddClusterResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.ServiceMeshAddCluster(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func main() {\n\n //bring up the services\n\tmasterSrvAddr := master.StartMasterSrv(9090) //9090\n\tworkerSrvAddr1 := worker.StartWorkerSrv(9091); //9091 ,9092, 9093\n\tworkerSrvAddr2 := worker.StartWorkerSrv(9092);\n\tworker.StartWorkerCli(masterSrvAddr, []string{workerSrvAddr1,workerSrvAddr2});\n\tmaster.StartMasterCli();\n\n\t//distributed map-reduce flow\n\tmapOutput,err := master.DoOperation([]string{\"/Users/k0c00nc/go/src/MapReduce/res/input.txt\", \"/Users/k0c00nc/go/src/distributedDb\" +\n\t\t\"/res/input1.txt\"},\"Map\")\n\tif err !=nil{\n\t\tfmt.Printf(\"map phase failed with err %s \", err.Error())\n\t}\n\n\tlocalAggregation,err :=master.DoOperation(mapOutput,\"LocalAggregation\")\n\tif err !=nil{\n\t\tfmt.Printf(\"localAggregation phase failed with err %s \", err.Error())\n\t}\n\n\tshuffing,err :=master.DoOperation(localAggregation,\"Shuffing\")\n\tif err !=nil{\n\t\tfmt.Printf(\"shuffing phase failed with err %s \", err.Error())\n\t}\n\n\treduce,err :=master.DoOperation(shuffing,\"Reduce\")\n\tif err !=nil{\n\t\tfmt.Printf(\"reduce phase failed with err %s \", err.Error())\n\t}\n\n fmt.Println(\"MR output are in file\", reduce[0])\n\n}", "func (*OktetoClusterHelper) Add(*credentials.Credentials) error {\n\treturn ErrNotImplemented\n}", "func getClusterData(c kclientset.Interface, config map[string]string) map[string]string {\n\tnewConfig := make(map[string]string)\n\tfor k, v := range config {\n\t\tif k == \"routerIP\" {\n\t\t\t// TODO sjug: make localhost func\n\t\t\t//v = localhost(f)\n\t\t\tv = \"127.0.0.1\"\n\t\t} else if k == \"targetHost\" {\n\t\t\t// getEndpointsWithLabel will not return single string\n\t\t\tv = concatenateIP(getEndpointsWithLabel(c, config[\"match\"]))\n\t\t}\n\t\tnewConfig[k] = v\n\t}\n\treturn newConfig\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"toolchaincluster-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource ToolchainCluster\n\treturn c.Watch(&source.Kind{Type: &toolchainv1alpha1.ToolchainCluster{}}, &handler.EnqueueRequestForObject{})\n}", "func (r *Cluster) ApplyTo(m *model.Cluster) {\n\tm.Name = r.Name\n\tm.Description = r.Description\n\tm.DataCenter = r.DataCenter.ID\n\tm.HaReservation = r.bool(r.HaReservation)\n\tm.KsmEnabled = r.bool(r.KSM.Enabled)\n}", "func (m *Monitor) updateCluster(managedCluster *clusterv1.ManagedCluster) {\n\tglog.V(2).Info(\"Processing Cluster Update.\")\n\n\tclusterToUpdate := managedCluster.GetName()\n\tclusterVendor, version, clusterID := GetClusterClaimInfo(managedCluster)\n\tclusterIdx, found := Find(m.ManagedClusterInfo, types.ManagedClusterInfo{\n\t\tNamespace: clusterToUpdate,\n\t\tClusterID: clusterID,\n\t})\n\tif found && clusterID != m.ManagedClusterInfo[clusterIdx].ClusterID {\n\t\t// If the cluster ID has changed update it - otherwise do nothing.\n\t\tglog.Infof(\"Updating %s from Insights cluster list\", clusterToUpdate)\n\t\tm.ManagedClusterInfo[clusterIdx] = types.ManagedClusterInfo{\n\t\t\tClusterID: clusterID,\n\t\t\tNamespace: managedCluster.GetName(),\n\t\t}\n\t\treturn\n\t}\n\n\t// Case to add a ManagedCluster to cluster list after it has been upgraded to version >= 4.X\n\tif !found && clusterVendor == \"OpenShift\" && version >= 4 {\n\t\tglog.Infof(\"Adding %s to Insights cluster list - Cluster was upgraded\", managedCluster.GetName())\n\t\tm.ManagedClusterInfo = append(m.ManagedClusterInfo, types.ManagedClusterInfo{\n\t\t\tClusterID: clusterID,\n\t\t\tNamespace: managedCluster.GetName(),\n\t\t})\n\t}\n}", "func (ct *ctrlerCtx) diffCluster(apicl apiclient.Services) {\n\topts := api.ListWatchOptions{}\n\n\t// get a list of all objects from API server\n\tobjlist, err := apicl.ClusterV1().Cluster().List(context.Background(), &opts)\n\tif err != nil {\n\t\tct.logger.Errorf(\"Error getting a list of objects. Err: %v\", err)\n\t\treturn\n\t}\n\n\tct.logger.Infof(\"diffCluster(): ClusterList returned %d objects\", len(objlist))\n\n\t// build an object map\n\tobjmap := make(map[string]*cluster.Cluster)\n\tfor _, obj := range objlist {\n\t\tobjmap[obj.GetKey()] = obj\n\t}\n\n\tlist, err := ct.Cluster().List(context.Background(), &opts)\n\tif err != nil && !strings.Contains(err.Error(), \"not found in local cache\") {\n\t\tct.logger.Infof(\"Failed to get a list of objects. Err: %s\", err)\n\t\treturn\n\t}\n\n\t// if an object is in our local cache and not in API server, trigger delete for it\n\tfor _, obj := range list {\n\t\t_, ok := objmap[obj.GetKey()]\n\t\tif !ok {\n\t\t\tct.logger.Infof(\"diffCluster(): Deleting existing object %#v since its not in apiserver\", obj.GetKey())\n\t\t\tevt := kvstore.WatchEvent{\n\t\t\t\tType: kvstore.Deleted,\n\t\t\t\tKey: obj.GetKey(),\n\t\t\t\tObject: &obj.Cluster,\n\t\t\t}\n\t\t\tct.handleClusterEvent(&evt)\n\t\t}\n\t}\n\n\t// trigger create event for all others\n\tfor _, obj := range objlist {\n\t\tct.logger.Infof(\"diffCluster(): Adding object %#v\", obj.GetKey())\n\t\tevt := kvstore.WatchEvent{\n\t\t\tType: kvstore.Created,\n\t\t\tKey: obj.GetKey(),\n\t\t\tObject: obj,\n\t\t}\n\t\tct.handleClusterEvent(&evt)\n\t}\n}", "func addInternalCluster(cluster clusterv1.Cluster) (bool, error) {\n\t_, err := multicluster.Interface().Get(cluster.Name)\n\tif err == nil {\n\t\t// return Immediately if active internal cluster exist\n\t\treturn true, nil\n\t} else {\n\t\t// create internal cluster relate with cluster cr\n\t\tconfig, err := kubeconfig.LoadKubeConfigFromBytes(cluster.Spec.KubeConfig)\n\t\tif err != nil {\n\t\t\treturn true, fmt.Errorf(\"load kubeconfig failed: %v\", err)\n\t\t}\n\n\t\tpivotClient := clients.Interface().Kubernetes(constants.PivotCluster).Direct()\n\n\t\tc := new(manager.InternalCluster)\n\t\tc.StopCh = make(chan struct{})\n\t\tc.Config = config\n\t\tc.Client = kubernetes.NewClientFor(config, c.StopCh)\n\t\tc.Scout = scout.NewScout(cluster.Name, 0, 0, pivotClient, c.StopCh)\n\n\t\terr = multicluster.Interface().Add(cluster.Name, c)\n\t\tif err != nil {\n\t\t\treturn true, fmt.Errorf(\"add internal cluster failed: %v\", err)\n\t\t}\n\t}\n\n\treturn false, nil\n}", "func (r *Orchestrator) initCluster(readTx store.ReadTx) error {\n\tclusters, err := store.FindClusters(readTx, store.ByName(store.DefaultClusterName))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(clusters) != 1 {\n\t\t// we'll just pick it when it is created.\n\t\treturn nil\n\t}\n\n\tr.cluster = clusters[0]\n\treturn nil\n}", "func ProtoToCluster(p *containerpb.ContainerCluster) *container.Cluster {\n\tobj := &container.Cluster{\n\t\tName: dcl.StringOrNil(p.Name),\n\t\tDescription: dcl.StringOrNil(p.Description),\n\t\tInitialNodeCount: dcl.Int64OrNil(p.InitialNodeCount),\n\t\tMasterAuth: ProtoToContainerClusterMasterAuth(p.GetMasterAuth()),\n\t\tLoggingService: dcl.StringOrNil(p.LoggingService),\n\t\tMonitoringService: dcl.StringOrNil(p.MonitoringService),\n\t\tNetwork: dcl.StringOrNil(p.Network),\n\t\tClusterIPv4Cidr: dcl.StringOrNil(p.ClusterIpv4Cidr),\n\t\tAddonsConfig: ProtoToContainerClusterAddonsConfig(p.GetAddonsConfig()),\n\t\tSubnetwork: dcl.StringOrNil(p.Subnetwork),\n\t\tEnableKubernetesAlpha: dcl.Bool(p.EnableKubernetesAlpha),\n\t\tLabelFingerprint: dcl.StringOrNil(p.LabelFingerprint),\n\t\tLegacyAbac: ProtoToContainerClusterLegacyAbac(p.GetLegacyAbac()),\n\t\tNetworkPolicy: ProtoToContainerClusterNetworkPolicy(p.GetNetworkPolicy()),\n\t\tIPAllocationPolicy: ProtoToContainerClusterIPAllocationPolicy(p.GetIpAllocationPolicy()),\n\t\tMasterAuthorizedNetworksConfig: ProtoToContainerClusterMasterAuthorizedNetworksConfig(p.GetMasterAuthorizedNetworksConfig()),\n\t\tBinaryAuthorization: ProtoToContainerClusterBinaryAuthorization(p.GetBinaryAuthorization()),\n\t\tAutoscaling: ProtoToContainerClusterAutoscaling(p.GetAutoscaling()),\n\t\tNetworkConfig: ProtoToContainerClusterNetworkConfig(p.GetNetworkConfig()),\n\t\tMaintenancePolicy: ProtoToContainerClusterMaintenancePolicy(p.GetMaintenancePolicy()),\n\t\tDefaultMaxPodsConstraint: ProtoToContainerClusterDefaultMaxPodsConstraint(p.GetDefaultMaxPodsConstraint()),\n\t\tResourceUsageExportConfig: ProtoToContainerClusterResourceUsageExportConfig(p.GetResourceUsageExportConfig()),\n\t\tAuthenticatorGroupsConfig: ProtoToContainerClusterAuthenticatorGroupsConfig(p.GetAuthenticatorGroupsConfig()),\n\t\tPrivateClusterConfig: ProtoToContainerClusterPrivateClusterConfig(p.GetPrivateClusterConfig()),\n\t\tDatabaseEncryption: ProtoToContainerClusterDatabaseEncryption(p.GetDatabaseEncryption()),\n\t\tVerticalPodAutoscaling: ProtoToContainerClusterVerticalPodAutoscaling(p.GetVerticalPodAutoscaling()),\n\t\tShieldedNodes: ProtoToContainerClusterShieldedNodes(p.GetShieldedNodes()),\n\t\tEndpoint: dcl.StringOrNil(p.Endpoint),\n\t\tMasterVersion: dcl.StringOrNil(p.MasterVersion),\n\t\tCreateTime: dcl.StringOrNil(p.GetCreateTime()),\n\t\tStatus: dcl.StringOrNil(p.Status),\n\t\tStatusMessage: dcl.StringOrNil(p.StatusMessage),\n\t\tNodeIPv4CidrSize: dcl.Int64OrNil(p.NodeIpv4CidrSize),\n\t\tServicesIPv4Cidr: dcl.StringOrNil(p.ServicesIpv4Cidr),\n\t\tExpireTime: dcl.StringOrNil(p.GetExpireTime()),\n\t\tLocation: dcl.StringOrNil(p.Location),\n\t\tEnableTPU: dcl.Bool(p.EnableTpu),\n\t\tTPUIPv4CidrBlock: dcl.StringOrNil(p.TpuIpv4CidrBlock),\n\t\tProject: dcl.StringOrNil(p.Project),\n\t}\n\tfor _, r := range p.GetNodePools() {\n\t\tobj.NodePools = append(obj.NodePools, *ProtoToContainerClusterNodePools(r))\n\t}\n\tfor _, r := range p.GetLocations() {\n\t\tobj.Locations = append(obj.Locations, r)\n\t}\n\tfor _, r := range p.GetConditions() {\n\t\tobj.Conditions = append(obj.Conditions, *ProtoToContainerClusterConditions(r))\n\t}\n\treturn obj\n}", "func syncToClusters(clustersAccessor clustersAccessorFunc, operationsAccessor operationsFunc, selector clusterSelectorFunc, execute executionFunc, adapter federatedtypes.FederatedTypeAdapter, informer util.FederatedInformer, obj pkgruntime.Object) reconciliationStatus {\n\tkind := adapter.Kind()\n\tkey := federatedtypes.ObjectKey(adapter, obj)\n\n\tglog.V(3).Infof(\"Syncing %s %q in underlying clusters\", kind, key)\n\n\tclusters, err := clustersAccessor()\n\tif err != nil {\n\t\truntime.HandleError(fmt.Errorf(\"Failed to get cluster list: %v\", err))\n\t\treturn statusNotSynced\n\t}\n\n\tselectedClusters, unselectedClusters, err := selector(adapter.ObjectMeta(obj), clusterselector.SendToCluster, clusters)\n\tif err != nil {\n\t\treturn statusError\n\t}\n\n\tvar schedulingInfo *federatedtypes.SchedulingInfo\n\tif adapter.IsSchedulingAdapter() {\n\t\tschedulingAdapter, ok := adapter.(federatedtypes.SchedulingAdapter)\n\t\tif !ok {\n\t\t\tglog.Fatalf(\"Adapter for kind %q does not properly implement SchedulingAdapter.\", kind)\n\t\t}\n\t\tschedulingInfo, err = schedulingAdapter.GetSchedule(obj, key, selectedClusters, informer)\n\t\tif err != nil {\n\t\t\truntime.HandleError(fmt.Errorf(\"adapter.GetSchedule() failed on adapter for %s %q: %v\", kind, key, err))\n\t\t\treturn statusError\n\t\t}\n\t}\n\n\toperations, err := operationsAccessor(adapter, selectedClusters, unselectedClusters, obj, schedulingInfo)\n\tif err != nil {\n\t\treturn statusError\n\t}\n\n\tif adapter.IsSchedulingAdapter() {\n\t\tschedulingAdapter, ok := adapter.(federatedtypes.SchedulingAdapter)\n\t\tif !ok {\n\t\t\tglog.Fatalf(\"Adapter for kind %q does not properly implement SchedulingAdapter.\", kind)\n\t\t}\n\t\terr = schedulingAdapter.UpdateFederatedStatus(obj, schedulingInfo.Status)\n\t\tif err != nil {\n\t\t\truntime.HandleError(fmt.Errorf(\"adapter.UpdateFinished() failed on adapter for %s %q: %v\", kind, key, err))\n\t\t\treturn statusError\n\t\t}\n\t}\n\n\tif len(operations) == 0 {\n\t\treturn statusAllOK\n\t}\n\n\terr = execute(operations)\n\tif err != nil {\n\t\truntime.HandleError(fmt.Errorf(\"Failed to execute updates for %s %q: %v\", kind, key, err))\n\t\treturn statusError\n\t}\n\n\t// Everything is in order but let's be double sure\n\treturn statusNeedsRecheck\n}", "func generateClusterConfig(cmd *cobra.Command, existing *config.ClusterConfig, k8sVersion string, rtime string, drvName string) (config.ClusterConfig, config.Node, error) {\n\tvar cc config.ClusterConfig\n\tif existing != nil {\n\t\tcc = updateExistingConfigFromFlags(cmd, existing)\n\n\t\t// identify appropriate cni then configure cruntime accordingly\n\t\t_, err := cni.New(&cc)\n\t\tif err != nil {\n\t\t\treturn cc, config.Node{}, errors.Wrap(err, \"cni\")\n\t\t}\n\t} else {\n\t\tklog.Info(\"no existing cluster config was found, will generate one from the flags \")\n\t\tcc = generateNewConfigFromFlags(cmd, k8sVersion, rtime, drvName)\n\n\t\tcnm, err := cni.New(&cc)\n\t\tif err != nil {\n\t\t\treturn cc, config.Node{}, errors.Wrap(err, \"cni\")\n\t\t}\n\n\t\tif _, ok := cnm.(cni.Disabled); !ok {\n\t\t\tklog.Infof(\"Found %q CNI - setting NetworkPlugin=cni\", cnm)\n\t\t\tcc.KubernetesConfig.NetworkPlugin = \"cni\"\n\t\t}\n\t}\n\n\tklog.Infof(\"config:\\n%+v\", cc)\n\n\tr, err := cruntime.New(cruntime.Config{Type: cc.KubernetesConfig.ContainerRuntime})\n\tif err != nil {\n\t\treturn cc, config.Node{}, errors.Wrap(err, \"new runtime manager\")\n\t}\n\n\t// Feed Docker our host proxy environment by default, so that it can pull images\n\t// doing this for both new config and existing, in case proxy changed since previous start\n\tif _, ok := r.(*cruntime.Docker); ok {\n\t\tproxy.SetDockerEnv()\n\t}\n\n\treturn createNode(cc, existing)\n}", "func (k *K8sClusterAdapter) ProvisionCluster(ctx context.Context) errors.Error {\n\tstateStoreURL, err := k.support.StateStoreURL(ctx)\n\tif err != nil {\n\t\treturn errors.NewK8sProvisionerKopsExecError().WithCause(err)\n\t}\n\n\tvars, err := k.support.EnvironmentVariables(ctx)\n\tif err != nil {\n\t\treturn errors.NewK8sProvisionerKopsExecError().WithCause(err)\n\t}\n\n\tvar res *resources\n\n\tlog.Println(\"checking if cluster exists\")\n\tres, err = k.getCluster(ctx)\n\tif err != nil {\n\t\tif !errors.IsK8sProvisionerClusterNotFound(err) {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Println(\"creating initial cluster resources\")\n\t\tres, err = k.generateInitialClusterResourcesHack(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tlog.Println(\"setting cluster configuration\")\n\tnodeCount := int32(k.spec.NodeCount)\n\tif nodeCount == 0 {\n\t\tnodeCount = DefaultNodeCount\n\t}\n\n\tmasterCount := int32(k.spec.MasterCount)\n\tif masterCount == 0 {\n\t\tmasterCount = DefaultMasterCount\n\t}\n\n\tif err := k.writeResource(\"cluster.json\", res.Cluster); err != nil {\n\t\treturn err\n\t}\n\n\tres.MasterInstanceGroup.Spec.MinSize = &masterCount\n\tres.MasterInstanceGroup.Spec.MaxSize = &masterCount\n\tres.MasterInstanceGroup.Spec.Zones = k.spec.Zones\n\n\tif err := k.writeResource(\"master-ig.json\", res.MasterInstanceGroup); err != nil {\n\t\treturn err\n\t}\n\n\tres.NodeInstanceGroup.Spec.MinSize = &nodeCount\n\tres.NodeInstanceGroup.Spec.MaxSize = &nodeCount\n\tres.NodeInstanceGroup.Spec.Zones = k.spec.Zones\n\n\tif err := k.writeResource(\"node-ig.json\", res.NodeInstanceGroup); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Println(\"synchronizing cluster state with cloud platform\")\n\tkerr := kopsExec(ctx, command{\n\t\targs: []string{\n\t\t\t\"--state\", stateStoreURL.String(),\n\t\t\t\"replace\", \"--force\",\n\t\t\t\"-f\", filepath.Join(k.workdir, \"cluster.json\"),\n\t\t\t\"-f\", filepath.Join(k.workdir, \"master-ig.json\"),\n\t\t\t\"-f\", filepath.Join(k.workdir, \"node-ig.json\"),\n\t\t},\n\t\tenv: vars,\n\t\tstdout: os.Stdout,\n\t\tstderr: os.Stderr,\n\t})\n\tif kerr != nil {\n\t\treturn errors.NewK8sProvisionerKopsExecError().WithCause(kerr)\n\t}\n\n\tp, err := k.support.SSHPublicKey(ctx)\n\tif err != nil {\n\t\treturn errors.NewK8sProvisionerKopsExecError().WithCause(err)\n\t}\n\n\tif p != \"\" {\n\t\tkerr := kopsExec(ctx, command{\n\t\t\targs: []string{\n\t\t\t\t\"--state\", stateStoreURL.String(),\n\t\t\t\t\"create\", \"secret\", \"sshpublickey\", \"admin\", \"-i\", p,\n\t\t\t\t\"--name\", k.spec.ClusterName,\n\t\t\t},\n\t\t\tenv: vars,\n\t\t\tstdout: os.Stdout,\n\t\t\tstderr: os.Stderr,\n\t\t})\n\t\tif kerr != nil {\n\t\t\treturn errors.NewK8sProvisionerKopsExecError().WithCause(kerr)\n\t\t}\n\t}\n\n\tkerr = kopsExec(ctx, command{\n\t\targs: []string{\n\t\t\t\"--state\", stateStoreURL.String(),\n\t\t\t\"update\", \"cluster\", k.spec.ClusterName,\n\t\t\t\"--yes\",\n\t\t},\n\t\tenv: vars,\n\t\tstdout: os.Stdout,\n\t\tstderr: os.Stderr,\n\t})\n\tif kerr != nil {\n\t\treturn errors.NewK8sProvisionerKopsExecError().WithCause(kerr)\n\t}\n\n\treturn nil\n}", "func NewCluster(client ExtendedClient, applier Applier, sshKeyRing ssh.KeyRing, logger log.Logger, allowedNamespaces map[string]struct{}, imageIncluder cluster.Includer, resourceExcludeList []string) *Cluster {\n\tif imageIncluder == nil {\n\t\timageIncluder = cluster.AlwaysInclude\n\t}\n\n\tc := &Cluster{\n\t\tclient: client,\n\t\tapplier: applier,\n\t\tlogger: logger,\n\t\tsshKeyRing: sshKeyRing,\n\t\tallowedNamespaces: allowedNamespaces,\n\t\tloggedAllowedNS: map[string]bool{},\n\t\timageIncluder: imageIncluder,\n\t\tresourceExcludeList: resourceExcludeList,\n\t}\n\n\treturn c\n}", "func WithCluster(c *corev1.ObjectReference) Option {\n\treturn func(o *options) {\n\t\to.cluster = c\n\t}\n}", "func (c *Controller) processCluster(updateCtx context.Context, workerNum uint, clusterInfo *ClusterInfo) {\n\tdefer c.clusterList.ClusterProcessed(clusterInfo)\n\n\tcluster := clusterInfo.Cluster\n\tclusterLog := c.logger.WithField(\"cluster\", cluster.Alias).WithField(\"worker\", workerNum)\n\n\tclusterLog.Infof(\"Processing cluster (%s)\", cluster.LifecycleStatus)\n\n\terr := c.doProcessCluster(updateCtx, clusterLog, clusterInfo)\n\n\t// log the error and resolve the special error cases\n\tif err != nil {\n\t\tclusterLog.Errorf(\"Failed to process cluster: %s\", err)\n\n\t\t// treat \"provider not supported\" as no error\n\t\tif err == provisioner.ErrProviderNotSupported {\n\t\t\terr = nil\n\t\t}\n\t} else {\n\t\tclusterLog.Infof(\"Finished processing cluster\")\n\t}\n\n\t// update the cluster state in the registry\n\tif !c.dryRun {\n\t\tif err != nil {\n\t\t\tif cluster.Status.Problems == nil {\n\t\t\t\tcluster.Status.Problems = make([]*api.Problem, 0, 1)\n\t\t\t}\n\t\t\tcluster.Status.Problems = append(cluster.Status.Problems, &api.Problem{\n\t\t\t\tTitle: err.Error(),\n\t\t\t\tType: errTypeGeneral,\n\t\t\t})\n\n\t\t\tif len(cluster.Status.Problems) > errorLimit {\n\t\t\t\tcluster.Status.Problems = cluster.Status.Problems[len(cluster.Status.Problems)-errorLimit:]\n\t\t\t\tcluster.Status.Problems[0] = &api.Problem{\n\t\t\t\t\tType: errTypeCoalescedProblems,\n\t\t\t\t\tTitle: \"<multiple problems>\",\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tcluster.Status.Problems = []*api.Problem{}\n\t\t}\n\t\terr = c.registry.UpdateCluster(cluster)\n\t\tif err != nil {\n\t\t\tclusterLog.Errorf(\"Unable to update cluster state: %s\", err)\n\t\t}\n\t}\n}", "func (sqlStore *SQLStore) LockClusterInstallationAPI(id string) error {\n\treturn sqlStore.setClusterInstallationAPILock(id, true)\n}", "func LoadInCluster() (*Config, error) {\n\thost := os.Getenv(\"KUBERNETES_SERVICE_HOST\")\n\tport := os.Getenv(\"KUBERNETES_SERVICE_PORT\")\n\n\tif len(host) == 0 || len(port) == 0 {\n\t\treturn nil, errors.New(\"unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined\")\n\t}\n\treturn load(\n\t\t&user{\n\t\t\tTokenFile: \"/var/run/secrets/kubernetes.io/serviceaccount/token\",\n\t\t},\n\t\t&cluster{\n\t\t\tServer: \"https://\" + host + \":\" + port,\n\t\t\tCA: \"/var/run/secrets/kubernetes.io/serviceaccount/ca.crt\",\n\t\t},\n\t)\n}", "func mutateClusterTaints(taints []corev1.Taint) {\n\tfor i := range taints {\n\t\tif taints[i].Effect == corev1.TaintEffectNoExecute && taints[i].TimeAdded == nil {\n\t\t\tnow := metav1.Now()\n\t\t\ttaints[i].TimeAdded = &now\n\t\t}\n\t}\n}", "func ExampleRDS_ModifyDBCluster_shared00() {\n\tsvc := rds.New(session.New())\n\tinput := &rds.ModifyDBClusterInput{\n\t\tApplyImmediately: aws.Bool(true),\n\t\tBackupRetentionPeriod: aws.Int64(14),\n\t\tDBClusterIdentifier: aws.String(\"cluster-2\"),\n\t\tMasterUserPassword: aws.String(\"newpassword99\"),\n\t}\n\n\tresult, err := svc.ModifyDBCluster(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.ErrCodeDBClusterNotFoundFault:\n\t\t\t\tfmt.Println(rds.ErrCodeDBClusterNotFoundFault, aerr.Error())\n\t\t\tcase rds.ErrCodeInvalidDBClusterStateFault:\n\t\t\t\tfmt.Println(rds.ErrCodeInvalidDBClusterStateFault, aerr.Error())\n\t\t\tcase rds.ErrCodeStorageQuotaExceededFault:\n\t\t\t\tfmt.Println(rds.ErrCodeStorageQuotaExceededFault, aerr.Error())\n\t\t\tcase rds.ErrCodeDBSubnetGroupNotFoundFault:\n\t\t\t\tfmt.Println(rds.ErrCodeDBSubnetGroupNotFoundFault, aerr.Error())\n\t\t\tcase rds.ErrCodeInvalidVPCNetworkStateFault:\n\t\t\t\tfmt.Println(rds.ErrCodeInvalidVPCNetworkStateFault, aerr.Error())\n\t\t\tcase rds.ErrCodeInvalidDBSubnetGroupStateFault:\n\t\t\t\tfmt.Println(rds.ErrCodeInvalidDBSubnetGroupStateFault, aerr.Error())\n\t\t\tcase rds.ErrCodeInvalidSubnet:\n\t\t\t\tfmt.Println(rds.ErrCodeInvalidSubnet, aerr.Error())\n\t\t\tcase rds.ErrCodeDBClusterParameterGroupNotFoundFault:\n\t\t\t\tfmt.Println(rds.ErrCodeDBClusterParameterGroupNotFoundFault, aerr.Error())\n\t\t\tcase rds.ErrCodeInvalidDBSecurityGroupStateFault:\n\t\t\t\tfmt.Println(rds.ErrCodeInvalidDBSecurityGroupStateFault, aerr.Error())\n\t\t\tcase rds.ErrCodeInvalidDBInstanceStateFault:\n\t\t\t\tfmt.Println(rds.ErrCodeInvalidDBInstanceStateFault, aerr.Error())\n\t\t\tcase rds.ErrCodeDBClusterAlreadyExistsFault:\n\t\t\t\tfmt.Println(rds.ErrCodeDBClusterAlreadyExistsFault, aerr.Error())\n\t\t\tcase rds.ErrCodeDBInstanceAlreadyExistsFault:\n\t\t\t\tfmt.Println(rds.ErrCodeDBInstanceAlreadyExistsFault, aerr.Error())\n\t\t\tcase rds.ErrCodeDomainNotFoundFault:\n\t\t\t\tfmt.Println(rds.ErrCodeDomainNotFoundFault, aerr.Error())\n\t\t\tcase rds.ErrCodeStorageTypeNotAvailableFault:\n\t\t\t\tfmt.Println(rds.ErrCodeStorageTypeNotAvailableFault, aerr.Error())\n\t\t\tdefault:\n\t\t\t\tfmt.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\tfmt.Println(err.Error())\n\t\t}\n\t\treturn\n\t}\n\n\tfmt.Println(result)\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 RegisterCluster(\n\tctx context.Context,\n\tbinaryName string,\n\tflags *pflag.FlagSet,\n\tclientsFactory common.ClientsFactory,\n\tkubeClientsFactory common.KubeClientsFactory,\n\topts *options.Options,\n\tout io.Writer,\n\tkubeLoader common_config.KubeLoader,\n) error {\n\n\tif err := cluster_internal.VerifyRemoteContextFlags(opts); err != nil {\n\t\treturn err\n\t}\n\n\tif err := cluster_internal.VerifyMasterCluster(clientsFactory, opts); err != nil {\n\t\treturn err\n\t}\n\n\tregisterOpts := opts.Cluster.Register\n\n\t// set up kube clients for the master cluster\n\tmasterCfg, err := kubeLoader.GetRestConfigForContext(opts.Root.KubeConfig, opts.Root.KubeContext)\n\tif err != nil {\n\t\treturn common.FailedLoadingMasterConfig(err)\n\t}\n\tmasterKubeClients, err := kubeClientsFactory(masterCfg, opts.Root.WriteNamespace)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set up kube clients for the remote cluster\n\n\t// default the remote kube config/context to the root settings\n\tremoteConfigPath, remoteContext := opts.Root.KubeConfig, opts.Root.KubeContext\n\tif registerOpts.RemoteKubeConfig != \"\" {\n\t\t// if we specified a kube config for the remote cluster, use that instead\n\t\tremoteConfigPath = registerOpts.RemoteKubeConfig\n\t}\n\n\t// if we didn't have a context from the root, or if we had an override for the\n\t// remote context, use the remote context instead\n\tif remoteContext == \"\" || registerOpts.RemoteContext != \"\" {\n\t\tremoteContext = registerOpts.RemoteContext\n\t}\n\n\tremoteCfg, err := kubeLoader.GetRestConfigForContext(remoteConfigPath, remoteContext)\n\tif err != nil {\n\t\treturn FailedLoadingRemoteConfig(err)\n\t}\n\tremoteKubeClients, err := kubeClientsFactory(remoteCfg, registerOpts.RemoteWriteNamespace)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// if overwrite returns ok than the program should continue, else return\n\t// The reason for the 2 return vars is that err may be nil and returned anyway\n\tif ok, err := shouldOverwrite(ctx, binaryName, flags, out, opts, masterKubeClients); !ok {\n\t\treturn err\n\t}\n\n\tif err = ensureRemoteNamespace(ctx, registerOpts.RemoteWriteNamespace, remoteKubeClients); err != nil {\n\t\treturn err\n\t}\n\n\tbearerTokenForServiceAccount, err := generateServiceAccountBearerToken(ctx, out, remoteKubeClients, remoteCfg, registerOpts)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Fprintf(out, \"Successfully wrote service account to remote cluster...\\n\")\n\n\tclients, err := clientsFactory(opts)\n\tif err != nil {\n\t\treturn eris.Errorf(\"Unexpected error: Clients should have already been built, but failed to build again\")\n\t}\n\t// Install CRDs to remote cluster. This must happen BEFORE kubeconfig Secret is written to master cluster because\n\t// relevant CRDs must exist before SMH attempts any cross cluster functionality.\n\tcsrAgentInstaller := clients.ClusterRegistrationClients.CsrAgentInstallerFactory(remoteKubeClients.HelmInstaller, masterKubeClients.DeployedVersionFinder)\n\terr = csrAgentInstaller.Install(\n\t\tctx,\n\t\t&csr.CsrAgentInstallOptions{\n\t\t\tKubeConfig: remoteConfigPath,\n\t\t\tKubeContext: remoteContext,\n\t\t\tClusterName: registerOpts.RemoteClusterName,\n\t\t\tSmhInstallNamespace: opts.Root.WriteNamespace,\n\t\t\tUseDevCsrAgentChart: registerOpts.UseDevCsrAgentChart,\n\t\t\tReleaseName: cliconstants.CsrAgentReleaseName,\n\t\t\tRemoteWriteNamespace: registerOpts.RemoteWriteNamespace,\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Fprintf(out, \"Successfully set up CSR agent...\\n\")\n\n\t// Write kubeconfig Secret and KubeCluster CRD to master cluster\n\tsecret, err := writeKubeConfigToMaster(\n\t\tctx,\n\t\topts.Root.WriteNamespace,\n\t\tregisterOpts,\n\t\tremoteConfigPath,\n\t\tbearerTokenForServiceAccount,\n\t\tmasterKubeClients,\n\t\tkubeLoader,\n\t\tclients.KubeConverter,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Fprintf(out, \"Successfully wrote kube config secret to master cluster...\\n\")\n\terr = writeKubeClusterToMaster(ctx, masterKubeClients, opts.Root.WriteNamespace, registerOpts, secret)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Fprintf(\n\t\tout,\n\t\t\"\\nCluster %s is now registered in your Service Mesh Hub installation\\n\",\n\t\tregisterOpts.RemoteClusterName,\n\t)\n\n\treturn nil\n}", "func (n *NetworkRemoveCommand) addFlags() {\n\t//TODO add flags\n}", "func performClusterHealthCheck(c client.Client, metricsClient metrics.Metrics, cvClient cv.ClusterVersion, cfg *osdUpgradeConfig, logger logr.Logger) (bool, error) {\n\tic := cfg.HealthCheck.IgnoredCriticals\n\ticQuery := \"\"\n\tif len(ic) > 0 {\n\t\ticQuery = `,alertname!=\"` + strings.Join(ic, `\",alertname!=\"`) + `\"`\n\t}\n\thealthCheckQuery := `ALERTS{alertstate=\"firing\",severity=\"critical\",namespace=~\"^openshift.*|^kube.*|^default$\",namespace!=\"openshift-customer-monitoring\",namespace!=\"openshift-logging\"` + icQuery + \"}\"\n\talerts, err := metricsClient.Query(healthCheckQuery)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"Unable to query critical alerts: %s\", err)\n\t}\n\n\tif len(alerts.Data.Result) > 0 {\n\t\tlogger.Info(\"There are critical alerts exists, cannot upgrade now\")\n\t\treturn false, fmt.Errorf(\"There are %d critical alerts\", len(alerts.Data.Result))\n\t}\n\n\tresult, err := cvClient.HasDegradedOperators()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif len(result.Degraded) > 0 {\n\t\tlogger.Info(fmt.Sprintf(\"degraded operators :%s\", strings.Join(result.Degraded, \",\")))\n\t\t// Send the metrics for the cluster check failed if we have degraded operators\n\t\treturn false, fmt.Errorf(\"degraded operators :%s\", strings.Join(result.Degraded, \",\"))\n\t}\n\n\treturn true, nil\n}", "func getUpstreamServiceCluster(downstreamIdentity identity.ServiceIdentity, config trafficpolicy.MeshClusterConfig) *xds_cluster.Cluster {\n\tHTTP2ProtocolOptions, err := envoy.GetHTTP2ProtocolOptions()\n\tif err != nil {\n\t\tlog.Error().Err(err).Msgf(\"Error marshalling HTTP2ProtocolOptions for upstream cluster %s\", config.Name)\n\t\treturn nil\n\t}\n\n\tmarshalledUpstreamTLSContext, err := ptypes.MarshalAny(\n\t\tenvoy.GetUpstreamTLSContext(downstreamIdentity, config.Service))\n\tif err != nil {\n\t\tlog.Error().Err(err).Msgf(\"Error marshalling UpstreamTLSContext for upstream cluster %s\", config.Name)\n\t\treturn nil\n\t}\n\n\tremoteCluster := &xds_cluster.Cluster{\n\t\tName: config.Name,\n\t\tTypedExtensionProtocolOptions: HTTP2ProtocolOptions,\n\t\tTransportSocket: &xds_core.TransportSocket{\n\t\t\tName: wellknown.TransportSocketTls,\n\t\t\tConfigType: &xds_core.TransportSocket_TypedConfig{\n\t\t\t\tTypedConfig: marshalledUpstreamTLSContext,\n\t\t\t},\n\t\t},\n\t}\n\n\t// Configure service discovery based on traffic policies\n\tremoteCluster.ClusterDiscoveryType = &xds_cluster.Cluster_Type{Type: xds_cluster.Cluster_EDS}\n\tremoteCluster.EdsClusterConfig = &xds_cluster.Cluster_EdsClusterConfig{EdsConfig: envoy.GetADSConfigSource()}\n\tremoteCluster.LbPolicy = xds_cluster.Cluster_ROUND_ROBIN\n\n\tif config.EnableEnvoyActiveHealthChecks {\n\t\tenableHealthChecksOnCluster(remoteCluster, config.Service)\n\t}\n\treturn remoteCluster\n}", "func NewCluster(ctx *pulumi.Context,\n\tname string, args *ClusterArgs, opts ...pulumi.ResourceOpt) (*Cluster, error) {\n\tinputs := make(map[string]interface{})\n\tif args == nil {\n\t\tinputs[\"applyImmediately\"] = nil\n\t\tinputs[\"availabilityZones\"] = nil\n\t\tinputs[\"backupRetentionPeriod\"] = nil\n\t\tinputs[\"clusterIdentifier\"] = nil\n\t\tinputs[\"clusterIdentifierPrefix\"] = nil\n\t\tinputs[\"engine\"] = nil\n\t\tinputs[\"engineVersion\"] = nil\n\t\tinputs[\"finalSnapshotIdentifier\"] = nil\n\t\tinputs[\"iamDatabaseAuthenticationEnabled\"] = nil\n\t\tinputs[\"iamRoles\"] = nil\n\t\tinputs[\"kmsKeyArn\"] = nil\n\t\tinputs[\"neptuneClusterParameterGroupName\"] = nil\n\t\tinputs[\"neptuneSubnetGroupName\"] = nil\n\t\tinputs[\"port\"] = nil\n\t\tinputs[\"preferredBackupWindow\"] = nil\n\t\tinputs[\"preferredMaintenanceWindow\"] = nil\n\t\tinputs[\"replicationSourceIdentifier\"] = nil\n\t\tinputs[\"skipFinalSnapshot\"] = nil\n\t\tinputs[\"snapshotIdentifier\"] = nil\n\t\tinputs[\"storageEncrypted\"] = nil\n\t\tinputs[\"tags\"] = nil\n\t\tinputs[\"vpcSecurityGroupIds\"] = nil\n\t} else {\n\t\tinputs[\"applyImmediately\"] = args.ApplyImmediately\n\t\tinputs[\"availabilityZones\"] = args.AvailabilityZones\n\t\tinputs[\"backupRetentionPeriod\"] = args.BackupRetentionPeriod\n\t\tinputs[\"clusterIdentifier\"] = args.ClusterIdentifier\n\t\tinputs[\"clusterIdentifierPrefix\"] = args.ClusterIdentifierPrefix\n\t\tinputs[\"engine\"] = args.Engine\n\t\tinputs[\"engineVersion\"] = args.EngineVersion\n\t\tinputs[\"finalSnapshotIdentifier\"] = args.FinalSnapshotIdentifier\n\t\tinputs[\"iamDatabaseAuthenticationEnabled\"] = args.IamDatabaseAuthenticationEnabled\n\t\tinputs[\"iamRoles\"] = args.IamRoles\n\t\tinputs[\"kmsKeyArn\"] = args.KmsKeyArn\n\t\tinputs[\"neptuneClusterParameterGroupName\"] = args.NeptuneClusterParameterGroupName\n\t\tinputs[\"neptuneSubnetGroupName\"] = args.NeptuneSubnetGroupName\n\t\tinputs[\"port\"] = args.Port\n\t\tinputs[\"preferredBackupWindow\"] = args.PreferredBackupWindow\n\t\tinputs[\"preferredMaintenanceWindow\"] = args.PreferredMaintenanceWindow\n\t\tinputs[\"replicationSourceIdentifier\"] = args.ReplicationSourceIdentifier\n\t\tinputs[\"skipFinalSnapshot\"] = args.SkipFinalSnapshot\n\t\tinputs[\"snapshotIdentifier\"] = args.SnapshotIdentifier\n\t\tinputs[\"storageEncrypted\"] = args.StorageEncrypted\n\t\tinputs[\"tags\"] = args.Tags\n\t\tinputs[\"vpcSecurityGroupIds\"] = args.VpcSecurityGroupIds\n\t}\n\tinputs[\"arn\"] = nil\n\tinputs[\"clusterMembers\"] = nil\n\tinputs[\"clusterResourceId\"] = nil\n\tinputs[\"endpoint\"] = nil\n\tinputs[\"hostedZoneId\"] = nil\n\tinputs[\"readerEndpoint\"] = nil\n\ts, err := ctx.RegisterResource(\"aws:neptune/cluster:Cluster\", name, true, inputs, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Cluster{s: s}, nil\n}", "func (z *zpoolctl) Import2(ctx context.Context, dir string, d bool) *execute {\n\targs := []string{\"import\"}\n\tif len(dir) > 0 {\n\t\targs = append(args, dir)\n\t}\n\tif d {\n\t\targs = append(args, \"-D\")\n\t}\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func generateNewConfigFromFlags(cmd *cobra.Command, k8sVersion string, rtime string, drvName string) config.ClusterConfig {\n\tvar cc config.ClusterConfig\n\n\t// networkPlugin cni deprecation warning\n\tchosenNetworkPlugin := viper.GetString(networkPlugin)\n\tif chosenNetworkPlugin == \"cni\" {\n\t\tout.WarningT(\"With --network-plugin=cni, you will need to provide your own CNI. See --cni flag as a user-friendly alternative\")\n\t}\n\n\tif !(driver.IsKIC(drvName) || driver.IsKVM(drvName) || driver.IsQEMU(drvName)) && viper.GetString(network) != \"\" {\n\t\tout.WarningT(\"--network flag is only valid with the docker/podman, KVM and Qemu drivers, it will be ignored\")\n\t}\n\n\tcheckNumaCount(k8sVersion)\n\n\tcheckExtraDiskOptions(cmd, drvName)\n\n\tcc = config.ClusterConfig{\n\t\tName: ClusterFlagValue(),\n\t\tKeepContext: viper.GetBool(keepContext),\n\t\tEmbedCerts: viper.GetBool(embedCerts),\n\t\tMinikubeISO: viper.GetString(isoURL),\n\t\tKicBaseImage: viper.GetString(kicBaseImage),\n\t\tNetwork: getNetwork(drvName),\n\t\tSubnet: viper.GetString(subnet),\n\t\tMemory: getMemorySize(cmd, drvName),\n\t\tCPUs: getCPUCount(drvName),\n\t\tDiskSize: getDiskSize(),\n\t\tDriver: drvName,\n\t\tListenAddress: viper.GetString(listenAddress),\n\t\tHyperkitVpnKitSock: viper.GetString(vpnkitSock),\n\t\tHyperkitVSockPorts: viper.GetStringSlice(vsockPorts),\n\t\tNFSShare: viper.GetStringSlice(nfsShare),\n\t\tNFSSharesRoot: viper.GetString(nfsSharesRoot),\n\t\tDockerEnv: config.DockerEnv,\n\t\tDockerOpt: config.DockerOpt,\n\t\tInsecureRegistry: insecureRegistry,\n\t\tRegistryMirror: registryMirror,\n\t\tHostOnlyCIDR: viper.GetString(hostOnlyCIDR),\n\t\tHypervVirtualSwitch: viper.GetString(hypervVirtualSwitch),\n\t\tHypervUseExternalSwitch: viper.GetBool(hypervUseExternalSwitch),\n\t\tHypervExternalAdapter: viper.GetString(hypervExternalAdapter),\n\t\tKVMNetwork: viper.GetString(kvmNetwork),\n\t\tKVMQemuURI: viper.GetString(kvmQemuURI),\n\t\tKVMGPU: viper.GetBool(kvmGPU),\n\t\tKVMHidden: viper.GetBool(kvmHidden),\n\t\tKVMNUMACount: viper.GetInt(kvmNUMACount),\n\t\tDisableDriverMounts: viper.GetBool(disableDriverMounts),\n\t\tUUID: viper.GetString(uuid),\n\t\tNoVTXCheck: viper.GetBool(noVTXCheck),\n\t\tDNSProxy: viper.GetBool(dnsProxy),\n\t\tHostDNSResolver: viper.GetBool(hostDNSResolver),\n\t\tHostOnlyNicType: viper.GetString(hostOnlyNicType),\n\t\tNatNicType: viper.GetString(natNicType),\n\t\tStartHostTimeout: viper.GetDuration(waitTimeout),\n\t\tExposedPorts: viper.GetStringSlice(ports),\n\t\tSSHIPAddress: viper.GetString(sshIPAddress),\n\t\tSSHUser: viper.GetString(sshSSHUser),\n\t\tSSHKey: viper.GetString(sshSSHKey),\n\t\tSSHPort: viper.GetInt(sshSSHPort),\n\t\tExtraDisks: viper.GetInt(extraDisks),\n\t\tCertExpiration: viper.GetDuration(certExpiration),\n\t\tMount: viper.GetBool(createMount),\n\t\tMountString: viper.GetString(mountString),\n\t\tMount9PVersion: viper.GetString(mount9PVersion),\n\t\tMountGID: viper.GetString(mountGID),\n\t\tMountIP: viper.GetString(mountIPFlag),\n\t\tMountMSize: viper.GetInt(mountMSize),\n\t\tMountOptions: viper.GetStringSlice(mountOptions),\n\t\tMountPort: uint16(viper.GetUint(mountPortFlag)),\n\t\tMountType: viper.GetString(mountTypeFlag),\n\t\tMountUID: viper.GetString(mountUID),\n\t\tBinaryMirror: viper.GetString(binaryMirror),\n\t\tDisableOptimizations: viper.GetBool(disableOptimizations),\n\t\tDisableMetrics: viper.GetBool(disableMetrics),\n\t\tCustomQemuFirmwarePath: viper.GetString(qemuFirmwarePath),\n\t\tSocketVMnetClientPath: detect.SocketVMNetClientPath(),\n\t\tSocketVMnetPath: detect.SocketVMNetPath(),\n\t\tStaticIP: viper.GetString(staticIP),\n\t\tKubernetesConfig: config.KubernetesConfig{\n\t\t\tKubernetesVersion: k8sVersion,\n\t\t\tClusterName: ClusterFlagValue(),\n\t\t\tNamespace: viper.GetString(startNamespace),\n\t\t\tAPIServerName: viper.GetString(apiServerName),\n\t\t\tAPIServerNames: apiServerNames,\n\t\t\tAPIServerIPs: apiServerIPs,\n\t\t\tDNSDomain: viper.GetString(dnsDomain),\n\t\t\tFeatureGates: viper.GetString(featureGates),\n\t\t\tContainerRuntime: rtime,\n\t\t\tCRISocket: viper.GetString(criSocket),\n\t\t\tNetworkPlugin: chosenNetworkPlugin,\n\t\t\tServiceCIDR: viper.GetString(serviceCIDR),\n\t\t\tImageRepository: getRepository(cmd, k8sVersion),\n\t\t\tExtraOptions: getExtraOptions(),\n\t\t\tShouldLoadCachedImages: viper.GetBool(cacheImages),\n\t\t\tCNI: getCNIConfig(cmd),\n\t\t\tNodePort: viper.GetInt(apiServerPort),\n\t\t},\n\t\tMultiNodeRequested: viper.GetInt(nodes) > 1,\n\t}\n\tcc.VerifyComponents = interpretWaitFlag(*cmd)\n\tif viper.GetBool(createMount) && driver.IsKIC(drvName) {\n\t\tcc.ContainerVolumeMounts = []string{viper.GetString(mountString)}\n\t}\n\n\tif driver.IsKIC(drvName) {\n\t\tsi, err := oci.CachedDaemonInfo(drvName)\n\t\tif err != nil {\n\t\t\texit.Message(reason.Usage, \"Ensure your {{.driver_name}} is running and is healthy.\", out.V{\"driver_name\": driver.FullName(drvName)})\n\t\t}\n\t\tif si.Rootless {\n\t\t\tout.Styled(style.Notice, \"Using rootless {{.driver_name}} driver\", out.V{\"driver_name\": driver.FullName(drvName)})\n\t\t\tif cc.KubernetesConfig.ContainerRuntime == constants.Docker {\n\t\t\t\texit.Message(reason.Usage, \"--container-runtime must be set to \\\"containerd\\\" or \\\"cri-o\\\" for rootless\")\n\t\t\t}\n\t\t\t// KubeletInUserNamespace feature gate is essential for rootless driver.\n\t\t\t// See https://kubernetes.io/docs/tasks/administer-cluster/kubelet-in-userns/\n\t\t\tcc.KubernetesConfig.FeatureGates = addFeatureGate(cc.KubernetesConfig.FeatureGates, \"KubeletInUserNamespace=true\")\n\t\t} else {\n\t\t\tif oci.IsRootlessForced() {\n\t\t\t\tif driver.IsDocker(drvName) {\n\t\t\t\t\texit.Message(reason.Usage, \"Using rootless Docker driver was required, but the current Docker does not seem rootless. Try 'docker context use rootless' .\")\n\t\t\t\t} else {\n\t\t\t\t\texit.Message(reason.Usage, \"Using rootless driver was required, but the current driver does not seem rootless\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tout.Styled(style.Notice, \"Using {{.driver_name}} driver with root privileges\", out.V{\"driver_name\": driver.FullName(drvName)})\n\t\t}\n\t\t// for btrfs: if k8s < v1.25.0-beta.0 set kubelet's LocalStorageCapacityIsolation feature gate flag to false,\n\t\t// and if k8s >= v1.25.0-beta.0 (when it went ga and removed as feature gate), set kubelet's localStorageCapacityIsolation option (via kubeadm config) to false.\n\t\t// ref: https://github.com/kubernetes/minikube/issues/14728#issue-1327885840\n\t\tif si.StorageDriver == \"btrfs\" {\n\t\t\tif semver.MustParse(strings.TrimPrefix(k8sVersion, version.VersionPrefix)).LT(semver.MustParse(\"1.25.0-beta.0\")) {\n\t\t\t\tklog.Info(\"auto-setting LocalStorageCapacityIsolation to false because using btrfs storage driver\")\n\t\t\t\tcc.KubernetesConfig.FeatureGates = addFeatureGate(cc.KubernetesConfig.FeatureGates, \"LocalStorageCapacityIsolation=false\")\n\t\t\t} else if !cc.KubernetesConfig.ExtraOptions.Exists(\"kubelet.localStorageCapacityIsolation=false\") {\n\t\t\t\tif err := cc.KubernetesConfig.ExtraOptions.Set(\"kubelet.localStorageCapacityIsolation=false\"); err != nil {\n\t\t\t\t\texit.Error(reason.InternalConfigSet, \"failed to set extra option\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif runtime.GOOS == \"linux\" && si.DockerOS == \"Docker Desktop\" {\n\t\t\tout.WarningT(\"For an improved experience it's recommended to use Docker Engine instead of Docker Desktop.\\nDocker Engine installation instructions: https://docs.docker.com/engine/install/#server\")\n\t\t}\n\t}\n\n\treturn cc\n}", "func init() {\n\tRootCmd.AddCommand(ClusterCommand)\n}", "func (a *Client) V2InstallCluster(ctx context.Context, params *V2InstallClusterParams) (*V2InstallClusterAccepted, error) {\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"v2InstallCluster\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/v2/clusters/{cluster_id}/actions/install\",\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: &V2InstallClusterReader{formats: a.formats},\n\t\tAuthInfo: a.authInfo,\n\t\tContext: ctx,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*V2InstallClusterAccepted), nil\n\n}", "func setupCluster(synkPath string, cluster *cluster) error {\n\tkindcfg := &kindconfig.Cluster{\n\t\tNodes: []kindconfig.Node{\n\t\t\t{\n\t\t\t\tRole: kindconfig.ControlPlaneRole,\n\t\t\t\tImage: kinddefaults.Image,\n\t\t\t}, {\n\t\t\t\tRole: kindconfig.WorkerRole,\n\t\t\t\tImage: kinddefaults.Image,\n\t\t\t},\n\t\t},\n\t}\n\tcluster.kind = kindcluster.NewProvider()\n\n\t// Create kubeconfig file for use by synk or the dev.\n\tkubeConfig, err := ioutil.TempFile(\"\", \"kubeconfig-\")\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"create temp kubeconfig\")\n\t}\n\tcluster.kubeConfigPath = kubeConfig.Name()\n\tif err := kubeConfig.Close(); err != nil {\n\t\treturn errors.Wrap(err, \"close temp kubeconfig\")\n\t}\n\n\tif err := cluster.kind.Create(\n\t\tcluster.genName,\n\t\tkindcluster.CreateWithV1Alpha4Config(kindcfg),\n\t\tkindcluster.CreateWithKubeconfigPath(cluster.kubeConfigPath),\n\t); err != nil {\n\t\treturn errors.Wrapf(err, \"create cluster %q\", cluster.genName)\n\t}\n\tkubecfgRaw, err := ioutil.ReadFile(cluster.kubeConfigPath)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"read kube config\")\n\t}\n\tkubecfg, err := clientcmd.NewClientConfigFromBytes(kubecfgRaw)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"decode kube config\")\n\t}\n\tcluster.restCfg, err = kubecfg.ClientConfig()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"get rest config\")\n\t}\n\tlog.Printf(\"To use the cluster, run KUBECONFIG=%s kubectl cluster-info\", cluster.kubeConfigPath)\n\n\t// Setup permissive binding we also have in cloud and robot clusters.\n\tctx := context.Background()\n\n\tc, err := client.New(cluster.restCfg, client.Options{})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"create client\")\n\t}\n\tif err := c.Create(ctx, &rbac.ClusterRoleBinding{\n\t\tObjectMeta: meta.ObjectMeta{\n\t\t\tName: \"permissive-binding\",\n\t\t},\n\t\tRoleRef: rbac.RoleRef{\n\t\t\tAPIGroup: \"rbac.authorization.k8s.io\",\n\t\t\tKind: \"ClusterRole\",\n\t\t\tName: \"cluster-admin\",\n\t\t},\n\t\tSubjects: []rbac.Subject{{\n\t\t\tAPIGroup: \"rbac.authorization.k8s.io\",\n\t\t\tKind: \"Group\",\n\t\t\tName: \"system:serviceaccounts\",\n\t\t}},\n\t}); err != nil {\n\t\treturn errors.Wrap(err, \"create permissive role binding\")\n\t}\n\n\t// Setup service account and create image pull secrets.\n\tif token := os.Getenv(\"ACCESS_TOKEN\"); token != \"\" {\n\t\t// Use the same secret name as the GCR credential refresher would\n\t\t// on robots.\n\t\t// This makes some testing of components easier, that assume this\n\t\t// secret to exist, e.g. ChartAssignment controller.\n\t\tsecret := &core.Secret{\n\t\t\tObjectMeta: meta.ObjectMeta{\n\t\t\t\tNamespace: \"default\",\n\t\t\t\tName: gcr.SecretName,\n\t\t\t},\n\t\t\tType: core.SecretTypeDockercfg,\n\t\t\tData: map[string][]byte{\n\t\t\t\t\".dockercfg\": gcr.DockerCfgJSON(token),\n\t\t\t},\n\t\t}\n\t\tif err := c.Create(ctx, secret); err != nil {\n\t\t\treturn errors.Wrap(err, \"create pull secret\")\n\t\t}\n\t\tif err := backoff.Retry(\n\t\t\tfunc() error {\n\t\t\t\tvar sa core.ServiceAccount\n\t\t\t\terr := c.Get(ctx, client.ObjectKey{\"default\", \"default\"}, &sa)\n\t\t\t\tif k8serrors.IsNotFound(err) {\n\t\t\t\t\treturn errors.New(\"not found\")\n\t\t\t\t} else if err != nil {\n\t\t\t\t\treturn backoff.Permanent(errors.Wrap(err, \"get service account\"))\n\t\t\t\t}\n\t\t\t\tsa.ImagePullSecrets = append(sa.ImagePullSecrets, core.LocalObjectReference{\n\t\t\t\t\tName: gcr.SecretName,\n\t\t\t\t})\n\t\t\t\tif err = c.Update(ctx, &sa); k8serrors.IsConflict(err) {\n\t\t\t\t\treturn fmt.Errorf(\"conflict\")\n\t\t\t\t} else if err != nil {\n\t\t\t\t\treturn backoff.Permanent(errors.Wrap(err, \"update service account\"))\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tbackoff.WithMaxRetries(backoff.NewConstantBackOff(time.Second), 60),\n\t\t); err != nil {\n\t\t\treturn errors.Wrap(err, \"inject pull secret\")\n\t\t}\n\t}\n\n\t// Wait for a node to be ready, by checking for node taints (incl. NotReady)\n\t// (context: b/128660997)\n\tif err := backoff.Retry(\n\t\tfunc() error {\n\t\t\tvar nds core.NodeList\n\t\t\tif err := c.List(ctx, &nds); err != nil {\n\t\t\t\treturn backoff.Permanent(err)\n\t\t\t}\n\t\t\tfor _, n := range nds.Items {\n\t\t\t\tif len(n.Spec.Taints) == 0 {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"taints not removed\")\n\t\t},\n\t\tbackoff.WithMaxRetries(backoff.NewConstantBackOff(time.Second), 240),\n\t); err != nil {\n\t\treturn errors.Wrap(err, \"wait for node taints to be removed\")\n\t}\n\tcmd := exec.Command(\n\t\tsynkPath,\n\t\t\"init\",\n\t\t\"--kubeconfig\", cluster.kubeConfigPath,\n\t)\n\tif output, err := cmd.CombinedOutput(); err != nil {\n\t\treturn errors.Errorf(\"install Helm: %v; output:\\n%s\\n\", err, output)\n\t}\n\treturn nil\n}", "func (s *FederationSyncController) syncToClusters(selectedClusters, unselectedClusters []string,\n\ttemplate, override *unstructured.Unstructured) util.ReconciliationStatus {\n\n\ttemplateKind := s.typeConfig.GetTemplate().Kind\n\tkey := util.NewQualifiedName(template).String()\n\n\tglog.V(3).Infof(\"Syncing %s %q in underlying clusters, selected clusters are: %s, unselected clusters are: %s\",\n\t\ttemplateKind, key, selectedClusters, unselectedClusters)\n\n\toperations, err := s.clusterOperations(selectedClusters, unselectedClusters, template, override, key)\n\tif err != nil {\n\t\ts.eventRecorder.Eventf(template, corev1.EventTypeWarning, \"FedClusterOperationsError\",\n\t\t\t\"Error obtaining sync operations for %s: %s error: %s\", templateKind, key, err.Error())\n\t\treturn util.StatusError\n\t}\n\n\tif len(operations) == 0 {\n\t\treturn util.StatusAllOK\n\t}\n\n\t// TODO(marun) raise the visibility of operationErrors to aid in debugging\n\tversionMap, operationErrors := s.updater.Update(operations)\n\n\terr = s.versionManager.Update(template, override, selectedClusters, versionMap)\n\tif err != nil {\n\t\truntime.HandleError(fmt.Errorf(\"Failed to update version status for %s %q: %v\", templateKind, key, err))\n\t\treturn util.StatusError\n\t}\n\n\tif len(operationErrors) > 0 {\n\t\truntime.HandleError(fmt.Errorf(\"Failed to execute updates for %s %q: %v\", templateKind,\n\t\t\tkey, operationErrors))\n\t\treturn util.StatusError\n\t}\n\n\treturn util.StatusAllOK\n}", "func TestSyncClusterComplex(t *testing.T) {\n\tcontroller, clusterStore, machineSetStore, _, clusterOperatorClient := newTestClusterController()\n\n\tcluster := newClusterWithSizes(1,\n\t\tclusteroperator.ClusterMachineSet{\n\t\t\tMachineSetConfig: clusteroperator.MachineSetConfig{\n\t\t\t\tSize: 1,\n\t\t\t\tNodeType: clusteroperator.NodeTypeCompute,\n\t\t\t},\n\t\t\tName: \"realized and un-mutated\",\n\t\t},\n\t\tclusteroperator.ClusterMachineSet{\n\t\t\tMachineSetConfig: clusteroperator.MachineSetConfig{\n\t\t\t\tSize: 1,\n\t\t\t\tNodeType: clusteroperator.NodeTypeCompute,\n\t\t\t},\n\t\t\tName: \"realized but mutated\",\n\t\t},\n\t\tclusteroperator.ClusterMachineSet{\n\t\t\tMachineSetConfig: clusteroperator.MachineSetConfig{\n\t\t\t\tSize: 1,\n\t\t\t\tNodeType: clusteroperator.NodeTypeCompute,\n\t\t\t},\n\t\t\tName: \"unrealized\",\n\t\t},\n\t)\n\tclusterStore.Add(cluster)\n\n\tnewMachineSetsWithSizes(machineSetStore, cluster, 2,\n\t\tclusteroperator.ClusterMachineSet{\n\t\t\tMachineSetConfig: clusteroperator.MachineSetConfig{\n\t\t\t\tSize: 1,\n\t\t\t\tNodeType: clusteroperator.NodeTypeCompute,\n\t\t\t},\n\t\t\tName: \"realized and un-mutated\",\n\t\t},\n\t\tclusteroperator.ClusterMachineSet{\n\t\t\tMachineSetConfig: clusteroperator.MachineSetConfig{\n\t\t\t\tSize: 2,\n\t\t\t\tNodeType: clusteroperator.NodeTypeCompute,\n\t\t\t},\n\t\t\tName: \"realized but mutated\",\n\t\t},\n\t\tclusteroperator.ClusterMachineSet{\n\t\t\tMachineSetConfig: clusteroperator.MachineSetConfig{\n\t\t\t\tSize: 1,\n\t\t\t\tNodeType: clusteroperator.NodeTypeCompute,\n\t\t\t},\n\t\t\tName: \"removed from cluster\",\n\t\t},\n\t)\n\n\tcontroller.syncCluster(getKey(cluster, t))\n\n\tvalidateClientActions(t, \"TestSyncClusterComplex\", clusterOperatorClient,\n\t\tnewExpectedMachineSetDeleteAction(cluster, \"master\"),\n\t\tnewExpectedMachineSetCreateAction(cluster, \"master\"),\n\t\tnewExpectedMachineSetDeleteAction(cluster, \"realized but mutated\"),\n\t\tnewExpectedMachineSetCreateAction(cluster, \"realized but mutated\"),\n\t\tnewExpectedMachineSetCreateAction(cluster, \"unrealized\"),\n\t\tnewExpectedMachineSetDeleteAction(cluster, \"removed from cluster\"),\n\t\texpectedClusterStatusUpdateAction{machineSets: 3}, // status only counts the 2 realized compute nodes + 1 master\n\t)\n\n\tvalidateControllerExpectations(t, \"TestSyncClusterComplex\", controller, cluster, 3, 3)\n}", "func (m *Monitor) AddLocalCluster(versionObj *unstructured.Unstructured) bool {\n\tvar clusterVersionGvr = schema.GroupVersionResource{\n\t\tGroup: \"config.openshift.io\",\n\t\tVersion: \"v1\",\n\t\tResource: \"clusterversions\",\n\t}\n\tvar dynamicClient dynamic.Interface\n\tvar err error\n\tglog.V(2).Info(\"Adding Local Cluster ID.\")\n\tif versionObj == nil {\n\t\tdynamicClient = config.GetDynamicClient()\n\t\tversionObj, err = dynamicClient.Resource(clusterVersionGvr).Get(context.TODO(), \"version\", metav1.GetOptions{})\n\t}\n\tif err != nil {\n\t\tglog.V(2).Infof(\"Failed to get clusterversions : %v\", err)\n\t\treturn false\n\t}\n\tclusterID, _, err := unstructured.NestedString(versionObj.Object, \"spec\", \"clusterID\")\n\tif err != nil {\n\t\tglog.V(2).Infof(\"Failed to get OCP clusterID from version: %v\", err)\n\t\treturn false\n\t}\n\t// If the cluster ID is not empty add to list and return true\n\tif clusterID != \"\" {\n\t\tlock.Lock()\n\t\tm.ManagedClusterInfo = append(m.ManagedClusterInfo, types.ManagedClusterInfo{\n\t\t\tClusterID: clusterID,\n\t\t\tNamespace: localClusterName,\n\t\t})\n\t\tlock.Unlock()\n\t\treturn true\n\t}\n\n\treturn false\n}", "func startAccNeo4j(vcsa *vcsa.VcsaConnector, dcs []*datacenter.DatacenterConfig, timeStamp string, acc telegraf.Accumulator) error {\n\t// create dcaiAgent to get info\n\tdcaiAgent, err := dcai.GetDcaiAgent()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvcsaNode, err := genNode(\"VMClusterCenter\", dcaiAgent.GetSaiClusterDomainId(), dcaiAgent.GetSaiClusterName(), vcsa.Url)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tif dcs == nil {\n\t\t// if encount case that one vcsa doesn't contain any datacenter would update the time of vcsa without update datacenters' nodes information\n\t\tacc.AddFields(\"db_relay\", map[string]interface{}{\"cmd\": mergeNeo4jNdoes(vcsaNode, timeStamp)}, map[string]string{\"dc_tag\": \"na\"}, time.Now())\n\t\tlog.Printf(\"The vcsa %s doesn't contains any datacenters\", vcsa.Url)\n\n\t\treturn nil\n\t}\n\n\terr = vmClusterContainsVMHostAndVMDatastore(vcsaNode, dcaiAgent, dcs, timeStamp, acc)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func joinExisting(localNode *cluster.Node, tokenStorage cluster.LockableTokenStorage, resolver *cluster.Resolver, importer syncing.Importer) error {\n\ttoSteal, err := cluster.SuggestReservationsDistributed(tokenStorage, resolver)\n\tlog.Printf(\"Stealing %d tokens: [%s]\", len(toSteal), tokensToString(toSteal, \" \"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar reserved []int\n\tfor _, tokenToSteal := range toSteal {\n\n\t\tok, err := tokenStorage.Reserve(tokenToSteal, localNode.Name)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif ok {\n\t\t\treserved = append(reserved, tokenToSteal)\n\t\t}\n\t}\n\n\tlog.Println(\"Starting import of primary data\")\n\ttargetClient, _ := syncing.NewInfluxClientHTTPFromNode(*localNode)\n\timporter.ImportPartitioned(reserved, targetClient)\n\n\toldDataHolders := map[int][]*cluster.Node{}\n\tfor _, token := range reserved {\n\t\toldDataHolders[token] = resolver.FindNodesByKey(token, cluster.WRITE)\n\t\tfor _, secondary := range resolver.ReverseSecondaryLookup(token) {\n\t\t\toldDataHolders[secondary] = resolver.FindNodesByKey(secondary, cluster.WRITE)\n\t\t}\n\t}\n\tfor _, token := range reserved {\n\t\terr = tokenStorage.Release(token)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\terr = tokenStorage.Assign(token, localNode.Name)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\t// Update the resolver with the most current assignments.\n\t\tresolver.AddToken(token, localNode)\n\t}\n\n\tlocalNodeClient, _ := syncing.NewInfluxClientHTTPFromNode(*localNode)\n\n\t// This takes one token and finds what tokens are also replicated to to the same node this node is assigned to.\n\t// This can only be done after assigning the tokens as the resolver needs to understand which\n\t// nodes tokens are allocated to, as the logic is skipping tokens assigned to the same node.\n\tsecondaryTokens := []int{}\n\tfor _, token := range reserved {\n\t\tsecondaryTokens = append(secondaryTokens, resolver.ReverseSecondaryLookup(token)...)\n\t}\n\tif len(secondaryTokens) > 0 {\n\t\tlog.Println(\"Starting import of replicated data\")\n\t\timporter.ImportPartitioned(secondaryTokens, localNodeClient)\n\t}\n\n\t// Importing non partitioned after tokens been assigned to get primary and secondary data.\n\timporter.ImportNonPartitioned(localNodeClient)\n\n\t// The filtered list of primaries which not longer should hold data for assigned tokens.\n\tdeleteMap := map[int]*cluster.Node{}\n\tfor token, nodes := range oldDataHolders {\n\t\tfor _, node := range nodes {\n\t\t\t// check if the token still resolves the location\n\t\t\t// if not, the data should be deleted\n\t\t\tshouldDelete := true\n\t\t\tfor _, replLoc := range resolver.FindByKey(token, cluster.WRITE) {\n\t\t\t\tif replLoc == node.DataLocation {\n\t\t\t\t\tshouldDelete = false\n\t\t\t\t}\n\t\t\t}\n\t\t\tif shouldDelete {\n\t\t\t\tdeleteMap[token] = node\n\t\t\t}\n\t\t}\n\t}\n\tdeleteTokensData(deleteMap, importer)\n\treturn nil\n}", "func runNomadClusterSeparateTest(t *testing.T, packerBuildName string) {\n\texamplesDir := test_structure.CopyTerraformFolderToTemp(t, REPO_ROOT, \"/\")\n\n\tdefer test_structure.RunTestStage(t, \"teardown\", func() {\n\t\tterraformOptions := test_structure.LoadTerraformOptions(t, examplesDir)\n\t\tterraform.Destroy(t, terraformOptions)\n\n\t\tamiId := test_structure.LoadAmiId(t, examplesDir)\n\t\tawsRegion := test_structure.LoadString(t, examplesDir, SAVED_AWS_REGION)\n\t\taws.DeleteAmi(t, awsRegion, amiId)\n\t})\n\n\ttest_structure.RunTestStage(t, \"setup_ami\", func() {\n\t\tawsRegion := getRandomRegion(t)\n\t\ttest_structure.SaveString(t, examplesDir, SAVED_AWS_REGION, awsRegion)\n\n\t\tuniqueId := random.UniqueId()\n\t\ttest_structure.SaveString(t, examplesDir, SAVED_UNIQUE_ID, uniqueId)\n\n\t\tamiId := buildAmi(t, filepath.Join(examplesDir, \"examples\", \"nomad-consul-ami\", \"nomad-consul.json\"), packerBuildName, awsRegion, uniqueId)\n\t\ttest_structure.SaveAmiId(t, examplesDir, amiId)\n\t})\n\n\ttest_structure.RunTestStage(t, \"deploy\", func() {\n\t\tamiId := test_structure.LoadAmiId(t, examplesDir)\n\t\tawsRegion := test_structure.LoadString(t, examplesDir, SAVED_AWS_REGION)\n\t\tuniqueId := test_structure.LoadString(t, examplesDir, SAVED_UNIQUE_ID)\n\n\t\tterraformOptions := &terraform.Options{\n\t\t\tTerraformDir: filepath.Join(examplesDir, \"examples\", \"nomad-consul-separate-cluster\"),\n\t\t\tVars: map[string]interface{}{\n\t\t\t\tCLUSTER_SEPARATE_EXAMPLE_VAR_NOMAD_CLUSTER_NAME: fmt.Sprintf(\"test-%s\", uniqueId),\n\t\t\t\tCLUSTER_SEPARATE_EXAMPLE_VAR_CONSUL_CLUSTER_NAME: fmt.Sprintf(\"test-%s\", uniqueId),\n\t\t\t\tCLUSTER_SEPARATE_EXAMPLE_VAR_NUM_NOMAD_SERVERS: DEFAULT_NUM_SERVERS,\n\t\t\t\tCLUSTER_SEPARATE_EXAMPLE_VAR_NUM_CONSUL_SERVERS: DEFAULT_NUM_SERVERS,\n\t\t\t\tCLUSTER_SEPARATE_EXAMPLE_VAR_NUM_NOMAD_CLIENTS: DEFAULT_NUM_CLIENTS,\n\t\t\t\tVAR_AMI_ID: amiId,\n\t\t\t},\n\t\t\tEnvVars: map[string]string{\n\t\t\t\tENV_VAR_AWS_REGION: awsRegion,\n\t\t\t},\n\t\t}\n\t\ttest_structure.SaveTerraformOptions(t, examplesDir, terraformOptions)\n\n\t\tterraform.InitAndApply(t, terraformOptions)\n\t})\n\n\ttest_structure.RunTestStage(t, \"validate\", func() {\n\t\tterraformOptions := test_structure.LoadTerraformOptions(t, examplesDir)\n\t\tawsRegion := test_structure.LoadString(t, examplesDir, SAVED_AWS_REGION)\n\n\t\tcheckNomadClusterIsWorking(t, CLUSTER_SEPARATE_EXAMPLE_OUTPUT_NOMAD_SERVER_ASG_NAME, terraformOptions, awsRegion)\n\t})\n}", "func cmdAdd(args *skel.CmdArgs) error {\n\tipamConf, confVersion, err := allocator.LoadIPAMConfig(args.StdinData, args.Args)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresult := &current.Result{}\n\n\ttlsInfo := &transport.TLSInfo{\n\t\tCertFile: ipamConf.CertFile,\n\t\tKeyFile: ipamConf.KeyFile,\n\t\tTrustedCAFile: ipamConf.TrustedCAFile,\n\t}\n\ttlsConfig, _ := tlsInfo.ClientConfig()\n\n\tstore, err := etcd.New(ipamConf.Name, strings.Split(ipamConf.Endpoints, \",\"), tlsConfig)\n\tdefer store.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Get annotations of the pod, such as ipAddrs and current user.\n\n\t// 1. Get conf for k8s client and create a k8s_client\n\tk8sClient, err := k8s.NewK8sClient(ipamConf.Kubernetes, ipamConf.Policy)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// 2. Get K8S_POD_NAME and K8S_POD_NAMESPACE.\n\tk8sArgs := k8s.K8sArgs{}\n\tif err := types.LoadArgs(args.Args, &k8sArgs); err != nil {\n\t\treturn err\n\t}\n\n\t// 3. Get annotations from k8s_client via K8S_POD_NAME and K8S_POD_NAMESPACE.\n\tlabel, annot, err := k8s.GetK8sPodInfo(k8sClient, string(k8sArgs.K8S_POD_NAME), string(k8sArgs.K8S_POD_NAMESPACE))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error while read annotaions for pod\" + err.Error())\n\t}\n\n\tuserDefinedSubnet := annot[\"cni.daocloud.io/subnet\"]\n\tuserDefinedRoutes := annot[\"cni.daocloud.io/routes\"]\n\tuserDefinedGateway := annot[\"cni.daocloud.io/gateway\"]\n\n\t// app := label[\"io.daocloud.dce.app\"]\n\tapp := label[\"dce.daocloud.io/app\"]\n\tif app == \"\" {\n\t\tapp = \"unknown\"\n\t}\n\tservice, err := k8s.ResourceControllerName(k8sClient, string(k8sArgs.K8S_POD_NAME), string(k8sArgs.K8S_POD_NAMESPACE))\n\n\tif service == \"\" {\n\t\tservice = \"unknown\"\n\t}\n\n\tif userDefinedSubnet == \"\" {\n\t\treturn fmt.Errorf(\"No ip found for pod \" + string(k8sArgs.K8S_POD_NAME))\n\t}\n\n\t_, subnet, err := net.ParseCIDR(userDefinedSubnet)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif userDefinedGateway != \"\" {\n\t\tgw := types.Route{\n\t\t\tDst: net.IPNet{\n\t\t\t\tIP: net.IPv4zero,\n\t\t\t\tMask: net.IPv4Mask(0, 0, 0, 0),\n\t\t\t},\n\t\t\tGW: net.ParseIP(userDefinedGateway),\n\t\t}\n\t\tresult.Routes = append(result.Routes, &gw)\n\t}\n\n\tif userDefinedRoutes != \"\" {\n\t\troutes := strings.Split(userDefinedRoutes, \";\")\n\t\tfor _, r := range routes {\n\t\t\t_, dst, _ := net.ParseCIDR(strings.Split(r, \",\")[0])\n\t\t\tgateway := strings.Split(r, \",\")[1]\n\n\t\t\tgw := types.Route{\n\t\t\t\tDst: *dst,\n\t\t\t\tGW: net.ParseIP(gateway),\n\t\t\t}\n\t\t\tresult.Routes = append(result.Routes, &gw)\n\t\t}\n\t}\n\t// result.Routes = append(result.Routes, ipamConf.Routes...)\n\n\tif ipamConf.Service_IPNet != \"\" {\n\t\t_, service_net, err := net.ParseCIDR(ipamConf.Service_IPNet)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Invalid service cluster ip range: \" + ipamConf.Service_IPNet)\n\t\t}\n\t\tfor _, node_ip := range ipamConf.Node_IPs {\n\t\t\tif subnet.Contains(net.ParseIP(node_ip)) {\n\t\t\t\tsn := types.Route{\n\t\t\t\t\tDst: *service_net,\n\t\t\t\t\tGW: net.ParseIP(node_ip),\n\t\t\t\t}\n\t\t\t\tresult.Routes = append(result.Routes, &sn)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// If none of node_ip in subnet, nothing to do.\n\t\t}\n\t}\n\n\tuserDefinedNameserver := annot[\"cni.daocloud.io/nameserver\"]\n\tuserDefinedDomain := annot[\"cni.daocloud.io/domain\"]\n\tuserDefinedSearch := annot[\"cni.daocloud.io/search\"]\n\tuserDefinedOptions := annot[\"cni.daocloud.io/options\"]\n\tdns, err := generateDNS(userDefinedNameserver, userDefinedDomain, userDefinedSearch, userDefinedOptions)\n\tresult.DNS = *dns\n\n\talloc := allocator.NewAnchorAllocator(subnet, store, string(k8sArgs.K8S_POD_NAME), string(k8sArgs.K8S_POD_NAMESPACE), app, service)\n\n\tipConf, err := alloc.Get(args.ContainerID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Below here, if error, we should call store.Release(args.ContainerID) to release the IP written to database.\n\tif userDefinedGateway == \"\" {\n\t\tgw := types.Route{\n\t\t\tDst: net.IPNet{\n\t\t\t\tIP: net.IPv4zero,\n\t\t\t\tMask: net.IPv4Mask(0, 0, 0, 0),\n\t\t\t},\n\t\t\tGW: ipConf.Gateway,\n\t\t}\n\t\tresult.Routes = append(result.Routes, &gw)\n\t}\n\tresult.IPs = append(result.IPs, ipConf)\n\n\treturn types.PrintResult(result, confVersion)\n}", "func GenerateCluster(resp *svcsdk.DescribeClustersOutput) *svcapitypes.Cluster {\n\tcr := &svcapitypes.Cluster{}\n\n\tfound := false\n\tfor _, elem := range resp.Clusters {\n\t\tif elem.ActiveServicesCount != nil {\n\t\t\tcr.Status.AtProvider.ActiveServicesCount = elem.ActiveServicesCount\n\t\t} else {\n\t\t\tcr.Status.AtProvider.ActiveServicesCount = nil\n\t\t}\n\t\tif elem.Attachments != nil {\n\t\t\tf1 := []*svcapitypes.Attachment{}\n\t\t\tfor _, f1iter := range elem.Attachments {\n\t\t\t\tf1elem := &svcapitypes.Attachment{}\n\t\t\t\tif f1iter.Details != nil {\n\t\t\t\t\tf1elemf0 := []*svcapitypes.KeyValuePair{}\n\t\t\t\t\tfor _, f1elemf0iter := range f1iter.Details {\n\t\t\t\t\t\tf1elemf0elem := &svcapitypes.KeyValuePair{}\n\t\t\t\t\t\tif f1elemf0iter.Name != nil {\n\t\t\t\t\t\t\tf1elemf0elem.Name = f1elemf0iter.Name\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif f1elemf0iter.Value != nil {\n\t\t\t\t\t\t\tf1elemf0elem.Value = f1elemf0iter.Value\n\t\t\t\t\t\t}\n\t\t\t\t\t\tf1elemf0 = append(f1elemf0, f1elemf0elem)\n\t\t\t\t\t}\n\t\t\t\t\tf1elem.Details = f1elemf0\n\t\t\t\t}\n\t\t\t\tif f1iter.Id != nil {\n\t\t\t\t\tf1elem.ID = f1iter.Id\n\t\t\t\t}\n\t\t\t\tif f1iter.Status != nil {\n\t\t\t\t\tf1elem.Status = f1iter.Status\n\t\t\t\t}\n\t\t\t\tif f1iter.Type != nil {\n\t\t\t\t\tf1elem.Type = f1iter.Type\n\t\t\t\t}\n\t\t\t\tf1 = append(f1, f1elem)\n\t\t\t}\n\t\t\tcr.Status.AtProvider.Attachments = f1\n\t\t} else {\n\t\t\tcr.Status.AtProvider.Attachments = nil\n\t\t}\n\t\tif elem.AttachmentsStatus != nil {\n\t\t\tcr.Status.AtProvider.AttachmentsStatus = elem.AttachmentsStatus\n\t\t} else {\n\t\t\tcr.Status.AtProvider.AttachmentsStatus = nil\n\t\t}\n\t\tif elem.CapacityProviders != nil {\n\t\t\tf3 := []*string{}\n\t\t\tfor _, f3iter := range elem.CapacityProviders {\n\t\t\t\tvar f3elem string\n\t\t\t\tf3elem = *f3iter\n\t\t\t\tf3 = append(f3, &f3elem)\n\t\t\t}\n\t\t\tcr.Spec.ForProvider.CapacityProviders = f3\n\t\t} else {\n\t\t\tcr.Spec.ForProvider.CapacityProviders = nil\n\t\t}\n\t\tif elem.ClusterArn != nil {\n\t\t\tcr.Status.AtProvider.ClusterARN = elem.ClusterArn\n\t\t} else {\n\t\t\tcr.Status.AtProvider.ClusterARN = nil\n\t\t}\n\t\tif elem.ClusterName != nil {\n\t\t\tcr.Spec.ForProvider.ClusterName = elem.ClusterName\n\t\t} else {\n\t\t\tcr.Spec.ForProvider.ClusterName = nil\n\t\t}\n\t\tif elem.Configuration != nil {\n\t\t\tf6 := &svcapitypes.ClusterConfiguration{}\n\t\t\tif elem.Configuration.ExecuteCommandConfiguration != nil {\n\t\t\t\tf6f0 := &svcapitypes.ExecuteCommandConfiguration{}\n\t\t\t\tif elem.Configuration.ExecuteCommandConfiguration.KmsKeyId != nil {\n\t\t\t\t\tf6f0.KMSKeyID = elem.Configuration.ExecuteCommandConfiguration.KmsKeyId\n\t\t\t\t}\n\t\t\t\tif elem.Configuration.ExecuteCommandConfiguration.LogConfiguration != nil {\n\t\t\t\t\tf6f0f1 := &svcapitypes.ExecuteCommandLogConfiguration{}\n\t\t\t\t\tif elem.Configuration.ExecuteCommandConfiguration.LogConfiguration.CloudWatchEncryptionEnabled != nil {\n\t\t\t\t\t\tf6f0f1.CloudWatchEncryptionEnabled = elem.Configuration.ExecuteCommandConfiguration.LogConfiguration.CloudWatchEncryptionEnabled\n\t\t\t\t\t}\n\t\t\t\t\tif elem.Configuration.ExecuteCommandConfiguration.LogConfiguration.CloudWatchLogGroupName != nil {\n\t\t\t\t\t\tf6f0f1.CloudWatchLogGroupName = elem.Configuration.ExecuteCommandConfiguration.LogConfiguration.CloudWatchLogGroupName\n\t\t\t\t\t}\n\t\t\t\t\tif elem.Configuration.ExecuteCommandConfiguration.LogConfiguration.S3BucketName != nil {\n\t\t\t\t\t\tf6f0f1.S3BucketName = elem.Configuration.ExecuteCommandConfiguration.LogConfiguration.S3BucketName\n\t\t\t\t\t}\n\t\t\t\t\tif elem.Configuration.ExecuteCommandConfiguration.LogConfiguration.S3EncryptionEnabled != nil {\n\t\t\t\t\t\tf6f0f1.S3EncryptionEnabled = elem.Configuration.ExecuteCommandConfiguration.LogConfiguration.S3EncryptionEnabled\n\t\t\t\t\t}\n\t\t\t\t\tif elem.Configuration.ExecuteCommandConfiguration.LogConfiguration.S3KeyPrefix != nil {\n\t\t\t\t\t\tf6f0f1.S3KeyPrefix = elem.Configuration.ExecuteCommandConfiguration.LogConfiguration.S3KeyPrefix\n\t\t\t\t\t}\n\t\t\t\t\tf6f0.LogConfiguration = f6f0f1\n\t\t\t\t}\n\t\t\t\tif elem.Configuration.ExecuteCommandConfiguration.Logging != nil {\n\t\t\t\t\tf6f0.Logging = elem.Configuration.ExecuteCommandConfiguration.Logging\n\t\t\t\t}\n\t\t\t\tf6.ExecuteCommandConfiguration = f6f0\n\t\t\t}\n\t\t\tcr.Spec.ForProvider.Configuration = f6\n\t\t} else {\n\t\t\tcr.Spec.ForProvider.Configuration = nil\n\t\t}\n\t\tif elem.DefaultCapacityProviderStrategy != nil {\n\t\t\tf7 := []*svcapitypes.CapacityProviderStrategyItem{}\n\t\t\tfor _, f7iter := range elem.DefaultCapacityProviderStrategy {\n\t\t\t\tf7elem := &svcapitypes.CapacityProviderStrategyItem{}\n\t\t\t\tif f7iter.Base != nil {\n\t\t\t\t\tf7elem.Base = f7iter.Base\n\t\t\t\t}\n\t\t\t\tif f7iter.CapacityProvider != nil {\n\t\t\t\t\tf7elem.CapacityProvider = f7iter.CapacityProvider\n\t\t\t\t}\n\t\t\t\tif f7iter.Weight != nil {\n\t\t\t\t\tf7elem.Weight = f7iter.Weight\n\t\t\t\t}\n\t\t\t\tf7 = append(f7, f7elem)\n\t\t\t}\n\t\t\tcr.Spec.ForProvider.DefaultCapacityProviderStrategy = f7\n\t\t} else {\n\t\t\tcr.Spec.ForProvider.DefaultCapacityProviderStrategy = nil\n\t\t}\n\t\tif elem.PendingTasksCount != nil {\n\t\t\tcr.Status.AtProvider.PendingTasksCount = elem.PendingTasksCount\n\t\t} else {\n\t\t\tcr.Status.AtProvider.PendingTasksCount = nil\n\t\t}\n\t\tif elem.RegisteredContainerInstancesCount != nil {\n\t\t\tcr.Status.AtProvider.RegisteredContainerInstancesCount = elem.RegisteredContainerInstancesCount\n\t\t} else {\n\t\t\tcr.Status.AtProvider.RegisteredContainerInstancesCount = nil\n\t\t}\n\t\tif elem.RunningTasksCount != nil {\n\t\t\tcr.Status.AtProvider.RunningTasksCount = elem.RunningTasksCount\n\t\t} else {\n\t\t\tcr.Status.AtProvider.RunningTasksCount = nil\n\t\t}\n\t\tif elem.Settings != nil {\n\t\t\tf11 := []*svcapitypes.ClusterSetting{}\n\t\t\tfor _, f11iter := range elem.Settings {\n\t\t\t\tf11elem := &svcapitypes.ClusterSetting{}\n\t\t\t\tif f11iter.Name != nil {\n\t\t\t\t\tf11elem.Name = f11iter.Name\n\t\t\t\t}\n\t\t\t\tif f11iter.Value != nil {\n\t\t\t\t\tf11elem.Value = f11iter.Value\n\t\t\t\t}\n\t\t\t\tf11 = append(f11, f11elem)\n\t\t\t}\n\t\t\tcr.Spec.ForProvider.Settings = f11\n\t\t} else {\n\t\t\tcr.Spec.ForProvider.Settings = nil\n\t\t}\n\t\tif elem.Statistics != nil {\n\t\t\tf12 := []*svcapitypes.KeyValuePair{}\n\t\t\tfor _, f12iter := range elem.Statistics {\n\t\t\t\tf12elem := &svcapitypes.KeyValuePair{}\n\t\t\t\tif f12iter.Name != nil {\n\t\t\t\t\tf12elem.Name = f12iter.Name\n\t\t\t\t}\n\t\t\t\tif f12iter.Value != nil {\n\t\t\t\t\tf12elem.Value = f12iter.Value\n\t\t\t\t}\n\t\t\t\tf12 = append(f12, f12elem)\n\t\t\t}\n\t\t\tcr.Status.AtProvider.Statistics = f12\n\t\t} else {\n\t\t\tcr.Status.AtProvider.Statistics = nil\n\t\t}\n\t\tif elem.Status != nil {\n\t\t\tcr.Status.AtProvider.Status = elem.Status\n\t\t} else {\n\t\t\tcr.Status.AtProvider.Status = nil\n\t\t}\n\t\tif elem.Tags != nil {\n\t\t\tf14 := []*svcapitypes.Tag{}\n\t\t\tfor _, f14iter := range elem.Tags {\n\t\t\t\tf14elem := &svcapitypes.Tag{}\n\t\t\t\tif f14iter.Key != nil {\n\t\t\t\t\tf14elem.Key = f14iter.Key\n\t\t\t\t}\n\t\t\t\tif f14iter.Value != nil {\n\t\t\t\t\tf14elem.Value = f14iter.Value\n\t\t\t\t}\n\t\t\t\tf14 = append(f14, f14elem)\n\t\t\t}\n\t\t\tcr.Spec.ForProvider.Tags = f14\n\t\t} else {\n\t\t\tcr.Spec.ForProvider.Tags = nil\n\t\t}\n\t\tfound = true\n\t\tbreak\n\t}\n\tif !found {\n\t\treturn cr\n\t}\n\n\treturn cr\n}", "func createIngressInClusters(kubeconfig, ingressFilename string, clusters []string) error {\n\tkubectlArgs := []string{\"kubectl\"}\n\tif kubeconfig != \"\" {\n\t\tkubectlArgs = append(kubectlArgs, fmt.Sprintf(\"--kubeconfig=%s\", kubeconfig))\n\t}\n\t// TODO(nikhiljindal): Validate and optionally add the gce-multi-cluster class annotation to the ingress YAML spec.\n\tcreateArgs := append(kubectlArgs, []string{\"create\", fmt.Sprintf(\"--filename=%s\", ingressFilename)}...)\n\tfor _, c := range clusters {\n\t\tfmt.Println(\"Creating ingress in context:\", c)\n\t\tcontextArgs := append(createArgs, fmt.Sprintf(\"--context=%s\", c))\n\t\toutput, err := runCommand(contextArgs)\n\t\tif err != nil {\n\t\t\t// TODO(nikhiljindal): Continue if this is an ingress already exists error.\n\t\t\tglog.V(2).Infof(\"error in running command: %s\", strings.Join(contextArgs, \" \"))\n\t\t\treturn fmt.Errorf(\"error in creating ingress in cluster %s: %s, output: %s\", c, err, output)\n\t\t}\n\t}\n\treturn nil\n}", "func loadClusterConfig() (*rest.Config, error) {\n\tclusterConfig, err := rest.InClusterConfig()\n\tif err == nil {\n\t\treturn clusterConfig, nil\n\t}\n\n\tcredentials, err := clientcmd.NewDefaultClientConfigLoadingRules().Load()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not load credentials from config: %v\", err)\n\t}\n\n\tclusterConfig, err = clientcmd.NewDefaultClientConfig(*credentials, &clientcmd.ConfigOverrides{}).ClientConfig()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not load client configuration: %v\", err)\n\t}\n\treturn clusterConfig, nil\n}", "func HttpClientClusterDo(request *http.Request) (*http.Response, error) {\n\tvar resp *http.Response\n\tclient, err := GetClient(request.URL.Scheme, request.URL.Host)\n\tif nil != err {\n\t\tlog.Println(\"new http cluster client err: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tif nil == client {\n\t\terr = fmt.Errorf(\"nil client\")\n\t\treturn nil, err\n\t}\n\n\tresp, err = client.Do(request)\n\treturn resp, err\n}", "func (ctx *zedmanagerContext) AddAgentSpecificCLIFlags(flagSet *flag.FlagSet) {\n\tctx.versionPtr = flagSet.Bool(\"v\", false, \"Version\")\n}", "func influunt_ExecutorAddOperation(self, args *pyObject) *C.PyObject {\n\tname, fn := parse2ObjectFromArgs(args)\n\tpyRetain(fn)\n\n\tnameStr, err := convertPyObjectToInterface(name)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\texecutor.AddOperation(nameStr.(string), func(c *executor.Context, e *executor.Executor, inputs []influunt.Node, attrs map[string]interface{}) ([]interface{}, error) {\n\t\targs := C.PyTuple_New(C.long(len(inputs)))\n\t\tdefer pyRelease(args)\n\n\t\tfor i, input := range inputs {\n\t\t\tval, err := e.ExecuteOp(c, input)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tpyVal, err := convertGoTypeToPyObject(val)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tC.PyTuple_SetItem(args, C.long(i), pyVal)\n\t\t}\n\n\t\tres := C.PyObject_CallObject(fn, args)\n\t\tif res == nil {\n\t\t\t// TODO return error\n\t\t\tC.PyErr_Print()\n\t\t}\n\n\t\tresGoVal, err := convertPyObjectToInterface(res)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn []interface{}{resGoVal}, nil\n\t})\n\n\tpyRetain(C.Py_None)\n\treturn C.Py_None\n}", "func updateExistingConfigFromFlags(cmd *cobra.Command, existing *config.ClusterConfig) config.ClusterConfig { //nolint to suppress cyclomatic complexity 45 of func `updateExistingConfigFromFlags` is high (> 30)\n\n\tvalidateFlags(cmd, existing.Driver)\n\n\tcc := *existing\n\n\tif cmd.Flags().Changed(memory) && getMemorySize(cmd, cc.Driver) != cc.Memory {\n\t\tout.WarningT(\"You cannot change the memory size for an existing minikube cluster. Please first delete the cluster.\")\n\t}\n\n\tif cmd.Flags().Changed(cpus) && viper.GetInt(cpus) != cc.CPUs {\n\t\tout.WarningT(\"You cannot change the CPUs for an existing minikube cluster. Please first delete the cluster.\")\n\t}\n\n\t// validate the memory size in case user changed their system memory limits (example change docker desktop or upgraded memory.)\n\tvalidateRequestedMemorySize(cc.Memory, cc.Driver)\n\n\tif cmd.Flags().Changed(humanReadableDiskSize) && getDiskSize() != existing.DiskSize {\n\t\tout.WarningT(\"You cannot change the disk size for an existing minikube cluster. Please first delete the cluster.\")\n\t}\n\n\tcheckExtraDiskOptions(cmd, cc.Driver)\n\tif cmd.Flags().Changed(extraDisks) && viper.GetInt(extraDisks) != existing.ExtraDisks {\n\t\tout.WarningT(\"You cannot add or remove extra disks for an existing minikube cluster. Please first delete the cluster.\")\n\t}\n\n\tif cmd.Flags().Changed(staticIP) && viper.GetString(staticIP) != existing.StaticIP {\n\t\tout.WarningT(\"You cannot change the static IP of an existing minikube cluster. Please first delete the cluster.\")\n\t}\n\n\tupdateBoolFromFlag(cmd, &cc.KeepContext, keepContext)\n\tupdateBoolFromFlag(cmd, &cc.EmbedCerts, embedCerts)\n\tupdateStringFromFlag(cmd, &cc.MinikubeISO, isoURL)\n\tupdateStringFromFlag(cmd, &cc.KicBaseImage, kicBaseImage)\n\tupdateStringFromFlag(cmd, &cc.Network, network)\n\tupdateStringFromFlag(cmd, &cc.HyperkitVpnKitSock, vpnkitSock)\n\tupdateStringSliceFromFlag(cmd, &cc.HyperkitVSockPorts, vsockPorts)\n\tupdateStringSliceFromFlag(cmd, &cc.NFSShare, nfsShare)\n\tupdateStringFromFlag(cmd, &cc.NFSSharesRoot, nfsSharesRoot)\n\tupdateStringFromFlag(cmd, &cc.HostOnlyCIDR, hostOnlyCIDR)\n\tupdateStringFromFlag(cmd, &cc.HypervVirtualSwitch, hypervVirtualSwitch)\n\tupdateBoolFromFlag(cmd, &cc.HypervUseExternalSwitch, hypervUseExternalSwitch)\n\tupdateStringFromFlag(cmd, &cc.HypervExternalAdapter, hypervExternalAdapter)\n\tupdateStringFromFlag(cmd, &cc.KVMNetwork, kvmNetwork)\n\tupdateStringFromFlag(cmd, &cc.KVMQemuURI, kvmQemuURI)\n\tupdateBoolFromFlag(cmd, &cc.KVMGPU, kvmGPU)\n\tupdateBoolFromFlag(cmd, &cc.KVMHidden, kvmHidden)\n\tupdateBoolFromFlag(cmd, &cc.DisableDriverMounts, disableDriverMounts)\n\tupdateStringFromFlag(cmd, &cc.UUID, uuid)\n\tupdateBoolFromFlag(cmd, &cc.NoVTXCheck, noVTXCheck)\n\tupdateBoolFromFlag(cmd, &cc.DNSProxy, dnsProxy)\n\tupdateBoolFromFlag(cmd, &cc.HostDNSResolver, hostDNSResolver)\n\tupdateStringFromFlag(cmd, &cc.HostOnlyNicType, hostOnlyNicType)\n\tupdateStringFromFlag(cmd, &cc.NatNicType, natNicType)\n\tupdateDurationFromFlag(cmd, &cc.StartHostTimeout, waitTimeout)\n\tupdateStringSliceFromFlag(cmd, &cc.ExposedPorts, ports)\n\tupdateStringFromFlag(cmd, &cc.SSHIPAddress, sshIPAddress)\n\tupdateStringFromFlag(cmd, &cc.SSHUser, sshSSHUser)\n\tupdateStringFromFlag(cmd, &cc.SSHKey, sshSSHKey)\n\tupdateIntFromFlag(cmd, &cc.SSHPort, sshSSHPort)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.Namespace, startNamespace)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.APIServerName, apiServerName)\n\tupdateStringSliceFromFlag(cmd, &cc.KubernetesConfig.APIServerNames, \"apiserver-names\")\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.DNSDomain, dnsDomain)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.FeatureGates, featureGates)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.ContainerRuntime, containerRuntime)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.CRISocket, criSocket)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.NetworkPlugin, networkPlugin)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.ServiceCIDR, serviceCIDR)\n\tupdateBoolFromFlag(cmd, &cc.KubernetesConfig.ShouldLoadCachedImages, cacheImages)\n\tupdateIntFromFlag(cmd, &cc.KubernetesConfig.NodePort, apiServerPort)\n\tupdateDurationFromFlag(cmd, &cc.CertExpiration, certExpiration)\n\tupdateBoolFromFlag(cmd, &cc.Mount, createMount)\n\tupdateStringFromFlag(cmd, &cc.MountString, mountString)\n\tupdateStringFromFlag(cmd, &cc.Mount9PVersion, mount9PVersion)\n\tupdateStringFromFlag(cmd, &cc.MountGID, mountGID)\n\tupdateStringFromFlag(cmd, &cc.MountIP, mountIPFlag)\n\tupdateIntFromFlag(cmd, &cc.MountMSize, mountMSize)\n\tupdateStringSliceFromFlag(cmd, &cc.MountOptions, mountOptions)\n\tupdateUint16FromFlag(cmd, &cc.MountPort, mountPortFlag)\n\tupdateStringFromFlag(cmd, &cc.MountType, mountTypeFlag)\n\tupdateStringFromFlag(cmd, &cc.MountUID, mountUID)\n\tupdateStringFromFlag(cmd, &cc.BinaryMirror, binaryMirror)\n\tupdateBoolFromFlag(cmd, &cc.DisableOptimizations, disableOptimizations)\n\tupdateStringFromFlag(cmd, &cc.CustomQemuFirmwarePath, qemuFirmwarePath)\n\tupdateStringFromFlag(cmd, &cc.SocketVMnetClientPath, socketVMnetClientPath)\n\tupdateStringFromFlag(cmd, &cc.SocketVMnetPath, socketVMnetPath)\n\n\tif cmd.Flags().Changed(kubernetesVersion) {\n\t\tkubeVer, err := getKubernetesVersion(existing)\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"failed getting Kubernetes version: %v\", err)\n\t\t}\n\t\tcc.KubernetesConfig.KubernetesVersion = kubeVer\n\t}\n\tif cmd.Flags().Changed(containerRuntime) {\n\t\tcc.KubernetesConfig.ContainerRuntime = getContainerRuntime(existing)\n\t}\n\n\tif cmd.Flags().Changed(\"extra-config\") {\n\t\tcc.KubernetesConfig.ExtraOptions = getExtraOptions()\n\t}\n\n\tif cmd.Flags().Changed(cniFlag) || cmd.Flags().Changed(enableDefaultCNI) {\n\t\tcc.KubernetesConfig.CNI = getCNIConfig(cmd)\n\t}\n\n\tif cmd.Flags().Changed(waitComponents) {\n\t\tcc.VerifyComponents = interpretWaitFlag(*cmd)\n\t}\n\n\tif cmd.Flags().Changed(\"apiserver-ips\") {\n\t\t// IPSlice not supported in Viper\n\t\t// https://github.com/spf13/viper/issues/460\n\t\tcc.KubernetesConfig.APIServerIPs = apiServerIPs\n\t}\n\n\t// Handle flags and legacy configuration upgrades that do not contain KicBaseImage\n\tif cmd.Flags().Changed(kicBaseImage) || cc.KicBaseImage == \"\" {\n\t\tcc.KicBaseImage = viper.GetString(kicBaseImage)\n\t}\n\n\t// If this cluster was stopped by a scheduled stop, clear the config\n\tif cc.ScheduledStop != nil && time.Until(time.Unix(cc.ScheduledStop.InitiationTime, 0).Add(cc.ScheduledStop.Duration)) <= 0 {\n\t\tcc.ScheduledStop = nil\n\t}\n\n\treturn cc\n}", "func (rc *ResourceCommand) createTrustedCluster(ctx context.Context, client auth.ClientI, raw services.UnknownResource) error {\n\ttc, err := services.UnmarshalTrustedCluster(raw.Raw)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\t// check if such cluster already exists:\n\tname := tc.GetName()\n\t_, err = client.GetTrustedCluster(ctx, name)\n\tif err != nil && !trace.IsNotFound(err) {\n\t\treturn trace.Wrap(err)\n\t}\n\n\texists := (err == nil)\n\tif !rc.force && exists {\n\t\treturn trace.AlreadyExists(\"trusted cluster %q already exists\", name)\n\t}\n\n\tout, err := client.UpsertTrustedCluster(ctx, tc)\n\tif err != nil {\n\t\t// If force is used and UpsertTrustedCluster returns trace.AlreadyExists,\n\t\t// this means the user tried to upsert a cluster whose exact match already\n\t\t// exists in the backend, nothing needs to occur other than happy message\n\t\t// that the trusted cluster has been created.\n\t\tif rc.force && trace.IsAlreadyExists(err) {\n\t\t\tout = tc\n\t\t} else {\n\t\t\treturn trace.Wrap(err)\n\t\t}\n\t}\n\tif out.GetName() != tc.GetName() {\n\t\tfmt.Printf(\"WARNING: trusted cluster %q resource has been renamed to match remote cluster name %q\\n\", name, out.GetName())\n\t}\n\tfmt.Printf(\"trusted cluster %q has been %v\\n\", out.GetName(), UpsertVerb(exists, rc.force))\n\treturn nil\n}", "func (s *BasePlSqlParserListener) EnterCluster_index_clause(ctx *Cluster_index_clauseContext) {}", "func (o *Options) Run(ctx context.Context) error {\n\tctx, cancel := context.WithTimeout(ctx, o.Timeout)\n\tdefer cancel()\n\n\t// Create and initialize cluster 1.\n\tcluster1 := inband.NewCluster(o.LocalFactory, o.RemoteFactory)\n\tif err := cluster1.Init(ctx); err != nil {\n\t\treturn err\n\t}\n\n\t// Create and initialize cluster 2.\n\tcluster2 := inband.NewCluster(o.RemoteFactory, o.LocalFactory)\n\tif err := cluster2.Init(ctx); err != nil {\n\t\treturn err\n\t}\n\n\t// Check whether a ForeignCluster resource already exists in cluster 1 for cluster 2, and perform sanity checks.\n\tif err := cluster1.CheckForeignCluster(ctx, cluster2.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Check whether a ForeignCluster resource already exists in cluster 2 for cluster 1, and perform sanity checks.\n\tif err := cluster2.CheckForeignCluster(ctx, cluster1.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// SetUp tenant namespace for cluster 2 in cluster 1.\n\tif err := cluster1.SetUpTenantNamespace(ctx, cluster2.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\tcluster2.SetRemTenantNS(cluster1.GetLocTenantNS())\n\n\t// SetUp tenant namespace for cluster in cluster 2.\n\tif err := cluster2.SetUpTenantNamespace(ctx, cluster1.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\tcluster1.SetRemTenantNS(cluster2.GetLocTenantNS())\n\n\t// Configure network configuration for cluster 1.\n\tif err := cluster1.ExchangeNetworkCfg(ctx, cluster2.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Configure network configuration for cluster 2.\n\tif err := cluster2.ExchangeNetworkCfg(ctx, cluster1.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Port-forwarding ipam service for cluster 1.\n\tif err := cluster1.PortForwardIPAM(ctx); err != nil {\n\t\treturn err\n\t}\n\tdefer cluster1.StopPortForwardIPAM()\n\n\t// Port-forwarding ipam service for cluster 2.\n\tif err := cluster2.PortForwardIPAM(ctx); err != nil {\n\t\treturn err\n\t}\n\tdefer cluster2.StopPortForwardIPAM()\n\n\t// Creating IPAM client for cluster 1.\n\tipamClient1, err := cluster1.NewIPAMClient(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Creating IPAM client for cluster 2.\n\tipamClient2, err := cluster2.NewIPAMClient(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Mapping proxy's ip in cluster1 for cluster2.\n\tif err := cluster1.MapProxyIPForCluster(ctx, ipamClient1, cluster2.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Mapping proxy's ip in cluster2 for cluster2\n\tif err := cluster2.MapProxyIPForCluster(ctx, ipamClient2, cluster1.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Mapping auth's ip in cluster1 for cluster2.\n\tif err := cluster1.MapAuthIPForCluster(ctx, ipamClient1, cluster2.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Mapping auth's ip in cluster2 for cluster1\n\tif err := cluster2.MapAuthIPForCluster(ctx, ipamClient2, cluster1.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Creating foreign cluster in cluster1 for cluster 2.\n\tif err := cluster1.EnforceForeignCluster(ctx, cluster2.GetClusterID(), cluster2.GetAuthToken(),\n\t\tcluster2.GetAuthURL(), cluster2.GetProxyURL()); err != nil {\n\t\treturn err\n\t}\n\n\t// Creating foreign cluster in cluster2 for cluster 1.\n\tif err := cluster2.EnforceForeignCluster(ctx, cluster1.GetClusterID(), cluster1.GetAuthToken(),\n\t\tcluster1.GetAuthURL(), cluster1.GetProxyURL()); err != nil {\n\t\treturn err\n\t}\n\n\t// Setting the foreign cluster outgoing flag in cluster 1 for cluster 2\n\t// This operation is performed after that both foreign clusters have already been successfully created, to prevent a\n\t// possible race condition in which the resource request originated by the local foreign cluster is replicated to and\n\t// reconciled in the remote cluster before we create the corresponding foreign cluster. This would cause an incorrect\n\t// foreign cluster (i.e., of type OutOfBand) to be automatically created, leading to a broken peering.\n\tif err := cluster1.EnforceOutgoingPeeringFlag(ctx, cluster2.GetClusterID(), true); err != nil {\n\t\treturn err\n\t}\n\n\t// Setting the foreign cluster outgoing flag in cluster 2 for cluster 1\n\tif err := cluster2.EnforceOutgoingPeeringFlag(ctx, cluster1.GetClusterID(), o.Bidirectional); err != nil {\n\t\treturn err\n\t}\n\n\t// Waiting for VPN connection to be established in cluster 1.\n\tif err := cluster1.Waiter.ForNetwork(ctx, cluster2.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Waiting for VPN connection to be established in cluster 2.\n\tif err := cluster2.Waiter.ForNetwork(ctx, cluster1.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Waiting for authentication to complete in cluster 1.\n\tif err := cluster1.Waiter.ForAuth(ctx, cluster2.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Waiting for authentication to complete in cluster 2.\n\tif err := cluster2.Waiter.ForAuth(ctx, cluster1.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Waiting for outgoing peering to complete in cluster 1.\n\tif err := cluster1.Waiter.ForOutgoingPeering(ctx, cluster2.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Waiting for virtual node to be created in cluster 1.\n\tif err := cluster1.Waiter.ForNode(ctx, cluster2.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\tif !o.Bidirectional {\n\t\treturn nil\n\t}\n\n\t// Waiting for outgoing peering to complete in cluster 2.\n\tif err := cluster2.Waiter.ForOutgoingPeering(ctx, cluster1.GetClusterID()); err != nil {\n\t\treturn err\n\t}\n\n\t// Waiting for virtual node to be created in cluster 2.\n\treturn cluster2.Waiter.ForNode(ctx, cluster1.GetClusterID())\n}", "func (c *Controller) clusterAction(admin submarine.AdminInterface, cluster *rapi.SubmarineCluster, infos *submarine.ClusterInfos) (bool, error) {\n\tglog.Info(\"clusterAction()\")\n\tvar err error\n\t/* run sanity check if needed\n\tneedSanity, err := sanitycheck.RunSanityChecks(admin, &c.config.submarine, c.podControl, cluster, infos, true)\n\tif err != nil {\n\t\tglog.Errorf(\"[clusterAction] cluster %s/%s, an error occurs during sanitycheck: %v \", cluster.Namespace, cluster.Name, err)\n\t\treturn false, err\n\t}\n\tif needSanity {\n\t\tglog.V(3).Infof(\"[clusterAction] run sanitycheck cluster: %s/%s\", cluster.Namespace, cluster.Name)\n\t\treturn sanitycheck.RunSanityChecks(admin, &c.config.submarine, c.podControl, cluster, infos, false)\n\t}*/\n\n\t// Start more pods in needed\n\tif needMorePods(cluster) {\n\t\tif setScalingCondition(&cluster.Status, true) {\n\t\t\tif cluster, err = c.updateHandler(cluster); err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\t\tpod, err2 := c.podControl.CreatePod(cluster)\n\t\tif err2 != nil {\n\t\t\tglog.Errorf(\"[clusterAction] unable to create a pod associated to the SubmarineCluster: %s/%s, err: %v\", cluster.Namespace, cluster.Name, err2)\n\t\t\treturn false, err2\n\t\t}\n\n\t\tglog.V(3).Infof(\"[clusterAction]create a Pod %s/%s\", pod.Namespace, pod.Name)\n\t\treturn true, nil\n\t}\n\tif setScalingCondition(&cluster.Status, false) {\n\t\tif cluster, err = c.updateHandler(cluster); err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\t// Reconfigure the Cluster if needed\n\thasChanged, err := c.applyConfiguration(admin, cluster)\n\tif err != nil {\n\t\tglog.Errorf(\"[clusterAction] cluster %s/%s, an error occurs: %v \", cluster.Namespace, cluster.Name, err)\n\t\treturn false, err\n\t}\n\n\tif hasChanged {\n\t\tglog.V(6).Infof(\"[clusterAction] cluster has changed cluster: %s/%s\", cluster.Namespace, cluster.Name)\n\t\treturn true, nil\n\t}\n\n\tglog.Infof(\"[clusterAction] cluster hasn't changed cluster: %s/%s\", cluster.Namespace, cluster.Name)\n\treturn false, 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}" ]
[ "0.6103863", "0.57436365", "0.5697269", "0.54563576", "0.54550797", "0.53302664", "0.53095317", "0.5288244", "0.5267604", "0.5254226", "0.5233511", "0.52175516", "0.5189461", "0.5116505", "0.5082574", "0.5072907", "0.5043684", "0.5035357", "0.50312465", "0.5026622", "0.50176287", "0.49569488", "0.49401003", "0.48675734", "0.48656854", "0.48471567", "0.48436496", "0.48304468", "0.48193657", "0.48184985", "0.48166996", "0.47812134", "0.47806033", "0.47653988", "0.4745857", "0.47453994", "0.4744211", "0.47228533", "0.4676455", "0.46751952", "0.46688554", "0.46566188", "0.46450794", "0.4632999", "0.4626902", "0.46088532", "0.4604008", "0.4603297", "0.46013832", "0.46006688", "0.45900962", "0.45848694", "0.45796445", "0.4575076", "0.45723087", "0.45677295", "0.45646024", "0.45564008", "0.4554577", "0.4550871", "0.45429254", "0.45380467", "0.453329", "0.45326793", "0.45220578", "0.45205492", "0.4519689", "0.45067978", "0.44980767", "0.44955522", "0.44923422", "0.44896844", "0.4489477", "0.44888276", "0.44873518", "0.44813362", "0.44809726", "0.44762346", "0.44740492", "0.44727182", "0.4470745", "0.44691104", "0.446548", "0.4464971", "0.44643506", "0.44642836", "0.44641396", "0.44628024", "0.44591254", "0.44564083", "0.44506565", "0.44434667", "0.4442898", "0.44427", "0.44418314", "0.44402063", "0.44365302", "0.44309616", "0.44300097", "0.44277734" ]
0.8505771
0
GetSession returns a MongoDB Session
func GetSession() *mgo.Session { if session == nil { var err error session, err = mgo.DialWithInfo(&mgo.DialInfo{ Addrs: []string{AppConfig.MongoDBHost}, Username: AppConfig.DBUser, Password: AppConfig.DBPwd, Timeout: 60 * time.Second, }) if err != nil { log.Fatalf("[GetSession]: %s\n", err) } } return session }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetSession() *mgo.Session {\n\n\tsession, err := mgo.Dial(\"mongodb://localhost\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn session\n}", "func getSession() *mgo.Session {\n\n\t// We need this object to establish a session to our MongoDB.\n\t// using the .env to load the database information\n\tmongoDBDialInfo := &mgo.DialInfo{\n\t\tAddrs: []string{EnvGetter(\"MongoDBHosts\")},\n\t\tDatabase: EnvGetter(\"AuthDatabase\"),\n\t\tUsername: EnvGetter(\"AuthUserName\"),\n\t\tPassword: EnvGetter(\"AuthPassword\"),\n\t\t//Timeout: 60 * time.Second,\n\t}\n\n\t// Connect to our local mongo\n\t// s = sessions\n\ts, err := mgo.DialWithInfo(mongoDBDialInfo)\n\tif err != nil {\n\t\tpanic(err)\n\t\t//log.Fatal(panic(err))\n\t} // Check if connection error, is mongo running?\n\t//defer s.Closing()\n\n\t// Reads may not be entirely up-to-date, but they will always see the\n\t// history of changes moving forward, the data read will be consistent\n\t// across sequential queries in the same session, and modifications made\n\t// within the session will be observed in following queries (read-your-writes).\n\t// http://godoc.org/labix.org/v2/mgo#Session.SetMode\n\ts.SetMode(mgo.Monotonic, true)\n\n\tfmt.Println(\"Session created\")\n\n\t// Deliver session\n\treturn s\n}", "func getSession() *mgo.Session {\n\t// Connect to our local mongo\n\ts, err := mgo.Dial(\"mongodb://localhost:27017\")\n\n\t// Check if connection error, is mongo running?\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Deliver session\n\treturn s\n}", "func getSession() *mgo.Session {\n\t// Connect to our local mongo\n\ts, err := mgo.Dial(\"mongodb://localhost\")\n\n\t// Check if connection error, is mongo running?\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Deliver session\n\treturn s\n}", "func getSession(config Config) (*mgo.Session, error) {\n\tinfo := mgo.DialInfo{\n\t\tAddrs: []string{config.Host},\n\t\tTimeout: 60 * time.Second,\n\t\tDatabase: config.AuthDB,\n\t\tUsername: config.User,\n\t\tPassword: config.Password,\n\t}\n\n\t// Create a session which maintains a pool of socket connections\n\t// to our MongoDB.\n\tses, err := mgo.DialWithInfo(&info)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tses.SetMode(mgo.Monotonic, true)\n\n\treturn ses, nil\n}", "func GetSession(goRoutine string) (*mgo.Session, error) {\n\tvar err error\n\tdefer helper.CatchPanic(&err, goRoutine, \"GetSession\")\n\thelper.WriteStdout(goRoutine, \"mongo.GetSession\", \"Started\")\n\n\t// Establish a session MongoDB\n\tmongoSession, err := mgo.DialWithInfo(mm.MongoDBDialInfo)\n\tif err != nil {\n\t\thelper.WriteStdoutf(goRoutine, \"mongo.GetSession\", \"ERROR : %s\", err)\n\t\treturn nil, err\n\t}\n\n\t// Reads and writes will always be made to the master server using a\n\t// unique connection so that reads and writes are fully consistent,\n\t// ordered, and observing the most up-to-date data.\n\tmongoSession.SetMode(mgo.Strong, true)\n\n\t// Have the session check for errors.\n\tmongoSession.SetSafe(&mgo.Safe{})\n\n\t// Don't want any longer than 10 second for an operation to complete.\n\tmongoSession.SetSyncTimeout(10 * time.Second)\n\n\thelper.WriteStdout(goRoutine, \"mongo.GetSession\", \"Completed\")\n\treturn mongoSession, err\n}", "func (db *MongoDatabase) GetSession() *mgo.Session {\n\treturn db.global_session.Copy()\n}", "func (mdb *MongoDBConnection) GetSession() *mgo.Session {\n\tif mdb.session != nil {\n\t\treturn mdb.session.Copy()\n\t}\n\tsession, err := mgo.Dial(\"localhost\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tsession.SetMode(mgo.Monotonic, true)\n\treturn session\n}", "func (mdb *MongoDBConnection) GetSession() *mgo.Session {\n\tif mdb.session != nil {\n\t\treturn mdb.session.Copy()\n\t}\n\tsession, err := mgo.Dial(\"localhost\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tsession.SetMode(mgo.Monotonic, true)\n\treturn session\n}", "func getSession() *mgo.Session {\n\t// Connect to our local mongo\n\tmongoURL := strings.Replace(os.Getenv(\"MONGO_PORT\"), \"tcp\", \"mongodb\", 1)\n\tif mongoURL == \"\" {\n\t\tpanic(\"MONGO_PORT env var not set.\")\n\t} else {\n\t\tfmt.Printf(\"MONGO_PORT: %s\", mongoURL)\n\t}\n\ts, err := mgo.Dial(mongoURL)\n\n\t// Check if connection error, is mongo running?\n\tif err != nil {\n\t\tprintln(\"Is mongo running?\")\n\t\tpanic(err)\n\t}\n\n\t// Deliver session\n\treturn s\n}", "func getSession() *mgo.Session {\n\tif mgoSession == nil {\n\t\tvar err error\n\t\tmgoSession, err = mgo.Dial(testuri)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error connecting to Mongo: \", err)\n\t\t}\n\t}\n\treturn mgoSession.Copy()\n}", "func getSession() *mgo.Session {\n\tconnect, err:= mgo.Dial(\"mongodb://suyash:[email protected]:31531/trip-planner\")\n\tif err!= nil {\n\t\t\tpanic(err)\n\t\t}\t\n\t\treturn connect\n}", "func GetMongoSession() (*mgo.Session, error) {\n\tif mgoSession == nil {\n\t\tvar err error\n\t\tmgoSession, err = mgo.Dial(mongo_conn_str)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn mgoSession.Clone(), nil\n}", "func GetMongoSession() *mgo.Session {\n\tif mgoSession == nil {\n\t\tvar err error\n\t\tmgoSession, err = mgo.Dial(\"mongodb://127.0.0.1:27017/demo\")\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Failed to start the Mongo session\")\n\t\t}\n\t}\n\treturn mgoSession.Clone()\n}", "func GetSession() *discordgo.Session {\n\treturn session\n}", "func GetMongoSession(url string, authDB string, username string, password string) *mgo.Session {\n\tif mgoSession == nil {\n\t\tvar err error\n\n\t\ttlsConfig := &tls.Config{}\n\n\t\tdialInfo := &mgo.DialInfo{\n\n\t\t\tAddrs: []string{url},\n\t\t\tDatabase: authDB,\n\t\t\tUsername: username,\n\t\t\tPassword: password,\n\t\t}\n\n\t\tdialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) {\n\t\t\tconn, err := tls.Dial(\"tcp\", addr.String(), tlsConfig)\n\t\t\treturn conn, err\n\t\t}\n\t\tmgoSession, err = mgo.DialWithInfo(dialInfo)\n\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Failed to start the Mongo session\")\n\t\t}\n\t}\n\treturn mgoSession.Clone()\n}", "func (m mongod) Session() *mgo.Session {\n\treturn m.session\n}", "func GetMongo() *mgo.Session {\n\treturn mongoSession.Copy()\n}", "func MongoSession() (*mgo.Session, error) {\n\tif session == nil {\n\t\tvar err error\n\t\tsession, err = mgo.Dial(host+\":\"+port)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn session, nil\n}", "func (m *Driver) GetSession(sessID string) (*models.Session, error) {\n\t// DB-specific session struct\n\tvar mSess Session\n\n\t// check whether valid session ID\n\tif !bson.IsObjectIdHex(sessID) {\n\t\treturn nil, errors.New(\"invalid session id\")\n\t}\n\n\t// lookup the database\n\terr := m.DB.C(sessCol).Find(bson.M{\"_id\": bson.ObjectIdHex(sessID)}).One(&mSess)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsess := &models.Session{\n\t\tID: mSess.ID.Hex(),\n\t\tKeyword: mSess.Keyword,\n\t\tVersion: mSess.Version,\n\t\tTimestamp: mSess.ID.Time(),\n\t\tSchemas: mSess.Schemas,\n\t\tMetadata: mSess.Metadata,\n\t}\n\n\treturn sess, nil\n}", "func GetMongoSession() (*mgo.Session, error) {\n\tif mgoSession != nil {\n\t\tmgoSession.Refresh()\n\t\treturn mgoSession.Copy(), nil\n\t}\n\n\tLoadMongoConfig()\n\tvar err error\n\tmgoSession, err = mgo.Dial(mongoDbURI)\n\tif err != nil {\n\t\tlog.Printf(\"[GetMongoSession] Error opening mongo db session: [%s]\\n\", err.Error())\n\t\treturn nil, err\n\t}\n\treturn mgoSession.Copy(), err\n}", "func GetSession(ctx context.Context) session.Session {\n\ts, ok := ctx.Value(sessionCtx).(session.Session)\n\tif !ok {\n\t\tpanic(\"context does not have an edgegrid session\")\n\t}\n\n\treturn s\n}", "func GetMongoSession(msg string, databaseURI string) (*MgoSession, error) {\n\tmongoSession, err := mgo.Dial(databaseURI) // dial uri can be any mongodatabase\n\tif err != nil {\n\t\treturn nil, errors.New(fmt.Sprintf(`[MongoDB] %s`, err))\n\t}\n\n\tmongoSession.SetMode(mgo.Monotonic, true)\n\tmongoSession.SetSocketTimeout(1 * time.Hour) //extend for long result\n\n\tlog.Printf(\"[MongoDB] session started! %s\", msg)\n\treturn newMgoSession(mongoSession), nil\n}", "func GetSession(cm *kuberlogicv1.KuberLogicService, client kubernetes.Interface, db string) (session interfaces.Session, err error) {\n\top, err := GetCluster(cm)\n\tif err != nil {\n\t\treturn\n\t}\n\tsession, err = op.GetSession(cm, client, db)\n\treturn\n}", "func (this *DBDao) GetSession() *Session {\n\treturn this.Engine.NewSession()\n}", "func GetConnected() *mgo.Session {\r\n\tdialInfo, err := mgo.ParseURL(\"mongodb://localhost:27017\")\r\n\tdialInfo.Direct = true\r\n\tdialInfo.FailFast = true\r\n\tdialInfo.Database = \"task_db\"\r\n\t// leaving db releted info empty replace it \r\n\t// dialInfo.Database = os.Getenv(\"Db_Name\") // db name \r\n\t// dialInfo.Username = os.Getenv(\"User_Name\") // username \r\n\t// dialInfo.Password = \tdb := os.Getenv(\"password\") // password\r\n\tsess, err := mgo.DialWithInfo(dialInfo)\r\n\tif err != nil {\r\n\t\tfmt.Println(\"Can't connect to mongo, go error %v\\n\", err)\r\n\t\tpanic(err)\r\n\t} else {\r\n\t\treturn sess\r\n\t\tdefer sess.Close()\r\n\t}\r\n\treturn sess\r\n}", "func Get() *discordgo.Session {\n\treturn &session\n}", "func GetSession(ctx appengine.Context) (session *Session, err error) {\n\treqId := appengine.RequestID(ctx)\n\tsession, ok := authenticatedSessions[reqId]\n\tif ok {\n\t\treturn\n\t}\n\treturn nil, Unauthenticated\n}", "func getMongoDBConnection(connectionString string) (*mgo.Session, error) {\n\tsession, err := mgo.Dial(connectionString)\n\treturn session, err\n}", "func getSessionCopy(conn string) (*mgo.Session, error){\n\tdata, isOk:=mgoSessionPool.Load(conn)\n\tif isOk{\n\t\tsession, isSuccess := data.(*mgo.Session)\n\t\tif isSuccess{\n\t\t\treturn session.Clone(), nil\n\t\t}\n\t}\n\n\tsession, err := mgo.Dial(conn)\n\tif err!= nil{\n\t\tlogger.Log(\"repository.impl.getSessionCopy::Dial[\"+conn+\"]失败 - \"+err.Error(), logdefine.LogTarget_MongoDB, logdefine.LogLevel_Error)\n\t\treturn nil, err\n\t}else{\n\t\tsession.SetPoolLimit(MaxSessionPoolLimit)\n\t\tmgoSessionPool.Store(conn, session)\n\t\treturn session.Clone(), nil\n\t}\n}", "func (m *MongoDBStore) Get(r *http.Request, name string) (*sessions.Session, error) {\n\treturn sessions.GetRegistry(r).Get(m, name)\n}", "func GetSession(c echo.Context) *sessions.Session {\n\tsess, err := session.Get(sessionID, c)\n\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn sess\n}", "func getSession(ctx context.Context) *session.Session {\n\treturn ctx.Value(sessKey{}).(*session.Session)\n}", "func GetSession(conn *dbus.Conn, path dbus.ObjectPath) (Session, error) {\n\tobj := conn.Object(SecretServiceDest, dbus.ObjectPath(path))\n\n\treturn &session{\n\t\tpath: path,\n\t\tobj: obj,\n\t}, nil\n}", "func (mongoDBConnection MongoDBConnect) GetSocketConn() (session *mgo.Session) {\n\tsession = mongoDBConnection.mongoSession.Copy()\n\treturn\n}", "func (sc *SessionContext) GetSession() (*sessions.Session, error) {\n\tif sc.request == nil || sc.response == nil {\n\t\treturn nil, errors.New(\"Runtime tried to sccess a session before this SessionContext was fully initialized.\")\n\t}\n\n\t//TODO: Lazy load session here.\n\tsession, _ := sc.store.Get(sc.request, \"user\")\n\n\treturn session, nil\n}", "func GetSession(ctx iris.Context) *sessions.Session {\n\treturn manager.Start(ctx)\n}", "func Get(ctx context.Context) *Session {\n\t// TODO maybe check this\n\treturn ctx.Value(sessionContextKey{}).(*Session)\n}", "func (s *service) GetSession(sessionID string) (*Session, []error) {\n\tsess, errs := (*s.repo).GetSession(sessionID)\n\tif len(errs) > 0 {\n\t\treturn nil, errs\n\t}\n\t// use UpdateSession to refresh last access time\n\tsess, errs = s.UpdateSession(sess)\n\tsess.sessionService = s\n\tsess.syncFromArrayToMap()\n\treturn sess, errs\n}", "func (controller *Controller) GetSession(c web.C) *sessions.Session {\n\treturn c.Env[\"Session\"].(*sessions.Session)\n}", "func GetSession() (*session.Session, error) {\n\tos.Getenv(\"\")\n\tsess, err := session.NewSession()\n\n\tif err != nil {\n\t\tlog.LogError(\"util:aws:AwsSession:GetSession\", \"Failed to initiate AWS session\", err)\n\t\treturn nil, err\n\t}\n\treturn sess, nil\n}", "func GetSession() (*session.Session, error) {\n\tif awsSession != nil {\n\t\treturn awsSession, nil\n\t}\n\n\tcreds := credentials.NewStaticCredentials(config.AWSSecretID, config.AWSSecretKey, \"\")\n\tsess, err := session.NewSession(&aws.Config{\n\t\tCredentials: creds,\n\t\tRegion: aws.String(\"us-east-1\"),\n\t})\n\n\tif err != nil {\n\t\tlogrus.Errorf(\"Unable to create aws session: %s\", err.Error())\n\t\treturn nil, fmt.Errorf(\"Unable to create aws session: %s\", err.Error())\n\t}\n\n\tawsSession = sess\n\treturn sess, nil\n}", "func GetSession(token string) (Session, *errors.Error) {\n\tvar session Session\n\tconnPool, err := GetDBConnectionFunc(sessionStore)\n\tif err != nil {\n\t\treturn session, errors.PackError(err.ErrNo(), \"error while trying to connecting to DB: \", err.Error())\n\t}\n\tsessionData, err := connPool.Read(\"session\", token)\n\tif err != nil {\n\t\treturn session, errors.PackError(err.ErrNo(), \"error while trying to get the session from DB: \", err.Error())\n\t}\n\tif jerr := json.Unmarshal([]byte(sessionData), &session); jerr != nil {\n\t\treturn session, errors.PackError(errors.UndefinedErrorType, \"error while trying to unmarshal session data: \", jerr)\n\t}\n\treturn session, nil\n}", "func GetSession(r *http.Request) (*sessions.Session, error) {\n\treturn configurations.Configuration.Session.Store.Get(r, configurations.Configuration.Session.Name)\n}", "func GetMongoDBConnection(config MongoDBConfig) (*mgo.Session, error) {\n\tvar session *mgo.Session\n\tvar err error\n\tif config.Auth {\n\t\tcred := &mgo.Credential{\n\t\t\tUsername: config.Username,\n\t\t\tPassword: config.Password,\n\t\t\tMechanism: config.Mechanism,\n\t\t\tSource: config.Source,\n\t\t}\n\t\tsession, err = mgo.Dial(config.Host)\n\t\tif err = session.Login(cred); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tsession, err = mgo.Dial(config.Host)\n\t}\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tsession.SetMode(mgo.Monotonic, true)\n\tsession.SetSafe(&mgo.Safe{})\n\treturn session, nil\n}", "func GetSession(c context.Context, r *http.Request) context.Session {\n\tif val, ok := c.Get(r, context.BaseCtxKey(\"session\")); ok {\n\t\treturn val.(context.Session)\n\t}\n\n\tconf := GetConfig(c)\n\tvar abspath string\n\n\tif filepath.IsAbs(conf.Session.Dir) {\n\t\tabspath = conf.Session.Dir\n\t} else {\n\t\tvar err error\n\t\tabspath, err = filepath.Abs(path.Join(filepath.Dir(os.Args[0]), conf.Session.Dir))\n\n\t\tif err != nil {\n\t\t\tabspath = os.TempDir()\n\t\t}\n\t}\n\n\tsess := context.NewSession([]byte(conf.Session.Secret), []byte(conf.Session.Cipher), abspath)\n\tsess.SetName(util.UUID())\n\treturn sess\n}", "func (sp *SessionProxy) GetSession() (session Session) {\n\tsp.lock.RLock()\n\tsession = sp.session\n\tsp.lock.RUnlock()\n\treturn\n}", "func getSession(r *http.Request) (*sessions.Session, error) {\n\tsession, err := store.Get(r, sessionName)\n\tif err != nil {\n\t\tif session.IsNew {\n\t\t\tglog.V(1).Infof(\"ignoring initial session fetch error since session IsNew: %v\\n\", err)\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"error fetching session: %v\", err)\n\t\t}\n\t}\n\treturn session, nil\n}", "func (s *SessionStore) GetSession(r *http.Request) *Session {\n\tsess, _ := s.Get(r, s.sessionName)\n\treturn &Session{sess}\n}", "func (v *Voice) GetSession(guildID discord.GuildID) (*Session, bool) {\n\tv.mapmutex.Lock()\n\tdefer v.mapmutex.Unlock()\n\n\t// For some reason you cannot just put `return v.sessions[]` and return a bool D:\n\tconn, ok := v.sessions[guildID]\n\treturn conn, ok\n}", "func GetSession(w http.ResponseWriter, r *http.Request, sessionCookie string) *sessions.Session {\n\tsession, err := store.Get(r, sessionCookie)\n\tif err != nil {\n\t\tfmt.Printf(\"session error\")\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn nil\n\t}\n\treturn session\n}", "func GetConn() *mongo.Client {\n\tif Client == nil {\n\t\tCreateConnection(nil)\n\t}\n\treturn Client\n}", "func (ctx *MqttSrvContext) GetSession(fd int) interface{} {\n\tctx.Clock.RLock()\n\ts := ctx.Connections[fd]\n\tctx.Clock.RUnlock()\n\treturn s\n}", "func (node *DataNode) GetSession() *sessionutil.Session {\n\tnode.sessionMu.Lock()\n\tdefer node.sessionMu.Unlock()\n\treturn node.session\n}", "func openSession() (*mgo.Session, error) {\n\thost := os.Getenv(\"MONGODB_URI\")\n\tsession, err := mgo.Dial(host)\n\treturn session, err\n}", "func (s *Storage) GetDBSession() *mgo.Session {\n\treturn s.session.Copy()\n}", "func (s *Storage) GetDBSession() *mgo.Session {\n\treturn s.session.Copy()\n}", "func (mc *MongoController) SessionClone() (sesh *mgo.Session, err error) {\n\tif mc.DBSession == nil {\n\t\tmongoConnect(mc)\n\t}\n\tif mc.DBSession == nil {\n\t\terr = errors.New(\"Could not connect to MongoDB\")\n\t\tlogging.Error(\"Connecting to MongoDB\", err)\n\t\treturn\n\t}\n\treturn mc.DBSession.Clone(), nil\n}", "func CopySession(goRoutine string) (*mgo.Session, error) {\n\tvar err error\n\tdefer helper.CatchPanic(&err, goRoutine, \"GetSession\")\n\thelper.WriteStdout(goRoutine, \"mongo.GetSession\", \"Started\")\n\n\t// Copy the master session\n\tmongoSession := mm.MongoSession.Copy()\n\n\thelper.WriteStdout(goRoutine, \"mongo.GetSession\", \"Completed\")\n\treturn mongoSession, err\n}", "func (hc *httpContext) getSession() *sessions.Session {\n\t// Get a session. We're ignoring the error resulted from decoding an\n\t// existing session: Get() always returns a session, even if empty.\n\tsession, err := store.Get(hc.r, sessionName)\n\tif err != nil {\n\t\thttp.Error(hc.w, err.Error(), http.StatusInternalServerError)\n\t\treturn nil\n\t}\n\treturn session\n}", "func (client BastionClient) getSession(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/sessions/{sessionId}\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response GetSessionResponse\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 GetSession(sessionID string) (session *Session) {\n\tsession = &Session{ID: sessionID}\n\n\tconn := redisConnPool.Get()\n\tdefer conn.Close()\n\n\tkey := fmt.Sprintf(\"sessions:%s\", sessionID)\n\treply, err := redis.String(conn.Do(\"GET\", key))\n\tif err != nil {\n\t\t// NOTE: This is a normal situation, if the session is not stored in the cache, it will hit this condition.\n\t\treturn\n\t}\n\n\terr = json.Unmarshal([]byte(reply), session)\n\n\treturn\n}", "func connectionDB() *mgo.Session {\n\t//session, err := mgo.Dial(os.Getenv(\"DB_PORT_27017_TCP_ADDR\")+\":\"+os.Getenv(\"DB_PORT_27017_TCP_PORT\"))\n\tsession, err := mgo.Dial(os.Getenv(\"MONGODB_URI\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn session\n}", "func (this *SessionStorage) GetSession(w http.ResponseWriter, req *http.Request) (*Session,error) {\n //look for session cookie\n sCookie,err := req.Cookie(\"session\")\n var sessionId uint64\n this.mutex.Lock()\n defer this.mutex.Unlock()\n if(err != nil) {\n //if there's no session associated\n return this.CreateSession(w),nil\n } else {\n //if a session already exists\n sessionId,err = strconv.ParseUint(sCookie.Value,10,64)\n if(err != nil) {\n //if conversion failed\n return nil,err;\n }\n }\n session,ok := this.sessions[sessionId]\n if !ok {\n return this.CreateSession(w),nil\n }\n session.lastAccessed = time.Now()\n return session,nil\n}", "func (c *Controller) GetSession(name interface{}) interface{} {\n\tif c.CruSession == nil {\n\t\tc.StartSession()\n\t}\n\treturn c.CruSession.Get(context2.Background(), name)\n}", "func (s *Server) GetSession(sessionId string) (tp.Session, bool) {\n\treturn s.peer.GetSession(sessionId)\n}", "func Conexion() *mgo.Session {\n\tsesion, err := mgo.Dial(\"mongodb://localhost\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn sesion\n}", "func Get(c echo.Context) (*sessions.Session, error) {\n\tsess, err := session.Get(sessionStr, c)\n\treturn sess, err\n}", "func getSession(ctx context.Context, id string) (middleware.Session, error) {\n\tsessionUUID, err := uuid.FromString(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsession, err := loader.Loader.GetSession(ctx, sessionUUID)\n\n\treturn Session{Row: session}, err\n}", "func (s *StorageBase) GetSession(ctx context.Context, sessionId string, ttl time.Duration) (*gmap.StrAnyMap, error) {\n\treturn nil, ErrorDisabled\n}", "func (cl *APIClient) GetSession() (string, error) {\n\tsessid := cl.socketConfig.GetSession()\n\tif len(sessid) == 0 {\n\t\treturn \"\", errors.New(\"Could not find an active session\")\n\t}\n\treturn sessid, nil\n}", "func (sess *SessionHandler) GetSession(request *http.Request) *model.Session {\n\ttoken := request.Header.Get(\"Authorization\")\n\ttoken = strings.TrimPrefix(token, \"Bearer \")\n\tif token == \"\" {\n\t\treturn nil\n\t}\n\tsession := &model.Session{}\n\ttkn, err := jwt.ParseWithClaims(token, session, func(token *jwt.Token) (interface{}, error) {\n\t\treturn []byte(jwtKey), nil\n\t})\n\tif err != nil {\n\t\treturn nil\n\t}\n\tif !tkn.Valid {\n\t\treturn nil\n\t}\n\treturn session\n}", "func GetSession(r *http.Request) (models.Session, error) {\n\n\tvar session models.Session\n\n\tCookie, err := r.Cookie(CookieKey)\n\n\tif err != nil {\n\t\treturn session, err\n\t}\n\n\tc := Controller{}\n\tdata, err := c.Load(r)\n\n\tfound := false\n\tsession.UUID = Cookie.Value\n\tfor _, s := range data.Sessions {\n\t\tif s.UUID == session.UUID {\n\t\t\tsession = s\n\t\t\tfound = true\n\t\t}\n\t}\n\n\tif !found {\n\t\treturn session, errSessionNotFound\n\t}\n\n\treturn session, nil\n}", "func Mongo(dbsession *mgo.Session, contextKey string) func(next http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\t\tsCopy := dbsession.Copy()\n\t\t\tdefer sCopy.Close()\n\n\t\t\tvar ctx context.Context\n\t\t\tvar newReq *http.Request\n\n\t\t\tif contextKey == \"\" {\n\t\t\t\tctx = context.WithValue(r.Context(), \"db\", sCopy)\n\t\t\t\tnewReq = r.WithContext(ctx)\n\t\t\t} else {\n\t\t\t\tctx = context.WithValue(r.Context(), contextKey, sCopy)\n\t\t\t\tnewReq = r.WithContext(ctx)\n\t\t\t}\n\t\t\t// Process request\n\t\t\tnext.ServeHTTP(w, newReq)\n\t\t}\n\t\treturn http.HandlerFunc(fn)\n\t}\n}", "func (sr *SessionGormRepo) Session(sessionID string) (*entity.Session, []error) {\n\tsession := entity.Session{}\n\terrs := sr.conn.Find(&session, \"uuid=?\", sessionID).GetErrors()\n\tif len(errs) > 0 {\n\t\treturn nil, errs\n\t}\n\treturn &session, errs\n}", "func (n *Node) GetSession() (*ssh.Session, error) {\n\tif n.sshClient == nil {\n\t\t_, err := n.GetClient()\n\n\t\tif err != nil {\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"host\": n.IP,\n\t\t\t\t\"package\": \"dispatcher\",\n\t\t\t}).Fatal(\"Error getting session: \" + err.Error())\n\n\t\t\treturn &ssh.Session{}, errors.New(\"Error getting session: \" + err.Error())\n\t\t}\n\t}\n\n\tsession, err := n.sshClient.NewSession()\n\tif err != nil {\n\t\treturn &ssh.Session{}, errors.New(\"Failed to create session: \" + err.Error())\n\t}\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 &ssh.Session{}, errors.New(\"request for pseudo terminal failed: \" + err.Error())\n\t}\n\n\tstdout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn &ssh.Session{}, err\n\t}\n\n\tstderr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn &ssh.Session{}, err\n\t}\n\n\tgo n.sessionListenerRoutine(bufio.NewScanner(stdout))\n\tgo n.sessionListenerRoutine(bufio.NewScanner(stderr))\n\n\treturn session, nil\n}", "func (this *SessionTab) GetSession(sid string) (SessionTab, error) {\n\to := orm.NewOrm()\n\tvar sess SessionTab\n\n\tsess.Session = sid\n\terr := o.Read(&sess, \"session\")\n\n\treturn sess, err\n}", "func GetContext(name string) (*mgo.Session, *mgo.Collection) {\n\tsession := common.GetSession().Copy()\n\tcollection := session.DB(common.AppConfig.Database).C(name)\n\n\treturn session, collection\n}", "func GetSession(token string) (Session, error) {\n\tif m == nil {\n\t\treturn emptySession(), errors.New(\"Sessions not started\")\n\t}\n\n\tsession, err := m.provider.Read(token)\n\n\tif err != nil {\n\t\treturn emptySession(), err\n\t}\n\n\tsession.lifetime = time.Now().Add(m.maxLifetime) // reset lifetime\n\terr = m.updateSession(&session)\n\n\tif err != nil {\n\t\treturn emptySession(), err\n\t}\n\n\treturn session, nil\n}", "func GetSession(token string) (*Session, bool) {\n\tconst q = `SELECT * FROM Sessions WHERE token=$1 AND expires > now()`\n\n\tsession := &Session{}\n\terr := database.Get(session, q, token)\n\tif err != nil && err != sql.ErrNoRows {\n\t\tpanic(err)\n\t}\n\n\treturn session, err == nil\n}", "func (s *S3) getSession() (*session.Session, error) {\n\tif s.session == nil {\n\t\tcfg := aws.Config{\n\t\t\tCredentials: credentials.NewStaticCredentials(\n\t\t\t\tviper.GetString(\"s3.id\"),\n\t\t\t\tviper.GetString(\"s3.secret\"),\n\t\t\t\t\"\",\n\t\t\t),\n\t\t\tRegion: aws.String(viper.GetString(\"s3.region\")),\n\t\t}\n\n\t\tsession, err := session.NewSessionWithOptions(session.Options{Config: cfg})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ts.session = session\n\t}\n\n\treturn s.session, nil\n}", "func (m *Mongo) Init() (session *mgo.Session, err error) {\n\tif session != nil {\n\t\treturn nil, errors.New(\"session already exists\")\n\t}\n\n\tif session, err = mgo.Dial(m.URI); err != nil {\n\t\treturn nil, err\n\t}\n\n\tsession.EnsureSafe(&mgo.Safe{WMode: \"majority\"})\n\tsession.SetMode(mgo.Strong, true)\n\treturn session, nil\n}", "func (handler *IdentityProviderHandler) GetSession(sessionID string, userAgent string, remoteAddr string) (r *services.Session, err error) {\n\thandler.log.Printf(\"getSession(%v, %v, %v)\", sessionID, userAgent, remoteAddr)\n\n\tsession, err := handler.SessionInteractor.Find(sessionID)\n\tif err != nil {\n\t\te := err.(*errs.Error)\n\t\treturn nil, errorToServiceError(e)\n\t}\n\n\tif !session.Domain.Enabled || !session.User.Enabled {\n\t\te := services.NewUnauthorizedError()\n\t\te.Msg = \"Domain and/or user disabled\"\n\t\treturn nil, e\n\t}\n\n\tif session.UserAgent != userAgent || session.RemoteAddr != remoteAddr {\n\t\te := services.NewNotFoundError()\n\t\te.Msg = \"Session not found\"\n\t\treturn nil, e\n\t}\n\n\tif session.IsExpired() {\n\t\te := services.NewUnauthorizedError()\n\t\te.Msg = \"Session expired\"\n\t\treturn nil, e\n\t}\n\n\terr = handler.SessionInteractor.Retain(*session)\n\tif err != nil {\n\t\te := err.(*errs.Error)\n\t\treturn nil, errorToServiceError(e)\n\t}\n\n\treturn sessionToResponse(session), nil\n}", "func (b *OGame) GetSession() string {\n\treturn b.ogameSession\n}", "func (s *Server) GetSession(r *http.Request, name string) (*sessions.Session, error) {\n\treturn s.sessionStore.Get(r, name)\n}", "func SessionGet(token string) (*Session, bool) {\n\ts, ok := Sessions[token]\n\treturn s, ok\n}", "func (token SessionToken) GetSession() (*Session, error) {\n\tLoadDb()\n\tstmt, err := db.Prepare(\"select username, expires from session where token = ? and expires > ? and deleted is null\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstmt.Bind(token, time.Now())\n\trows, res, err := stmt.Exec()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(rows) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tname := rows[0].Str(res.Map(\"username\"))\n\tuser := &User{name}\n\n\texpires := rows[0].Localtime(res.Map(\"expires\"))\n\tsession := &Session{token, expires, user}\n\n\treturn session, nil\n}", "func GetSessionFromContext(context context.Context) *mgo.Session {\n\treturn context.Value(sessionKey).(*mgo.Session)\n}", "func (db *MongoDB) GetUserSession(id string) (*UserSession, error) {\n\tresult := db.instance.Collection(sessionCollection).FindOne(context.Background(), bson.M{\"sid\": id})\n\tif result.Err() != nil {\n\t\tif result.Err() == mongo.ErrNoDocuments {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, result.Err()\n\t}\n\tvar session UserSession\n\tif err := result.Decode(&session); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &session, nil\n}", "func GetSession(c *gin.Context) {\n\tvar session models.Session\n\tif err := models.DB.Where(\"code = ?\", strings.ToUpper(c.Param(\"code\"))).First(&session).Error; err != nil {\n\t\tif errors.Is(err, gorm.ErrRecordNotFound) {\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\t} else {\n\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": err.Error()})\n\t\t}\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\"data\": session})\n}", "func (margelet *Margelet) GetSessionRepository() SessionRepository {\n\treturn margelet.SessionRepository\n}", "func (s *Store) Get(clientID string) (*entities.Session, error) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\treturn s.sess[clientID], nil\n}", "func GetSession(ctx context.Context, name string) *sessions.Session {\n\tstore := ctx.Value(HTTPKey(\"fcare\")).(*sessions.CookieStore)\n\thttpContext := ctx.Value(HTTPKey(\"http\")).(HTTP)\n\n\t// Ignore err because a session is always returned even if one doesn't exist\n\tsession, _ := store.Get(httpContext.R, name)\n\n\treturn session\n}", "func (c *Client) Session(ctx context.Context) (*Session, error) {\n\tvar s Session\n\treq := c.Resource(internal.SessionPath).WithAction(\"get\").Request(http.MethodPost)\n\terr := c.Do(ctx, req, &s)\n\tif err != nil {\n\t\tif e, ok := err.(*statusError); ok {\n\t\t\tif e.res.StatusCode == http.StatusUnauthorized {\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn &s, nil\n}", "func (p *MongodbProvider) Read(sid string) (session.RawStore, error) {\n\tresult := sessionDoc{}\n\terr := p.c.Find(bson.M{\"key\": sid}).One(&result)\n\tif err != nil {\n\t\terr = p.c.Insert(&sessionDoc{Key: sid, Expiry: time.Now().Unix()})\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar kv map[interface{}]interface{}\n\tif len(result.Data) == 0 {\n\t\tkv = make(map[interface{}]interface{})\n\t} else {\n\t\tkv, err = session.DecodeGob(result.Data)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn NewMongodbStore(p.c, sid, kv), nil\n}", "func get() *mgo.Session {\n\tsession, err := mgo.Dial(SERVER)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t\treturn nil\n\t}\n\n\treturn session\n}", "func (t *SessionManager) GetSession(session_uuid string) (session *Session, err error) {\n\terr = nil\n\n\t// If it wasn't loaded into the cache, check if it's in the database.\n\tin_db, uid, expires, err := t.get_session_from_db(session_uuid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif in_db {\n\t\t// Load the session back into the cache and return it\n\t\tUserSession := new(Session)\n\t\tUserSession.User, err = GetUserById(t.db, uid)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tUserSession.Expires = expires\n\t\treturn UserSession, nil\n\t}\n\t// If it isn't in cache or DB, return false.\n\treturn nil, errors.New(\"Could not locate session in DB\")\n}", "func (service *SessionService) Session(sessionID string) (*entity.Session, error) {\n\tsess, err := service.conn.Session(sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn sess, err\n}", "func (ss *SessionServiceImpl) Session(sessionID string) (*entity.Session, error) {\n\tsess, err := ss.sessionRepo.Session(sessionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn sess, err\n}", "func (h *SessionHandler) GetSession(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tsession, err := h.SessionCore.GetSession(params[\"id\"])\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tjson.NewEncoder(w).Encode(&session)\n}" ]
[ "0.7763258", "0.7729244", "0.77174616", "0.7714797", "0.7622922", "0.7610538", "0.7607445", "0.7607404", "0.7607404", "0.75904083", "0.74248", "0.7197448", "0.70316523", "0.70088005", "0.69970316", "0.6957453", "0.69071007", "0.68869203", "0.68112403", "0.66923857", "0.65671736", "0.6521119", "0.6513103", "0.6487854", "0.6474006", "0.6450814", "0.6426192", "0.6414673", "0.6383536", "0.6370542", "0.6348702", "0.63426334", "0.63363856", "0.63179886", "0.62539405", "0.6241279", "0.6206975", "0.6189065", "0.61758167", "0.617043", "0.6152638", "0.61517626", "0.6140906", "0.6131909", "0.6120334", "0.60720277", "0.606748", "0.6025353", "0.60186344", "0.598632", "0.5981622", "0.59603167", "0.5960202", "0.59552795", "0.5940042", "0.5906368", "0.5906368", "0.5897357", "0.5894772", "0.5877557", "0.58725756", "0.58641994", "0.58541197", "0.5850171", "0.58456635", "0.58454525", "0.5839865", "0.5831052", "0.5829493", "0.5816281", "0.58118016", "0.5759837", "0.5757004", "0.5752853", "0.5750685", "0.57444215", "0.57433796", "0.5740251", "0.5732445", "0.5729021", "0.57233816", "0.57223994", "0.5706589", "0.5703239", "0.56936336", "0.56888676", "0.5685209", "0.56779516", "0.565324", "0.56364596", "0.5635234", "0.5621519", "0.5608115", "0.5597151", "0.55888325", "0.5583259", "0.5578527", "0.55701095", "0.55632895", "0.5555667" ]
0.76879805
4
Add indexes into MongoDB
func addIndexes() { var err error userIndex := mgo.Index{ Key: []string{"email"}, Unique: true, Background: true, Sparse: true, } // Add indexes into MongoDB session := GetSession().Copy() defer session.Close() userCol := session.DB(AppConfig.Database).C("users") err = userCol.EnsureIndex(userIndex) if err != nil { log.Fatalf("[addIndexes]: %s\n", err) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func addIndexes() {\n\tvar err error\n\tuserIndex := mgo.Index{\n\t\tKey: []string{\"email\"},\n\t\tUnique: true,\n\t\tBackground: true,\n\t\tSparse: true,\n\t}\n\n\tauthIndex := mgo.Index{\n\t\tKey: []string{\"sender_id\"},\n\t\tUnique: true,\n\t\tBackground: true,\n\t\tSparse: true,\n\t}\n\n\t// Add indexes into MongoDB\n\tsession := GetSession().Copy()\n\tdefer session.Close()\n\tuserCol := session.DB(AppConfig.MongoDBName).C(\"users\")\n\tauthCol := session.DB(AppConfig.MongoDBName).C(\"auth\")\n\n\terr = userCol.EnsureIndex(userIndex)\n\tif err != nil {\n\t\tlog.Fatalf(\"[addIndexes]: %s\\n\", err)\n\t}\n\n\terr = authCol.EnsureIndex(authIndex)\n\tif err != nil {\n\t\tlog.Fatalf(\"[addIndexes]: %s\\n\", err)\n\t}\n\n}", "func addIndexes() {\n\tvar err error\n\n\tufIndex1 := mgo.Index{\n\t\tKey: []string{\"codigo\"},\n\t\tUnique: true,\n\t\tBackground: true,\n\t\tSparse: true,\n\t}\n\tmunicipioIndex1 := mgo.Index{\n\t\tKey: []string{\"codigo\"},\n\t\tUnique: true,\n\t\tBackground: true,\n\t\tSparse: true,\n\t}\n\t// Add indexes into MongoDB\n\tsession := Session.Copy()\n\tdefer session.Close()\n\tufCol := session.DB(commons.AppConfig.Database).C(\"ufs\")\n\tmunicipioCol := session.DB(commons.AppConfig.Database).C(\"municipios\")\n\n\t// cria indice codigo para UF\n\terr = ufCol.EnsureIndex(ufIndex1)\n\tif err != nil {\n\t\tlog.Fatalf(\"[addIndexes]: %s\\n\", err)\n\t}\n\tlog.Println(\"Indice para UF criado com sucesso\")\n\n\t// cria indice codigo para Municipio\n\terr = municipioCol.EnsureIndex(municipioIndex1)\n\tif err != nil {\n\t\tlog.Fatalf(\"[addIndexes]: %s\\n\", err)\n\t}\n\tlog.Println(\"Indice para Municipio criado com sucesso\")\n\n}", "func (api *Api) createIndexes() {\n\t// username and email will be unique.\n\tkeys := bsonx.Doc{\n\t\t{Key: \"username\", Value: bsonx.Int32(1)},\n\t\t{Key: \"email\", Value: bsonx.Int32(1)},\n\t}\n\tpeople := api.DB.Collection(\"people\")\n\tdb.SetIndexes(people, keys)\n}", "func (b *Backend) createMongoIndexes() error {\n\top, err := b.connect()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn op.Do(func() error {\n\t\tindexes := []mgo.Index{\n\t\t\t{\n\t\t\t\tKey: []string{\"state\"},\n\t\t\t\tBackground: true, // can be used while index is being built\n\t\t\t\tExpireAfter: time.Duration(b.GetConfig().ResultsExpireIn) * time.Second,\n\t\t\t},\n\t\t\t{\n\t\t\t\tKey: []string{\"lock\"},\n\t\t\t\tBackground: true, // can be used while index is being built\n\t\t\t\tExpireAfter: time.Duration(b.GetConfig().ResultsExpireIn) * time.Second,\n\t\t\t},\n\t\t}\n\n\t\tfor _, index := range indexes {\n\t\t\t// Check if index already exists, if it does, skip\n\t\t\tif err := op.tasksCollection.EnsureIndex(index); err == nil {\n\t\t\t\tlog.INFO.Printf(\"%s index already exist, skipping create step\", index.Key[0])\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Create index (keep in mind EnsureIndex is blocking operation)\n\t\t\tlog.INFO.Printf(\"Creating %s index\", index.Key[0])\n\t\t\tif err := op.tasksCollection.DropIndex(index.Key[0]); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := op.tasksCollection.EnsureIndex(index); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}", "func (m *Mongo) Index(gid string, background bool) error {\n\tm.Session.ResetIndexCache()\n\n\tsessionCopy := m.Session.Copy()\n\tdefer sessionCopy.Close()\n\tcol := sessionCopy.DB(m.DBName).C(gid)\n\n\tcInfo := &mgo.CollectionInfo{DisableIdIndex: true}\n\terr := col.Create(cInfo)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\n\t/*\n\t\t// TODO figure out the magic of mongo indexes\n\t\tindex := mgo.Index{\n\t\t\tKey: []string{\"g\", \"s\", \"p\", \"o\"},\n\t\t\tBackground: false,\n\t\t\tSparse: true,\n\t\t\tUnique: true,\n\t\t\tDropDups: true,\n\t\t}\n\t\terr := col.EnsureIndex(index)\n\t\treturn err\n\t*/\n\n\tindex := mgo.Index{\n\t\tKey: []string{\"g\", \"s\"},\n\t\tBackground: background,\n\t\tSparse: true,\n\t}\n\terr = col.EnsureIndex(index)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\t//return err\n\t}\n\tlog.V(2).Infof(\"%+v\", index)\n\n\tindex.Key = []string{\"g\", \"o\"}\n\terr = col.EnsureIndex(index)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\t//return err\n\t}\n\tlog.V(2).Infof(\"%+v\", index)\n\n\tindex.Key = []string{\"g\", \"p\"}\n\terr = col.EnsureIndex(index)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\t//return err\n\t}\n\tlog.V(2).Infof(\"%+v\", index)\n\n\tindex.Key = []string{\"g\", \"s\", \"p\"}\n\terr = col.EnsureIndex(index)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\t//return err\n\t}\n\tlog.V(2).Infof(\"%+v\", index)\n\n\tindex.Key = []string{\"g\", \"s\", \"o\"}\n\terr = col.EnsureIndex(index)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\t//return err\n\t}\n\tlog.V(2).Infof(\"%+v\", index)\n\n\tindex.Key = []string{\"g\", \"p\", \"o\"}\n\terr = col.EnsureIndex(index)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\t//return err\n\t}\n\tlog.V(2).Infof(\"%+v\", index)\n\n\tindex.Key = []string{\"g\", \"s\", \"p\", \"o\"}\n\tindex.Unique = true\n\tindex.DropDups = true\n\terr = col.EnsureIndex(index)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\t//return err\n\t}\n\tlog.V(2).Infof(\"%+v\", index)\n\n\treturn nil\n}", "func ConfigureIndexes(mClient *mongo.Client) {\n\tcollection := getMarkdownCollection(mClient)\n\n\tindex := []mongo.IndexModel{\n\t\t{\n\t\t\tKeys: bsonx.Doc{\n\t\t\t\t{Key: \"title\", Value: bsonx.String(\"text\")},\n\t\t\t\t{Key: \"body\", Value: bsonx.String(\"text\")},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tKeys: bsonx.Doc{{Key: \"createDate\", Value: bsonx.Int32(1)}},\n\t\t},\n\t}\n\tname, err := collection.Indexes().CreateMany(context.TODO(), index)\n\tif err != nil {\n\t\tfmt.Printf(\"Error Creating Text Index: %s\", err)\n\t\treturn\n\t}\n\tfmt.Printf(\"Index Created: %s\\n\", name)\n}", "func SetIndexes(collection *mongo.Collection, keys bsonx.Doc) {\n\tindex := mongo.IndexModel{}\n\tindex.Keys = keys\n\tunique := true\n\tindex.Options = &options.IndexOptions{\n\t\tUnique: &unique,\n\t}\n\topts := options.CreateIndexes().SetMaxTime(10 * time.Second)\n\t_, err := collection.Indexes().CreateOne(context.Background(), index, opts)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error while creating indexs: %v\", err)\n\t}\n}", "func (db *MongoDb) Setup(indexes []mgo.Index) error {\n\t// Copy mongo session (thread safe) and close after function\n\tconn := db.Conn.Copy()\n\tdefer conn.Close()\n\n\t// Ensure indexes\n\tcol := conn.DB(db.Name).C(db.Collection)\n\n\tfor _, i := range indexes {\n\t\tif err := col.EnsureIndex(i); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func AddIndex(db MongoDB, m metrics.Metrics, col string, indexes ...mgo.Index) error {\n\tdefer m.CollectMetrics(\"DB.AddIndex\")\n\n\tif len(indexes) == 0 {\n\t\treturn nil\n\t}\n\n\tdatabase, session, err := db.New(false)\n\tif err != nil {\n\t\tm.Emit(metrics.Errorf(\"Failed to create session for index\"), metrics.With(\"collection\", col), metrics.With(\"error\", err.Error()))\n\t\treturn err\n\t}\n\n\tdefer session.Close()\n\n\tcollection := database.C(col)\n\n\tfor _, index := range indexes {\n\t\tif err := collection.EnsureIndex(index); err != nil {\n\t\t\tm.Emit(metrics.Errorf(\"Failed to ensure session index\"), metrics.With(\"collection\", col), metrics.With(\"index\", index), metrics.With(\"error\", err.Error()))\n\t\t\treturn err\n\t\t}\n\n\t\tm.Emit(metrics.Info(\"Succeeded in ensuring collection index\"), metrics.With(\"collection\", col), metrics.With(\"index\", index))\n\t}\n\n\tm.Emit(metrics.Info(\"Finished adding index\"), metrics.With(\"collection\", col))\n\treturn nil\n}", "func (b *Bucket) createIndexes(ctx context.Context) error {\n\t// must use primary read pref mode to check if files coll empty\n\tcloned, err := b.filesColl.Clone(options.Collection().SetReadPreference(readpref.Primary()))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdocRes := cloned.FindOne(ctx, bson.D{}, options.FindOne().SetProjection(bson.D{{\"_id\", 1}}))\n\n\t_, err = docRes.DecodeBytes()\n\tif err != mongo.ErrNoDocuments {\n\t\t// nil, or error that occurred during the FindOne operation\n\t\treturn err\n\t}\n\n\tfilesIv := b.filesColl.Indexes()\n\tchunksIv := b.chunksColl.Indexes()\n\n\tfilesModel := mongo.IndexModel{\n\t\tKeys: bson.D{\n\t\t\t{\"filename\", int32(1)},\n\t\t\t{\"uploadDate\", int32(1)},\n\t\t},\n\t}\n\n\tchunksModel := mongo.IndexModel{\n\t\tKeys: bson.D{\n\t\t\t{\"files_id\", int32(1)},\n\t\t\t{\"n\", int32(1)},\n\t\t},\n\t\tOptions: options.Index().SetUnique(true),\n\t}\n\n\tif err = createNumericalIndexIfNotExists(ctx, filesIv, filesModel); err != nil {\n\t\treturn err\n\t}\n\treturn createNumericalIndexIfNotExists(ctx, chunksIv, chunksModel)\n}", "func CreateIndexes(collections []models.Collection) {\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\tfor _, collection := range collections {\n\t\tmodels := []mongo.IndexModel{}\n\n\t\tfor _, field := range collection.Fields {\n\t\t\tmodels = append(models, mongo.IndexModel{\n\t\t\t\tKeys: bson.M{field.FieldName: 1},\n\t\t\t\tOptions: options.Index().SetUnique(field.Unique),\n\t\t\t})\n\t\t}\n\n\t\tdatabase := ConnectDB().Database(utils.Config.DatabaseName).Collection(collection.CollectionName)\n\t\t_, err := database.Indexes().CreateMany(ctx, models)\n\t\tif err != nil {\n\t\t\tfmt.Println(err.Error())\n\t\t\treturn\n\t\t}\n\t}\n}", "func addUserIndexes(db *mgo.Session) error {\n\tsession := db.Copy()\n\tdefer session.Close()\n\tc := session.DB(\"\").C(userCollection)\n\ti := mgo.Index{\n\t\tKey: []string{\"phone\"},\n\t\tUnique: true,\n\t}\n\terr := c.EnsureIndex(i)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to add index: %v\", err)\n\t}\n\n\treturn nil\n}", "func TestBaseModel_EnsureIndexes(t *testing.T) {\n\tconfig := mongo.Configuration{\n\t\tURL: \"mongodb://localhost:27017/some-test-db\",\n\t\tUseSSL: false,\n\t\tSSLCert: []byte{},\n\t\tPingFrequency: 100,\n\t}\n\n\tdb, teardown := mongo.InitMongoFromConfig(config)\n\tdefer teardown()\n\n\t// initialize the collection..\n\tdb.C(\"some-collection\").Insert(&testDocument{})\n\n\tmodel := &BaseModel{\n\t\tDB: db,\n\t\tCollectionName: \"some-collection\",\n\t\tIndexes: []*mgo.Index{\n\t\t\t{\n\t\t\t\tUnique: true,\n\t\t\t\tName: \"test_1\",\n\t\t\t\tKey: []string{\"first_key\"},\n\t\t\t},\n\t\t},\n\t}\n\n\tEnsureIndexes([]Model{model}, false)\n\n\tindexes, err := db.C(\"some-collection\").Indexes()\n\tassert.Nil(t, err)\n\tassert.Equal(t, []mgo.Index{\n\t\t{Key: []string{\"_id\"}, Name: \"_id_\"},\n\t\t{Key: []string{\"first_key\"}, Name: \"test_1\", Unique: true},\n\t}, indexes)\n}", "func (c *Collection) addIndex(schema *jsonschema.Schema, index Index, opts ...Option) error {\n\targs := &Options{}\n\tfor _, opt := range opts {\n\t\topt(args)\n\t}\n\n\t// Don't allow the default index to be overwritten\n\tif index.Path == idFieldName {\n\t\tif _, ok := c.indexes[idFieldName]; ok {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t// Validate path and type.\n\tjt, err := getSchemaTypeAtPath(schema, index.Path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar valid bool\n\tfor _, t := range indexTypes {\n\t\tif jt.Type == t {\n\t\t\tvalid = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !valid {\n\t\treturn ErrNotIndexable\n\t}\n\n\t// Skip if nothing to do\n\tif x, ok := c.indexes[index.Path]; ok && index.Unique == x.Unique {\n\t\treturn nil\n\t}\n\n\t// Ensure collection does not contain multiple instances with the same value at path\n\tif index.Unique && index.Path != idFieldName {\n\t\tvals := make(map[interface{}]struct{})\n\t\tall, err := c.Find(&Query{}, WithTxnToken(args.Token))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, i := range all {\n\t\t\tres := gjson.GetBytes(i, index.Path)\n\t\t\tif !res.Exists() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, ok := vals[res.Value()]; ok {\n\t\t\t\treturn ErrCantCreateUniqueIndex\n\t\t\t} else {\n\t\t\t\tvals[res.Value()] = struct{}{}\n\t\t\t}\n\t\t}\n\t}\n\n\tc.indexes[index.Path] = index\n\treturn c.saveIndexes()\n}", "func (c *MongoStoreClient) EnsureIndexes() error {\n\tmedtronicIndexDateTime, _ := time.Parse(medtronicDateFormat, medtronicIndexDate)\n\tdataIndexes := []mongo.IndexModel{\n\t\t{\n\t\t\tKeys: bson.D{{Key: \"_userId\", Value: 1}, {Key: \"deviceModel\", Value: 1}, {Key: \"fakefield\", Value: 1}},\n\t\t\tOptions: options.Index().\n\t\t\t\tSetName(\"GetLoopableMedtronicDirectUploadIdsAfter_v2_DateTime\").\n\t\t\t\tSetBackground(true).\n\t\t\t\tSetPartialFilterExpression(\n\t\t\t\t\tbson.D{\n\t\t\t\t\t\t{Key: \"_active\", Value: true},\n\t\t\t\t\t\t{Key: \"type\", Value: \"upload\"},\n\t\t\t\t\t\t{Key: \"deviceModel\", Value: bson.M{\n\t\t\t\t\t\t\t\"$exists\": true,\n\t\t\t\t\t\t}},\n\t\t\t\t\t\t{Key: \"time\", Value: bson.M{\n\t\t\t\t\t\t\t\"$gte\": medtronicIndexDateTime,\n\t\t\t\t\t\t}},\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t},\n\t\t{\n\t\t\tKeys: bson.D{{Key: \"_userId\", Value: 1}, {Key: \"origin.payload.device.manufacturer\", Value: 1}, {Key: \"fakefield\", Value: 1}},\n\t\t\tOptions: options.Index().\n\t\t\t\tSetName(\"HasMedtronicLoopDataAfter_v2_DateTime\").\n\t\t\t\tSetBackground(true).\n\t\t\t\tSetPartialFilterExpression(\n\t\t\t\t\tbson.D{\n\t\t\t\t\t\t{Key: \"_active\", Value: true},\n\t\t\t\t\t\t{Key: \"origin.payload.device.manufacturer\", Value: \"Medtronic\"},\n\t\t\t\t\t\t{Key: \"time\", Value: bson.M{\n\t\t\t\t\t\t\t\"$gte\": medtronicIndexDateTime,\n\t\t\t\t\t\t}},\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t},\n\t\t{\n\t\t\tKeys: bson.D{{Key: \"_userId\", Value: 1}, {Key: \"time\", Value: -1}, {Key: \"type\", Value: 1}},\n\t\t\tOptions: options.Index().\n\t\t\t\tSetName(\"UserIdTimeWeighted_v2\").\n\t\t\t\tSetBackground(true).\n\t\t\t\tSetPartialFilterExpression(\n\t\t\t\t\tbson.D{\n\t\t\t\t\t\t{Key: \"_active\", Value: true},\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t},\n\t}\n\n\tif _, err := dataCollection(c).Indexes().CreateMany(context.Background(), dataIndexes); err != nil {\n\t\tlog.Fatal(dataStoreAPIPrefix, fmt.Sprintf(\"Unable to create indexes: %s\", err))\n\t}\n\n\t// Not sure if all these indexes need to also be on the deviceDataSets collection.\n\tdataSetsIndexes := []mongo.IndexModel{\n\t\t{\n\t\t\tKeys: bson.D{{Key: \"_userId\", Value: 1}, {Key: \"deviceModel\", Value: 1}, {Key: \"fakefield\", Value: 1}},\n\t\t\tOptions: options.Index().\n\t\t\t\tSetName(\"GetLoopableMedtronicDirectUploadIdsAfter_v2_DateTime\").\n\t\t\t\tSetBackground(true).\n\t\t\t\tSetPartialFilterExpression(\n\t\t\t\t\tbson.D{\n\t\t\t\t\t\t{Key: \"_active\", Value: true},\n\t\t\t\t\t\t{Key: \"type\", Value: \"upload\"},\n\t\t\t\t\t\t{Key: \"deviceModel\", Value: bson.M{\n\t\t\t\t\t\t\t\"$exists\": true,\n\t\t\t\t\t\t}},\n\t\t\t\t\t\t{Key: \"time\", Value: bson.M{\n\t\t\t\t\t\t\t\"$gte\": medtronicIndexDateTime,\n\t\t\t\t\t\t}},\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t},\n\t\t{\n\t\t\tKeys: bson.D{{Key: \"_userId\", Value: 1}, {Key: \"origin.payload.device.manufacturer\", Value: 1}, {Key: \"fakefield\", Value: 1}},\n\t\t\tOptions: options.Index().\n\t\t\t\tSetName(\"HasMedtronicLoopDataAfter_v2_DateTime\").\n\t\t\t\tSetBackground(true).\n\t\t\t\tSetPartialFilterExpression(\n\t\t\t\t\tbson.D{\n\t\t\t\t\t\t{Key: \"_active\", Value: true},\n\t\t\t\t\t\t{Key: \"origin.payload.device.manufacturer\", Value: \"Medtronic\"},\n\t\t\t\t\t\t{Key: \"time\", Value: bson.M{\n\t\t\t\t\t\t\t\"$gte\": medtronicIndexDateTime,\n\t\t\t\t\t\t}},\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t},\n\t\t{\n\t\t\tKeys: bson.D{{Key: \"_userId\", Value: 1}, {Key: \"time\", Value: -1}, {Key: \"type\", Value: 1}},\n\t\t\tOptions: options.Index().\n\t\t\t\tSetName(\"UserIdTimeWeighted_v2\").\n\t\t\t\tSetBackground(true).\n\t\t\t\tSetPartialFilterExpression(\n\t\t\t\t\tbson.D{\n\t\t\t\t\t\t{Key: \"_active\", Value: true},\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t},\n\t}\n\n\tif _, err := dataSetsCollection(c).Indexes().CreateMany(context.Background(), dataSetsIndexes); err != nil {\n\t\tlog.Fatal(dataStoreAPIPrefix, fmt.Sprintf(\"Unable to create indexes: %s\", err))\n\t}\n\n\treturn nil\n}", "func init() {\n\tindexFields := []string{\"name\"}\n\tconfig.CreateHashIndexedCollection(CollectionName, indexFields)\n}", "func (m *DataRepositoryMongo) CreateIndex(collectionName string, indexes map[string]interface{}) <-chan error {\n\tresult := make(chan error)\n\tgo func() {\n\n\t\tvar (\n\t\t\terr error\n\t\t\tcollection *mongo.Collection\n\t\t\tctx context.Context\n\t\t)\n\n\t\tcollection, err = m.Client.GetCollection(collectionName)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Get collection %s err (%s)! \\n\", collectionName, err.Error())\n\t\t\tresult <- err\n\t\t}\n\n\t\tctx, err = m.Client.GetContext()\n\t\tif err != nil {\n\t\t\tlog.Error(\"Get context err (%s)! \\n\", err.Error())\n\t\t\tresult <- err\n\t\t}\n\n\t\tvar indexList []mongo.IndexModel\n\n\t\tfor key, value := range indexes {\n\t\t\tindexOption := &options.IndexOptions{}\n\t\t\tindexOption = indexOption.SetBackground(true)\n\t\t\tindex := mongo.IndexModel{Keys: bson.M{key: value}, Options: indexOption}\n\t\t\tindexList = append(indexList, index)\n\t\t}\n\n\t\t_, err = collection.Indexes().CreateMany(ctx, indexList)\n\t\tresult <- err\n\t\tclose(result)\n\t}()\n\n\treturn result\n}", "func EnsureIndex(db *mongo.Database, collectionName string, keys bson.M, opt *options.IndexOptions) {\n\tvar keyIndex []string\n\tfor k := range keys {\n\t\tkeyIndex = append(keyIndex, k)\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\tcollection := db.Collection(collectionName)\n\n\tindexes := collection.Indexes()\n\tcursor, err := indexes.List(ctx)\n\tif err != nil {\n\t\tlog.Panicf(\"index list error %v\", err)\n\t}\n\n\tif cursor != nil {\n\t\tfor cursor.Next(ctx) {\n\t\t\tvar index []primitive.E\n\t\t\terrCursor := cursor.Decode(&index)\n\t\t\tif errCursor != nil {\n\t\t\t\tlog.Panicf(\"index list error %v\", errCursor)\n\t\t\t}\n\n\t\t\t// skip creating index if key field already exist\n\t\t\tkeyIsExist := keyFieldIndexIsExist(index, keyIndex)\n\t\t\tif keyIsExist {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tmod := mongo.IndexModel{\n\t\t\tKeys: keys,\n\t\t\tOptions: opt,\n\t\t}\n\n\t\topts := options.CreateIndexes().SetMaxTime(5 * time.Second)\n\t\t_, err = collection.Indexes().CreateOne(ctx, mod, opts)\n\t\tif err != nil {\n\t\t\tlog.Panicf(\"ensure index error %v\", err)\n\t\t}\n\t}\n}", "func updateDBIndexes(mi *modelInfo) {\n\tadapter := adapters[db.DriverName()]\n\t// update column indexes\n\tfor colName, fi := range mi.fields.registryByJSON {\n\t\tif !fi.index {\n\t\t\tcontinue\n\t\t}\n\t\tif !adapter.indexExists(mi.tableName, fmt.Sprintf(\"%s_%s_index\", mi.tableName, colName)) {\n\t\t\tcreateColumnIndex(mi.tableName, colName)\n\t\t}\n\t}\n}", "func EnsureIndex(cd *mongo.Collection, indexQuery []string) error {\n\n\t// options for index\n\topts := options.CreateIndexes().SetMaxTime(5 * time.Second)\n\n\t// index model\n\tindex := []mongo.IndexModel{}\n\n\t// creating multiple index query\n\tfor _, val := range indexQuery {\n\t\ttemp := mongo.IndexModel{}\n\t\ttemp.Keys = bsonx.Doc{{Key: val, Value: bsonx.Int32(1)}}\n\t\tindex = append(index, temp)\n\t}\n\n\t// executng index query\n\t_, err := cd.Indexes().CreateMany(context.Background(), index, opts)\n\tif err != nil {\n\t\tfmt.Errorf(\"Error while executing index Query\", err.Error())\n\t\treturn err\n\t}\n\n\t// if executed successfully then return nil\n\treturn nil\n}", "func (c *Collection) indexAdd(tx ds.Txn, key ds.Key, data []byte) error {\n\tfor path, index := range c.indexes {\n\t\terr := c.indexUpdate(path, index, tx, key, data, false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func ExampleMongoDBIndexes() {\n\ta := fixture\n\tconst x = \"myReplicaSet_1\"\n\ti, found := search.MongoDBIndexes(a.IndexConfigs, func(r *opsmngr.IndexConfig) bool {\n\t\treturn r.RSName == x\n\t})\n\n\tif i < len(a.IndexConfigs) && found {\n\t\tfmt.Printf(\"found %v at index %d\\n\", x, i)\n\t} else {\n\t\tfmt.Printf(\"%s not found\\n\", x)\n\t}\n\t// Output:\n\t// found myReplicaSet_1 at index 0\n}", "func (m *MongoDB) CreateIndex(name, key string, order int) (string, error) {\n\tcoll, ok := m.coll[name]\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"not defined collection %s\", name)\n\t}\n\n\tasscending := 1\n\tif order == -1 {\n\t\tasscending = -1\n\t}\n\n\tmodel := mongo.IndexModel{\n\t\tKeys: bson.D{{Key: key, Value: asscending}},\n\t\t//Options: options.Index().SetBackground(true),\n\t}\n\n\topts := options.CreateIndexes().SetMaxTime(2 * time.Second)\n\n\treturn coll.Indexes().CreateOne(m.ctx, model, opts)\n}", "func GetIndexesFromDB(client *mongo.Client, dbName string) string {\n\tvar err error\n\tvar cur *mongo.Cursor\n\tvar icur *mongo.Cursor\n\tvar scur *mongo.Cursor\n\tvar buffer bytes.Buffer\n\tvar ctx = context.Background()\n\t// var pipeline = mongo.Pipeline{{{Key: \"$indexStats\", Value: bson.M{}}}}\n\tvar pipeline = MongoPipeline(`{\"$indexStats\": {}}`)\n\tif cur, err = client.Database(dbName).ListCollections(ctx, bson.M{}); err != nil {\n\t\treturn err.Error()\n\t}\n\tdefer cur.Close(ctx)\n\n\tfor cur.Next(ctx) {\n\t\tvar elem = bson.M{}\n\t\tif err = cur.Decode(&elem); err != nil {\n\t\t\tfmt.Println(\"0.1\", err)\n\t\t\tcontinue\n\t\t}\n\t\tcoll := fmt.Sprintf(\"%v\", elem[\"name\"])\n\t\tcollType := fmt.Sprintf(\"%v\", elem[\"type\"])\n\t\tif strings.Index(coll, \"system.\") == 0 || (elem[\"type\"] != nil && collType != \"collection\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tbuffer.WriteString(\"\\n\")\n\t\tbuffer.WriteString(dbName)\n\t\tbuffer.WriteString(\".\")\n\t\tbuffer.WriteString(coll)\n\t\tbuffer.WriteString(\":\\n\")\n\n\t\tif scur, err = client.Database(dbName).Collection(coll).Aggregate(ctx, pipeline); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tvar indexStats = []bson.M{}\n\t\tfor scur.Next(ctx) {\n\t\t\tvar result = bson.M{}\n\t\t\tif err = scur.Decode(&result); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tindexStats = append(indexStats, result)\n\t\t}\n\t\tscur.Close(ctx)\n\t\tindexView := client.Database(dbName).Collection(coll).Indexes()\n\t\tif icur, err = indexView.List(ctx); err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tdefer icur.Close(ctx)\n\t\tvar list []IndexStatsDoc\n\n\t\tfor icur.Next(ctx) {\n\t\t\tvar idx = bson.D{}\n\t\t\tif err = icur.Decode(&idx); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar keys bson.D\n\t\t\tvar indexName string\n\t\t\tfor _, v := range idx {\n\t\t\t\tif v.Key == \"name\" {\n\t\t\t\t\tindexName = v.Value.(string)\n\t\t\t\t} else if v.Key == \"key\" {\n\t\t\t\t\tkeys = v.Value.(bson.D)\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar strbuf bytes.Buffer\n\t\t\tfor n, value := range keys {\n\t\t\t\tif n == 0 {\n\t\t\t\t\tstrbuf.WriteString(\"{ \")\n\t\t\t\t}\n\t\t\t\tstrbuf.WriteString(value.Key + \": \" + fmt.Sprint(value.Value))\n\t\t\t\tif n == len(keys)-1 {\n\t\t\t\t\tstrbuf.WriteString(\" }\")\n\t\t\t\t} else {\n\t\t\t\t\tstrbuf.WriteString(\", \")\n\t\t\t\t}\n\t\t\t}\n\t\t\to := IndexStatsDoc{Key: strbuf.String()}\n\t\t\to.EffectiveKey = strings.Replace(o.Key[:len(o.Key)-2], \": -1\", \": 1\", -1)\n\t\t\to.Usage = []UsageDoc{}\n\t\t\tfor _, result := range indexStats {\n\t\t\t\tif result[\"name\"].(string) == indexName {\n\t\t\t\t\tdoc := result[\"accesses\"].(bson.M)\n\t\t\t\t\thost := result[\"host\"].(string)\n\t\t\t\t\tb, _ := bson.Marshal(doc)\n\t\t\t\t\tvar accesses UsageDoc\n\t\t\t\t\tbson.Unmarshal(b, &accesses)\n\t\t\t\t\taccesses.Hostname = host\n\t\t\t\t\to.Usage = append(o.Usage, accesses)\n\t\t\t\t}\n\t\t\t}\n\t\t\tlist = append(list, o)\n\t\t}\n\t\ticur.Close(ctx)\n\t\tsort.Slice(list, func(i, j int) bool { return (list[i].EffectiveKey <= list[j].EffectiveKey) })\n\t\tfor i, o := range list {\n\t\t\tfont := \"\\x1b[0m \"\n\t\t\tif o.Key != \"{ _id: 1 }\" {\n\t\t\t\tif i < len(list)-1 && strings.Index(list[i+1].EffectiveKey, o.EffectiveKey) == 0 {\n\t\t\t\t\tfont = \"\\x1b[31;1mx \" // red\n\t\t\t\t} else {\n\t\t\t\t\tsum := 0\n\t\t\t\t\tfor _, u := range o.Usage {\n\t\t\t\t\t\tsum += u.Ops\n\t\t\t\t\t}\n\t\t\t\t\tif sum == 0 {\n\t\t\t\t\t\tfont = \"\\x1b[34;1m? \" // blue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbuffer.WriteString(font + o.Key + \"\\x1b[0m\")\n\t\t\tfor _, u := range o.Usage {\n\t\t\t\tbuffer.Write([]byte(\"\\n\\thost: \" + u.Hostname + \", ops: \" + fmt.Sprintf(\"%v\", u.Ops) + \", since: \" + fmt.Sprintf(\"%v\", u.Since)))\n\t\t\t}\n\t\t\tbuffer.WriteString(\"\\n\")\n\t\t}\n\t}\n\treturn buffer.String()\n}", "func (g *Graph) addIndexes(schema *load.Schema) {\n\ttyp, _ := g.typ(schema.Name)\n\tfor _, idx := range schema.Indexes {\n\t\tcheck(typ.AddIndex(idx), \"invalid index for schema %q\", schema.Name)\n\t}\n}", "func (indexStore *IndexStore) InitIndex() {\n\tdocs := indexStore.db.getAllDocs()\n\tuniqueIndexes := make(map[string]int)\n\ti := 0\n\tfor _, doc := range docs {\n\t\tif _, present := indexStore.store[doc.Index]; !present {\n\t\t\tindexStore.NewIndex(doc.Index)\n\t\t}\n\t\tindexStore.AddDocument(doc.Index, doc.Title, doc.Contents, doc.Id)\n\t\tuniqueIndexes[doc.Index] = 1\n\n\t\tif i%50 == 0 {\n\t\t\tfmt.Printf(\"%v documents indexed\\n\", i)\n\t\t}\n\t\ti++\n\t}\n\n\tfor index := range uniqueIndexes {\n\t\tindexStore.UpdateIndex(index)\n\t}\n}", "func Initialize() {\n\tsession := db.Connection.Session.Copy()\n\tdefer session.Close()\n\tc := session.DB(conf.MONGODB_DATABASE).C(\"Nodes\")\n\tc.EnsureIndex(mgo.Index{Key: []string{\"acl.owner\"}, Background: true})\n\tc.EnsureIndex(mgo.Index{Key: []string{\"acl.read\"}, Background: true})\n\tc.EnsureIndex(mgo.Index{Key: []string{\"acl.write\"}, Background: true})\n\tc.EnsureIndex(mgo.Index{Key: []string{\"acl.delete\"}, Background: true})\n\tc.EnsureIndex(mgo.Index{Key: []string{\"created_on\"}, Background: true})\n\tc.EnsureIndex(mgo.Index{Key: []string{\"expiration\"}, Background: true})\n\tc.EnsureIndex(mgo.Index{Key: []string{\"type\"}, Background: true})\n\tc.EnsureIndex(mgo.Index{Key: []string{\"priority\"}, Background: true})\n\tc.EnsureIndex(mgo.Index{Key: []string{\"file.path\"}, Background: true})\n\tc.EnsureIndex(mgo.Index{Key: []string{\"file.virtual_parts\"}, Background: true})\n\tc.EnsureIndex(mgo.Index{Key: []string{\"file.checksum.md5\"}, Background: true})\n\tc.EnsureIndex(mgo.Index{Key: []string{\"id\"}, Unique: true})\n\tif conf.MONGODB_ATTRIBUTE_INDEXES != \"\" {\n\t\tfor _, v := range strings.Split(conf.MONGODB_ATTRIBUTE_INDEXES, \",\") {\n\t\t\tv = \"attributes.\" + strings.TrimSpace(v)\n\t\t\tc.EnsureIndex(mgo.Index{Key: []string{v}, Background: true})\n\t\t}\n\t}\n}", "func (iv IndexView) CreateMany(ctx context.Context, models []IndexModel, opts ...*options.CreateIndexesOptions) ([]string, error) {\n\tnames := make([]string, 0, len(models))\n\n\tvar indexes bsoncore.Document\n\taidx, indexes := bsoncore.AppendArrayStart(indexes)\n\n\tfor i, model := range models {\n\t\tif model.Keys == nil {\n\t\t\treturn nil, fmt.Errorf(\"index model keys cannot be nil\")\n\t\t}\n\n\t\tif isUnorderedMap(model.Keys) {\n\t\t\treturn nil, ErrMapForOrderedArgument{\"keys\"}\n\t\t}\n\n\t\tkeys, err := marshal(model.Keys, iv.coll.bsonOpts, iv.coll.registry)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tname, err := getOrGenerateIndexName(keys, model)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tnames = append(names, name)\n\n\t\tvar iidx int32\n\t\tiidx, indexes = bsoncore.AppendDocumentElementStart(indexes, strconv.Itoa(i))\n\t\tindexes = bsoncore.AppendDocumentElement(indexes, \"key\", keys)\n\n\t\tif model.Options == nil {\n\t\t\tmodel.Options = options.Index()\n\t\t}\n\t\tmodel.Options.SetName(name)\n\n\t\toptsDoc, err := iv.createOptionsDoc(model.Options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tindexes = bsoncore.AppendDocument(indexes, optsDoc)\n\n\t\tindexes, err = bsoncore.AppendDocumentEnd(indexes, iidx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tindexes, err := bsoncore.AppendArrayEnd(indexes, aidx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsess := sessionFromContext(ctx)\n\n\tif sess == nil && iv.coll.client.sessionPool != nil {\n\t\tsess = session.NewImplicitClientSession(iv.coll.client.sessionPool, iv.coll.client.id)\n\t\tdefer sess.EndSession()\n\t}\n\n\terr = iv.coll.client.validSession(sess)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twc := iv.coll.writeConcern\n\tif sess.TransactionRunning() {\n\t\twc = nil\n\t}\n\tif !writeconcern.AckWrite(wc) {\n\t\tsess = nil\n\t}\n\n\tselector := makePinnedSelector(sess, iv.coll.writeSelector)\n\n\toption := options.MergeCreateIndexesOptions(opts...)\n\n\top := operation.NewCreateIndexes(indexes).\n\t\tSession(sess).WriteConcern(wc).ClusterClock(iv.coll.client.clock).\n\t\tDatabase(iv.coll.db.name).Collection(iv.coll.name).CommandMonitor(iv.coll.client.monitor).\n\t\tDeployment(iv.coll.client.deployment).ServerSelector(selector).ServerAPI(iv.coll.client.serverAPI).\n\t\tTimeout(iv.coll.client.timeout).MaxTime(option.MaxTime)\n\tif option.CommitQuorum != nil {\n\t\tcommitQuorum, err := marshalValue(option.CommitQuorum, iv.coll.bsonOpts, iv.coll.registry)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\top.CommitQuorum(commitQuorum)\n\t}\n\n\terr = op.Execute(ctx)\n\tif err != nil {\n\t\t_, err = processWriteError(err)\n\t\treturn nil, err\n\t}\n\n\treturn names, nil\n}", "func (i *Index) Index(docs []index.Document, opts interface{}) error {\n blk := i.conn.Bulk()\n\tfor _, doc := range docs {\n //fmt.Println(\"indexing \", doc.Id)\n\t\treq := elastic.NewBulkIndexRequest().Index(i.name).Type(\"doc\").Id(doc.Id).Doc(doc.Properties)\n\t\tblk.Add(req)\n\t\t/*_, err := i.conn.Index().Index(i.name).Type(\"doc\").Id(doc.Id).BodyJson(doc.Properties).Do()\n if err != nil {\n // Handle error\n panic(err)\n }*/\n //fmt.Printf(\"Indexed tweet %s to index %s, type %s\\n\", put2.Id, put2.Index, put2.Type)\n\t}\n\t//_, err := blk.Refresh(true).Do()\n\t_, err := blk.Refresh(false).Do()\n if err != nil {\n panic(err)\n fmt.Println(\"Get Error during indexing\", err)\n }\n\treturn err\n\t//return nil\n}", "func createIndexes(ts *Schema, ti *Info, idxs []schema.Index, store *stor.Stor) {\n\tif len(idxs) == 0 {\n\t\treturn\n\t}\n\tts.Indexes = slices.Clip(ts.Indexes) // copy on write\n\tnold := len(ts.Indexes)\n\tfor i := range idxs {\n\t\tix := &idxs[i]\n\t\tif ts.FindIndex(ix.Columns) != nil {\n\t\t\tpanic(\"duplicate index: \" +\n\t\t\t\tstr.Join(\"(,)\", ix.Columns) + \" in \" + ts.Table)\n\t\t}\n\t\tts.Indexes = append(ts.Indexes, *ix)\n\t}\n\tidxs = ts.SetupNewIndexes(nold)\n\tn := len(ti.Indexes)\n\tti.Indexes = slices.Clip(ti.Indexes) // copy on write\n\tfor i := range idxs {\n\t\tbt := btree.CreateBtree(store, &ts.Indexes[n+i].Ixspec)\n\t\tti.Indexes = append(ti.Indexes, index.OverlayFor(bt))\n\t}\n}", "func EnsureIndex(ctx context.Context, c *mongo.Collection, keys []bson.E, unique bool) error {\n\tks := bson.D{}\n\tindexNames := []string{}\n\tfor _, k := range keys {\n\t\tindexNames = append(indexNames, fmt.Sprintf(\"%v_%v\", k.Key, k.Value))\n\t\tks = append(ks, k)\n\t}\n\tidxoptions := &options.IndexOptions{}\n\tidxoptions.SetBackground(true)\n\tidxoptions.SetUnique(unique)\n\tidm := mongo.IndexModel{\n\t\tKeys: ks,\n\t\tOptions: idxoptions,\n\t}\n\n\tidxs := c.Indexes()\n\tcur, err := idxs.List(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tindexName := strings.Join(indexNames, \"_\")\n\tfound := false\n\tfor cur.Next(ctx) {\n\t\td := bson.D{}\n\t\tcur.Decode(&d)\n\n\t\tfor _, v := range d {\n\t\t\tif v.Key == \"name\" && v.Value == indexName {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif found {\n\t\treturn nil\n\t}\n\n\t_, err = idxs.CreateOne(ctx, idm)\n\tif err != nil {\n\t\tfmt.Printf(\"create index error, name: %v, err: %v\", indexName, err)\n\t}\n\n\treturn err\n}", "func (repo *mongoBaseRepo) CreateIndexes(indexes interface{}, args ...interface{}) ([]string, error) {\n\ttimeout := DefaultTimeout\n\topts := &options.CreateIndexesOptions{}\n\n\tfor i := 0; i < len(args); i++ {\n\t\tswitch val := args[i].(type) {\n\t\tcase time.Duration:\n\t\t\ttimeout = val\n\t\tcase *options.CreateIndexesOptions:\n\t\t\topts = val\n\t\t}\n\t}\n\n\t// Convert indexModels\n\tindexModels, ok := indexes.([]mongo.IndexModel)\n\tif !ok {\n\t\treturn []string{}, ErrIndexConvert\n\t}\n\n\t// create indexes\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\treturn repo.collection.Indexes().CreateMany(ctx, indexModels, opts)\n}", "func (i *Index) Index(docs []index.Document, options interface{}) error {\n\n\tvar opts IndexingOptions\n\thasOpts := false\n\tif options != nil {\n\t\tif opts, hasOpts = options.(IndexingOptions); !hasOpts {\n\t\t\treturn errors.New(\"invalid indexing options\")\n\t\t}\n\t}\n\n\tconn := i.getConn()\n\tdefer conn.Close()\n\n\tn := 0\n\n\tfor _, doc := range docs {\n\t\targs := make(redis.Args, 0, len(i.md.Fields)*2+4)\n\t\targs = append(args, i.name, doc.Id, doc.Score)\n\t\t// apply options\n\t\tif hasOpts {\n\t\t\tif opts.NoSave {\n\t\t\t\targs = append(args, \"NOSAVE\")\n\t\t\t}\n\t\t\tif opts.Language != \"\" {\n\t\t\t\targs = append(args, \"LANGUAGE\", opts.Language)\n\t\t\t}\n\t\t}\n\n\t\targs = append(args, \"FIELDS\")\n\n\t\tfor k, f := range doc.Properties {\n\t\t\targs = append(args, k, f)\n\t\t}\n\n\t\tif err := conn.Send(i.commandPrefix+\".ADD\", args...); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tn++\n\t}\n\n\tif err := conn.Flush(); err != nil {\n\t\treturn err\n\t}\n\n\tfor n > 0 {\n\t\tif _, err := conn.Receive(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tn--\n\t}\n\n\treturn nil\n}", "func addAllFieldIndexes(ctx context.Context, indexer client.FieldIndexer) error {\n\tif err := indexer.IndexField(ctx, &gardencorev1beta1.Project{}, gardencore.ProjectNamespace, func(obj client.Object) []string {\n\t\tproject, ok := obj.(*gardencorev1beta1.Project)\n\t\tif !ok {\n\t\t\treturn []string{\"\"}\n\t\t}\n\t\tif project.Spec.Namespace == nil {\n\t\t\treturn []string{\"\"}\n\t\t}\n\t\treturn []string{*project.Spec.Namespace}\n\t}); err != nil {\n\t\treturn fmt.Errorf(\"failed to add indexer to Project Informer: %w\", err)\n\t}\n\n\tif err := indexer.IndexField(ctx, &gardencorev1beta1.Shoot{}, gardencore.ShootSeedName, func(obj client.Object) []string {\n\t\tshoot, ok := obj.(*gardencorev1beta1.Shoot)\n\t\tif !ok {\n\t\t\treturn []string{\"\"}\n\t\t}\n\t\tif shoot.Spec.SeedName == nil {\n\t\t\treturn []string{\"\"}\n\t\t}\n\t\treturn []string{*shoot.Spec.SeedName}\n\t}); err != nil {\n\t\treturn fmt.Errorf(\"failed to add indexer to Shoot Informer: %w\", err)\n\t}\n\n\tif err := indexer.IndexField(ctx, &seedmanagementv1alpha1.ManagedSeed{}, seedmanagement.ManagedSeedShootName, func(obj client.Object) []string {\n\t\tms, ok := obj.(*seedmanagementv1alpha1.ManagedSeed)\n\t\tif !ok {\n\t\t\treturn []string{\"\"}\n\t\t}\n\t\tif ms.Spec.Shoot == nil {\n\t\t\treturn []string{\"\"}\n\t\t}\n\t\treturn []string{ms.Spec.Shoot.Name}\n\t}); err != nil {\n\t\treturn fmt.Errorf(\"failed to add indexer to ManagedSeed Informer: %w\", err)\n\t}\n\n\treturn nil\n}", "func createIndexes(db *sql.DB, table string) error {\n\tindexes := []string{}\n\n\tswitch table {\n\tcase \"dfp\":\n\t\tindexes = []string{\n\t\t\t\"CREATE INDEX IF NOT EXISTS dfp_metrics ON dfp (CODE, ID_CIA, YEAR, VL_CONTA);\",\n\t\t\t\"CREATE INDEX IF NOT EXISTS dfp_year_ver ON dfp (ID_CIA, YEAR, VERSAO);\",\n\t\t}\n\tcase \"itr\":\n\t\tindexes = []string{\n\t\t\t\"CREATE INDEX IF NOT EXISTS itr_metrics ON itr (CODE, ID_CIA, YEAR, VL_CONTA);\",\n\t\t\t\"CREATE INDEX IF NOT EXISTS itr_quarter_ver ON itr (ID_CIA, DT_FIM_EXERC, VERSAO);\",\n\t\t}\n\tcase \"stock_quotes\":\n\t\tindexes = []string{\n\t\t\t\"CREATE UNIQUE INDEX IF NOT EXISTS stock_quotes_stockdate ON stock_quotes (stock, date);\",\n\t\t}\n\tcase \"fii_dividends\":\n\t\tindexes = []string{\n\t\t\t\"CREATE UNIQUE INDEX IF NOT EXISTS fii_dividends_pk ON fii_dividends (trading_code, base_date);\",\n\t\t}\n\t}\n\n\tfor _, idx := range indexes {\n\t\t_, err := db.Exec(idx)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"erro ao criar índice\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func createIndex(collection *mongo.Collection, field string, unique bool) bool {\n\tmod := mongo.IndexModel{\n\t\tKeys: bson.M{field: 1}, // index in ascending order or -1 for descending order\n\t\tOptions: options.Index().SetUnique(unique),\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\t_, err := collection.Indexes().CreateOne(ctx, mod)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (st *Schema) addCreateIndex(ci sql.CreateIndexStmt) {\n\tst.Indexes = append(st.Indexes, SchemaIndex{\n\t\tIndex: ci.Index,\n\t\tColumns: st.toIndexColumns(ci.IndexedColumns),\n\t})\n}", "func (db *MongoDbBridge) updateIndexes(col *mongo.Collection, list []mongo.IndexModel, sig chan bool) error {\n\tview := col.Indexes()\n\n\t// load list of all indexes known\n\tknown, err := view.ListSpecifications(context.Background())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// loop prescriptions and make sure each index exists by name\n\tfor _, ix := range list {\n\t\t// respect possible terminate signal\n\t\tselect {\n\t\tcase <-sig:\n\t\t\tsig <- true\n\t\t\treturn nil\n\t\tdefault:\n\t\t}\n\n\t\t// create missing index\n\t\terr = db.createIndexIfNotExists(col, &view, ix, known)\n\t\tif err != nil {\n\t\t\tdb.log.Errorf(err.Error())\n\t\t}\n\t}\n\n\t// loop indexes and remove indexes missing in the prescriptions\n\tfor _, spec := range known {\n\t\terr = db.removeIndexIfShouldNotExists(col, &view, spec, list)\n\t\tif err != nil {\n\t\t\tdb.log.Errorf(err.Error())\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s *Server) getIndexes(w http.ResponseWriter, r *http.Request) {\n\tfs, err := s.db.List(\"file\")\n\tif err != nil {\n\t\ts.logf(\"error listing files from mpd for building indexes: %v\", err)\n\t\twriteXML(w, errGeneric)\n\t\treturn\n\t}\n\tfiles := indexFiles(fs)\n\n\twriteXML(w, func(c *container) {\n\t\tc.Indexes = &indexesContainer{\n\t\t\tLastModified: time.Now().Unix(),\n\t\t}\n\n\t\t// Incremented whenever it's time to create a new index for a new\n\t\t// initial letter\n\t\tidx := -1\n\n\t\tvar indexes []index\n\n\t\t// A set of initial characters, used to deduplicate the addition of\n\t\t// nwe indexes\n\t\tseenChars := make(map[rune]struct{}, 0)\n\n\t\tfor _, f := range files {\n\t\t\t// Filter any non-top level items\n\t\t\tif strings.Contains(f.Name, string(os.PathSeparator)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Initial rune is used to create an index name\n\t\t\tc, _ := utf8.DecodeRuneInString(f.Name)\n\t\t\tname := string(c)\n\n\t\t\t// If initial rune is a digit, put index under a numeric section\n\t\t\tif unicode.IsDigit(c) {\n\t\t\t\tc = '#'\n\t\t\t\tname = \"#\"\n\t\t\t}\n\n\t\t\t// If a new rune appears, create a new index for it\n\t\t\tif _, ok := seenChars[c]; !ok {\n\t\t\t\tseenChars[c] = struct{}{}\n\t\t\t\tindexes = append(indexes, index{Name: name})\n\t\t\t\tidx++\n\t\t\t}\n\n\t\t\tindexes[idx].Artists = append(indexes[idx].Artists, artist{\n\t\t\t\tName: f.Name,\n\t\t\t\tID: strconv.Itoa(f.ID),\n\t\t\t})\n\t\t}\n\n\t\tc.Indexes.Indexes = indexes\n\t})\n}", "func InitDB(db *mgo.Database) {\n\tfor i := range workIndexes {\n\t\terr := db.C(workIndexes[i].Name).EnsureIndex(workIndexes[i].Index)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t}\n\t}\n}", "func indexHandler(s *search.SearchServer, w http.ResponseWriter, r *http.Request) {\n\tparams := r.URL.Query()\n\tcollection := params.Get(\"collection\")\n\n\tif collection == \"\" {\n\t\trespondWithError(w, r, \"Collection query parameter is required\")\n\t\treturn\n\t}\n\n\tif !s.Exists(collection) {\n\t\trespondWithError(w, r, \"Collection does not exist\")\n\t\treturn\n\t}\n\n\tbytes, err := ioutil.ReadAll(r.Body)\n\n\tif err != nil {\n\t\trespondWithError(w, r, \"Error reading body\")\n\t\treturn\n\t}\n\n\tif len(bytes) == 0 {\n\t\trespondWithError(w, r, \"Error document missing\")\n\t\treturn\n\t}\n\n\tvar doc document\n\terr = json.Unmarshal(bytes, &doc)\n\tif err != nil {\n\t\trespondWithError(w, r, \"Error parsing document JSON\")\n\t\treturn\n\t}\n\n\tif len(doc.Id) == 0 {\n\t\trespondWithError(w, r, fmt.Sprintf(\"Error document id is required, not found in: %v\", string(bytes)))\n\t\treturn\n\t}\n\n\tif len(doc.Fields) == 0 {\n\t\trespondWithError(w, r, \"Error document is missing fields\")\n\t\treturn\n\t}\n\n\td := search.NewDocument()\n\td.Id = doc.Id\n\tfor k, v := range doc.Fields {\n\t\td.Fields[k] = &search.Field{Value: v}\n\t}\n\n\ts.Index(collection, d)\n\trespondWithSuccess(w, r, \"Success, document indexed\")\n}", "func (db *MongoDB) Init() {\n\tindex := mgo.Index{\n\t\tKey: []string{\"date\"},\n\t\tUnique: true,\n\t\tDropDups: true,\n\t\tBackground: true,\n\t\tSparse: true,\n\t}\n\n\terr := Session.DB(db.DatabaseName).C(db.ExchangeCollectionName).EnsureIndex(index)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (m *MongoClient) initAllCollection() {\n\tm.UserCollection = m.Database.Collection(Collections[UserCollection])\n\tm.ProjectCollection = m.Database.Collection(Collections[ProjectCollection])\n\n\t// Initialize chaos infra collection\n\terr := m.Database.CreateCollection(context.TODO(), Collections[ChaosInfraCollection], nil)\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(\"failed to create chaosInfrastructures collection\")\n\t}\n\n\tm.ChaosInfraCollection = m.Database.Collection(Collections[ChaosInfraCollection])\n\t_, err = m.ChaosInfraCollection.Indexes().CreateMany(backgroundContext, []mongo.IndexModel{\n\t\t{\n\t\t\tKeys: bson.M{\n\t\t\t\t\"infra_id\": 1,\n\t\t\t},\n\t\t\tOptions: options.Index().SetUnique(true),\n\t\t},\n\t\t{\n\t\t\tKeys: bson.M{\n\t\t\t\t\"name\": 1,\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(\"failed to create indexes for chaosInfrastructures collection\")\n\t}\n\n\t// Initialize chaos experiment collection\n\terr = m.Database.CreateCollection(context.TODO(), Collections[ChaosExperimentCollection], nil)\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(\"failed to create chaosExperiments collection\")\n\t}\n\n\tm.ChaosExperimentCollection = m.Database.Collection(Collections[ChaosExperimentCollection])\n\t_, err = m.ChaosExperimentCollection.Indexes().CreateMany(backgroundContext, []mongo.IndexModel{\n\t\t{\n\t\t\tKeys: bson.M{\n\t\t\t\t\"experiment_id\": 1,\n\t\t\t},\n\t\t\tOptions: options.Index().SetUnique(true),\n\t\t},\n\t\t{\n\t\t\tKeys: bson.M{\n\t\t\t\t\"name\": 1,\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(\"failed to create indexes for chaosExperiments collection\")\n\t}\n\n\t// Initialize chaos experiment runs collection\n\terr = m.Database.CreateCollection(context.TODO(), Collections[ChaosExperimentRunsCollection], nil)\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(\"failed to create chaosExperimentRuns collection\")\n\t}\n\n\tm.ChaosExperimentRunsCollection = m.Database.Collection(Collections[ChaosExperimentRunsCollection])\n\t_, err = m.ChaosExperimentRunsCollection.Indexes().CreateMany(backgroundContext, []mongo.IndexModel{\n\t\t{\n\t\t\tKeys: bson.M{\n\t\t\t\t\"experiment_run_id\": 1,\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tlogrus.WithError(err).Fatal(\"failed to create indexes for chaosExperimentRuns collection\")\n\t}\n\n\t// Initialize chaos hubs collection\n\terr = m.Database.CreateCollection(context.TODO(), Collections[ChaosHubCollection], nil)\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(\"failed to create chaosHubs collection\")\n\t}\n\n\tm.ChaosHubCollection = m.Database.Collection(Collections[ChaosHubCollection])\n\t_, err = m.ChaosHubCollection.Indexes().CreateMany(backgroundContext, []mongo.IndexModel{\n\t\t{\n\t\t\tKeys: bson.M{\n\t\t\t\t\"hub_id\": 1,\n\t\t\t},\n\t\t\tOptions: options.Index().SetUnique(true),\n\t\t},\n\t\t{\n\t\t\tKeys: bson.M{\n\t\t\t\t\"name\": 1,\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tlogrus.WithError(err).Fatal(\"failed to create indexes for chaosHubs collection\")\n\t}\n\n\tm.GitOpsCollection = m.Database.Collection(Collections[GitOpsCollection])\n\t_, err = m.GitOpsCollection.Indexes().CreateMany(backgroundContext, []mongo.IndexModel{\n\t\t{\n\t\t\tKeys: bson.M{\n\t\t\t\t\"project_id\": 1,\n\t\t\t},\n\t\t\tOptions: options.Index().SetUnique(true),\n\t\t},\n\t})\n\tif err != nil {\n\t\tlogrus.WithError(err).Fatal(\"Error Creating Index for GitOps Collection : \", err)\n\t}\n\tm.ImageRegistryCollection = m.Database.Collection(Collections[ImageRegistryCollection])\n\tm.ServerConfigCollection = m.Database.Collection(Collections[ServerConfigCollection])\n\t_, err = m.ServerConfigCollection.Indexes().CreateMany(backgroundContext, []mongo.IndexModel{\n\t\t{\n\t\t\tKeys: bson.M{\n\t\t\t\t\"key\": 1,\n\t\t\t},\n\t\t\tOptions: options.Index().SetUnique(true),\n\t\t},\n\t})\n\tif err != nil {\n\t\tlogrus.WithError(err).Fatal(\"Error Creating Index for Server Config Collection : \", err)\n\t}\n\tm.EnvironmentCollection = m.Database.Collection(Collections[EnvironmentCollection])\n\t_, err = m.EnvironmentCollection.Indexes().CreateMany(backgroundContext, []mongo.IndexModel{\n\t\t{\n\t\t\tKeys: bson.M{\n\t\t\t\t\"environment_id\": 1,\n\t\t\t},\n\t\t\tOptions: options.Index().SetUnique(true),\n\t\t},\n\t\t{\n\t\t\tKeys: bson.M{\n\t\t\t\t\"name\": 1,\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tlogrus.WithError(err).Fatal(\"failed to create indexes for environments collection\")\n\t}\n\t// Initialize chaos probes collection\n\terr = m.Database.CreateCollection(context.TODO(), Collections[ChaosProbeCollection], nil)\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(\"failed to create chaosProbes collection\")\n\t}\n\n\tm.ChaosProbeCollection = m.Database.Collection(Collections[ChaosProbeCollection])\n\t_, err = m.ChaosProbeCollection.Indexes().CreateMany(backgroundContext, []mongo.IndexModel{\n\t\t{\n\t\t\tKeys: bson.M{\n\t\t\t\t\"name\": 1,\n\t\t\t},\n\t\t\tOptions: options.Index().SetUnique(true),\n\t\t},\n\t\t{\n\t\t\tKeys: bson.D{\n\t\t\t\t{\"project_id\", 1},\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(\"failed to create indexes for chaosProbes collection\")\n\t}\n}", "func (st *Schema) addIndex(pk bool, name string, cols []IndexColumn) bool {\n\tif reflect.DeepEqual(st.PK, cols) {\n\t\treturn false\n\t}\n\tfor _, ind := range st.Indexes {\n\t\tif reflect.DeepEqual(ind.Columns, cols) {\n\t\t\tif pk {\n\t\t\t\tst.PrimaryKey = ind.Index\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t}\n\tst.Indexes = append(st.Indexes, SchemaIndex{\n\t\tIndex: name,\n\t\tColumns: cols,\n\t})\n\tif pk {\n\t\tst.PrimaryKey = name\n\t}\n\treturn true\n}", "func (c *Collection) saveIndexes() error {\n\tib, err := json.Marshal(c.indexes)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.db.datastore.Put(dsIndexes.ChildString(c.name), ib)\n}", "func addStoringIndex(ctx context.Context, w io.Writer, adminClient *database.DatabaseAdminClient, database string) error {\n\top, err := adminClient.UpdateDatabaseDdl(ctx, &adminpb.UpdateDatabaseDdlRequest{\n\t\tDatabase: database,\n\t\tStatements: []string{\n\t\t\t\"CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle) STORING (MarketingBudget)\",\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := op.Wait(ctx); err != nil {\n\t\treturn err\n\t}\n\tfmt.Fprintf(w, \"Added storing index\\n\")\n\treturn nil\n}", "func (b *Bucket) EnsureIndexes(ctx context.Context, force bool) error {\n\t// acquire mutex\n\tb.indexMutex.Lock()\n\tdefer b.indexMutex.Unlock()\n\n\t// return if indexes have been ensured\n\tif b.indexEnsured {\n\t\treturn nil\n\t}\n\n\t// clone collection with primary read preference\n\tfiles, err := b.files.Clone(options.Collection().SetReadPreference(readpref.Primary()))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// unless force is specified, skip index ensuring if files exists already\n\tif !force {\n\t\terr = files.FindOne(ctx, bson.M{}).Err()\n\t\tif err != nil && err != ErrNoDocuments {\n\t\t\treturn err\n\t\t} else if err == nil {\n\t\t\tb.indexEnsured = true\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t// prepare files index\n\tfilesIndex := mongo.IndexModel{\n\t\tKeys: bson.D{\n\t\t\t{Key: \"filename\", Value: 1},\n\t\t\t{Key: \"uploadDate\", Value: 1},\n\t\t},\n\t}\n\n\t// prepare chunks index\n\tchunksIndex := mongo.IndexModel{\n\t\tKeys: bson.D{\n\t\t\t{Key: \"files_id\", Value: 1},\n\t\t\t{Key: \"n\", Value: 1},\n\t\t},\n\t\tOptions: options.Index().SetUnique(true),\n\t}\n\n\t// prepare markers index\n\tmarkersIndex := mongo.IndexModel{\n\t\tKeys: bson.D{\n\t\t\t{Key: \"files_id\", Value: 1},\n\t\t},\n\t\tOptions: options.Index().SetUnique(true),\n\t}\n\n\t// check files index existence\n\thasFilesIndex, err := b.hasIndex(ctx, b.files, filesIndex)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// check chunks index existence\n\thasChunksIndex, err := b.hasIndex(ctx, b.chunks, chunksIndex)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// check markers index existence\n\thasMarkersIndex, err := b.hasIndex(ctx, b.markers, markersIndex)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// create files index if missing\n\tif !hasFilesIndex {\n\t\t_, err = b.files.Indexes().CreateOne(ctx, filesIndex)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// create chunks index if missing\n\tif !hasChunksIndex {\n\t\t_, err = b.chunks.Indexes().CreateOne(ctx, chunksIndex)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// create markers index if missing\n\tif !hasMarkersIndex {\n\t\t_, err = b.markers.Indexes().CreateOne(ctx, markersIndex)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// set flag\n\tb.indexEnsured = true\n\n\treturn nil\n}", "func (db *Database) createTimestampIndex() {\n\tindexView := db.database.Collection(TRACKS.String()).Indexes()\n\n\tindexModel := mongo.IndexModel{\n\t\tKeys: bson.NewDocument(bson.EC.Int32(\"ts\", -1))}\n\n\t_, err := indexView.CreateOne(context.Background(), indexModel, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func CreateAllIndexes() error {\n\terr := questionAnswerDAO.CreateIndexes()\n\n\treturn err\n}", "func updateIndex(indexName string, objects []algoliasearch.Object) error {\n\n\tindex := algoliaClient.InitIndex(indexName)\n\terr := populateIndex(index, objects)\n\tif err != nil {\n\t\treturn errors.New(\"Error updating index -\" + err.Error())\n\t}\n\n\treturn nil\n}", "func (mdbc *MongoDbController) initUserCollection(dbName string) error {\n\tdb := mdbc.MongoClient.Database(dbName)\n\n\tjsonSchema := bson.M{\n\t\t\"bsonType\": \"object\",\n\t\t\"required\": []string{\"username\", \"passwordHash\", \"email\", \"enabled\", \"admin\"},\n\t\t\"properties\": bson.M{\n\t\t\t\"username\": bson.M{\n\t\t\t\t\"bsonType\": \"string\",\n\t\t\t\t\"description\": \"username is required and must be a string\",\n\t\t\t},\n\t\t\t\"passwordHash\": bson.M{\n\t\t\t\t\"bsonType\": \"string\",\n\t\t\t\t\"description\": \"passwordHash is required and must be a string\",\n\t\t\t},\n\t\t\t\"email\": bson.M{\n\t\t\t\t\"bsonType\": \"string\",\n\t\t\t\t\"description\": \"email is required and must be a string\",\n\t\t\t},\n\t\t\t\"enabled\": bson.M{\n\t\t\t\t\"bsonType\": \"bool\",\n\t\t\t\t\"description\": \"enabled is required and must be a boolean\",\n\t\t\t},\n\t\t\t\"admin\": bson.M{\n\t\t\t\t\"bsonType\": \"bool\",\n\t\t\t\t\"description\": \"admin is required and must be a boolean\",\n\t\t\t},\n\t\t},\n\t}\n\n\tcolOpts := options.CreateCollection().SetValidator(bson.M{\"$jsonSchema\": jsonSchema})\n\n\tcreateCollectionErr := db.CreateCollection(context.TODO(), \"users\", colOpts)\n\n\tif createCollectionErr != nil {\n\t\treturn dbController.NewDBError(createCollectionErr.Error())\n\t}\n\n\tmodels := []mongo.IndexModel{\n\t\t{\n\t\t\tKeys: bson.D{{Key: \"username\", Value: 1}},\n\t\t\tOptions: options.Index().SetUnique(true),\n\t\t},\n\t\t{\n\t\t\tKeys: bson.D{{Key: \"email\", Value: 1}},\n\t\t\tOptions: options.Index().SetUnique(true),\n\t\t},\n\t}\n\n\topts := options.CreateIndexes().SetMaxTime(2 * time.Second)\n\n\tcollection, _, _ := mdbc.getCollection(\"users\")\n\t_, setIndexErr := collection.Indexes().CreateMany(context.TODO(), models, opts)\n\n\tif setIndexErr != nil {\n\t\treturn dbController.NewDBError(setIndexErr.Error())\n\t}\n\n\thashedPass, hashedPassErr := authUtils.HashPassword(\"password\")\n\n\tif hashedPassErr != nil {\n\t\treturn hashedPassErr\n\t}\n\n\t// Add an administrative user\n\taddUserErr := mdbc.AddUser(dbController.FullUserDocument{\n\t\tUsername: \"admin\",\n\t\tEmail: \"[email protected]\",\n\t\tEnabled: true,\n\t\tAdmin: true,\n\t\tPasswordHash: hashedPass,\n\t},\n\t)\n\n\tif addUserErr != nil {\n\t\tfmt.Println(addUserErr.Error())\n\t\treturn dbController.NewDBError(addUserErr.Error())\n\t}\n\n\treturn nil\n}", "func InitializeIndexes(bucket base.Bucket, useXattrs bool, numReplicas uint, numHousekeepingReplicas uint) error {\n\n\tbase.Logf(\"Initializing indexes with numReplicas: %d\", numReplicas)\n\n\tgocbBucket, ok := bucket.(*base.CouchbaseBucketGoCB)\n\tif !ok {\n\t\tbase.Log(\"Using a non-Couchbase bucket - indexes will not be created.\")\n\t\treturn nil\n\t}\n\n\tfor _, sgIndex := range sgIndexes {\n\t\terr := sgIndex.createIfNeeded(gocbBucket, useXattrs, numReplicas)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to install index %s: %v\", sgIndex.simpleName, err)\n\t\t}\n\t}\n\n\treturn waitForIndexes(gocbBucket, useXattrs)\n}", "func (conf *Config) CreateIndexes(client *pilosa.Client) error {\n\treturn conf.CompareIndexes(client, true, true)\n}", "func TestEnsureIndex(t *testing.T) {\n\ttests.ResetLog()\n\tdefer tests.DisplayLog()\n\n\tconst fixture = \"basic.json\"\n\tset1, err := qfix.Get(fixture)\n\tif err != nil {\n\t\tt.Fatalf(\"\\t%s\\tShould load query record from file : %v\", tests.Failed, err)\n\t}\n\tt.Logf(\"\\t%s\\tShould load query record from file.\", tests.Success)\n\n\tdb, err := db.NewMGO(tests.Context, tests.TestSession)\n\tif err != nil {\n\t\tt.Fatalf(\"\\t%s\\tShould be able to get a Mongo session : %v\", tests.Failed, err)\n\t}\n\tdefer db.CloseMGO(tests.Context)\n\n\tdefer func() {\n\t\tif err := qfix.Remove(db, prefix); err != nil {\n\t\t\tt.Fatalf(\"\\t%s\\tShould be able to remove the query set : %v\", tests.Failed, err)\n\t\t}\n\t\tt.Logf(\"\\t%s\\tShould be able to remove the query set.\", tests.Success)\n\t}()\n\n\tt.Log(\"Given the need to validate ensureing indexes.\")\n\t{\n\t\tt.Log(\"\\tWhen using fixture\", fixture)\n\t\t{\n\t\t\tif err := query.EnsureIndexes(tests.Context, db, set1); err != nil {\n\t\t\t\tt.Fatalf(\"\\t%s\\tShould be able to ensure a query set index : %s\", tests.Failed, err)\n\t\t\t}\n\t\t\tt.Logf(\"\\t%s\\tShould be able to ensure a query set index.\", tests.Success)\n\t\t}\n\t}\n}", "func loadIndexs() {\n\tdb := open()\n\tindexs = make(map[string][]*Index)\n\tdb.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(INDEX_BUCKET))\n\t\tif b == nil {\n\t\t\tlogger.Infof(\"bucket[%s] not exist\", INDEX_BUCKET)\n\t\t\treturn nil\n\t\t}\n\t\tc := b.Cursor()\n\t\tfor k, v := c.First(); k != nil; k, v = c.Next() {\n\t\t\tkey := string(k)\n\t\t\tvar _indexs []string\n\t\t\terr := json.Unmarshal(v, &_indexs)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(\"parse index[%s] error -> %v\", k, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t__indexs := make([]*Index, len(_indexs)) \n\t\t\t// parse index\n\t\t\tfor i, _index := range _indexs {\n\t\t\t\tsps :=strings.Split(_index, INDEX_SPLIT) \n\t\t\t\tindex := &Index {\n\t\t\t\t\tbucket: key,\n\t\t\t\t\tindexs: sps,\n\t\t\t\t}\n\t\t\t\t__indexs[i] = index\n\t\t\t}\n\t\t\tindexs[key] = __indexs\n\t\t}\n\t\treturn nil\n\t})\n}", "func (db *DB) AddIndex(indexes ...*Index) error {\n\tfunc() {\n\t\tdb.m.Lock()\n\t\tdefer db.m.Unlock()\n\t\tfor _, v := range indexes {\n\t\t\tdb.indexes[v.name] = v\n\t\t}\n\t}()\n\tdb.m.RLock()\n\tdefer db.m.RUnlock()\n\treturn db.Update(func(tx *Tx) error {\n\t\tfor _, v := range db.indexes {\n\t\t\tif _, err := tx.CreateBucketIfNotExists([]byte(v.name)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif _, err := tx.CreateBucketIfNotExists([]byte(v.name + bkkeyssuffix)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}", "func (w *mongoWriter) createCollection(coll *Collection) error {\n\tc := w.session.Database(coll.DB).Collection(coll.Name)\n\n\tif w.append || w.indexOnly {\n\t\treturn nil\n\t}\n\terr := c.Drop(context.Background())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"fail to drop collection '%s'\\ncause %v\", coll.Name, err)\n\t}\n\n\tcreateCommand := bson.D{\n\t\tbson.E{Key: \"create\", Value: coll.Name},\n\t}\n\tif coll.CompressionLevel != \"\" {\n\t\tcreateCommand = append(createCommand, bson.E{Key: \"storageEngine\", Value: bson.M{\"wiredTiger\": bson.M{\"configString\": \"block_compressor=\" + coll.CompressionLevel}}})\n\t}\n\terr = w.session.Database(coll.DB).RunCommand(context.Background(), createCommand).Err()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"coulnd't create collection with compression level '%s'\\n cause: %v\", coll.CompressionLevel, err)\n\t}\n\n\tif coll.ShardConfig.ShardCollection != \"\" {\n\t\tnm := coll.DB + \".\" + coll.Name\n\t\tif coll.ShardConfig.ShardCollection != nm {\n\t\t\treturn fmt.Errorf(\"wrong value for 'shardConfig.shardCollection', should be <database>.<collection>: found '%s', expected '%s'\", coll.ShardConfig.ShardCollection, nm)\n\t\t}\n\t\tif len(coll.ShardConfig.Key) == 0 {\n\t\t\treturn fmt.Errorf(\"wrong value for 'shardConfig.key', can't be null and must be an object like {'_id': 'hashed'}, found: %v\", coll.ShardConfig.Key)\n\t\t}\n\t\terr := w.session.Database(\"admin\").RunCommand(context.Background(), bson.D{bson.E{Key: \"enableSharding\", Value: coll.DB}}).Err()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"fail to enable sharding on db '%s'\\n cause: %v\", coll.DB, err)\n\t\t}\n\t\t// as the collection is empty, no need to create the indexes on the sharded key before creating the collection,\n\t\t// because it will be created automatically by mongodb. See https://docs.mongodb.com/manual/core/sharding-shard-key/#shard-key-indexes\n\t\t// for details\n\t\terr = runMgoCompatCommand(context.Background(), w.session, \"admin\", coll.ShardConfig)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"fail to shard collection '%s' in db '%s'\\n cause: %v\", coll.Name, coll.DB, err)\n\t\t}\n\t}\n\treturn nil\n}", "func TestEnsureGeoIndex(t *testing.T) {\n\tc := createClient(t, nil)\n\tdb := ensureDatabase(nil, c, \"index_test\", nil, t)\n\n\ttestOptions := []*driver.EnsureGeoIndexOptions{\n\t\tnil,\n\t\t{GeoJSON: true},\n\t\t{GeoJSON: false},\n\t}\n\n\tfor i, options := range testOptions {\n\t\tcol := ensureCollection(nil, db, fmt.Sprintf(\"geo_index_test_%d\", i), nil, t)\n\n\t\tidx, created, err := col.EnsureGeoIndex(nil, []string{\"name\"}, options)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to create new index: %s\", describe(err))\n\t\t}\n\t\tif !created {\n\t\t\tt.Error(\"Expected created to be true, got false\")\n\t\t}\n\t\tif idxType := idx.Type(); idxType != driver.GeoIndex {\n\t\t\tt.Errorf(\"Expected GeoIndex, found `%s`\", idxType)\n\t\t}\n\t\tif options != nil && idx.GeoJSON() != options.GeoJSON {\n\t\t\tt.Errorf(\"Expected GeoJSON to be %t, found `%t`\", options.GeoJSON, idx.GeoJSON())\n\t\t}\n\n\t\t// Index must exists now\n\t\tif found, err := col.IndexExists(nil, idx.Name()); err != nil {\n\t\t\tt.Fatalf(\"Failed to check index '%s' exists: %s\", idx.Name(), describe(err))\n\t\t} else if !found {\n\t\t\tt.Errorf(\"Index '%s' does not exist, expected it to exist\", idx.Name())\n\t\t}\n\n\t\t// Ensure again, created must be false now\n\t\t_, created, err = col.EnsureGeoIndex(nil, []string{\"name\"}, options)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to re-create index: %s\", describe(err))\n\t\t}\n\t\tif created {\n\t\t\tt.Error(\"Expected created to be false, got true\")\n\t\t}\n\n\t\t// Remove index\n\t\tif err := idx.Remove(nil); err != nil {\n\t\t\tt.Fatalf(\"Failed to remove index '%s': %s\", idx.Name(), describe(err))\n\t\t}\n\n\t\t// Index must not exists now\n\t\tif found, err := col.IndexExists(nil, idx.Name()); err != nil {\n\t\t\tt.Fatalf(\"Failed to check index '%s' exists: %s\", idx.Name(), describe(err))\n\t\t} else if found {\n\t\t\tt.Errorf(\"Index '%s' does exist, expected it not to exist\", idx.Name())\n\t\t}\n\t}\n}", "func buildIndexes(s N1QLStore, indexNames []string) error {\n\tif len(indexNames) == 0 {\n\t\treturn nil\n\t}\n\n\t// Not using strings.Join because we want to escape each index name\n\tindexNameList := StringSliceToN1QLArray(indexNames, \"`\")\n\n\tbuildStatement := fmt.Sprintf(\"BUILD INDEX ON %s(%s)\", s.EscapedKeyspace(), indexNameList)\n\terr := s.executeStatement(buildStatement)\n\n\t// If indexer reports build will be completed in the background, wait to validate build actually happens.\n\tif IsIndexerRetryBuildError(err) {\n\t\tInfofCtx(context.TODO(), KeyQuery, \"Indexer error creating index - waiting for background build. Error:%v\", err)\n\t\t// Wait for bucket to be created in background before returning\n\t\treturn s.WaitForIndexesOnline(indexNames, false)\n\t}\n\n\treturn err\n}", "func (db *MongoDbBridge) createIndexIfNotExists(col *mongo.Collection, view *mongo.IndexView, ix mongo.IndexModel, known []*mongo.IndexSpecification) error {\n\t// throw if index is not explicitly named\n\tif ix.Options.Name == nil {\n\t\treturn fmt.Errorf(\"index name not defined on %s\", col.Name())\n\t}\n\n\t// do we know the index?\n\tfor _, spec := range known {\n\t\tif spec.Name == *ix.Options.Name {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tcreatedName, err := view.CreateOne(context.Background(), ix)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create index %s on %s\", *ix.Options.Name, col.Name())\n\t}\n\tdb.log.Noticef(\"created index %s on %s\", createdName, col.Name())\n\treturn nil\n}", "func (c *Couchbase) RegisterIndexes(indexes []*Index) {\n\tc.indexes = indexes\n}", "func addToIndex(repo *git.Repository, path string) error {\n\n\tindex, err := repo.Index()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = index.AddByPath(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = index.WriteTree()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = index.Write()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn err\n}", "func (mdbc *MongoDbController) initNonceDatabase(dbName string) error {\n\tdb := mdbc.MongoClient.Database(dbName)\n\n\tjsonSchema := bson.M{\n\t\t\"bsonType\": \"object\",\n\t\t\"required\": []string{\"hash\", \"time\", \"remoteAddress\"},\n\t\t\"properties\": bson.M{\n\t\t\t\"hash\": bson.M{\n\t\t\t\t\"bsonType\": \"string\",\n\t\t\t\t\"description\": \"hash is required and must be a string\",\n\t\t\t},\n\t\t\t\"time\": bson.M{\n\t\t\t\t\"bsonType\": \"long\",\n\t\t\t\t\"description\": \"time is required and must be a 64-bit integer (aka a long)\",\n\t\t\t},\n\t\t\t\"remoteAddress\": bson.M{\n\t\t\t\t\"bsonType\": \"string\",\n\t\t\t\t\"description\": \"remoteAddress is required and must be a string\",\n\t\t\t},\n\t\t},\n\t}\n\n\tcolOpts := options.CreateCollection().SetValidator(bson.M{\"$jsonSchema\": jsonSchema})\n\n\tcreateCollectionErr := db.CreateCollection(context.TODO(), \"authNonces\", colOpts)\n\n\tif createCollectionErr != nil {\n\t\treturn dbController.NewDBError(createCollectionErr.Error())\n\t}\n\n\tmodels := []mongo.IndexModel{\n\t\t{\n\t\t\tKeys: bson.D{{Key: \"hash\", Value: 1}},\n\t\t\tOptions: options.Index().SetUnique(true),\n\t\t},\n\t\t{\n\t\t\tKeys: bson.D{{Key: \"remoteAddress\", Value: 1}},\n\t\t\tOptions: options.Index().SetUnique(true),\n\t\t},\n\t}\n\n\topts := options.CreateIndexes().SetMaxTime(2 * time.Second)\n\n\tcollection, _, _ := mdbc.getCollection(\"authNonces\")\n\tnames, setIndexErr := collection.Indexes().CreateMany(context.TODO(), models, opts)\n\n\tif setIndexErr != nil {\n\t\treturn dbController.NewDBError(setIndexErr.Error())\n\t}\n\n\tfmt.Printf(\"created indexes %v\\n\", names)\n\n\treturn nil\n}", "func TestEnsurePersistentIndex(t *testing.T) {\n\tc := createClient(t, nil)\n\tdb := ensureDatabase(nil, c, \"index_test\", nil, t)\n\n\ttestOptions := []*driver.EnsurePersistentIndexOptions{\n\t\tnil,\n\t\t{Unique: true, Sparse: false},\n\t\t{Unique: true, Sparse: true},\n\t\t{Unique: false, Sparse: false},\n\t\t{Unique: false, Sparse: true},\n\t}\n\n\tfor i, options := range testOptions {\n\t\tcol := ensureCollection(nil, db, fmt.Sprintf(\"persistent_index_test_%d\", i), nil, t)\n\n\t\tidx, created, err := col.EnsurePersistentIndex(nil, []string{\"age\", \"name\"}, options)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to create new index: %s\", describe(err))\n\t\t}\n\t\tif !created {\n\t\t\tt.Error(\"Expected created to be true, got false\")\n\t\t}\n\t\tif idxType := idx.Type(); idxType != driver.PersistentIndex {\n\t\t\tt.Errorf(\"Expected PersistentIndex, found `%s`\", idxType)\n\t\t}\n\t\tif options != nil && idx.Unique() != options.Unique {\n\t\t\tt.Errorf(\"Expected Unique to be %t, found `%t`\", options.Unique, idx.Unique())\n\t\t}\n\t\tif options != nil && idx.Sparse() != options.Sparse {\n\t\t\tt.Errorf(\"Expected Sparse to be %t, found `%t`\", options.Sparse, idx.Sparse())\n\t\t}\n\n\t\t// Index must exist now\n\t\tif found, err := col.IndexExists(nil, idx.Name()); err != nil {\n\t\t\tt.Fatalf(\"Failed to check index '%s' exists: %s\", idx.Name(), describe(err))\n\t\t} else if !found {\n\t\t\tt.Errorf(\"Index '%s' does not exist, expected it to exist\", idx.Name())\n\t\t}\n\n\t\t// Ensure again, created must be false now\n\t\t_, created, err = col.EnsurePersistentIndex(nil, []string{\"age\", \"name\"}, options)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to re-create index: %s\", describe(err))\n\t\t}\n\t\tif created {\n\t\t\tt.Error(\"Expected created to be false, got true\")\n\t\t}\n\n\t\t// Remove index\n\t\tif err := idx.Remove(nil); err != nil {\n\t\t\tt.Fatalf(\"Failed to remove index '%s': %s\", idx.Name(), describe(err))\n\t\t}\n\n\t\t// Index must not exist now\n\t\tif found, err := col.IndexExists(nil, idx.Name()); err != nil {\n\t\t\tt.Fatalf(\"Failed to check index '%s' exists: %s\", idx.Name(), describe(err))\n\t\t} else if found {\n\t\t\tt.Errorf(\"Index '%s' does exist, expected it not to exist\", idx.Name())\n\t\t}\n\t}\n}", "func (i indexer) Index(ctx context.Context, req IndexQuery) (\n\tresp *IndexResult, err error) {\n\n\tlog.Info(\"index [%v] root [%v] len_dirs=%v len_files=%v\",\n\t\treq.Key, req.Root, len(req.Dirs), len(req.Files))\n\tstart := time.Now()\n\t// Setup the response\n\tresp = NewIndexResult()\n\tif err = req.Normalize(); err != nil {\n\t\tlog.Info(\"index [%v] error: %v\", req.Key, err)\n\t\tresp.Error = errs.NewStructError(err)\n\t\treturn\n\t}\n\n\t// create index shards\n\tvar nshards int\n\tif nshards = i.cfg.NumShards; nshards == 0 {\n\t\tnshards = 1\n\t}\n\tnshards = utils.MinInt(nshards, maxShards)\n\ti.shards = make([]index.IndexWriter, nshards)\n\ti.root = getRoot(i.cfg, &req)\n\n\tfor n := range i.shards {\n\t\tname := path.Join(i.root, shardName(req.Key, n))\n\t\tixw, err := getIndexWriter(ctx, name)\n\t\tif err != nil {\n\t\t\tresp.Error = errs.NewStructError(err)\n\t\t\treturn resp, nil\n\t\t}\n\t\ti.shards[n] = ixw\n\t}\n\n\tfs := getFileSystem(ctx, i.root)\n\trepo := newRepoFromQuery(&req, i.root)\n\trepo.SetMeta(i.cfg.RepoMeta, req.Meta)\n\tresp.Repo = repo\n\n\t// Add query Files and scan Dirs for files to index\n\tnames, err := i.scanner(fs, &req)\n\tch := make(chan int, nshards)\n\tchnames := make(chan string, 100)\n\tgo func() {\n\t\tfor _, name := range names {\n\t\t\tchnames <- name\n\t\t}\n\t\tclose(chnames)\n\t}()\n\treqch := make(chan par.RequestFunc, nshards)\n\tfor _, shard := range i.shards {\n\t\treqch <- indexShard(&i, &req, shard, fs, chnames, ch)\n\t}\n\tclose(reqch)\n\terr = par.Requests(reqch).WithConcurrency(nshards).DoWithContext(ctx)\n\tclose(ch)\n\n\t// Await results, each indicating the number of files scanned\n\tfor num := range ch {\n\t\trepo.NumFiles += num\n\t}\n\n\trepo.NumShards = len(i.shards)\n\t// Flush our index shard files\n\tfor _, shard := range i.shards {\n\t\tshard.Flush()\n\t\trepo.SizeIndex += ByteSize(shard.IndexBytes())\n\t\trepo.SizeData += ByteSize(shard.DataBytes())\n\t\tlog.Debug(\"index flush %v (data) %v (index)\",\n\t\t\trepo.SizeData, repo.SizeIndex)\n\t}\n\trepo.ElapsedIndexing = time.Since(start)\n\trepo.TimeUpdated = time.Now().UTC()\n\n\tvar msg string\n\tif err != nil {\n\t\trepo.State = ERROR\n\t\tresp.SetError(err)\n\t\tmsg = \"error: \" + resp.Error.Error()\n\t} else {\n\t\trepo.State = OK\n\t\tmsg = \"ok \" + fmt.Sprintf(\n\t\t\t\"(%v files, %v data, %v index)\",\n\t\t\trepo.NumFiles, repo.SizeData, repo.SizeIndex)\n\t}\n\tlog.Info(\"index [%v] %v [%v]\", req.Key, msg, repo.ElapsedIndexing)\n\treturn\n}", "func TestSQLSmith_LoadIndexes(t *testing.T) {\n\te := Executor{\n\t\tconn: nil,\n\t\tdb: dbname,\n\t\ttables: make(map[string]*types.Table),\n\t}\n\tindexes[\"users\"] = []types.CIStr{\"idx1\", \"idx2\"}\n\te.loadSchema(schema, indexes)\n\n\tassert.Equal(t, len(e.tables), 6)\n\tassert.Equal(t, len(e.tables[\"users\"].Indexes), 2)\n}", "func (s *searcher) CreateIndex() error {\n\tcolor.Cyan(\"[start] initialize index.\")\n\t// get user\n\tuser, reload, err := s.getUser()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"[err] createIndex %w\", err)\n\t}\n\n\t// check to whether exist starred items or not.\n\tvar isNewIndex bool\n\tif err := s.db.Update(func(tx *bolt.Tx) error {\n\t\tvar err error\n\t\tbucket := tx.Bucket([]byte(starredBucketName(s.gitToken)))\n\t\tif bucket == nil {\n\t\t\tbucket, err = tx.CreateBucket([]byte(starredBucketName(s.gitToken)))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tisNewIndex = true\n\t\t} else {\n\t\t\tisNewIndex = false\n\t\t}\n\t\treturn nil\n\t}); err != nil {\n\t\tClearAll()\n\t\tcolor.Yellow(\"[err] collapse db file, so delete db file\")\n\t\treturn fmt.Errorf(\"[err] createIndex %w\", err)\n\t}\n\n\t// read old database.\n\tvar oldStarredList []*git.Starred\n\toldStarredMap := map[string]*git.Starred{}\n\tif !isNewIndex {\n\t\t// read old starred from db\n\t\ts.db.View(func(tx *bolt.Tx) error {\n\t\t\tbucket := tx.Bucket([]byte(starredBucketName(s.gitToken)))\n\t\t\tbucket.ForEach(func(k, v []byte) error {\n\t\t\t\tvar starred *git.Starred\n\t\t\t\tif err := json.Unmarshal(v, &starred); err != nil {\n\t\t\t\t\tcolor.Yellow(\"[err] parsing %s\", string(k))\n\t\t\t\t} else {\n\t\t\t\t\toldStarredList = append(oldStarredList, starred)\n\t\t\t\t\toldStarredMap[starred.FullName] = starred\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\treturn nil\n\t\t})\n\n\t\t// write old starred to index\n\t\tfor _, starred := range oldStarredList {\n\t\t\tif err := s.index.Index(starred.FullName, starred); err != nil {\n\t\t\t\tcolor.Yellow(\"[err] indexing %s\", starred.FullName)\n\t\t\t}\n\t\t}\n\t}\n\n\t// are you all ready?\n\tif !reload && !isNewIndex {\n\t\tcount, _ := s.index.DocCount()\n\t\tcolor.Green(\"[success][using cache] %d items\", count)\n\t\treturn nil\n\t}\n\n\t// reload new starred list.\n\tnewStarredList, err := s.git.ListStarredAll()\n\tif err != nil {\n\t\tcolor.Yellow(\"[err] don't getting starred list %s\", err.Error())\n\t\tif !isNewIndex {\n\t\t\tcount, _ := s.index.DocCount()\n\t\t\tcolor.Yellow(\"[fail][using cache] %d items\", count)\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"[err] CreateIndex %w\", err)\n\t}\n\tnewStarredMap := map[string]*git.Starred{}\n\tfor _, starred := range newStarredList {\n\t\tnewStarredMap[starred.FullName] = starred\n\t}\n\n\t// update and insert\n\tif isNewIndex {\n\t\tcolor.White(\"[refresh] all repositories\")\n\t\ts.git.SetReadme(newStarredList)\n\t\ts.writeDBAndIndex(newStarredList)\n\t} else {\n\t\t// insert or update starred\n\t\tvar insertList []*git.Starred\n\t\tvar updateList []*git.Starred\n\t\tfor _, newStarred := range newStarredList {\n\t\t\tif oldStarred, ok := oldStarredMap[newStarred.FullName]; !ok {\n\t\t\t\tinsertList = append(insertList, newStarred)\n\t\t\t\tcolor.White(\"[insert] %s repository pushed_at %s\",\n\t\t\t\t\tnewStarred.FullName, newStarred.PushedAt.Format(time.RFC3339))\n\t\t\t} else {\n\t\t\t\tif oldStarred.PushedAt.Unix() != newStarred.PushedAt.Unix() &&\n\t\t\t\t\toldStarred.CachedAt.Unix() < time.Now().Add(-24*7*time.Hour).Unix() { // after 7 days.\n\t\t\t\t\tupdateList = append(updateList, newStarred)\n\t\t\t\t\tcolor.White(\"[update] %s repository pushed_at %s\",\n\t\t\t\t\t\tnewStarred.FullName, newStarred.PushedAt.Format(time.RFC3339))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// insert\n\t\ts.git.SetReadme(insertList)\n\t\ts.writeDBAndIndex(insertList)\n\n\t\t// update\n\t\ts.git.SetReadme(updateList)\n\t\ts.writeDBAndIndex(updateList)\n\n\t\t// delete starred\n\t\tvar deleteList []*git.Starred\n\t\tfor _, oldStarred := range oldStarredList {\n\t\t\tif _, ok := newStarredMap[oldStarred.FullName]; !ok {\n\t\t\t\tdeleteList = append(deleteList, oldStarred)\n\t\t\t\tcolor.White(\"[delete] %s repository pushed_at %s\",\n\t\t\t\t\toldStarred.FullName, oldStarred.PushedAt.Format(time.RFC3339))\n\t\t\t}\n\t\t}\n\t\t// delete\n\t\ts.deleteDBAndIndex(deleteList)\n\t}\n\n\t// rewrite a user to db\n\tuserData, err := json.Marshal(user)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"[err] createIndex %w\", err)\n\t}\n\ts.db.Update(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket([]byte(userBucketName))\n\t\tbucket.Put([]byte(s.gitToken), userData)\n\t\treturn nil\n\t})\n\n\tcount, _ := s.index.DocCount()\n\tcolor.Green(\"[success][new reload] %d items\", count)\n\treturn nil\n}", "func (db *MongoDbBridge) updateDatabaseIndexes() {\n\t// define index list loaders\n\tvar ixLoaders = map[string]indexListProvider{\n\t\tcolNetworkNodes: operaNodeCollectionIndexes,\n\t\tcolLockedDelegations: lockedDelegationsIndexes,\n\t}\n\n\t// the DB bridge needs a way to terminate this thread\n\tsig := make(chan bool, 1)\n\tdb.sig = append(db.sig, sig)\n\n\t// prep queue and start the updater\n\tiq := make(chan *IndexList, indexListQueueCapacity)\n\tdb.wg.Add(1)\n\tgo db.indexUpdater(iq, sig)\n\n\t// check indexes\n\tfor cn, ld := range ixLoaders {\n\t\tiq <- &IndexList{\n\t\t\tCollection: db.client.Database(db.dbName).Collection(cn),\n\t\t\tIndexes: ld(),\n\t\t}\n\t}\n\n\t// close the channel as no more updates will be sent\n\tclose(iq)\n}", "func (i *Index) Create() error {\n\n\tdoc := mapping{Properties: map[string]mappingProperty{}}\n\tfor _, f := range i.md.Fields {\n\t\tdoc.Properties[f.Name] = mappingProperty{}\n\t\tfs, err := fieldTypeString(f.Type)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdoc.Properties[f.Name][\"type\"] = fs\n\t}\n\n // Added for apple to apple benchmark\n doc.Properties[\"body\"][\"type\"] = \"text\"\n doc.Properties[\"body\"][\"analyzer\"] = \"my_english_analyzer\"\n doc.Properties[\"body\"][\"search_analyzer\"] = \"whitespace\"\n doc.Properties[\"body\"][\"index_options\"] = \"offsets\"\n //doc.Properties[\"body\"][\"test\"] = \"test\"\n index_map := map[string]int{\n \"number_of_shards\" : 1,\n \"number_of_replicas\" : 0,\n }\n analyzer_map := map[string]interface{}{\n \"my_english_analyzer\": map[string]interface{}{\n \"tokenizer\": \"standard\",\n \"char_filter\": []string{ \"html_strip\" } ,\n \"filter\" : []string{\"english_possessive_stemmer\", \n \"lowercase\", \"english_stop\", \n \"english_stemmer\", \n \"asciifolding\", \"icu_folding\"},\n },\n }\n filter_map := map[string]interface{}{\n \"english_stop\": map[string]interface{}{\n \"type\": \"stop\",\n \"stopwords\": \"_english_\",\n },\n \"english_possessive_stemmer\": map[string]interface{}{\n \"type\": \"stemmer\",\n \"language\": \"possessive_english\",\n },\n \"english_stemmer\" : map[string]interface{}{\n \"type\" : \"stemmer\",\n \"name\" : \"english\",\n },\n \"my_folding\": map[string]interface{}{\n \"type\": \"asciifolding\",\n \"preserve_original\": \"false\",\n },\n }\n analysis_map := map[string]interface{}{\n \"analyzer\": analyzer_map,\n \"filter\" : filter_map,\n }\n settings := map[string]interface{}{\n \"index\": index_map,\n \"analysis\": analysis_map,\n }\n\n // TODO delete?\n\t// we currently manually create the autocomplete mapping\n\t/*ac := mapping{\n\t\tProperties: map[string]mappingProperty{\n\t\t\t\"sugg\": mappingProperty{\n\t\t\t\t\"type\": \"completion\",\n\t\t\t\t\"payloads\": true,\n\t\t\t},\n\t\t},\n\t}*/\n\n\tmappings := map[string]mapping{\n\t\ti.typ: doc,\n //\t\"autocomplete\": ac,\n\t}\n\n fmt.Println(mappings)\n\n\t//_, err := i.conn.CreateIndex(i.name).BodyJson(map[string]interface{}{\"mappings\": mappings}).Do()\n\t_, err := i.conn.CreateIndex(i.name).BodyJson(map[string]interface{}{\"mappings\": mappings, \"settings\": settings}).Do()\n\n if err != nil {\n fmt.Println(\"Error \", err)\n\t\tfmt.Println(\"!!!!Get Error when using client to create index\")\n\t}\n\n\treturn err\n}", "func (e *ElasticSearch) Setup(bangs []Bang) error {\n\tif _, err := e.Client.CreateIndex(e.Index).Body(e.mapping()).Do(context.TODO()); err != nil {\n\t\treturn err\n\t}\n\n\tfor _, b := range bangs {\n\t\tfor _, t := range b.Triggers {\n\t\t\tq := struct {\n\t\t\t\tCompletion *elastic.SuggestField `json:\"bang_suggest\"`\n\t\t\t}{\n\t\t\t\telastic.NewSuggestField().Input(t).Weight(0),\n\t\t\t}\n\n\t\t\t_, err := e.Client.Index().\n\t\t\t\tIndex(e.Index).\n\t\t\t\tType(e.Type).\n\t\t\t\tBodyJson(&q).\n\t\t\t\tDo(context.TODO())\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func CreateCommonIndexes(mgr manager.Manager) error {\n\tfor _, ia := range getIndexArgs() {\n\t\tif err := mgr.GetFieldIndexer().IndexField(context.TODO(), ia.obj, ia.field, ia.extractValue); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (conf *Config) CompareIndexes(client *pilosa.Client, mayCreate, mustCreate bool) error {\n\terrs := make([]error, 0)\n\tschema, err := client.Schema()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"retrieving schema\")\n\t}\n\tdbIndexes := schema.Indexes()\n\tvar dbIndex *pilosa.Index\n\tchanged := false\n\tfor _, index := range conf.indexes {\n\t\tdbIndex = dbIndexes[index.FullName]\n\t\tif dbIndex == nil {\n\t\t\tif !mayCreate {\n\t\t\t\terrs = append(errs, fmt.Errorf(\"index '%s' does not exist\", index.FullName))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tchanged = true\n\t\t\tdbIndex = schema.Index(index.FullName)\n\t\t} else {\n\t\t\tif mustCreate {\n\t\t\t\terrs = append(errs, fmt.Errorf(\"index '%s' already exists\", index.FullName))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\t// if we got here, the index now exists, so we can do the same thing to fields...\n\t\tchangedFields, fieldErrs := conf.CompareFields(client, dbIndex, index, mayCreate, mustCreate)\n\t\tif changedFields {\n\t\t\tchanged = true\n\t\t}\n\t\terrs = append(errs, fieldErrs...)\n\t}\n\tif changed {\n\t\tfmt.Printf(\"changes made to db, syncing...\\n\")\n\t\terr = client.SyncSchema(schema)\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\tif len(errs) > 0 {\n\t\treturn errs[0]\n\t}\n\treturn nil\n}", "func (s *SiteSearchTagsDAO) AddTagsSearchIndex(docID string, doctype string, tags []string) error {\n\n\tfor _, v := range tags {\n\n\t\tcount, err := s.Exists(v)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error attempting to get record count for keyword %s with error %s\", v, err)\n\t\t}\n\n\t\tlog.Info().Msgf(\"Found %d site search tag records for keyworkd %s\", count, v)\n\n\t\t// Determine if the document exists already\n\t\tif count == 0 {\n\t\t\tlog.Info().Msgf(\"]Tag does not exist for %s in the database\", v)\n\t\t\tvar newSTM models.SiteSearchTagsModel\n\t\t\tnewSTM.Name = v\n\t\t\tnewSTM.TagsID = models.GenUUID()\n\t\t\tvar doc models.Documents\n\t\t\tvar docs []models.Documents\n\t\t\tdoc.DocType = doctype\n\t\t\tdoc.DocumentID = docID\n\t\t\tdocs = append(docs, doc)\n\n\t\t\tnewSTM.Documents = docs\n\t\t\tlog.Info().Msgf(\"Inserting new tag %s into database\", v)\n\t\t\terr = s.InsertSiteSearchTags(&newSTM)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error inserting new site search tag for keyword %s with error %s\", v, err)\n\t\t\t}\n\t\t\tlog.Info().Msgf(\"Tag %s inserted successfully\", v)\n\t\t\t// If not, then we add to existing documents\n\t\t} else {\n\n\t\t\tstm, err := s.GetSiteSearchTagByName(v)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error getting current instance of searchtag for keyword %s with error %s\", v, err)\n\t\t\t}\n\t\t\tlog.Info().Msgf(\"Found existing searchtagid record for %s\", stm.Name)\n\t\t\t//fmt.Println(mtm.Documents)\n\n\t\t\t// Get the list of documents\n\t\t\tdocs := stm.Documents\n\n\t\t\t// For the list of documents, find the document ID we are looking for\n\t\t\t// If not found, then we update the document list with the document ID\n\t\t\tfound := false\n\t\t\tfor _, d := range docs {\n\t\t\t\tif d.DocumentID == v {\n\t\t\t\t\tfound = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif found {\n\t\t\t\tlog.Info().Msgf(\"Updating tag, %s with document id %s\", v, docID)\n\t\t\t\tvar doc models.Documents\n\t\t\t\tdoc.DocType = doctype\n\t\t\t\tdoc.DocumentID = docID\n\t\t\t\tdocs = append(docs, doc)\n\t\t\t\tstm.Documents = docs\n\t\t\t\t//fmt.Println(mtm)\n\t\t\t\terr = s.UpdateSiteSearchTags(&stm)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"error updating searchtag for keyword %s with error %s\", v, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (esHandler *ESHandler) Index(verses []Verse) error {\n\tctx := context.Background()\n\tserivce, err := esHandler.Client.BulkProcessor().Name(\"ScriptureProcessor\").Workers(2).BulkActions(1000).Do(ctx)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Error initializing BulkProcessor\")\n\t}\n\tdefer serivce.Close()\n\n\tfor _, v := range verses {\n\t\tid := v.GetID()\n\t\tr := elastic.NewBulkIndexRequest().Index(esHandler.ESIndex).Type(\"Verse\").Id(id).Doc(v)\n\t\tserivce.Add(r)\n\t}\n\treturn nil\n}", "func (c *Couchbase) CreateIndexes(numReplicas int) ([]gocb.IndexInfo, []error) {\n\thosts := strings.Split(c.config.Hosts, \",\")\n\n\tvar indexErrors []error\n\n\tif len(c.indexes) == 0 {\n\t\tnoIndexes := errorNoRegisteredIndexes\n\t\tindexerLog.With(noIndexes)\n\t\tindexErrors = append(indexErrors, noIndexes)\n\t}\n\n\tfor _, index := range c.indexes {\n\n\t\terr := c.createIndex(index, hosts[0], numReplicas, true)\n\n\t\tif err != nil {\n\t\t\tindexerLog.With(\"error\", pkgerr.WithStack(err)).Error()\n\t\t\tindexErrors = append(indexErrors, err)\n\t\t}\n\t}\n\n\tindexes, err := c.Bucket.Manager(Cb.config.BucketName, Cb.config.BucketPassword).GetIndexes()\n\n\tif err != nil {\n\t\tindexErrors = append(indexErrors, err)\n\t}\n\n\tfor _, indexInfo := range indexes {\n\t\tindexerLog.With(structs.Map(indexInfo)).Info(\"Registered index\")\n\t}\n\n\treturn indexes, indexErrors\n}", "func EnsureIndexes(ctx context.Context, adminSvc *apiv1.FirestoreAdminClient, tuples IndexList, indexParent string) error {\n\tl := log.WithFields(log.Fields{trace.Component: BackendName})\n\tvar tasks []indexTask\n\n\t// create the indexes\n\tfor _, tuple := range tuples {\n\t\toperation, err := adminSvc.CreateIndex(ctx, &adminpb.CreateIndexRequest{\n\t\t\tParent: indexParent,\n\t\t\tIndex: &adminpb.Index{\n\t\t\t\tQueryScope: adminpb.Index_COLLECTION,\n\t\t\t\tFields: tuple,\n\t\t\t},\n\t\t})\n\t\tif err != nil && status.Code(err) != codes.AlreadyExists {\n\t\t\treturn ConvertGRPCError(err)\n\t\t}\n\t\t// operation can be nil if error code is codes.AlreadyExists.\n\t\tif operation != nil {\n\t\t\ttasks = append(tasks, indexTask{operation, tuple})\n\t\t}\n\t}\n\n\tstop := periodIndexUpdate(l)\n\tfor _, task := range tasks {\n\t\terr := waitOnIndexCreation(ctx, l, task)\n\t\tif err != nil {\n\t\t\treturn trace.Wrap(err)\n\t\t}\n\t}\n\tstop <- struct{}{}\n\n\treturn nil\n}", "func TestEnsureHashIndex(t *testing.T) {\n\tc := createClient(t, nil)\n\tdb := ensureDatabase(nil, c, \"index_test\", nil, t)\n\n\ttestOptions := []*driver.EnsureHashIndexOptions{\n\t\tnil,\n\t\t{Unique: true, Sparse: false},\n\t\t{Unique: true, Sparse: true},\n\t\t{Unique: false, Sparse: false},\n\t\t{Unique: false, Sparse: true},\n\t}\n\n\tfor i, options := range testOptions {\n\t\tcol := ensureCollection(nil, db, fmt.Sprintf(\"hash_index_test_%d\", i), nil, t)\n\n\t\tidx, created, err := col.EnsureHashIndex(nil, []string{\"name\"}, options)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to create new index: %s\", describe(err))\n\t\t}\n\t\tif !created {\n\t\t\tt.Error(\"Expected created to be true, got false\")\n\t\t}\n\t\tif idxType := idx.Type(); idxType != driver.HashIndex {\n\t\t\tt.Errorf(\"Expected HashIndex, found `%s`\", idxType)\n\t\t}\n\t\tif options != nil && idx.Unique() != options.Unique {\n\t\t\tt.Errorf(\"Expected Unique to be %t, found `%t`\", options.Unique, idx.Unique())\n\t\t}\n\t\tif options != nil && idx.Sparse() != options.Sparse {\n\t\t\tt.Errorf(\"Expected Sparse to be %t, found `%t`\", options.Sparse, idx.Sparse())\n\t\t}\n\n\t\t// Index must exists now\n\t\tif found, err := col.IndexExists(nil, idx.Name()); err != nil {\n\t\t\tt.Fatalf(\"Failed to check index '%s' exists: %s\", idx.Name(), describe(err))\n\t\t} else if !found {\n\t\t\tt.Errorf(\"Index '%s' does not exist, expected it to exist\", idx.Name())\n\t\t}\n\n\t\t// Ensure again, created must be false now\n\t\t_, created, err = col.EnsureHashIndex(nil, []string{\"name\"}, options)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to re-create index: %s\", describe(err))\n\t\t}\n\t\tif created {\n\t\t\tt.Error(\"Expected created to be false, got true\")\n\t\t}\n\n\t\t// Remove index\n\t\tif err := idx.Remove(nil); err != nil {\n\t\t\tt.Fatalf(\"Failed to remove index '%s': %s\", idx.Name(), describe(err))\n\t\t}\n\n\t\t// Index must not exists now\n\t\tif found, err := col.IndexExists(nil, idx.Name()); err != nil {\n\t\t\tt.Fatalf(\"Failed to check index '%s' exists: %s\", idx.Name(), describe(err))\n\t\t} else if found {\n\t\t\tt.Errorf(\"Index '%s' does exist, expected it not to exist\", idx.Name())\n\t\t}\n\t}\n}", "func (h *HTTPApi) listIndex(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tcollections := h.storageNode.Datasources[ps.ByName(\"datasource\")].GetMeta().Databases[ps.ByName(\"dbname\")].ShardInstances[ps.ByName(\"shardinstance\")].Collections[ps.ByName(\"collectionname\")]\n\n\t// Now we need to return the results\n\tif bytes, err := json.Marshal(collections.Indexes); err != nil {\n\t\t// TODO: log this better?\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t} else {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(bytes)\n\t}\n}", "func (db *MongoDB) Init() error {\n\tsess := db.sess.Copy()\n\tdefer sess.Close()\n\ttasks := db.tasks(sess)\n\tnodes := db.nodes(sess)\n\n\tnames, err := sess.DB(db.conf.Database).CollectionNames()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error listing collection names in database %s: %v\", db.conf.Database, err)\n\t}\n\tvar tasksFound bool\n\tvar nodesFound bool\n\tfor _, n := range names {\n\t\tswitch n {\n\t\tcase \"tasks\":\n\t\t\ttasksFound = true\n\t\tcase \"nodes\":\n\t\t\tnodesFound = true\n\t\t}\n\t}\n\n\tif !tasksFound {\n\t\terr = tasks.Create(&mgo.CollectionInfo{})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error creating tasks collection in database %s: %v\", db.conf.Database, err)\n\t\t}\n\n\t\terr = tasks.EnsureIndex(mgo.Index{\n\t\t\tKey: []string{\"-id\", \"-creationtime\"},\n\t\t\tUnique: true,\n\t\t\tDropDups: true,\n\t\t\tBackground: true,\n\t\t\tSparse: true,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !nodesFound {\n\t\terr = nodes.Create(&mgo.CollectionInfo{})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error creating nodes collection in database %s: %v\", db.conf.Database, err)\n\t\t}\n\n\t\terr = nodes.EnsureIndex(mgo.Index{\n\t\t\tKey: []string{\"id\"},\n\t\t\tUnique: true,\n\t\t\tDropDups: true,\n\t\t\tBackground: true,\n\t\t\tSparse: true,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func Index(s *mgo.Session) {\n\tsession := s.Copy()\n\tdefer session.Close()\n\n\tcontext := session.DB(\"store\").C(\"locations\")\n\n\tindex := mgo.Index{\n\t\tKey: []string{\"id\"}, //Index key fields; prefix name with dash (-) for descending order\n\t\tUnique: true, //Prevent two documents from having the same index key\n\t\tDropDups: true, //Drop documents with the same index key as a previously indexed one\n\t\tBackground: true, //Build index in background and return immediately\n\t\tSparse: true, //Only index documents containing the Key fields\n\t}\n\n\terr := context.EnsureIndex(index)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func (m *Mongodb) Execute() {\n\tm.createExpireIndex()\n\tm.backupData()\n}", "func CompressIndex(ctx context.Context, dbo Database) error {\n\tdb := dbo.(*database)\n\tsql := db.getRawDB()\n\n\tconn, err := sql.Conn(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\ttx, err := conn.BeginTx(ctx, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif tx != nil {\n\t\t\ttx.Rollback()\n\t\t}\n\t}()\n\n\t_, err = tx.ExecContext(ctx, `update docs set txt=compress(txt) where not iscompressed(txt)`)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttx = nil\n\treturn nil\n}", "func DBIndexer(db *sql.DB, dbPipe <-chan RollupState) {\n\n\tdbInsertMap := make(map[string]*bulkinsert.BulkInsert)\n\tfor data := range dbPipe {\n\t\ttableName := fmt.Sprintf(\"monitor_metrics_%s_%s\", data.granularity.windowName, data.msg.PluginName)\n\t\tcolumnNames, err := plugins.GetColumnsForTable(tableName, db)\n\t\tif len(columnNames) == 0 || err != nil {\n\t\t\tlog.Error().Err(err).Msgf(\"Table %s does not exist \", tableName)\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, ok := dbInsertMap[tableName]; !ok { //New DB Bulk inserter\n\t\t\tdbInsertMap[tableName] = bulkinsert.NewBulkInsert(\n\t\t\t\tdb,\n\t\t\t\ttableName,\n\t\t\t\tdbConfigMap[data.granularity.windowName].maxBatchSize,\n\t\t\t\tdbConfigMap[data.granularity.windowName].maxBatchAge,\n\t\t\t\tcolumnNames)\n\t\t}\n\t\tmetricNames := []string{\n\t\t\t\"ConnectTimeAvg\",\n\t\t\t\"Es\",\n\t\t\t\"EsResponse\",\n\t\t\t\"EsTimeout\",\n\t\t\t\"FirstByteTimeAvg\",\n\t\t\t\"ResponseTimeAvg\",\n\t\t\t\"ResponseTimeMax\",\n\t\t\t\"ResponseTimeMin\",\n\t\t\t\"SizeAvg\",\n\t\t\t\"SpeedAvg\",\n\t\t}\n\t\tcolumnValues := metricsToString(metricNames,data.msg)\n\t\tif err := dbInsertMap[tableName].Insert(columnValues); err != nil {\n\t\t\tlog.Error().Err(err).Msgf(\"Error Inserting column values to table %s \", tableName)\n\t\t}\n\t}\n}", "func CreateIndex(context *web.AppContext) *web.AppError {\n\n\tdb := context.MDB\n\tvar input model.Index\n\tjson.NewDecoder(context.Body).Decode(&input)\n\n\terr := db.Session.DB(\"\").C(input.Target).EnsureIndex(input.Index)\n\tif err != nil {\n\t\tmessage := fmt.Sprintf(\"Error creating index [%+v]\", input)\n\t\treturn &web.AppError{err, message, http.StatusInternalServerError}\n\t}\n\n\treturn nil\n}", "func (o MongoDBCollectionResourceOutput) Indexes() MongoIndexArrayOutput {\n\treturn o.ApplyT(func(v MongoDBCollectionResource) []MongoIndex { return v.Indexes }).(MongoIndexArrayOutput)\n}", "func (i ImageIndexer) AddToIndex(request AddToIndexRequest) error {\n\tbuildDir, outDockerfile, cleanup, err := buildContext(request.Generate, request.OutDockerfile)\n\tdefer cleanup()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdatabasePath, err := i.ExtractDatabase(buildDir, request.FromIndex, request.CaFile, request.SkipTLSVerify, request.PlainHTTP)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Run opm registry add on the database\n\taddToRegistryReq := registry.AddToRegistryRequest{\n\t\tBundles: request.Bundles,\n\t\tInputDatabase: databasePath,\n\t\tPermissive: request.Permissive,\n\t\tMode: request.Mode,\n\t\tSkipTLSVerify: request.SkipTLSVerify,\n\t\tPlainHTTP: request.PlainHTTP,\n\t\tContainerTool: i.PullTool,\n\t\tOverwrite: request.Overwrite,\n\t\tEnableAlpha: request.EnableAlpha,\n\t}\n\n\t// Add the bundles to the registry\n\terr = i.RegistryAdder.AddToRegistry(addToRegistryReq)\n\tif err != nil {\n\t\ti.Logger.WithError(err).Debugf(\"unable to add bundle to registry\")\n\t\treturn err\n\t}\n\n\t// generate the dockerfile\n\tdockerfile := i.DockerfileGenerator.GenerateIndexDockerfile(request.BinarySourceImage, databasePath)\n\terr = write(dockerfile, outDockerfile, i.Logger)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif request.Generate {\n\t\treturn nil\n\t}\n\n\t// build the dockerfile\n\terr = build(outDockerfile, request.Tag, i.CommandRunner, i.Logger)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func m4accountIndices(db *IndexerDb, state *MigrationState) error {\n\tsqlLines := []string{\n\t\t\"CREATE INDEX IF NOT EXISTS account_asset_by_addr ON account_asset ( addr )\",\n\t\t\"CREATE INDEX IF NOT EXISTS asset_by_creator_addr ON asset ( creator_addr )\",\n\t\t\"CREATE INDEX IF NOT EXISTS app_by_creator ON app ( creator )\",\n\t\t\"CREATE INDEX IF NOT EXISTS account_app_by_addr ON account_app ( addr )\",\n\t}\n\treturn sqlMigration(db, state, sqlLines)\n}", "func DB_IndexAccount(db gorm.DB) {\n\n\tcols := []string{\n\t\t\"acc_active\", \"company\", \"ticker\", \"acc_ref\",\n\t\t\"on_hold\"\t, \"is_client\", \"is_supplier\", \"online\"}\n\n\tfor _, c := range cols {\n\t\tdb.Model(&Account{}).AddIndex(\"idx_\" + c, c)\n\t}\n}", "func TestEnsureFullTextIndex(t *testing.T) {\n\tc := createClient(t, nil)\n\tdb := ensureDatabase(nil, c, \"index_test\", nil, t)\n\n\ttestOptions := []*driver.EnsureFullTextIndexOptions{\n\t\tnil,\n\t\t{MinLength: 2},\n\t\t{MinLength: 20},\n\t}\n\n\tfor i, options := range testOptions {\n\t\tcol := ensureCollection(nil, db, fmt.Sprintf(\"fulltext_index_test_%d\", i), nil, t)\n\n\t\tidx, created, err := col.EnsureFullTextIndex(nil, []string{\"name\"}, options)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to create new index: %s\", describe(err))\n\t\t}\n\t\tif !created {\n\t\t\tt.Error(\"Expected created to be true, got false\")\n\t\t}\n\t\tif idxType := idx.Type(); idxType != driver.FullTextIndex {\n\t\t\tt.Errorf(\"Expected FullTextIndex, found `%s`\", idxType)\n\t\t}\n\t\tif options != nil && idx.MinLength() != options.MinLength {\n\t\t\tt.Errorf(\"Expected %d, found `%d`\", options.MinLength, idx.MinLength())\n\t\t}\n\n\t\t// Index must exists now\n\t\tif found, err := col.IndexExists(nil, idx.Name()); err != nil {\n\t\t\tt.Fatalf(\"Failed to check index '%s' exists: %s\", idx.Name(), describe(err))\n\t\t} else if !found {\n\t\t\tt.Errorf(\"Index '%s' does not exist, expected it to exist\", idx.Name())\n\t\t}\n\n\t\t// Ensure again, created must be false now\n\t\t_, created, err = col.EnsureFullTextIndex(nil, []string{\"name\"}, options)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to re-create index: %s\", describe(err))\n\t\t}\n\t\tif created {\n\t\t\tt.Error(\"Expected created to be false, got true\")\n\t\t}\n\n\t\t// Remove index\n\t\tif err := idx.Remove(nil); err != nil {\n\t\t\tt.Fatalf(\"Failed to remove index '%s': %s\", idx.Name(), describe(err))\n\t\t}\n\n\t\t// Index must not exists now\n\t\tif found, err := col.IndexExists(nil, idx.Name()); err != nil {\n\t\t\tt.Fatalf(\"Failed to check index '%s' exists: %s\", idx.Name(), describe(err))\n\t\t} else if found {\n\t\t\tt.Errorf(\"Index '%s' does exist, expected it not to exist\", idx.Name())\n\t\t}\n\t}\n}", "func (c *Client) Index(d Document, extraArgs url.Values) (*Response, error) {\n\tr := Request{\n\t\tQuery: d.Fields,\n\t\tIndexList: []string{d.Index.(string)},\n\t\tTypeList: []string{d.Type},\n\t\tExtraArgs: extraArgs,\n\t\tMethod: \"POST\",\n\t}\n\n\tif d.ID != nil {\n\t\tr.Method = \"PUT\"\n\t\tr.ID = d.ID.(string)\n\t}\n\n\treturn c.Do(&r)\n}", "func create_index_files(ps []Post, indexname string) {\n\tvar prev, next int\n\tindex_page_flag := false\n\tindex := 1\n\tnum := 0\n\tlength := len(ps)\n\tsort.Sort(ByODate(ps))\n\tsort_index := make([]Post, 0)\n\tfor i := range ps {\n\t\tif ps[i].Changed {\n\t\t\tindex_page_flag = true\n\t\t}\n\t\tsort_index = append(sort_index, ps[i])\n\t\tnum = num + 1\n\t\tif num == POSTN {\n\t\t\tif !check_index(indexname, index) {\n\t\t\t\tindex_page_flag = true\n\t\t\t}\n\n\t\t\t/* Only changed indexes should get rebuild*/\n\t\t\tif index_page_flag == true {\n\t\t\t\tindex_page_flag = false\n\t\t\t\tsort.Sort(ByDate(sort_index))\n\t\t\t\tif index == 1 {\n\t\t\t\t\tprev = 0\n\t\t\t\t} else {\n\t\t\t\t\tprev = index - 1\n\t\t\t\t}\n\t\t\t\tif (index*POSTN) < length && (length-index*POSTN) > POSTN {\n\t\t\t\t\tnext = index + 1\n\t\t\t\t} else if (index * POSTN) == length {\n\t\t\t\t\tnext = -1\n\t\t\t\t} else {\n\t\t\t\t\tnext = 0\n\t\t\t\t}\n\n\t\t\t\tbuild_index(sort_index, index, prev, next, indexname)\n\t\t\t}\n\n\t\t\tsort_index = make([]Post, 0)\n\t\t\tindex = index + 1\n\t\t\tnum = 0\n\n\t\t}\n\t}\n\tif len(sort_index) > 0 {\n\t\tsort.Sort(ByDate(sort_index))\n\t\tbuild_index(sort_index, 0, index-1, -1, indexname)\n\n\t}\n}", "func (oplog *OpLog) init(maxBytes int) {\n\toplogExists := false\n\tobjectsExists := false\n\tnames, _ := oplog.s.DB(\"\").CollectionNames()\n\tfor _, name := range names {\n\t\tswitch name {\n\t\tcase \"oplog_ops\":\n\t\t\toplogExists = true\n\t\tcase \"oplog_states\":\n\t\t\tobjectsExists = true\n\t\t}\n\t}\n\tif !oplogExists {\n\t\tlog.Info(\"OPLOG creating capped collection\")\n\t\terr := oplog.s.DB(\"\").C(\"oplog_ops\").Create(&mgo.CollectionInfo{\n\t\t\tCapped: true,\n\t\t\tMaxBytes: maxBytes,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\tif !objectsExists {\n\t\tlog.Info(\"OPLOG creating objects index\")\n\t\tc := oplog.s.DB(\"\").C(\"oplog_states\")\n\t\t// Replication query\n\t\tif err := c.EnsureIndexKey(\"event\", \"ts\"); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t// Replication query with a filter on types\n\t\tif err := c.EnsureIndexKey(\"event\", \"data.t\", \"ts\"); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t// Fallback query\n\t\tif err := c.EnsureIndexKey(\"ts\"); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t// Fallback query with a filter on types\n\t\tif err := c.EnsureIndexKey(\"data.t\", \"ts\"); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n}", "func BackupIndexes(metadataFile *utils.FileWithByteCount) {\n\tgplog.Verbose(\"Writing CREATE INDEX statements to metadata file\")\n\tindexes := GetIndexes(connectionPool)\n\tobjectCounts[\"Indexes\"] = len(indexes)\n\tindexMetadata := GetCommentsForObjectType(connectionPool, TYPE_INDEX)\n\tPrintCreateIndexStatements(metadataFile, globalTOC, indexes, indexMetadata)\n}", "func CreateIndexIfNotExists(e *elastic.Client, index string) error {\n\t// Use the IndexExists service to check if a specified index exists.\n\texists, err := e.IndexExists(index).Do(context.Background())\n\tif err != nil {\n\t\tlog.Printf(\"elastic: unable to check if Index exists - %s\\n\", err)\n\t\treturn err\n\t}\n\n\tif exists {\n\t\treturn nil\n\t}\n\n\t// Create a new index.\n\tv := reflect.TypeOf(Point{})\n\n\tmapping := MapStr{\n\t\t\"settings\": MapStr{\n\t\t\t\"number_of_shards\": 1,\n\t\t\t\"number_of_replicas\": 1,\n\t\t},\n\t\t\"mappings\": MapStr{\n\t\t\t\"doc\": MapStr{\n\t\t\t\t\"properties\": MapStr{},\n\t\t\t},\n\t\t},\n\t}\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tfield := v.Field(i)\n\t\ttag := field.Tag.Get(\"elastic\")\n\t\tif len(tag) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\ttagfields := strings.Split(tag, \",\")\n\t\tmapping[\"mappings\"].(MapStr)[\"doc\"].(MapStr)[\"properties\"].(MapStr)[field.Name] = MapStr{}\n\t\tfor _, tagfield := range tagfields {\n\t\t\ttagfieldValues := strings.Split(tagfield, \":\")\n\t\t\tmapping[\"mappings\"].(MapStr)[\"doc\"].(MapStr)[\"properties\"].(MapStr)[field.Name].(MapStr)[tagfieldValues[0]] = tagfieldValues[1]\n\t\t}\n\t}\n\tmappingJSON, err := json.Marshal(mapping)\n\tif err != nil {\n\t\tlog.Printf(\"elastic: error on json marshal - %s\\n\", err)\n\t\treturn err\n\t}\n\n\t_, err = e.CreateIndex(index).BodyString(string(mappingJSON)).Do(context.Background())\n\tif err != nil {\n\t\tlog.Printf(\"elastic: error creating elastic index %s - %s\\n\", index, err)\n\t\treturn err\n\t}\n\tlog.Printf(\"elastic: index %s created\\n\", index)\n\treturn nil\n}", "func (o Model) RebuildIndexes(pattern string) error {\n\t// Quick exit in case no index exists\n\tif o.IndexSet == nil || len(o.IndexSet.Indexes) == 0 {\n\t\treturn nil\n\t}\n\n\tp := res.Pattern(pattern)\n\tif !p.IsValid() {\n\t\treturn errors.New(\"invalid pattern\")\n\t}\n\n\t// Drop existing index entries\n\tfor _, idx := range o.IndexSet.Indexes {\n\t\terr := o.BadgerDB.DB.DropPrefix([]byte(idx.Name))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tt := reflect.TypeOf(o.Type)\n\n\t// Create a prefix to seek from\n\tridPrefix := pattern\n\ti := p.IndexWildcard()\n\tif i >= 0 {\n\t\tridPrefix = pattern[:i]\n\t}\n\n\t// Create new index entries in a single transaction\n\treturn o.BadgerDB.DB.Update(func(txn *badger.Txn) error {\n\t\tit := txn.NewIterator(badger.DefaultIteratorOptions)\n\t\tdefer it.Close()\n\t\tprefix := []byte(ridPrefix)\n\t\tfor it.Seek(prefix); it.ValidForPrefix(prefix); it.Next() {\n\t\t\t// Ensure the key matches the pattern\n\t\t\tif !p.Matches(string(it.Item().Key())) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Load item and unmarshal it\n\t\t\titem := it.Item()\n\t\t\tv := reflect.New(t)\n\t\t\terr := item.Value(func(dta []byte) error {\n\t\t\t\treturn json.Unmarshal(dta, v.Interface())\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// Loop through indexes and generate a new entry per index\n\t\t\tfor _, idx := range o.IndexSet.Indexes {\n\t\t\t\trname := item.KeyCopy(nil)\n\t\t\t\tidxKey := idx.getKey(rname, idx.Key(v.Elem().Interface()))\n\t\t\t\terr = txn.SetEntry(&badger.Entry{Key: idxKey, Value: nil, UserMeta: typeIndex})\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\treturn nil\n\t})\n}", "func AddDefaultIndexes(ctx context.Context, mgr ctrl.Manager) error {\n\tif err := ByMachineNode(ctx, mgr); err != nil {\n\t\treturn err\n\t}\n\n\tif err := ByMachineProviderID(ctx, mgr); err != nil {\n\t\treturn err\n\t}\n\n\tif feature.Gates.Enabled(feature.ClusterTopology) {\n\t\tif err := ByClusterClassName(ctx, mgr); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif feature.Gates.Enabled(feature.MachinePool) {\n\t\tif err := ByMachinePoolNode(ctx, mgr); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := ByMachinePoolProviderID(ctx, mgr); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func UpdatePhotosIndexes(gallery models.Gallery, photos []models.Photo) error {\n\tfor _, photo := range photos {\n\t\terr := DB.C(photosCollection).Update(bson.M{\n\t\t\t\"site_id\": gallery.SiteID,\n\t\t\t\"_id\": photo.ID,\n\t\t}, bson.M{\n\t\t\t\"$set\": bson.M{\n\t\t\t\t\"index\": photo.Index,\n\t\t\t},\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (handler StormWatchHandler) Index(c *gin.Context) {\n\tstormWatchs := []m.StormWatch{}\t\n\tvar query = handler.db\n\n\tstartParam,startParamExist := c.GetQuery(\"start\")\n\tlimitParam,limitParamExist := c.GetQuery(\"limit\")\n\n\t//start param exist\n\tif startParamExist {\n\t\tstart,_ := strconv.Atoi(startParam)\n\t\tif start != 0 {\n\t\t\tquery = query.Offset(start).Order(\"created_at asc\")\t\t\n\t\t} else {\n\t\t\tquery = query.Offset(0).Order(\"created_at desc\")\n\t\t}\n\t} \n\n\t//limit param exist\n\tif limitParamExist {\n\t\tlimit,_ := strconv.Atoi(limitParam)\n\t\tquery = query.Limit(limit)\n\t} else {\n\t\tquery = query.Limit(10)\n\t}\n\n\tquery.Order(\"created_at desc\").Find(&stormWatchs)\n\tc.JSON(http.StatusOK, stormWatchs)\n\treturn\n}", "func (engine *Engine) initIndexer(options *types.EngineOpts) {\n\t// 初始化索引器\n\tengine.indexers = make([]*core.Indexer, options.NumShards)\n\tfor shard := 0; shard < options.NumShards; shard++ {\n\t\tindexer, _ := core.NewIndexer(*options.IndexerOpts)\n\t\tengine.indexers[shard] = indexer\n\t}\n\n\t// 初始所有管道\n\tengine.indexerAddDocChans = make([]chan indexerAddDocReq, options.NumShards)\n\tengine.indexerLookupChans = make([]chan indexerLookupReq, options.NumShards)\n\tfor shard := 0; shard < options.NumShards; shard++ {\n\t\tengine.indexerAddDocChans[shard] = make(chan indexerAddDocReq, options.IndexerBufLen)\n\t\tengine.indexerLookupChans[shard] = make(chan indexerLookupReq, options.IndexerBufLen)\n\t}\n}", "func (tbl DbCompoundTable) CreateIndexes(ifNotExist bool) (err error) {\n\n\terr = tbl.CreateAlphaBetaIndex(ifNotExist)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}" ]
[ "0.8049515", "0.7906946", "0.71204585", "0.71009797", "0.7069479", "0.6932295", "0.6842536", "0.6802358", "0.679094", "0.6670864", "0.6619791", "0.6590732", "0.65583503", "0.6502643", "0.64861286", "0.6485306", "0.64831126", "0.6381865", "0.63740486", "0.6362152", "0.6322755", "0.6283525", "0.62645125", "0.6252674", "0.62487954", "0.6153335", "0.6134187", "0.6091021", "0.6054684", "0.6052088", "0.6037294", "0.6029919", "0.6022047", "0.5980085", "0.59556526", "0.5949157", "0.5947896", "0.59262794", "0.59196", "0.59172755", "0.5907397", "0.5899823", "0.58811724", "0.5857784", "0.57990444", "0.5791122", "0.5787423", "0.57657844", "0.57313854", "0.56801826", "0.5654066", "0.56465226", "0.5626995", "0.5607443", "0.5590192", "0.55881894", "0.5562969", "0.55553347", "0.55323625", "0.5525016", "0.55119574", "0.54958254", "0.5488434", "0.54700917", "0.54661673", "0.5446133", "0.54446876", "0.5443767", "0.54345435", "0.54235077", "0.54217744", "0.5419904", "0.5401066", "0.53812224", "0.53651243", "0.53623617", "0.5341431", "0.53377175", "0.5335746", "0.53325784", "0.5331743", "0.533153", "0.5324507", "0.53222203", "0.53214425", "0.5319794", "0.53166366", "0.53160787", "0.5315086", "0.5300466", "0.5293192", "0.528744", "0.5278224", "0.52612734", "0.5244726", "0.5242925", "0.5237758", "0.52203137", "0.5215778", "0.521095" ]
0.7849583
2
unmarshalPrio parses the Prioencoded data and stores the result in the value pointed to by info.
func unmarshalPrio(data []byte, info *Prio) error { return unmarshalStruct(data, info) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func marshalPrio(info *Prio) ([]byte, error) {\n\tif info == nil {\n\t\treturn []byte{}, fmt.Errorf(\"Prio: %w\", ErrNoArg)\n\t}\n\treturn marshalStruct(info)\n}", "func (pi *ProtoInfo) unmarshal(ad *netlink.AttributeDecoder) error {\n\n\t// Make sure we don't unmarshal into the same ProtoInfo twice.\n\tif pi.filled() {\n\t\treturn errReusedProtoInfo\n\t}\n\n\tif ad.Len() != 1 {\n\t\treturn errors.Wrap(errNeedSingleChild, opUnProtoInfo)\n\t}\n\n\t// Step into the single nested child, return on error.\n\tif !ad.Next() {\n\t\treturn ad.Err()\n\t}\n\n\tswitch protoInfoType(ad.Type()) {\n\tcase ctaProtoInfoTCP:\n\t\tvar tpi ProtoInfoTCP\n\t\tad.Nested(tpi.unmarshal)\n\t\tpi.TCP = &tpi\n\tcase ctaProtoInfoDCCP:\n\t\tvar dpi ProtoInfoDCCP\n\t\tad.Nested(dpi.unmarshal)\n\t\tpi.DCCP = &dpi\n\tcase ctaProtoInfoSCTP:\n\t\tvar spi ProtoInfoSCTP\n\t\tad.Nested(spi.unmarshal)\n\t\tpi.SCTP = &spi\n\tdefault:\n\t\treturn fmt.Errorf(errAttributeChild, ad.Type())\n\t}\n\n\treturn ad.Err()\n}", "func unconvertData(data []byte) interface{} {\n\tif data == nil || string(data) == \"\" {\n\t\treturn nil\n\t}\n\n\tvar proto interface{}\n\tresult, err := serial.Deserialize(data, proto, serial.PERSISTENT)\n\tif err != nil {\n\t\tlog.Fatal(\"Persistent Deserialization Failed\", \"err\", err, \"data\", data)\n\t}\n\treturn result\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 Unmarshal(curve elliptic.Curve, data []byte) (*big.Int, *big.Int)", "func (pbProcessor *PBProcessor) UnmarshalWithOutRelease(clientId uint64, data []byte) (interface{}, error) {\n\tvar msgType uint16\n\tif pbProcessor.LittleEndian == true {\n\t\tmsgType = binary.LittleEndian.Uint16(data[:2])\n\t} else {\n\t\tmsgType = binary.BigEndian.Uint16(data[:2])\n\t}\n\n\tinfo, ok := pbProcessor.mapMsg[msgType]\n\tif ok == false {\n\t\treturn nil, fmt.Errorf(\"cannot find register %d msgtype!\", msgType)\n\t}\n\tmsg := reflect.New(info.msgType.Elem()).Interface()\n\tprotoMsg := msg.(proto.Message)\n\terr := proto.Unmarshal(data[2:], protoMsg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &PBPackInfo{typ: msgType, msg: protoMsg}, nil\n}", "func (this *petPiranha) UnmarshalBinary(data []byte) (err error) {\n\t// var addrs = map[uint64]uintptr{}\n\tvar pos0 int\n\terr = this.unmarshalFrom(&pos0, data /*, addrs*/)\n\treturn\n}", "func unmarshalAmino(i *big.Int, text string) (err error) {\n\treturn i.UnmarshalText([]byte(text))\n}", "func unmarshalPrecise(data []byte, v interface{}) error {\n\tdecoder := json.NewDecoder(bytes.NewBuffer(data))\n\tdecoder.UseNumber()\n\tif err := decoder.Decode(v); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (a *ArithResponse) Unmarshal(data []byte) error {\n\tvar length = uint64(len(data))\n\tvar offset uint64\n\tvar n uint64\n\tvar tag uint64\n\tvar fieldNumber int\n\tvar wireType uint8\n\tfor {\n\t\tif offset < length {\n\t\t\ttag = uint64(data[offset])\n\t\t\toffset++\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t\tfieldNumber = int(tag >> 3)\n\t\twireType = uint8(tag & 0x7)\n\t\tswitch fieldNumber {\n\t\tcase 1:\n\t\t\tif wireType != 0 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Pro\", wireType)\n\t\t\t}\n\t\t\tvar t uint64\n\t\t\tn = code.DecodeVarint(data[offset:], &t)\n\t\t\ta.Pro = int32(t)\n\t\t\toffset += n\n\t\t}\n\t}\n\treturn nil\n}", "func (un *Decoder) ProcInst(pi xml.ProcInst) error { return nil }", "func (p *Parameters) UnMarshalBinary(data []byte) error {\n\tif len(data) < 3 {\n\t\treturn errors.New(\"invalid parameters encoding\")\n\t}\n\tb := utils.NewBuffer(data)\n\tp.N = 1 << uint64(b.ReadUint8())\n\tif p.N > MaxN {\n\t\treturn errors.New(\"polynomial degree is too large\")\n\t}\n\tlenQi := uint64(b.ReadUint8())\n\tif lenQi > MaxModuliCount {\n\t\treturn fmt.Errorf(\"len(Qi) is larger than %d\", MaxModuliCount)\n\t}\n\tlenPi := uint64(b.ReadUint8())\n\tif lenPi > MaxModuliCount {\n\t\treturn fmt.Errorf(\"len(Pi) is larger than %d\", MaxModuliCount)\n\t}\n\tp.T = b.ReadUint64()\n\tp.Sigma = math.Round((float64(b.ReadUint64())/float64(1<<32))*100) / 100\n\tp.Qi = make([]uint64, lenQi, lenQi)\n\tp.Pi = make([]uint64, lenPi, lenPi)\n\tb.ReadUint64Slice(p.Qi)\n\tb.ReadUint64Slice(p.Pi)\n\treturn nil\n}", "func (*nopSerializer) Unmarshal([]byte, Message) error { return nil }", "func (lump *Generic) Unmarshall(data []byte) (err error) {\n\tlump.length = len(data)\n\tlump.data = data\n\n\treturn err\n}", "func IntUnmarshalJSON(z *big.Int, text []byte) error", "func IntUnmarshalText(z *big.Int, text []byte) error", "func Unserialize(data []byte, v interface{}) error {\n\treturn gob.NewDecoder(bytes.NewBuffer(data)).Decode(v)\n}", "func (c *core) Unmarshal(in []byte) *point {\n\tif x, y := c.Decompress(c.Curve, in); x != nil && y != nil {\n\t\treturn &point{x, y}\n\t}\n\treturn nil\n}", "func (protocol *Protocol) UnMarshal(data []byte) (int, error) {\n if(len(data) < TypeEnd) {\n //不完整的数据 待下次再读\n return 0, fmt.Errorf(\"incomplete data\"); \n }\n \n idSplit := data[:IDEnd]\n ptypeSplit := data[IDEnd:TypeEnd]\n packSplit := data[TypeEnd:]\n \n protocol.ID = ProtoID(binary.LittleEndian.Uint32(idSplit))\n protocol.PType = ProtoType(binary.LittleEndian.Uint32(ptypeSplit))\n \n protocol.Packet = NewPBPacket(protocol.ID)\n \n if nil == protocol.Packet {\n return -1, fmt.Errorf(\"Invalid packetId, need Close client??? id = %d, data = %v\", protocol.ID, data)\n }\n \n ms, _ := protocol.Packet.(proto.Message);\n err := proto.Unmarshal(packSplit, ms)\n \n if nil != err {\n return 0, fmt.Errorf(\"PBMessage Unmarshal Error!!! incomplete packet or need close client\")\n }\n \n msLen := proto.Size(ms)\n\n packetLen := msLen + TypeEnd\n return packetLen, nil\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 (this *pet) UnmarshalBinary(data []byte) (err error) {\n\t// var addrs = map[uint64]uintptr{}\n\tvar pos0 int\n\terr = this.unmarshalFrom(&pos0, data /*, addrs*/)\n\treturn\n}", "func (pg *PreGenerator) Unmarshall(f *Fountain, d []byte) *PreGenerator {\n\tif len(d) < 64 {\n\t\treturn nil\n\t}\n\tpgn := &PreGenerator{\n\t\tratchet: f.serviceDesc.ratchet.Copy(),\n\t\tstartdate: int64(binary.BigEndian.Uint64(d[:8])),\n\t\tduration: int64(binary.BigEndian.Uint64(d[8:16])),\n\t\tlastCounter: binary.BigEndian.Uint64(d[16:24]),\n\t\tpregenInterval: int64(binary.BigEndian.Uint64(d[24:32])),\n\t}\n\tcopy(pgn.lastLineHash[:], d[32:])\n\treturn pgn\n}", "func (pk *PublicKey) Unmarshal(data []byte) error {\n\tvar json = jsoniter.ConfigCompatibleWithStandardLibrary\n\terr := json.Unmarshal(data, pk)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Unmarshal(curve elliptic.Curve, data []byte) (x, y *big.Int) {\n\tbyteLen := (curve.Params().BitSize + 7) >> 3\n\tif (data[0] &^ 1) != 2 {\n\t\treturn\n\t}\n\tif len(data) != 1+byteLen {\n\t\treturn\n\t}\n\n\tx0 := new(big.Int).SetBytes(data[1 : 1+byteLen])\n\tP := curve.Params().P\n\tySq := new(big.Int)\n\tySq.Exp(x0, Three, P)\n\tySq.Add(ySq, Seven)\n\tySq.Mod(ySq, P)\n\ty0 := new(big.Int)\n\tP1 := new(big.Int).Add(P, One)\n\td := new(big.Int).Mod(P1, Four)\n\tP1.Sub(P1, d)\n\tP1.Div(P1, Four)\n\ty0.Exp(ySq, P1, P)\n\n\tif new(big.Int).Exp(y0, Two, P).Cmp(ySq) != 0 {\n\t\treturn\n\t}\n\tif y0.Bit(0) != uint(data[0]&1) {\n\t\ty0.Sub(P, y0)\n\t}\n\tx, y = x0, y0\n\treturn\n}", "func (pk *PublicKey) UnmarshalBinary(data []byte) error {\n\tif len(data) != PublicKeySize {\n\t\treturn errors.New(\"packed public key must be of eddilithium2.PublicKeySize bytes\")\n\t}\n\tvar buf [PublicKeySize]byte\n\tcopy(buf[:], data)\n\tpk.Unpack(&buf)\n\treturn nil\n}", "func (s *BaseRFC5424Listener) ExitPri(ctx *PriContext) {}", "func unmarshalerHook(opts *options) DecodeHookFunc {\n\treturn func(from, to reflect.Type, data reflect.Value) (reflect.Value, error) {\n\t\tif from == to {\n\t\t\treturn data, nil\n\t\t}\n\n\t\tif !reflect.PtrTo(to).Implements(opts.Unmarshaler.Interface) {\n\t\t\treturn data, nil\n\t\t}\n\n\t\t// The following lines are roughly equivalent to,\n\t\t// \tvalue := new(foo)\n\t\t// \terr := value.Decode(...)\n\t\t// \treturn *value, err\n\t\tvalue := reflect.New(to)\n\t\terr := opts.Unmarshaler.Unmarshal(value, decodeFrom(opts, data.Interface()))\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"could not decode %v from %v: %v\", to, from, err)\n\t\t}\n\t\treturn value.Elem(), err\n\t}\n}", "func uno(numero int) int {\n\treturn numero * 2\n}", "func (this *petHamster) UnmarshalBinary(data []byte) (err error) {\n\t// var addrs = map[uint64]uintptr{}\n\tvar pos0 int\n\terr = this.unmarshalFrom(&pos0, data /*, addrs*/)\n\treturn\n}", "func unpack(value nlgo.Binary, out interface{}) error {\n\treturn binary.Read(bytes.NewReader(([]byte)(value)), binary.BigEndian, out)\n}", "func Unserialize(val string, v interface{}) error {\n\tby, err := base64.StdEncoding.DecodeString(val)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tb := new(bytes.Buffer)\n\tb.Write(by)\n\terr = gob.NewDecoder(b).Decode(v)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func UnmarshalResultInfo(m map[string]json.RawMessage, result interface{}) (err error) {\n\tobj := new(ResultInfo)\n\terr = core.UnmarshalPrimitive(m, \"page\", &obj.Page)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"per_page\", &obj.PerPage)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"count\", &obj.Count)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"total_count\", &obj.TotalCount)\n\tif err != nil {\n\t\treturn\n\t}\n\treflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj))\n\treturn\n}", "func (c *MemcachedManager) unmarshal(data []byte, v interface{}) error {\n\treturn gob.NewDecoder(bytes.NewBuffer(data)).Decode(v)\n}", "func unmarshalMappingsP2P(a []byte) (MappingsP2P, error) {\n\tvar mappingsP2p MappingsP2P\n\n\tdecoder := gob.NewDecoder(bytes.NewReader(a))\n\terr := decoder.Decode(&mappingsP2p)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\n\treturn mappingsP2p, err\n}", "func (res *SearchRes) Unpack(data []byte) (n uint, err error) {\n\treturn util.UnpackSome(data, &res.Control, &res.DescriptionB.DeviceHardware, &res.DescriptionB.SupportedServices)\n}", "func (dpi *ProtoInfoDCCP) unmarshal(ad *netlink.AttributeDecoder) error {\n\n\tif ad.Len() == 0 {\n\t\treturn errors.Wrap(errNeedChildren, opUnProtoInfoDCCP)\n\t}\n\n\tfor ad.Next() {\n\t\tswitch protoInfoDCCPType(ad.Type()) {\n\t\tcase ctaProtoInfoDCCPState:\n\t\t\tdpi.State = ad.Uint8()\n\t\tcase ctaProtoInfoDCCPRole:\n\t\t\tdpi.Role = ad.Uint8()\n\t\tcase ctaProtoInfoDCCPHandshakeSeq:\n\t\t\tdpi.HandshakeSeq = ad.Uint64()\n\t\tdefault:\n\t\t\treturn fmt.Errorf(errAttributeChild, ad.Type())\n\t\t}\n\t}\n\n\treturn ad.Err()\n}", "func (mtr *Msmsintprp2Metrics) Unmarshal() error {\n\tvar offset int\n\n\tgometrics.DecodeScalarKey(&mtr.key, mtr.metrics.GetKey())\n\n\tmtr.Read = mtr.metrics.GetCounter(offset)\n\toffset += mtr.Read.Size()\n\n\tmtr.Security = mtr.metrics.GetCounter(offset)\n\toffset += mtr.Security.Size()\n\n\tmtr.Decode = mtr.metrics.GetCounter(offset)\n\toffset += mtr.Decode.Size()\n\n\treturn nil\n}", "func (this *person) UnmarshalBinary(data []byte) (err error) {\n\t// var addrs = map[uint64]uintptr{}\n\tvar pos0 int\n\terr = this.unmarshalFrom(&pos0, data /*, addrs*/)\n\treturn\n}", "func unmarshal(data []byte, v interface{}) (int, error) {\n\tif data == nil || v == nil {\n\t\treturn 0, ErrCannotBeNil\n\t}\n\tptrRef := reflect.ValueOf(v)\n\tif ptrRef.Kind() != reflect.Ptr {\n\t\treturn 0, ErrNotAStructPtr\n\t}\n\tref := ptrRef.Elem()\n\tif ref.Kind() != reflect.Struct {\n\t\treturn 0, ErrNotAStructPtr\n\t}\n\treturn doUnmarshal(data, ref)\n}", "func (i *Int) UnmarshalAmino(text string) error {\n\tif i.i == nil { // Necessary since default Int initialization has i.i as nil\n\t\ti.i = new(big.Int)\n\t}\n\treturn unmarshalAmino(i.i, text)\n}", "func (m *MsgProofs) Unmarshal(b []byte) error {\n\treturn m.UnmarshalSSZ(b)\n}", "func (p *publicKey) UnmarshalBinary(data []byte) error {\n\treturn p.PublicKey.DecodeBytes(data)\n}", "func (a *ArithResponse) MarshalTo(buf []byte) (int, error) {\n\tvar size = uint64(a.Size())\n\tif uint64(cap(buf)) >= size {\n\t\tbuf = buf[:size]\n\t} else {\n\t\treturn 0, fmt.Errorf(\"proto: buf is too short\")\n\t}\n\tvar offset uint64\n\tvar n uint64\n\tif a.Pro != 0 {\n\t\tbuf[offset] = 1<<3 | 0\n\t\toffset++\n\t\tn = code.EncodeVarint(buf[offset:], uint64(a.Pro))\n\t\toffset += n\n\t}\n\treturn int(offset), nil\n}", "func (z *Int) UnmarshalText(text []byte) error {}", "func Unmarshal(data []byte, o interface{}) error {\n\tbuf := bytes.NewBuffer(data)\n\tdecoder := gob.NewDecoder(buf)\n\n\terr := decoder.Decode(o)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Unmarshal(curve elliptic.Curve, data []byte) (x, y *big.Int) {\n\tbyteLen := (curve.Params().BitSize + 7) >> 3\n\tif (data[0] &^ 1) != 2 {\n\t\treturn // unrecognized point encoding\n\t}\n\tif len(data) != 1+byteLen {\n\t\treturn\n\t}\n\n\t// Based on Routine 2.2.4 in NIST Mathematical routines paper\n\tparams := curve.Params()\n\ttx := new(big.Int).SetBytes(data[1 : 1+byteLen])\n\ty2 := y2(params, tx)\n\tsqrt := defaultSqrt\n\tty := sqrt(y2, params.P)\n\tif ty == nil {\n\t\treturn // \"y^2\" is not a square: invalid point\n\t}\n\tvar y2c big.Int\n\ty2c.Mul(ty, ty).Mod(&y2c, params.P)\n\tif y2c.Cmp(y2) != 0 {\n\t\treturn // sqrt(y2)^2 != y2: invalid point\n\t}\n\tif ty.Bit(0) != uint(data[0]&1) {\n\t\tty.Sub(params.P, ty)\n\t}\n\n\tx, y = tx, ty // valid point: return it\n\treturn\n}", "func Unmarshal(data string, out interface{}) error {\n\tdata = strings.Trim(data, \"\\n\")\n\n\tl := Lexer{s: newScanner(data)}\n\tif yyParse(&l) != 0 {\n\t\treturn fmt.Errorf(\"Parse error\")\n\t}\n\n\tv := reflect.ValueOf(out)\n\tif v.Kind() == reflect.Ptr && !v.IsNil() {\n\t\tv = v.Elem()\n\t}\n\n\tunmarshal(l.result, v)\n\n\treturn nil\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 (v Palette) UnmarshalBinary(data []byte) error {\n\tif len(v)*3 != len(data) {\n\t\treturn fmt.Errorf(\"Len is not valid. required: %d, actual: %d\", len(v)*3, len(data))\n\t}\n\tfor i := 0; i < len(v); i++ {\n\t\tv[i].r = data[i*3]\n\t\tv[i].g = data[i*3+1]\n\t\tv[i].b = data[i*3+2]\n\t}\n\treturn nil\n}", "func (p *Parser) Unmarshal(data []byte, v any) error {\n\tty, err := extractMsgType(data)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"extract proto message type: %w\", err)\n\t}\n\tdesc, err := globalTypes.FindMessageByName(protoreflect.FullName(ty))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"look up message type %q: %w\", ty, err)\n\t}\n\tmsg, ok := desc.Zero().(protoreflect.ProtoMessage)\n\tif !ok {\n\t\treturn fmt.Errorf(\"could not assert ProtoMessage for %q\", ty)\n\t}\n\tif err := prototext.Unmarshal(data, msg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshal textproto: %w\", err)\n\t}\n\n\tby, err := marshaller.Marshal(msg)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"marshal JSON: %w\", err)\n\t}\n\tif err := json.Unmarshal(by, v); err != nil {\n\t\treturn fmt.Errorf(\"unmarshal JSON: %w\", err)\n\t}\n\n\treturn nil\n}", "func (hinfo *RDataHINFO) unpack(packet []byte) error {\n\tvar (\n\t\tx = 0\n\t\tsize = int(packet[x])\n\t)\n\tx++\n\thinfo.CPU = libbytes.Copy(packet[x : x+size])\n\tx = x + size\n\tsize = int(packet[x])\n\tx++\n\thinfo.OS = libbytes.Copy(packet[x : x+size])\n\treturn nil\n}", "func (p *PooledUnmarshaller) Unmarshal(b []byte, obj interface{}) error {\n\tu := p.pool.Get().(*Unmarshaller)\n\terr := u.Unmarshal(b, obj)\n\tp.pool.Put(u)\n\treturn err\n}", "func (c *core) DecodeProof(pi []byte) (gamma *point, C, S *big.Int, err error) {\n\tvar (\n\t\tptlen = (c.Curve.Params().BitSize+7)/8 + 1\n\t\tclen = c.N()\n\t\tslen = (c.Q().BitLen() + 7) / 8\n\t)\n\tif len(pi) != ptlen+clen+slen {\n\t\terr = errors.New(\"invalid proof length\")\n\t\treturn\n\t}\n\n\tif gamma = c.Unmarshal(pi[:ptlen]); gamma == nil {\n\t\terr = errors.New(\"invalid point\")\n\t\treturn\n\t}\n\n\tC = new(big.Int).SetBytes(pi[ptlen : ptlen+clen])\n\tS = new(big.Int).SetBytes(pi[ptlen+clen:])\n\treturn\n}", "func (p *Probe) Unpack(v starlark.Value) error {\n\tif v == nil || v == starlark.None {\n\t\treturn nil\n\t}\n\n\tif probe, ok := v.(Probe); ok {\n\t\t*p = probe\n\t} else {\n\t\treturn fmt.Errorf(\"got %T, want %s\", v, p.Type())\n\t}\n\n\treturn nil\n}", "func (*Parser) Unmarshal(p []byte, v interface{}) error {\n\tbomFileFormat := cyclonedx.BOMFileFormatJSON\n\tif !json.Valid(p) {\n\t\tbomFileFormat = cyclonedx.BOMFileFormatXML\n\t}\n\tbom := new(cyclonedx.BOM)\n\tdecoder := cyclonedx.NewBOMDecoder(bytes.NewBuffer(p), bomFileFormat)\n\tif err := decoder.Decode(bom); err != nil {\n\t\tpanic(err)\n\t}\n\n\ttemp := p\n\n\tif bomFileFormat == cyclonedx.BOMFileFormatXML {\n\t\tvar data cyclonedx.BOM\n\t\tif err := xml.Unmarshal(p, &data); err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling XML error: %v\", err)\n\t\t}\n\t\tif d, err := json.Marshal(data); err == nil {\n\t\t\ttemp = d\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"marshalling JSON error: %v\", err)\n\t\t}\n\t}\n\n\terr := json.Unmarshal(temp, v)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling JSON error: %v\", err)\n\t}\n\n\treturn nil\n}", "func unmarshalVLan(data []byte, info *VLan) error {\n\tad, err := netlink.NewAttributeDecoder(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar multiError error\n\tfor ad.Next() {\n\t\tswitch ad.Type() {\n\t\tcase tcaVLanParms:\n\t\t\tparms := &VLanParms{}\n\t\t\terr = unmarshalStruct(ad.Bytes(), parms)\n\t\t\tmultiError = concatError(multiError, err)\n\t\t\tinfo.Parms = parms\n\t\tcase tcaVLanTm:\n\t\t\ttcft := &Tcft{}\n\t\t\terr = unmarshalStruct(ad.Bytes(), tcft)\n\t\t\tmultiError = concatError(multiError, err)\n\t\t\tinfo.Tm = tcft\n\t\tcase tcaVLanPushVLanID:\n\t\t\ttmp := ad.Uint16()\n\t\t\tinfo.PushID = &tmp\n\t\tcase tcaVLanPushVLanProtocol:\n\t\t\ttmp := ad.Uint16()\n\t\t\tinfo.PushProtocol = &tmp\n\t\tcase tcaVLanPushVLanPriority:\n\t\t\ttmp := ad.Uint32()\n\t\t\tinfo.PushPriority = &tmp\n\t\tcase tcaVLanPad:\n\t\t\t// padding does not contain data, we just skip it\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"unmarshalVLan()\\t%d\\n\\t%v\", ad.Type(), ad.Bytes())\n\t\t}\n\t}\n\treturn concatError(multiError, ad.Err())\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 (mtr *Msmsintprp1Metrics) Unmarshal() error {\n\tvar offset int\n\n\tgometrics.DecodeScalarKey(&mtr.key, mtr.metrics.GetKey())\n\n\tmtr.Read = mtr.metrics.GetCounter(offset)\n\toffset += mtr.Read.Size()\n\n\tmtr.Security = mtr.metrics.GetCounter(offset)\n\toffset += mtr.Security.Size()\n\n\tmtr.Decode = mtr.metrics.GetCounter(offset)\n\toffset += mtr.Decode.Size()\n\n\treturn nil\n}", "func (obj *ServerMemoryInfoImpl) UnmarshalBinary(data []byte) error {\n\t// A simple encoding: plain text.\n\tb := bytes.NewBuffer(data)\n\t_, err := fmt.Fscanln(b, &obj.processMemory, &obj.sharedMemory)\n\tif err != nil {\n\t\tlogger.Error(fmt.Sprintf(\"ERROR: Returning ServerMemoryInfoImpl:UnmarshalBinary w/ Error: '%+v'\", err.Error()))\n\t\treturn err\n\t}\n\treturn nil\n}", "func Deserialize(data []byte, value interface{}) error {\n\treturn rlp.DecodeBytes(data, value)\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 (tpi *ProtoInfoTCP) unmarshal(ad *netlink.AttributeDecoder) error {\n\n\t// A ProtoInfoTCP has at least 3 members, TCP_STATE and TCP_FLAGS_ORIG/REPLY.\n\tif ad.Len() < 3 {\n\t\treturn errors.Wrap(errNeedChildren, opUnProtoInfoTCP)\n\t}\n\n\tfor ad.Next() {\n\t\tswitch protoInfoTCPType(ad.Type()) {\n\t\tcase ctaProtoInfoTCPState:\n\t\t\ttpi.State = ad.Uint8()\n\t\tcase ctaProtoInfoTCPWScaleOriginal:\n\t\t\ttpi.OriginalWindowScale = ad.Uint8()\n\t\tcase ctaProtoInfoTCPWScaleReply:\n\t\t\ttpi.ReplyWindowScale = ad.Uint8()\n\t\tcase ctaProtoInfoTCPFlagsOriginal:\n\t\t\ttpi.OriginalFlags = ad.Uint16()\n\t\tcase ctaProtoInfoTCPFlagsReply:\n\t\t\ttpi.ReplyFlags = ad.Uint16()\n\t\tdefault:\n\t\t\treturn fmt.Errorf(errAttributeChild, ad.Type())\n\t\t}\n\t}\n\n\treturn ad.Err()\n}", "func UnmarshalData(data []byte, v interface{}) (int, error) {\n\treturn unmarshal(data[postIDLength:], v)\n}", "func UnmarshalProvenance(b []byte) (Provenance, error) {\n\tvar provenance Provenance\n\tif err := json.Unmarshal(b, &provenance); err != nil {\n\t\treturn provenance, err\n\t}\n\treturn provenance, nil\n}", "func (o *Organism) UnmarshalBinary(data []byte) error {\n\t// A simple encoding: plain text.\n\tb := bytes.NewBuffer(data)\n\tvar genotype_id int\n\t_, err := fmt.Fscanln(b, &o.Fitness, &o.Generation, &o.highestFitness, &o.isPopulationChampionChild, &genotype_id)\n\to.Genotype, err = ReadGenome(b, genotype_id)\n\tif err == nil {\n\t\to.Phenotype, err = o.Genotype.Genesis(genotype_id)\n\t}\n\n\treturn err\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 (p *ProcessInfo) populate(proc *process.Process) {\n\tvar err error\n\n\tif p.Payload.Pid == 0 {\n\t\tp.Payload.Pid = proc.Pid\n\t}\n\tparentPid, err := proc.Ppid()\n\tp.saveError(\"parent_pid\", err)\n\tif err == nil {\n\t\tp.Payload.Parent = parentPid\n\t}\n\n\tmemInfo, err := proc.MemoryInfo()\n\tp.saveError(\"meminfo\", err)\n\tif err == nil && memInfo != nil {\n\t\tp.Payload.Memory = *memInfo\n\t}\n\n\tmemInfoEx, err := proc.MemoryInfoEx()\n\tp.saveError(\"meminfo_extended\", err)\n\tif err == nil && memInfoEx != nil {\n\t\tp.Payload.MemoryPlatform = *memInfoEx\n\t}\n\n\tthreads, err := proc.NumThreads()\n\tp.Payload.Threads = int(threads)\n\tp.saveError(\"num_threads\", err)\n\n\tp.Payload.NetStat, err = proc.NetIOCounters(false)\n\tp.saveError(\"netstat\", err)\n\n\tp.Payload.Command, err = proc.Cmdline()\n\tp.saveError(\"cmd args\", err)\n\n\tcpuTimes, err := proc.Times()\n\tp.saveError(\"cpu_times\", err)\n\tif err == nil && cpuTimes != nil {\n\t\tp.Payload.CPU = convertCPUTimes(*cpuTimes)\n\t}\n\n\tioStat, err := proc.IOCounters()\n\tp.saveError(\"iostat\", err)\n\tif err == nil && ioStat != nil {\n\t\tp.Payload.IoStat = *ioStat\n\t}\n\n\tp.rendered.Set(func() string {\n\t\treturn renderStatsString(p.Message, p.Payload)\n\t})\n}", "func UpuInfoToNas(upuInfo models.UpuInfo) (buf []uint8) {}", "func (this *Codec) deserialize(data string) *TreeNode {\n\tints := strings.Split(data, \",\")\n\n\treturn dHelper(&ints)\n}", "func (op *GenericOperation) parseSerializedNumberOffset(offset int) *big.Int {\n\tvar num *big.Int\n\t// Numbers always begin at this index\n\tindex := 56\n\tfor i := 0; i <= offset; i++ {\n\t\tnum, index = op.parseSerializedNumber(index)\n\t}\n\treturn num\n}", "func processPbo(redisServer redis.Conn) {\n\tendpoint, err := redis.String(redisServer.Do(\"LPOP\", REDIS_LIST))\n\tif err == nil && endpoint != \"\" {\n\t\tpostback := Pbo{}\n\t\tjson.Unmarshal([]byte(endpoint), &postback)\n\t\tv_trace.Println(\"endpoint: \" + endpoint)\n\t\tv_trace.Println(\"postback: \" + fmt.Sprint(postback))\n\t\tmappingUrlKeystoValues(&postback)\n\t\tv_trace.Println(\"postback.Url: \" + postback.Url)\n\t\tif strings.ToUpper(postback.Method) == \"GET\" {\n\t\t\tdeliverForGetType(postback)\n\t\t} else if strings.ToUpper(postback.Method) == \"POST\" {\n\t\t\tdeliverForPostType(postback)\n\t\t} else {\n\t\t\tv_error.Println(\"Unsupported Postback Method.\")\n\t\t}\n\t} else if fmt.Sprint(err) == \"redigo: nil returned\" {\n\t\t//There is no data yet to deliver.\n\t} else if err != nil {\n\t\tv_warning.Println(\"Redis Problem: \" + fmt.Sprint(err))\n\t} else {\n\t\tv_warning.Println(\"Received empty Redis Object.\")\n\t}\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 unmarshalChoke(data []byte, info *Choke) error {\n\tad, err := netlink.NewAttributeDecoder(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar multiError error\n\tfor ad.Next() {\n\t\tswitch ad.Type() {\n\t\tcase tcaChokeParms:\n\t\t\topt := &RedQOpt{}\n\t\t\terr = unmarshalStruct(ad.Bytes(), opt)\n\t\t\tmultiError = concatError(multiError, err)\n\t\t\tinfo.Parms = opt\n\t\tcase tcaChokeMaxP:\n\t\t\tinfo.MaxP = uint32Ptr(ad.Uint32())\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"unmarshalChoke()\\t%d\\n\\t%v\", ad.Type(), ad.Bytes())\n\t\t}\n\t}\n\treturn concatError(multiError, ad.Err())\n}", "func (this *petCat) UnmarshalBinary(data []byte) (err error) {\n\t// var addrs = map[uint64]uintptr{}\n\tvar pos0 int\n\terr = this.unmarshalFrom(&pos0, data /*, addrs*/)\n\treturn\n}", "func (RestartPostprocessing) Unmarshal(v []byte) (interface{}, error) {\n\te := RestartPostprocessing{}\n\terr := json.Unmarshal(v, &e)\n\treturn e, err\n}", "func (sco *SiacoinOutput) UnmarshalSia(r io.Reader) error {\n\td := encoding.NewDecoder(r)\n\tsco.Value.UnmarshalSia(d)\n\td.ReadFull(sco.UnlockHash[:])\n\treturn d.Err()\n}", "func Unmarshal(data []byte, handles []zx.Handle, s Payload) error {\n\t// First, let's make sure we have the right type in s.\n\tt := reflect.TypeOf(s)\n\tif t.Kind() != reflect.Ptr {\n\t\treturn errors.New(\"expected a pointer\")\n\t}\n\tt = t.Elem()\n\tif t.Kind() != reflect.Struct {\n\t\treturn errors.New(\"primary object must be a struct\")\n\t}\n\n\t// Get the payload's value and unmarshal it.\n\tnextObject := align(s.InlineSize(), 8)\n\td := decoder{\n\t\tbuffer: data,\n\t\thandles: handles,\n\t\tnextObject: nextObject,\n\t}\n\treturn d.unmarshalStructFields(t, reflect.ValueOf(s).Elem())\n}", "func (ResumePostprocessing) Unmarshal(v []byte) (interface{}, error) {\n\te := ResumePostprocessing{}\n\terr := json.Unmarshal(v, &e)\n\treturn e, err\n}", "func Unmarshal(data []byte, val interface{}) error {\n\ts := nvlistReader{\n\t\tnvlist: data,\n\t}\n\tif err := s.readNvHeader(); err != nil {\n\t\treturn err\n\t}\n\treturn s.readPairs(reflect.ValueOf(val))\n}", "func (this *hobby) UnmarshalBinary(data []byte) (err error) {\n\t// var addrs = map[uint64]uintptr{}\n\tvar pos0 int\n\terr = this.unmarshalFrom(&pos0, data /*, addrs*/)\n\treturn\n}", "func (sk *PrivKey) Unmarshal(bz []byte, curve elliptic.Curve, expectedSize int) error {\n\tif len(bz) != expectedSize {\n\t\treturn fmt.Errorf(\"wrong ECDSA SK bytes, expecting %d bytes\", expectedSize)\n\t}\n\n\tsk.Curve = curve\n\tsk.D = new(big.Int).SetBytes(bz)\n\tsk.X, sk.Y = curve.ScalarBaseMult(bz)\n\treturn nil\n}", "func (privKey *PrivKey) UnmarshalAmino(bz []byte) error {\n\tif len(bz) != PrivKeySize {\n\t\treturn fmt.Errorf(\"invalid privkey size\")\n\t}\n\tprivKey.Key = bz\n\n\treturn nil\n}", "func (v *PageResult) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson25363b2dDecodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi58(&r, v)\n\treturn r.Error()\n}", "func (l *Libvirt) DomainGetVcpuPinInfo(Dom Domain, Ncpumaps int32, Maplen int32, Flags uint32) (rCpumaps []byte, rNum int32, err error) {\n\tvar buf []byte\n\n\targs := DomainGetVcpuPinInfoArgs {\n\t\tDom: Dom,\n\t\tNcpumaps: Ncpumaps,\n\t\tMaplen: Maplen,\n\t\tFlags: Flags,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar r response\n\tr, err = l.requestStream(230, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Return value unmarshaling\n\ttpd := typedParamDecoder{}\n\tct := map[string]xdr.TypeDecoder{\"libvirt.TypedParam\": tpd}\n\trdr := bytes.NewReader(r.Payload)\n\tdec := xdr.NewDecoderCustomTypes(rdr, 0, ct)\n\t// Cpumaps: []byte\n\t_, err = dec.Decode(&rCpumaps)\n\tif err != nil {\n\t\treturn\n\t}\n\t// Num: int32\n\t_, err = dec.Decode(&rNum)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func unmarshal(data []byte) (installation *Installation, err error) {\n\tinstallation = &Installation{}\n\n\terr = yaml.Unmarshal(data, installation)\n\treturn\n}", "func Unmarshal(data []byte, out interface{}) (err error) {\n\tlex := &lexer{scan: scanner.Scanner{Mode: scanner.GoTokens}}\n\tlex.scan.Init(bytes.NewReader(data))\n\tlex.next() // get the first token\n\tdefer func() {\n\t\t// NOTE: this is not an example of ideal error handling.\n\t\tif x := recover(); x != nil {\n\t\t\terr = fmt.Errorf(\"error at %s: %v\", lex.scan.Position, x)\n\t\t}\n\t}()\n\tread(lex, reflect.ValueOf(out).Elem())\n\treturn nil\n}", "func Unpack(data []byte) ([]int64, error) {\n\tif len(data) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tvar ret []int64\n\tvar value int64\n\tvar base int64 = 1\n\tvar last int64\n\n\tr, err := zlib.NewReader(bytes.NewReader(data))\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to get zlib reader\").Err()\n\t}\n\tdefer r.Close()\n\n\tdata, err = ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to read all\").Err()\n\t}\n\n\tfor _, valByte := range data {\n\t\tvalue += int64(valByte&0x7f) * base\n\t\tif valByte&0x80 > 0 {\n\t\t\tbase <<= 7\n\t\t\tcontinue\n\t\t}\n\t\tret = append(ret, value+last)\n\t\tlast += value\n\t\tvalue = 0\n\t\tbase = 1\n\t}\n\n\treturn ret, nil\n}", "func (n *Node) Unmarshal(encoded []byte) error {\n\tvar pbn pb.PBNode\n\tif err := pbn.Unmarshal(encoded); err != nil {\n\t\treturn fmt.Errorf(\"Unmarshal failed. %v\", err)\n\t}\n\n\tpbnl := pbn.GetLinks()\n\tn.Links = make([]*Link, len(pbnl))\n\tfor i, l := range pbnl {\n\t\tn.Links[i] = &Link{Name: l.GetName(), Size: l.GetTsize()}\n\t\th, err := mh.Cast(l.GetHash())\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Link hash is not valid multihash. %v\", err)\n\t\t}\n\t\tn.Links[i].Hash = h\n\t}\n\tsort.Stable(LinkSlice(n.Links)) // keep links sorted\n\n\tn.Data = pbn.GetData()\n\treturn nil\n}", "func (d *decoder) unmarshal(node Node, v interface{}) error {\n\trv := reflect.ValueOf(v)\n\tif rv.Kind() != reflect.Ptr || rv.IsNil() {\n\t\tt := reflect.TypeOf(v)\n\t\tif t == nil {\n\t\t\treturn errors.New(\"metadata: Unmarshal(nil)\")\n\t\t}\n\t\tif t.Kind() != reflect.Ptr {\n\t\t\treturn errors.Errorf(\"metadata: Unmarshal(non-pointer %s)\", t)\n\t\t}\n\t\treturn errors.Errorf(\"metadata: Unmarshal(nil %s)\", t)\n\t}\n\tif err := d.value(node, rv); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\treturn nil\n}", "func (r Result) Into(v interface{}) error {\n\tif r.err != nil {\n\t\treturn r.Error()\n\t}\n\n\tif r.decoder == nil {\n\t\treturn fmt.Errorf(\"serializer doesn't exist\")\n\t}\n\n\tif err := r.decoder.Decode(r.body, &v); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func PackInfo(r IO, x *ResourcePackInfo) {\n\tr.String(&x.UUID)\n\tr.String(&x.Version)\n\tr.Uint64(&x.Size)\n\tr.String(&x.ContentKey)\n\tr.String(&x.SubPackName)\n\tr.String(&x.ContentIdentity)\n\tr.Bool(&x.HasScripts)\n}", "func (npdu *NPDU) Unmarshal(b []byte) ([]byte, error) {\n\tif len(b) < 2 {\n\t\treturn b, errBACNetPacketTooShort\n\t}\n\tnpdu.Version = b[0]\n\tnpdu.Control = b[1]\n\treturn b[2:], nil\n}", "func (d *decoder) unmarshal(t reflect.Type, v reflect.Value, n nestedTypeData) error {\n\tswitch t.Kind() {\n\tcase reflect.Ptr:\n\t\treturn d.unmarshalPointer(t, v, n)\n\tcase reflect.Slice:\n\t\treturn d.unmarshalVector(t, v, n)\n\tcase reflect.String:\n\t\treturn d.unmarshalString(t, v, n)\n\t}\n\tif isHandleType(t) {\n\t\treturn d.unmarshalHandle(v, n)\n\t}\n\tif isInterfaceType(t) || isInterfaceRequestType(t) {\n\t\t// An interface is represented by a Proxy, whose first field is\n\t\t// a zx.Channel, and we can just marshal that. Same goes for an\n\t\t// interface request, which is just an InterfaceRequest whose\n\t\t// first field is a zx.Channel.\n\t\treturn d.unmarshalHandle(v.Field(0), n)\n\t}\n\treturn d.unmarshalInline(t, v, n)\n}", "func (mtr *Msmsintprp3Metrics) Unmarshal() error {\n\tvar offset int\n\n\tgometrics.DecodeScalarKey(&mtr.key, mtr.metrics.GetKey())\n\n\tmtr.Read = mtr.metrics.GetCounter(offset)\n\toffset += mtr.Read.Size()\n\n\tmtr.Security = mtr.metrics.GetCounter(offset)\n\toffset += mtr.Security.Size()\n\n\tmtr.Decode = mtr.metrics.GetCounter(offset)\n\toffset += mtr.Decode.Size()\n\n\treturn nil\n}", "func (v *Boo) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson42239ddeDecodeMsgpJson(&r, v)\n\treturn r.Error()\n}", "func (t *Output) Unmarshal(v *Loader) error {\n\tif len(*v) == 0 {\n\t\treturn nil\n\t} else if len(*v) == 1 {\n\t\treturn msgpack.Unmarshal(t.Data, (*v)[0])\n\t}\n\t// in case is more we assume we have a longer list of objects\n\treturn msgpack.Unmarshal(t.Data, v)\n}", "func UnmarshalWithParams(b []byte, val interface{}, params string) (rest []byte, err error) {}", "func (z *Int) UnmarshalJSON(text []byte) error {}", "func (sp *StorageProof) UnmarshalSia(r io.Reader) error {\n\td := encoding.NewDecoder(r)\n\td.ReadFull(sp.ParentID[:])\n\td.ReadFull(sp.Segment[:])\n\tsp.HashSet = make([]crypto.Hash, d.NextPrefix(unsafe.Sizeof(crypto.Hash{})))\n\tfor i := range sp.HashSet {\n\t\td.ReadFull(sp.HashSet[i][:])\n\t}\n\treturn d.Err()\n}", "func (d *defaultProtoIO) Unwrap(msg interface{}) (interface{}, *OverlayMsg, error) {\n\tvar returnMsg interface{}\n\tvar returnOverlay = new(OverlayMsg)\n\tvar err error\n\n\tswitch inner := msg.(type) {\n\tcase *ProtocolMsg:\n\t\tonetMsg := inner\n\t\tvar err error\n\t\t_, protoMsg, err := network.Unmarshal(onetMsg.MsgSlice)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\t// Put the msg into ProtocolMsg\n\t\treturnOverlay.TreeNodeInfo = &TreeNodeInfo{\n\t\t\tTo: onetMsg.To,\n\t\t\tFrom: onetMsg.From,\n\t\t}\n\t\treturnMsg = protoMsg\n\tcase *RequestTree:\n\t\treturnOverlay.RequestTree = inner\n\tcase *RequestRoster:\n\t\treturnOverlay.RequestRoster = inner\n\tcase *TreeMarshal:\n\t\treturnOverlay.TreeMarshal = inner\n\tcase *Roster:\n\t\treturnOverlay.Roster = inner\n\tdefault:\n\t\terr = errors.New(\"default protoIO: unwraping an unknown message type\")\n\t}\n\treturn returnMsg, returnOverlay, err\n}" ]
[ "0.6577112", "0.5219782", "0.51016974", "0.5092685", "0.5073904", "0.5039395", "0.49995887", "0.49094743", "0.4806477", "0.4751718", "0.472503", "0.47232008", "0.4706695", "0.46945775", "0.46726182", "0.46441156", "0.45968992", "0.45847493", "0.45667946", "0.45524022", "0.45341808", "0.45327413", "0.45099157", "0.4494157", "0.4470823", "0.44562924", "0.4437618", "0.44206014", "0.44001535", "0.43877307", "0.4352231", "0.4348779", "0.43316922", "0.42945132", "0.42929202", "0.42899463", "0.42896605", "0.42830932", "0.42809844", "0.42725417", "0.42706716", "0.4265726", "0.42653283", "0.42617533", "0.42575273", "0.42503655", "0.4249863", "0.42466363", "0.42341864", "0.4221802", "0.42139158", "0.4203843", "0.41847456", "0.41811052", "0.41771844", "0.41689193", "0.41632593", "0.41615206", "0.41613778", "0.4154282", "0.41483378", "0.4148166", "0.4135863", "0.41319716", "0.41298348", "0.4124897", "0.41230944", "0.41225013", "0.41028953", "0.41028452", "0.40898886", "0.40895078", "0.40894523", "0.408892", "0.4088081", "0.40874952", "0.40805125", "0.40799767", "0.40799147", "0.4074575", "0.40700534", "0.40678817", "0.40671888", "0.40663204", "0.40620524", "0.40615708", "0.4047984", "0.40423185", "0.4037882", "0.40354183", "0.4034228", "0.40337977", "0.4028888", "0.4023284", "0.4023083", "0.40207106", "0.402025", "0.40146253", "0.40113896", "0.40060472" ]
0.8034607
0
marshalPrio returns the binary encoding of MqPrio
func marshalPrio(info *Prio) ([]byte, error) { if info == nil { return []byte{}, fmt.Errorf("Prio: %w", ErrNoArg) } return marshalStruct(info) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p *Parameters) MarshalBinary() ([]byte, error) {\n\tif p.N == 0 { // if N is 0, then p is the zero value\n\t\treturn []byte{}, nil\n\t}\n\tb := utils.NewBuffer(make([]byte, 0, 3+((2+len(p.Qi)+len(p.Pi))<<3)))\n\tb.WriteUint8(uint8(bits.Len64(p.N) - 1))\n\tb.WriteUint8(uint8(len(p.Qi)))\n\tb.WriteUint8(uint8(len(p.Pi)))\n\tb.WriteUint64(p.T)\n\tb.WriteUint64(uint64(p.Sigma * (1 << 32)))\n\tb.WriteUint64Slice(p.Qi)\n\tb.WriteUint64Slice(p.Pi)\n\treturn b.Bytes(), nil\n}", "func unmarshalPrio(data []byte, info *Prio) error {\n\treturn unmarshalStruct(data, info)\n}", "func Marshal(curve elliptic.Curve, x, y *big.Int) []byte", "func Marshal(curve elliptic.Curve, x, y *big.Int) []byte {\n\tbyteLen := (curve.Params().BitSize + 7) >> 3\n\n\tret := make([]byte, 1+byteLen)\n\tret[0] = 2 // compressed point\n\n\txBytes := x.Bytes()\n\tcopy(ret[1+byteLen-len(xBytes):], xBytes)\n\tret[0] += byte(y.Bit(0))\n\treturn ret\n}", "func (p *Proof) ProofBytes() []byte {\n\tbuff := new(bytes.Buffer)\n\n\t// The solution we serialise depends on the size of the cuckoo graph. The\n\t// cycle is always of length 42, but each vertex takes up more bits on\n\t// larger graphs, nonceLengthBits is this number of bits.\n\tnonceLengthBits := uint(p.EdgeBits)\n\n\t// Make a slice just large enough to fit all of the POW bits.\n\tbitvecLengthBits := nonceLengthBits * uint(ProofSize)\n\tbitvec := make([]uint8, (bitvecLengthBits+7)/8)\n\n\tfor n, nonce := range p.Nonces {\n\t\t// Pack this nonce into the bit stream.\n\t\tfor bit := uint(0); bit < nonceLengthBits; bit++ {\n\t\t\t// If this bit is set, then write it to the correct position in the\n\t\t\t// stream.\n\t\t\tif nonce&(1<<bit) != 0 {\n\t\t\t\toffsetBits := uint(n)*nonceLengthBits + bit\n\t\t\t\tbitvec[offsetBits/8] |= 1 << (offsetBits % 8)\n\t\t\t}\n\t\t}\n\t}\n\n\tif _, err := buff.Write(bitvec); err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\n\treturn buff.Bytes()\n}", "func (p *CRCProposalInfo) Serialize(w io.Writer, version byte) error {\n\n\tif err := common.WriteElement(w, p.ProposalType); err != nil {\n\t\treturn errors.New(\"failed to serialize ProposalType\")\n\t}\n\n\tif err := common.WriteVarString(w, p.CategoryData); err != nil {\n\t\treturn errors.New(\"failed to serialize CategoryData\")\n\t}\n\n\tif err := common.WriteVarBytes(w, p.OwnerPublicKey); err != nil {\n\t\treturn errors.New(\"failed to serialize OwnerPublicKey\")\n\t}\n\n\tif err := p.DraftHash.Serialize(w); err != nil {\n\t\treturn errors.New(\"failed to serialize DraftHash\")\n\t}\n\n\tif err := common.WriteVarUint(w, uint64(len(p.Budgets))); err != nil {\n\t\treturn errors.New(\"failed to serialize Budgets\")\n\t}\n\n\tfor _, v := range p.Budgets {\n\t\tif err := v.Serialize(w); err != nil {\n\t\t\treturn errors.New(\"failed to serialize Budgets\")\n\t\t}\n\t}\n\n\tif err := p.Recipient.Serialize(w); err != nil {\n\t\treturn errors.New(\"failed to serialize Recipient\")\n\t}\n\n\tif err := p.TargetProposalHash.Serialize(w); err != nil {\n\t\treturn errors.New(\"failed to serialize TargetProposalHash\")\n\t}\n\n\tif err := common.WriteVarUint(w, uint64(len(p.ReservedCustomIDList))); err != nil {\n\t\treturn errors.New(\"failed to serialize ReservedCustomIDList len\")\n\t}\n\n\tfor _, v := range p.ReservedCustomIDList {\n\t\tif err := common.WriteVarString(w, v); err != nil {\n\t\t\treturn errors.New(\"failed to serialize ReservedCustomIDList\")\n\t\t}\n\t}\n\n\tif err := common.WriteVarUint(w, uint64(len(p.ReceivedCustomIDList))); err != nil {\n\t\treturn errors.New(\"failed to serialize ReceivedCustomIDList len\")\n\t}\n\n\tfor _, v := range p.ReceivedCustomIDList {\n\t\tif err := common.WriteVarString(w, v); err != nil {\n\t\t\treturn errors.New(\"failed to serialize ReceivedCustomIDList\")\n\t\t}\n\t}\n\n\tif err := p.ReceiverDID.Serialize(w); err != nil {\n\t\treturn errors.New(\"failed to serialize ReceiverDID\")\n\t}\n\n\tif err := p.RateOfCustomIDFee.Serialize(w); err != nil {\n\t\treturn errors.New(\"failed to serialize RateOfCustomIDFee\")\n\t}\n\n\tif err := common.WriteUint32(w, p.EIDEffectiveHeight); err != nil {\n\t\treturn errors.New(\"failed to serialize EIDEffectiveHeight\")\n\t}\n\n\tif err := p.NewRecipient.Serialize(w); err != nil {\n\t\treturn errors.New(\"failed to serialize Recipient\")\n\t}\n\n\tif err := common.WriteVarBytes(w, p.NewOwnerPublicKey); err != nil {\n\t\treturn errors.New(\"failed to serialize NewOwnerPublicKey\")\n\t}\n\n\tif err := common.WriteVarBytes(w, p.SecretaryGeneralPublicKey); err != nil {\n\t\treturn errors.New(\"failed to serialize SecretaryGeneralPublicKey\")\n\t}\n\n\tif err := p.SecretaryGeneralDID.Serialize(w); err != nil {\n\t\treturn errors.New(\"failed to serialize SecretaryGeneralDID\")\n\t}\n\n\tif err := p.CRCouncilMemberDID.Serialize(w); err != nil {\n\t\treturn errors.New(\"failed to serialize CRCouncilMemberDID\")\n\t}\n\n\tif err := p.SideChainInfo.Serialize(w); err != nil {\n\t\treturn errors.New(\"failed to serialize SideChainInfo\")\n\t}\n\n\tif err := p.Hash.Serialize(w); err != nil {\n\t\treturn errors.New(\"failed to serialize Hash\")\n\t}\n\treturn nil\n}", "func marshalAmino(i *big.Int) (string, error) {\n\tbz, err := i.MarshalText()\n\treturn string(bz), err\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 serializeBigInt(x *big.Int) []byte {\n\txb := x.Bytes()\n\treverse(xb)\n\tfor len(xb) < EC_COORD_SIZE {\n\t\txb = append(xb, 0)\n\t}\n\treturn xb\n}", "func (o DomainOutput) SslPri() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Domain) pulumi.StringPtrOutput { return v.SslPri }).(pulumi.StringPtrOutput)\n}", "func (f *Filter) marshal() (buf *bytes.Buffer,\n\thash [sha512.Size384]byte,\n\terr error,\n) {\n\tf.lock.RLock()\n\tdefer f.lock.RUnlock()\n\n\tdebug(\"write bf k=%d n=%d m=%d\\n\", f.K(), f.n, f.m)\n\n\tbuf = new(bytes.Buffer)\n\n\terr = binary.Write(buf, binary.LittleEndian, f.K())\n\tif err != nil {\n\t\treturn nil, hash, err\n\t}\n\n\terr = binary.Write(buf, binary.LittleEndian, f.n)\n\tif err != nil {\n\t\treturn nil, hash, err\n\t}\n\n\terr = binary.Write(buf, binary.LittleEndian, f.m)\n\tif err != nil {\n\t\treturn nil, hash, err\n\t}\n\n\terr = binary.Write(buf, binary.LittleEndian, f.keys)\n\tif err != nil {\n\t\treturn nil, hash, err\n\t}\n\n\terr = binary.Write(buf, binary.LittleEndian, f.bits)\n\tif err != nil {\n\t\treturn nil, hash, err\n\t}\n\n\thash = sha512.Sum384(buf.Bytes())\n\terr = binary.Write(buf, binary.LittleEndian, hash)\n\treturn buf, hash, err\n}", "func polyToMsg(p Poly) []byte {\n\tmsg := make([]byte, 32)\n\tvar t uint16\n\tvar tmp byte\n\tp.reduce()\n\tfor i := 0; i < n/8; i++ {\n\t\ttmp = 0\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tt = (((uint16(p[8*i+j]) << 1) + uint16(q/2)) / uint16(q)) & 1\n\t\t\ttmp |= byte(t << j)\n\t\t}\n\t\tmsg[i] = tmp\n\t}\n\treturn msg\n}", "func (p *Parameters) MarshalBinary() (data []byte, err error) {\n\tdata = []byte{}\n\ttmp := []byte{}\n\n\tif tmp, err = p.SlotsToCoeffsParameters.MarshalBinary(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata = append(data, uint8(len(tmp)))\n\tdata = append(data, tmp...)\n\n\tif tmp, err = p.EvalModParameters.MarshalBinary(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata = append(data, uint8(len(tmp)))\n\tdata = append(data, tmp...)\n\n\tif tmp, err = p.CoeffsToSlotsParameters.MarshalBinary(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata = append(data, uint8(len(tmp)))\n\tdata = append(data, tmp...)\n\n\ttmp = make([]byte, 4)\n\ttmp[0] = uint8(p.H >> 24)\n\ttmp[1] = uint8(p.H >> 16)\n\ttmp[2] = uint8(p.H >> 8)\n\ttmp[3] = uint8(p.H >> 0)\n\tdata = append(data, tmp...)\n\treturn\n}", "func Marshal(val interface{}) ([]byte, error) {}", "func (c *MemcachedManager) marshal(v interface{}) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tif err := gob.NewEncoder(&buf).Encode(v); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (cred *credential) marshal() ([]byte, error) {\n\tvar b cryptobyte.Builder\n\n\tb.AddUint32(uint32(cred.validTime / time.Second))\n\tb.AddUint16(uint16(cred.expCertVerfAlgo))\n\n\t// Encode the public key\n\trawPub, err := cred.marshalPublicKeyInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Assert that the public key encoding is no longer than 2^24-1 bytes.\n\tif len(rawPub) > dcMaxPubLen {\n\t\treturn nil, errors.New(\"tls: public key length exceeds 2^24-1 limit\")\n\t}\n\n\tb.AddUint24(uint32(len(rawPub)))\n\tb.AddBytes(rawPub)\n\n\traw := b.BytesOrPanic()\n\treturn raw, nil\n}", "func (m *MsgProofs) Marshal() ([]byte, error) {\n\treturn m.MarshalSSZ()\n}", "func (p *page) marshal() string {\n\tb := &strings.Builder{}\n\tfmt.Fprintf(b, \"\\n%d 0 obj\\n<<\\n\", p.id)\n\tfmt.Fprintf(b, \" /MediaBox [ %f %f %f %f ]\\n\", p.mediaBox.llx, p.mediaBox.lly, p.mediaBox.urx, p.mediaBox.ury)\n\tfmt.Fprintf(b, \" /CropBox [ %f %f %f %f ]\\n\", p.cropBox.llx, p.cropBox.lly, p.cropBox.urx, p.cropBox.ury)\n\tfmt.Fprintf(b, \" /BleedBox [ %f %f %f %f ]\\n\", p.bleedBox.llx, p.bleedBox.lly, p.bleedBox.urx, p.bleedBox.ury)\n\tfmt.Fprintf(b, \" /TrimBox [ %f %f %f %f ]\\n\", p.trimBox.llx, p.trimBox.lly, p.trimBox.urx, p.trimBox.ury)\n\tfmt.Fprintf(b, \" /Contents [ \")\n\tfor _, cid := range p.contentIds {\n\t\tfmt.Fprintf(b, \" %d 0 R \", cid)\n\t}\n\tfmt.Fprintf(b, \" ]\\n\")\n\tfmt.Fprintf(b, \" /Parent %d 0 R\\n\", p.parentID)\n\tb.WriteString(p.raw)\n\tfmt.Fprintf(b, \"\\n>>\\nendobj\\n\")\n\treturn b.String()\n}", "func (v TxSchedulePriority) MarshalBinary() ([]byte, error) {\n\treturn marshalBinaryEnum(int32(v)), nil\n}", "func (p publicKey) MarshalBinary() (data []byte, err error) {\n\treturn p.PublicKey.Bytes(), nil\n}", "func (priv *PrivateKey) Marshal() []byte {\n\tout := make([]byte, 0, 3*32)\n\tout = appendN(out, priv.xi1)\n\tout = appendN(out, priv.xi2)\n\tout = appendN(out, priv.gamma)\n\treturn out\n}", "func (n *Uint256) toBin() []byte {\n\tif n.IsZero() {\n\t\treturn []byte(\"0\")\n\t}\n\n\t// Create space for the max possible number of output digits.\n\tmaxOutDigits := n.BitLen()\n\tresult := make([]byte, maxOutDigits)\n\n\t// Convert each internal base 2^64 word to base 2 from least to most\n\t// significant. Since the value is guaranteed to be non-zero per a previous\n\t// check, there will always be a nonzero most-significant word. Also, note\n\t// that no partial digit handling is needed in this case because the shift\n\t// amount evenly divides the bits per internal word.\n\tconst shift = 1\n\tconst mask = 1<<shift - 1\n\tconst digitsPerInternalWord = bitsPerInternalWord\n\toutputIdx := maxOutDigits - 1\n\tnumInputWords := n.numDigits()\n\tinputWord := n.n[0]\n\tfor inputIdx := 1; inputIdx < numInputWords; inputIdx++ {\n\t\tfor i := 0; i < digitsPerInternalWord; i++ {\n\t\t\tresult[outputIdx] = '0' + byte(inputWord&mask)\n\t\t\tinputWord >>= shift\n\t\t\toutputIdx--\n\t\t}\n\t\tinputWord = n.n[inputIdx]\n\t}\n\tfor inputWord != 0 {\n\t\tresult[outputIdx] = '0' + byte(inputWord&mask)\n\t\tinputWord >>= shift\n\t\toutputIdx--\n\t}\n\n\treturn result[outputIdx+1:]\n}", "func getRFC4251Mpint(n *big.Int) []byte {\n\tbuf := new(bytes.Buffer)\n\tb := n.Bytes()\n\t// RFC4251: If the most significant bit would be set for a positive number, the number MUST be preceded by a zero byte.\n\tif b[0]&0x80 > 0 {\n\t\tb = append([]byte{0}, b...)\n\t}\n\t// write a uint32 with the length of the byte stream to the buffer\n\tbinary.Write(buf, binary.BigEndian, uint32(len(b)))\n\t// write the byte stream representing of the rest of the integer to the buffer\n\tbinary.Write(buf, binary.BigEndian, b)\n\treturn buf.Bytes()\n}", "func marshalJSON(i *big.Int) ([]byte, error) {\n\ttext, err := i.MarshalText()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn json.Marshal(string(text))\n}", "func (extBtcCompatUTXO ExtBtcCompatUTXO) MarshalBinary() ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\tif err := binary.Write(buf, binary.LittleEndian, extBtcCompatUTXO.TxHash); err != nil {\n\t\treturn buf.Bytes(), fmt.Errorf(\"cannot write extBtcCompatUTXO.TxHash data: %v\", err)\n\t}\n\tvOutBytes, err := extBtcCompatUTXO.VOut.MarshalBinary()\n\tif err != nil {\n\t\treturn buf.Bytes(), fmt.Errorf(\"cannot marshal extBtcCompatUTXO.VOut: %v\", err)\n\t}\n\tif err := binary.Write(buf, binary.LittleEndian, vOutBytes); err != nil {\n\t\treturn buf.Bytes(), fmt.Errorf(\"cannot write extBtcCompatUTXO.VOut data: %v\", err)\n\t}\n\tif err := binary.Write(buf, binary.LittleEndian, uint64(len(extBtcCompatUTXO.ScriptPubKey))); err != nil {\n\t\treturn buf.Bytes(), fmt.Errorf(\"cannot write extBtcCompatUTXO.ScriptPubKey len: %v\", err)\n\t}\n\tif err := binary.Write(buf, binary.LittleEndian, extBtcCompatUTXO.ScriptPubKey); err != nil {\n\t\treturn buf.Bytes(), fmt.Errorf(\"cannot write extBtcCompatUTXO.ScriptPubKey data: %v\", err)\n\t}\n\tamountBytes, err := extBtcCompatUTXO.Amount.MarshalBinary()\n\tif err != nil {\n\t\treturn buf.Bytes(), fmt.Errorf(\"cannot marshal extBtcCompatUTXO.Amount: %v\", err)\n\t}\n\tif err := binary.Write(buf, binary.LittleEndian, amountBytes); err != nil {\n\t\treturn buf.Bytes(), fmt.Errorf(\"cannot write extBtcCompatUTXO.Amount data: %v\", err)\n\t}\n\tif err := binary.Write(buf, binary.LittleEndian, extBtcCompatUTXO.GHash); err != nil {\n\t\treturn buf.Bytes(), fmt.Errorf(\"cannot write extBtcCompatUTXO.GHash data: %v\", err)\n\t}\n\treturn buf.Bytes(), nil\n}", "func Serialize(o interface{}) ([]byte, error) {\n\tautil.TODO(\"CBOR-serialization\")\n\treturn nil, nil\n}", "func (e *GT) Marshal() []byte {\n\t// Each value is a 256-bit number.\n\tconst numBytes = 256 / 8\n\n\tif e.p == nil {\n\t\te.p = &gfP12{}\n\t}\n\n\tret := make([]byte, numBytes*12)\n\ttemp := &gfP{}\n\n\tmontDecode(temp, &e.p.x.x.x)\n\ttemp.Marshal(ret)\n\tmontDecode(temp, &e.p.x.x.y)\n\ttemp.Marshal(ret[numBytes:])\n\tmontDecode(temp, &e.p.x.y.x)\n\ttemp.Marshal(ret[2*numBytes:])\n\tmontDecode(temp, &e.p.x.y.y)\n\ttemp.Marshal(ret[3*numBytes:])\n\tmontDecode(temp, &e.p.x.z.x)\n\ttemp.Marshal(ret[4*numBytes:])\n\tmontDecode(temp, &e.p.x.z.y)\n\ttemp.Marshal(ret[5*numBytes:])\n\tmontDecode(temp, &e.p.y.x.x)\n\ttemp.Marshal(ret[6*numBytes:])\n\tmontDecode(temp, &e.p.y.x.y)\n\ttemp.Marshal(ret[7*numBytes:])\n\tmontDecode(temp, &e.p.y.y.x)\n\ttemp.Marshal(ret[8*numBytes:])\n\tmontDecode(temp, &e.p.y.y.y)\n\ttemp.Marshal(ret[9*numBytes:])\n\tmontDecode(temp, &e.p.y.z.x)\n\ttemp.Marshal(ret[10*numBytes:])\n\tmontDecode(temp, &e.p.y.z.y)\n\ttemp.Marshal(ret[11*numBytes:])\n\n\treturn ret\n}", "func IntMarshalJSON(x *big.Int,) ([]byte, error)", "func (c *core) Marshal(pt *point) []byte {\n\treturn elliptic.MarshalCompressed(c.Curve, pt.X, pt.Y)\n}", "func (a *ArithResponse) MarshalTo(buf []byte) (int, error) {\n\tvar size = uint64(a.Size())\n\tif uint64(cap(buf)) >= size {\n\t\tbuf = buf[:size]\n\t} else {\n\t\treturn 0, fmt.Errorf(\"proto: buf is too short\")\n\t}\n\tvar offset uint64\n\tvar n uint64\n\tif a.Pro != 0 {\n\t\tbuf[offset] = 1<<3 | 0\n\t\toffset++\n\t\tn = code.EncodeVarint(buf[offset:], uint64(a.Pro))\n\t\toffset += n\n\t}\n\treturn int(offset), nil\n}", "func toJSONPb(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\tvar msg *Message\n\tvar emitDefaults starlark.Bool\n\tif err := starlark.UnpackArgs(\"to_jsonpb\", args, kwargs, \"msg\", &msg, \"emit_defaults?\", &emitDefaults); err != nil {\n\t\treturn nil, err\n\t}\n\tpb, err := msg.ToProto()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// More jsonpb Marshaler options may be added here as needed.\n\tvar jsonMarshaler = &jsonpb.Marshaler{Indent: \"\\t\", EmitDefaults: bool(emitDefaults)}\n\tstr, err := jsonMarshaler.MarshalToString(pb)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn starlark.String(str), nil\n}", "func (c *CacheDB) createPrikey(structElemValue reflect.Value) (string, error) {\n\tvar (\n\t\tvalues = make([]interface{}, 0, 2)\n\t)\n\t// get pri values\n\tfor _, index := range c.priFieldsIndex {\n\t\tvalues = append(values, structElemValue.Field(index).Interface())\n\t}\n\tbs, err := json.Marshal(values)\n\tif err != nil {\n\t\treturn \"\", errors.New(\"*CacheableDB.createPrikey(): \" + err.Error())\n\t}\n\treturn c.cachePriKeyPrefix + gutil.BytesToString(bs), nil\n}", "func (h *HandShake) Serialize() []byte {\n\t// NOTE: Whenever we are sending a msg, it has to be in []byte type \n\tbuf := make([]byte, len(h.Pstr)+49)\n\tbuf[0] = byte(len(h.Pstr))\n\tcurr := 1\n\tcurr += copy(buf[curr:], h.Pstr)\n\tcurr += copy(buf[curr:], make([]byte, 8)) // 8 reserved bytes\n\tcurr += copy(buf[curr:], h.Info_hash[:])\n\tcurr += copy(buf[curr:], h.Peer_id[:])\n\treturn buf\n}", "func (p *Parameters) UnMarshalBinary(data []byte) error {\n\tif len(data) < 3 {\n\t\treturn errors.New(\"invalid parameters encoding\")\n\t}\n\tb := utils.NewBuffer(data)\n\tp.N = 1 << uint64(b.ReadUint8())\n\tif p.N > MaxN {\n\t\treturn errors.New(\"polynomial degree is too large\")\n\t}\n\tlenQi := uint64(b.ReadUint8())\n\tif lenQi > MaxModuliCount {\n\t\treturn fmt.Errorf(\"len(Qi) is larger than %d\", MaxModuliCount)\n\t}\n\tlenPi := uint64(b.ReadUint8())\n\tif lenPi > MaxModuliCount {\n\t\treturn fmt.Errorf(\"len(Pi) is larger than %d\", MaxModuliCount)\n\t}\n\tp.T = b.ReadUint64()\n\tp.Sigma = math.Round((float64(b.ReadUint64())/float64(1<<32))*100) / 100\n\tp.Qi = make([]uint64, lenQi, lenQi)\n\tp.Pi = make([]uint64, lenPi, lenPi)\n\tb.ReadUint64Slice(p.Qi)\n\tb.ReadUint64Slice(p.Pi)\n\treturn nil\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 (pub *PublicKey) ToBytes() (b []byte) {\n\t/* See Certicom SEC1 2.3.3, pg. 10 */\n\n\tx := pub.X.Bytes()\n\n\t/* Pad X to 32-bytes */\n\tpadded_x := append(bytes.Repeat([]byte{0x3f}, 32-len(x)), x...)\n\n\t/* Add prefix 0x02 or 0x03 depending on ylsb */\n\tif pub.Y.Bit(0) == 0 {\n\t\treturn append([]byte{0x02}, padded_x...)\n\t}\n\n\treturn append([]byte{0x03}, padded_x...)\n}", "func (n Number) MarshalText() ([]byte, error) { return []byte(n), nil }", "func (x Secp256k1N) Marshal(w io.Writer, m int) (int, error) {\n\tif m < 32 {\n\t\treturn m, surge.ErrMaxBytesExceeded\n\t}\n\tvar bs [32]byte\n\tx.GetB32(bs[:])\n\tn, err := w.Write(bs[:])\n\treturn m - n, err\n}", "func makePQ(counts []int) priq.PriQ {\n\tvar p priq.PriQ\n\tfor i, c := range counts {\n\t\tif c == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tn := node{c, byte(i), nil, nil}\n\t\tp.Add(&n)\n\t}\n\treturn p\n}", "func (p *PublicKey) Serialize() []byte {\n\treturn p.pk().SerializeCompressed()\n}", "func (i Int) Serialize() ([]byte, error) {\n\treturn []byte(strconv.Itoa(int(i))), nil\n}", "func (queue *Queue) ToJSON() ([]byte, error) {\n\treturn queue.heap.ToJSON()\n}", "func (query *Query) Serialize() []byte {\n bytes := make([]byte, 32, 32)\n\n bytes[0] = query.action\n bytes[1] = query.empty\n binary.BigEndian.PutUint32(bytes[2:6], query.replyIp)\n binary.BigEndian.PutUint16(bytes[6:8], query.replyPort)\n binary.BigEndian.PutUint64(bytes[8:16], query.key)\n binary.BigEndian.PutUint64(bytes[16:24], query.value)\n binary.BigEndian.PutUint32(bytes[24:28], query.timeToLive)\n binary.BigEndian.PutUint32(bytes[28:32], query.requestId)\n\n return bytes\n}", "func (v Palette) MarshalBinary() (data []byte, err error) {\n\tdata = make([]byte, 3*len(v))\n\tfor i := 0; i < len(v); i++ {\n\t\tdata[i*3] = v[i].r\n\t\tdata[i*3+1] = v[i].g\n\t\tdata[i*3+2] = v[i].b\n\t}\n\treturn data, nil\n}", "func IntMarshalText(x *big.Int,) ([]byte, error)", "func (epqsc EnsurePartitionQurumSafetyCheck) MarshalJSON() ([]byte, error) {\n\tepqsc.Kind = KindEnsurePartitionQuorum\n\tobjectMap := make(map[string]interface{})\n\tif epqsc.PartitionID != nil {\n\t\tobjectMap[\"PartitionId\"] = epqsc.PartitionID\n\t}\n\tif epqsc.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = epqsc.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func _proto_marshal(obj proto.Message) []byte {\n\tbuf, err := proto.Marshal(obj)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn buf\n}", "func numberToBytes(n interface{}) []byte {\n\tswitch i := n.(type) {\n\tcase uint64:\n\t\tb := make([]byte, 8)\n\t\tbinary.LittleEndian.PutUint64(b, i)\n\t\treturn b\n\tcase uint32:\n\t\tb := make([]byte, 4)\n\t\tbinary.LittleEndian.PutUint32(b, i)\n\t\treturn b\n\tcase uint16:\n\t\tb := make([]byte, 2)\n\t\tbinary.LittleEndian.PutUint16(b, i)\n\t\treturn b\n\tcase uint8:\n\t\tb := []byte{byte(i)}\n\t\treturn b\n\tdefault:\n\t\tpanic(errors.New(\"Unsupported type\"))\n\t}\n}", "func (oo *OmciCC) SendSetPrioQueueVar(ctx context.Context, timeout int, highPrio bool,\n\trxChan chan Message, params ...me.ParamData) (*me.ManagedEntity, error) {\n\ttid := oo.GetNextTid(highPrio)\n\tlogger.Debugw(ctx, \"send PrioQueue-Set-msg:\", log.Fields{\"device-id\": oo.deviceID,\n\t\t\"SequNo\": strconv.FormatInt(int64(tid), 16),\n\t\t\"InstId\": strconv.FormatInt(int64(params[0].EntityID), 16)})\n\n\tmeInstance, omciErr := me.NewPriorityQueue(params[0])\n\tif omciErr.GetError() == nil {\n\t\tomciLayer, msgLayer, err := oframe.EncodeFrame(meInstance, omci.SetRequestType, oframe.TransactionID(tid))\n\t\tif err != nil {\n\t\t\tlogger.Errorw(ctx, \"Cannot encode PrioQueue for set\", log.Fields{\n\t\t\t\t\"Err\": err, \"device-id\": oo.deviceID})\n\t\t\treturn nil, err\n\t\t}\n\n\t\tpkt, err := SerializeOmciLayer(ctx, omciLayer, msgLayer)\n\t\tif err != nil {\n\t\t\tlogger.Errorw(ctx, \"Cannot serialize PrioQueue set\", log.Fields{\n\t\t\t\t\"Err\": err, \"device-id\": oo.deviceID})\n\t\t\treturn nil, err\n\t\t}\n\n\t\tomciRxCallbackPair := CallbackPair{\n\t\t\tCbKey: tid,\n\t\t\tCbEntry: CallbackPairEntry{rxChan, oo.receiveOmciResponse, true},\n\t\t}\n\t\terr = oo.Send(ctx, pkt, timeout, CDefaultRetries, highPrio, omciRxCallbackPair)\n\t\tif err != nil {\n\t\t\tlogger.Errorw(ctx, \"Cannot send PrioQueue set\", log.Fields{\n\t\t\t\t\"Err\": err, \"device-id\": oo.deviceID})\n\t\t\treturn nil, err\n\t\t}\n\t\tlogger.Debug(ctx, \"send PrioQueue-set msg done\")\n\t\treturn meInstance, nil\n\t}\n\tlogger.Errorw(ctx, \"Cannot generate PrioQueue Instance\", log.Fields{\n\t\t\"Err\": omciErr.GetError(), \"device-id\": oo.deviceID})\n\treturn nil, omciErr.GetError()\n}", "func (m Message) Marshal() quickfix.Message { return quickfix.Marshal(m) }", "func (m Message) Marshal() quickfix.Message { return quickfix.Marshal(m) }", "func (m Message) Marshal() quickfix.Message { return quickfix.Marshal(m) }", "func (m Message) Marshal() quickfix.Message { return quickfix.Marshal(m) }", "func (m Message) Marshal() quickfix.Message { return quickfix.Marshal(m) }", "func (m Message) Marshal() quickfix.Message { return quickfix.Marshal(m) }", "func (m Message) Marshal() quickfix.Message { return quickfix.Marshal(m) }", "func (m Message) Marshal() quickfix.Message { return quickfix.Marshal(m) }", "func (m Message) Marshal() quickfix.Message { return quickfix.Marshal(m) }", "func (m Message) Marshal() quickfix.Message { return quickfix.Marshal(m) }", "func (m Message) Marshal() quickfix.Message { return quickfix.Marshal(m) }", "func (m Message) Marshal() quickfix.Message { return quickfix.Marshal(m) }", "func (m Message) Marshal() quickfix.Message { return quickfix.Marshal(m) }", "func (m Message) Marshal() quickfix.Message { return quickfix.Marshal(m) }", "func (m Message) Marshal() quickfix.Message { return quickfix.Marshal(m) }", "func (m Message) Marshal() quickfix.Message { return quickfix.Marshal(m) }", "func (m Message) Marshal() quickfix.Message { return quickfix.Marshal(m) }", "func (m Message) Marshal() quickfix.Message { return quickfix.Marshal(m) }", "func (m Message) Marshal() quickfix.Message { return quickfix.Marshal(m) }", "func (m Message) Marshal() quickfix.Message { return quickfix.Marshal(m) }", "func (pcg *PCGSource) MarshalBinary() ([]byte, error) {\n\tvar buf [16]byte\n\tbinary.BigEndian.PutUint64(buf[:8], pcg.high)\n\tbinary.BigEndian.PutUint64(buf[8:], pcg.low)\n\treturn buf[:], nil\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}", "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 var s string \n res:=helpSerialize(root,s)\n fmt.Println(res)\n return res\n}", "func encodeHash(x uint64, p, pPrime uint) (hashCode uint64) {\n\tif x&onesFromTo(64-pPrime, 63-p) == 0 {\n\t\tr := rho(extractShift(x, 0, 63-pPrime))\n\t\treturn concat([]concatInput{\n\t\t\t{x, 64 - pPrime, 63},\n\t\t\t{uint64(r), 0, 5},\n\t\t\t{1, 0, 0}, // this just adds a 1 bit at the end\n\t\t})\n\t} else {\n\t\treturn concat([]concatInput{\n\t\t\t{x, 64 - pPrime, 63},\n\t\t\t{0, 0, 0}, // this just adds a 0 bit at the end\n\t\t})\n\t}\n}", "func (c *Circle) Serialize() interface{} {\n\tcx := int64(math.Round(c.center.x * configs.HashPrecision))\n\tcy := int64(math.Round(c.center.y * configs.HashPrecision))\n\tcr := int64(math.Round(c.r * configs.HashPrecision))\n\treturn (cx*configs.Prime+cy)*configs.Prime + cr\n}", "func EncodeOnChainVRFProvingKey(vrfKey client.VRFKey) ([2]*big.Int, error) {\n\tuncompressed := vrfKey.Attributes.Uncompressed\n\tprovingKey := [2]*big.Int{}\n\tvar set1 bool\n\tvar set2 bool\n\t// strip 0x to convert to int\n\tprovingKey[0], set1 = new(big.Int).SetString(uncompressed[2:66], 16)\n\tif !set1 {\n\t\treturn [2]*big.Int{}, errors.New(\"can not convert VRF key to *big.Int\")\n\t}\n\tprovingKey[1], set2 = new(big.Int).SetString(uncompressed[66:], 16)\n\tif !set2 {\n\t\treturn [2]*big.Int{}, errors.New(\"can not convert VRF key to *big.Int\")\n\t}\n\treturn provingKey, nil\n}", "func (p *Pending) MarshalBinary() ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\n\tvar err error\n\tif _, err = buf.Write(p.Address); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif _, err = buf.Write(p.Amount.Bytes(binary.BigEndian)); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func mpi(data []byte) []byte {\n\t// Chop off leading zeros\n\tfor len(data) > 0 && data[0] == 0 {\n\t\tdata = data[1:]\n\t}\n\t// Zero-length is a special case (should never actually happen)\n\tif len(data) == 0 {\n\t\treturn []byte{0, 0}\n\t}\n\tc := len(data)*8 - bits.LeadingZeros8(data[0])\n\tmpi := []byte{byte(c >> 8), byte(c >> 0)}\n\treturn append(mpi, data...)\n}", "func (pk *PublicKey) MarshalBinary() ([]byte, error) {\n\treturn pk.Bytes(), nil\n}", "func (c *publicKey) Marshal() ([]byte, error) {\n\tpbuf, err := c.Encode()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn proto.Marshal(pbuf)\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 (m queueMapPtr) MarshalBinary() ([]byte, error) {\n\t// number of elements\n\tdata := make([]byte, 4)\n\tsz := m.Size()\n\tbinary.LittleEndian.PutUint32(data, uint32(sz))\n\tidx := 4\n\n\tm.Range(func(k, v interface{}) bool {\n\t\tn := k.(string)\n\t\tr := v.(queueRecordPtr)\n\n\t\t// name\n\t\tsz := len(n)\n\t\tdata = append(data, make([]byte, 4+sz)...)\n\t\tbinary.LittleEndian.PutUint32(data[idx:], uint32(sz))\n\t\tidx += 4\n\t\tidx += copy(data[idx:], []byte(n))\n\n\t\t// number of elements in the queue\n\t\tsz = r.Size()\n\t\tdata = append(data, make([]byte, 4)...)\n\t\tbinary.LittleEndian.PutUint32(data[idx:], uint32(sz))\n\t\tidx += 4\n\n\t\t// elements\n\t\tr.Range(func(v interface{}) bool {\n\t\t\telm := v.(entryPtr)\n\t\t\telmSz := len(elm.Value)\n\n\t\t\t// reserve space\n\t\t\tdata = append(data, make([]byte, 4+elmSz+8)...)\n\n\t\t\t// value size\n\t\t\tbinary.LittleEndian.PutUint32(data[idx:], uint32(elmSz))\n\t\t\tidx += 4\n\n\t\t\t// value\n\t\t\tidx += copy(data[idx:], elm.Value)\n\n\t\t\t// ttl\n\t\t\tbinary.LittleEndian.PutUint64(data[idx:], uint64(elm.TTLMillis))\n\t\t\tidx += 8\n\n\t\t\treturn true\n\t\t})\n\n\t\treturn true\n\t})\n\n\treturn data, nil\n}", "func (pt MDTurbo) Serialize() ([PartitionBlkLen]uint8, error) {\n\treturn Serialize(pt)\n}", "func generatePRData(l int) []byte {\n\tres := make([]byte, l)\n\tseed := uint64(1)\n\tfor i := 0; i < l; i++ {\n\t\tseed = seed * 48271 % 2147483647\n\t\tres[i] = byte(seed)\n\t}\n\treturn res\n}", "func (a *ArithRequest) MarshalTo(buf []byte) (int, error) {\n\tvar size = uint64(a.Size())\n\tif uint64(cap(buf)) >= size {\n\t\tbuf = buf[:size]\n\t} else {\n\t\treturn 0, fmt.Errorf(\"proto: buf is too short\")\n\t}\n\tvar offset uint64\n\tvar n uint64\n\tif a.A != 0 {\n\t\tbuf[offset] = 1<<3 | 0\n\t\toffset++\n\t\tn = code.EncodeVarint(buf[offset:], uint64(a.A))\n\t\toffset += n\n\t}\n\tif a.B != 0 {\n\t\tbuf[offset] = 2<<3 | 0\n\t\toffset++\n\t\tn = code.EncodeVarint(buf[offset:], uint64(a.B))\n\t\toffset += n\n\t}\n\treturn int(offset), 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 IntGobEncode(x *big.Int,) ([]byte, error)", "func (cfg frozenConfig) Marshal(val interface{}) ([]byte, error) {\n return encoder.Encode(val, cfg.encoderOpts)\n}", "func (this *petPiranha) MarshalBinary() (data []byte, err error) {\n\t// var addrs = map[uintptr]uint64{}\n\tbuf := bytes.NewBuffer(make([]byte, 0, (((29 + (8 + (len(this.pet.LastIllness.Notes) * 15))) + 17) + (8 + ((len(this.Weird) * 1238) + (len(this.Weird) * 6776))))))\n\tif err = this.marshalTo(buf /*, addrs*/); err == nil {\n\t\tdata = buf.Bytes()\n\t}\n\treturn\n}", "func PubKeySerialize(ctx *Context, publicKey *PublicKey, flags uint) (int, []byte, error) {\n\tvar size int\n\tif flags == EcCompressed {\n\t\tsize = CompressedLength\n\t} else {\n\t\tsize = UncompressedLength\n\t}\n\n\toutput := make([]C.uchar, size)\n\toutputLen := C.size_t(size)\n\tresult := int(C.secp256k1_ec_pubkey_serialize(ctx.ctx, &output[0], &outputLen, publicKey.pk, C.uint(flags)))\n\n\treturn result, goBytes(output, C.int(outputLen)), nil\n}", "func (tx *Genesis) MarshalBinary(scheme Scheme) ([]byte, error) {\n\tb, err := tx.BodyMarshalBinary(scheme)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to marshal Genesis transaction to bytes\")\n\t}\n\treturn b, nil\n}", "func (t Tag) ToBytes() ([]byte, error) {\n\tswitch t.Class {\n\tcase TagClassUniversal, TagClassApplication, TagClassContextSpecific, TagClassPrivate:\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid tag class: %d\", t.Class)\n\t}\n\tdata := []byte{byte(t.Class) << 6}\n\tif t.ConstructedEncoding {\n\t\tdata[0] = data[0] | b6\n\t}\n\tif t.BigNumber != nil {\n\t\treturn nil, fmt.Errorf(\"not implemented\")\n\t}\n\tif t.Number <= 30 {\n\t\tdata[0] = data[0] | byte(t.Number)\n\t\treturn data, nil\n\t}\n\tdata[0] = data[0] | 31\n\traw := make([]byte, 9) // Leading zeroes in case we need to use the MSB with an interval of 7 bits\n\tbinary.BigEndian.PutUint64(raw[1:], t.Number)\n\tupperLimit := uint64(0x7F)\n\trequiredBytes := 1\n\tfor upperLimit < t.Number {\n\t\trequiredBytes++\n\t\tupperLimit = upperLimit << 7\n\t\tupperLimit = upperLimit | 0x7F\n\t}\n\tformattedNumber := make([]byte, requiredBytes)\n\tbits := &reverseBitReader{\n\t\tdata: raw,\n\t}\n\tfor i := requiredBytes - 1; i >= 0; i-- {\n\t\tif i != requiredBytes-1 {\n\t\t\t// Last byte get marked by b8\n\t\t\tformattedNumber[i] = b8\n\t\t}\n\t\t// Set bits 0-7 according to the real data\n\t\tfor j := 0; j < 7; j++ {\n\t\t\tnextBit := bits.ReadBit()\n\t\t\tformattedNumber[i] = formattedNumber[i] | (nextBit << j)\n\t\t}\n\t}\n\tdata = append(data, formattedNumber...)\n\treturn data, nil\n}", "func Prim(graph *Graph.WeightedGraph) (*Graph.WeightedGraph, float64) {\n\tqueue := pq2.New()\n\tvertexPQMap := make(map[Node.Node]*Node.PQItem, 0)\n\tcount := 0\n\tMST := Graph.WeightedGraph{}\n\t//assign priorities to every vertex.\n\tfor _, vertex := range graph.Vertices {\n\t\tMST.AddVertex(vertex)\n\t\tvar item Node.PQItem\n\t\tif count == 0 {\n\t\t\titem = Node.PQItem{Value: *vertex, Priority: float64(0)}\n\t\t\tqueue.Insert(&item, float64(0))\n\t\t\tcount++\n\t\t} else {\n\t\t\titem = Node.PQItem{Value: *vertex, Priority: float64(999999999)}\n\t\t\tqueue.Insert(&item, float64(999999999))\n\t\t}\n\t\tvertexPQMap[*vertex] = &item\n\t}\n\n\t//heap.Init(&queue)\n\n\tvisited := make(map[Node.Node]bool, 0)\n\tparent := make(map[interface{}]interface{}, 0)\n\n\tfor queue.Len() > 0 {\n\t\tminVertexItem, _ := queue.Pop()\n\t\tvisited[minVertexItem.(*Node.PQItem).Value] = true\n\t\tfor _, edge := range graph.Edges[minVertexItem.(*Node.PQItem).Value] {\n\t\t\tu := edge.From\n\t\t\tv := edge.To\n\t\t\tif isVisited, _ := visited[*v]; !isVisited {\n\t\t\t\tvisited[*v] = true\n\t\t\t\tvertexPQMap[*v].Priority = edge.Cost\n\t\t\t\tqueue.UpdatePriority(vertexPQMap[*v], edge.Cost)\n\t\t\t\tparent[*v] = *u\n\t\t\t} else {\n\t\t\t\t//node is visited.\n\t\t\t\tif parent[*u].(Node.Node).Data != v.Data && vertexPQMap[*v].Priority > edge.Cost {\n\t\t\t\t\tvertexPQMap[*v].Priority = edge.Cost\n\t\t\t\t\tqueue.UpdatePriority(vertexPQMap[*v], edge.Cost)\n\t\t\t\t\tparent[*v] = *u\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t//make mst edges\n\ttotalCost := float64(0)\n\tfor key, value := range parent {\n\t\tvar v = key.(Node.Node)\n\t\tvar u = value.(Node.Node)\n\t\tMST.AddEdge(&u, &v, vertexPQMap[v].Priority, Graph.BIDIRECTIONAL)\n\t\ttotalCost += vertexPQMap[v].Priority\n\t}\n\treturn &MST, totalCost\n}", "func (self *Pages) ToBytes() uint {\n\treturn uint(self.ToUint32()) * WasmPageSize\n}", "func (v PHYVersion) MarshalBinary() ([]byte, error) {\n\treturn marshalBinaryEnum(int32(v)), nil\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 (o *ObjectId) MarshalJSONPB(m *jsonpb.Marshaler) ([]byte, error) {\n\ts, err := m.MarshalToString(&wrappers.StringValue{Value: o.Value})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn []byte(s), nil\n}", "func (v ADRAckLimitExponent) MarshalBinary() ([]byte, error) {\n\treturn marshalBinaryEnum(int32(v)), nil\n}", "func (src *MT19937_64) MarshalBinary() ([]byte, error) {\n\tvar buf [(mt19937_64NN + 1) * 8]byte\n\tfor i := 0; i < mt19937_64NN; i++ {\n\t\tbinary.BigEndian.PutUint64(buf[i*8:(i+1)*8], src.mt[i])\n\t}\n\tbinary.BigEndian.PutUint64(buf[mt19937_64NN*8:], src.mti)\n\treturn buf[:], nil\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}" ]
[ "0.58822757", "0.58489716", "0.54703814", "0.5352939", "0.5244442", "0.52092755", "0.5113366", "0.5069259", "0.5049839", "0.49863398", "0.4983973", "0.4955698", "0.49072796", "0.48997742", "0.489945", "0.48868656", "0.4884658", "0.4880819", "0.48767295", "0.48668808", "0.4858751", "0.48566717", "0.4853763", "0.4843846", "0.48425457", "0.4825922", "0.48244882", "0.48208526", "0.48206738", "0.4784234", "0.47788385", "0.4775259", "0.4762101", "0.4750231", "0.47471032", "0.47339046", "0.47282025", "0.4721037", "0.47179368", "0.47105128", "0.47018003", "0.469278", "0.46917066", "0.46903658", "0.46793562", "0.46772766", "0.4669654", "0.46632782", "0.466121", "0.4660692", "0.4660692", "0.4660692", "0.4660692", "0.4660692", "0.4660692", "0.4660692", "0.4660692", "0.4660692", "0.4660692", "0.4660692", "0.4660692", "0.4660692", "0.4660692", "0.4660692", "0.4660692", "0.4660692", "0.4660692", "0.4660692", "0.4660692", "0.46595275", "0.46580145", "0.46575367", "0.46528193", "0.46526438", "0.46340537", "0.46299297", "0.46243963", "0.4619758", "0.46123582", "0.4611642", "0.4610539", "0.45991138", "0.45985734", "0.45892173", "0.45862854", "0.45836195", "0.45824808", "0.45690626", "0.456733", "0.45635113", "0.45634365", "0.4562361", "0.4557041", "0.45450285", "0.45350224", "0.45249087", "0.45245102", "0.45225692", "0.45204422", "0.4520184" ]
0.7522036
0
Returns a copy of the array that as been solved with a simple sudoku style solver
func deduceWhatWeCan(restrictions [][]int) [][]int { updatedArray, changeMade := attemptToReduce(restrictions) for changeMade { updatedArray, changeMade = attemptToReduce(updatedArray) } return updatedArray }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func solveSudoku(board [][]byte) {\n\n}", "func solve(board [][]byte) {\n \n}", "func solveSudoku(board [][]byte) {\n\tsolve(board, 0, 0)\n}", "func (a Ant) BorraSolucion(){\n (*a.solution) = make([]int, 0)\n}", "func (this *Solution) Reset() []int {\nreturn this.arr\n}", "func (s *Sudoku) SudokuInit (unSolved [][]int) {\n\t//s.board = make([][]int, 9)\n\t//for ints := range s.board {\n\t//\ts.board[ints] = make([]int, 9)\n\t//}\n\n\tfor i := 0; i < 9; i++ {\n\t\tfor j := 0; j < 9; j++ {\n\t\t\ts.board[i][j] = unSolved[i][j]\n\t\t}\n\t}\n}", "func (this *Solution) Reset() []int {\n\treturn this.Arr\n}", "func (s *Sudoku) solveByUniqueCandidate() bool {\n var blockSolution [9]int\n var ret bool\n\n var a_min, b_min, a_max, b_max, a, b uint8\n\n //the easiest way to iterate through blocks and have stored their index boundaries\n for a_min = 0; a_min < 9; a_min += 3 {\n a_max = a_min + 2\n\n for b_min = 0; b_min < 9; b_min += 3 {\n b_max = b_min + 2\n \n fillZeroes9(&blockSolution)\n for a = a_min; a <= a_max; a++ {\n for b = b_min; b <= b_max; b++ {\n // interested in only not filled in cells\n if s.solution[a][b] == 0 {\n // ..that still have some potential solutions:\n for c := range s.markerTable[a][b] {\n if s.markerTable[a][b][c] {\n blockSolution[c]++\n //fmt.Printf(\"a = %d, b = %d, c = %d, truth = %d\\n\", a+1, b+1, c+1, blockSolution[c])\n }\n }\n }\n }\n } \n\n for sol_idx := range blockSolution {\n if blockSolution[sol_idx] == 1 {\n for a = a_min; a <= a_max; a++ {\n for b = b_min; b <= b_max; b++ {\n // interested in only not filled in cells\n if s.solution[a][b] == 0 {\n // ..that still have some potential solutions:\n if s.markerTable[a][b][sol_idx] {\n ret = true\n //fmt.Printf(\"unique candidate: new solution found, for a = %d, b = %d and it is %d\\n\", a+1, b+1, sol_idx+1)\n s.fillSolutionCell(a, b, uint8(sol_idx + 1)) \n }\n }\n }\n }\n }\n }\n }\n }\n return ret\n}", "func main() {\n\tboard := make([][]byte, 9)\n\tfor i := 0; i < 9; i++ {\n\t\tboard[i] = make([]byte, 9)\n\t}\n\tboard[0] = []byte{'.', '.', '9', '7', '4', '8', '.', '.', '.'}\n\tboard[1] = []byte{'7', '.', '.', '.', '.', '.', '.', '.', '.'}\n\tboard[2] = []byte{'.', '2', '.', '1', '.', '9', '.', '.', '.'}\n\tboard[3] = []byte{'.', '.', '7', '.', '.', '.', '2', '4', '.'}\n\tboard[4] = []byte{'.', '6', '4', '.', '1', '.', '5', '9', '.'}\n\tboard[5] = []byte{'.', '9', '8', '.', '.', '.', '3', '.', '.'}\n\tboard[7] = []byte{'.', '.', '.', '8', '.', '3', '.', '2', '.'}\n\tboard[6] = []byte{'.', '.', '.', '.', '.', '.', '.', '.', '6'}\n\tboard[8] = []byte{'.', '.', '.', '2', '7', '5', '9', '.', '.'}\n\n\t// [\"..9748...\",\"7........\",\".2.1.9...\",\"..7...24.\",\".64.1.59.\",\".98...3..\",\"...8.3.2.\",\"........6\",\"...2759..\"]\n\n\tsolveSudoku(board)\n\tfor i := 0; i < 9; i++ {\n\t\tfor j := 0; j < 9; j++ {\n\t\t\tfmt.Printf(\"%c\", board[i][j])\n\t\t}\n\t\tfmt.Print(\"\\n\")\n\t}\n\n}", "func (this *Solution) Reset() []int {\r\n return this.raw\r\n\r\n}", "func (this *Solution) Reset() []int {\n\tthis.nums = this.original\n\n\treturn this.original\n}", "func (s *Solution) Reset() []int {\n\treturn s.arr\n}", "func solve(check *[]bool, curList []int, ans *[][]int, nums []int) {\r\n n := len(nums)\r\n if len(curList) == n {\r\n tmp := make([]int, n)\r\n copy(tmp, curList)\r\n *ans = append(*ans, tmp)\r\n return\r\n }\r\n for i, num := range nums {\r\n if !(*check)[i] {\r\n curList = append(curList, num)\r\n (*check)[i] = true\r\n solve(check, curList, ans, nums)\r\n (*check)[i] = false\r\n curList = curList[:len(curList)-1]\r\n }\r\n }\r\n}", "func (s *Sudoku) solveByHiddenSingles() bool {\n var rowMarkers, columnMarkers [9]int\n var ret bool \n\n for a := range s.markerTable {\n for b := range s.markerTable[a] {\n for c := range s.markerTable[a][b] {\n\n if s.solution[a][b]==0 && s.markerTable[a][b][c] {\n rowMarkers[c]++\n }\n if s.solution[b][a]==0 && s.markerTable[b][a][c] {\n columnMarkers[c]++\n }\n }\n }\n\n for c := range rowMarkers {\n if rowMarkers[c] == 1 {\n for b := range s.markerTable[a] {\n if s.solution[a][b]==0 && s.markerTable[a][b][c] {\n s.fillSolutionCell(uint8(a), uint8(b), uint8(c+1))\n ret = true\n }\n }\n }\n\n if columnMarkers[c] == 1 {\n for b := range s.markerTable[a] {\n if s.solution[b][a]==0 && s.markerTable[b][a][c] {\n s.fillSolutionCell(uint8(b), uint8(a), uint8(c+1))\n ret = true\n }\n }\n }\n }\n\n fillZeroes9(&rowMarkers)\n fillZeroes9(&columnMarkers)\n }\n return ret\n}", "func NewSudoku(array [rows][columns]int) *sudokuGrid {\n\tvar grid sudokuGrid\n\tfor i := 0; i < columns; i++ {\n\t\tfor j := 0; j < rows; j++ {\n\t\t\tif array[i][j] > 0 {\n\t\t\t\tgrid[i][j].fixed = true\n\t\t\t\tgrid[i][j].digit = array[i][j]\n\t\t\t} else {\n\t\t\t\tgrid[i][j].fixed = false\n\t\t\t}\n\t\t}\n\t}\n\treturn &grid\n}", "func sudoku(s, rol, col, grid [][]int, row, column int) {\n\tif found {\n\t\treturn\n\t}\n\n\t// found answer\n\tif row == 9 && column == 0 {\n\t\tprintData(s)\n\t\tfound = true\n\t\treturn\n\t}\n\n\t// there already is a numbner in s[row][column], skip it\n\tif s[row][column] != 0 {\n\t\tif column == 8 {\n\t\t\tsudoku(s, rol, col, grid, row+1, 0)\n\t\t} else {\n\t\t\tsudoku(s, rol, col, grid, row, column+1)\n\t\t}\n\t\treturn\n\t}\n\n\tfor i := 1; i <= 9; i++ {\n\t\tif found {\n\t\t\treturn\n\t\t}\n\n\t\t// number i does exit at row or column or grid\n\t\tif rol[row][i] != 0 || col[column][i] != 0 || grid[column/3+row/3*3][i] != 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\ts[row][column] = i\n\t\trol[row][i] = 1\n\t\tcol[column][i] = 1\n\t\tgrid[column/3+row/3*3][i] = 1\n\n\t\tif column == 8 {\n\t\t\tsudoku(s, rol, col, grid, row+1, 0)\n\t\t} else {\n\t\t\tsudoku(s, rol, col, grid, row, column+1)\n\t\t}\n\n\t\t// rollback\n\t\ts[row][column] = 0\n\t\trol[row][i] = 0\n\t\tcol[column][i] = 0\n\t\tgrid[column/3+row/3*3][i] = 0\n\t}\n}", "func (this *Solution) Reset() []int {\n\treturn this.a\n}", "func solve(board [][]byte) {\n\t// 并查集\n\t//if len(board) == 0 {\n\t//\treturn\n\t//}\n\t//m, n := len(board), len(board[0])\n\t//parent, di, dj := make([]int, m*n+1), [4]int{-1, 0, 0, 1}, [4]int{0, -1, 1, 0}\n\t//for i, _ := range parent {\n\t//\tparent[i] = i\n\t//}\n\t//find := func(parent []int, p int) int {\n\t//\tfor p != parent[p] {\n\t//\t\tparent[p], p = parent[parent[p]], parent[parent[p]]\n\t//\t}\n\t//\treturn p\n\t//}\n\t//union := func(parent []int, p, q int) {\n\t//\trootP, rootQ := find(parent, p), find(parent, q)\n\t//\tif rootP != rootQ {\n\t//\t\tparent[rootP] = rootQ\n\t//\t}\n\t//}\n\t//var dfs func(i, j int)\n\t//dfs = func(i, j int) {\n\t//\tfmt.Println(i, j)\n\t//\tif i < 0 || i >= m || j < 0 || j >= n || board[i][j] == 'X' || find(parent, i*n+j) == len(parent)-1 {\n\t//\t\treturn\n\t//\t}\n\t//\tunion(parent, i*n+j, len(parent)-1)\n\t//\tfor k := 0; k < 4; k++ {\n\t//\t\tdfs(i+di[k], j+dj[k])\n\t//\t}\n\t//}\n\t//for j := 0; j < n; j++ {\n\t//\tif board[0][j] == 'O' {\n\t//\t\tdfs(0, j)\n\t//\t}\n\t//}\n\t//for i := 1; i < m; i++ {\n\t//\tif board[i][0] == 'O' {\n\t//\t\tdfs(i, 0)\n\t//\t}\n\t//}\n\t//for i := 1; i < m; i++ {\n\t//\tif board[i][n-1] == 'O' {\n\t//\t\tdfs(i, n-1)\n\t//\t}\n\t//}\n\t//for j := 1; j < n-1; j++ {\n\t//\tif board[m-1][j] == 'O' {\n\t//\t\tdfs(m-1, j)\n\t//\t}\n\t//}\n\t//for i := 0; i < m; i++ {\n\t//\tfor j := 0; j < n; j++ {\n\t//\t\tif board[i][j] == 'O' && find(parent, i*n+j) != len(parent)-1 {\n\t//\t\t\tboard[i][j] = 'X'\n\t//\t\t}\n\t//\t}\n\t//}\n\n\t// BFS:不会OOM,重点:四连通 添加了很多重复的元素到 队列 中\n\tif len(board) == 0 {\n\t\treturn\n\t}\n\tm, n := len(board), len(board[0])\n\tqueue, di, dj := list.New(), [4]int{-1, 0, 0, 1}, [4]int{0, -1, 1, 0}\n\tvisited := make([][]bool, m) // BFS oom 的关键不是队列中的元素多了,而是 四连通 添加了很多重复的元素到 队列 中\n\tfor i := 0; i < m; i++ {\n\t\tvisited[i] = make([]bool, n)\n\t}\n\tbfs := func(i, j int) {\n\t\tqueue.PushBack([2]int{i, j}) // 采用 list 作为队列\n\t\tvisited[i][j] = true\n\t\tfor queue.Len() > 0 {\n\t\t\tcurr := queue.Remove(queue.Front()).([2]int) // 新写法\n\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\tnI, nJ := curr[0]+di[k], curr[1]+dj[k]\n\t\t\t\tif nI < 0 || nI >= m || nJ < 0 || nJ >= n || board[nI][nJ] == 'X' || visited[nI][nJ] {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tqueue.PushBack([2]int{nI, nJ})\n\t\t\t\tvisited[nI][nJ] = true\n\t\t\t}\n\t\t}\n\t}\n\tfor i := 0; i < m; i++ {\n\t\tfor j := 0; j < n; j++ {\n\t\t\tif board[i][j] == 'O' && (i == 0 || i == m-1 || j == 0 || j == n-1) {\n\t\t\t\tbfs(i, j)\n\t\t\t}\n\t\t}\n\t}\n\tfor i := 0; i < m; i++ {\n\t\tfor j := 0; j < n; j++ {\n\t\t\tif board[i][j] == 'O' && !visited[i][j] {\n\t\t\t\tboard[i][j] = 'X'\n\t\t\t}\n\t\t}\n\t}\n\n\t// BFS:难点,out of memory(太多O),重点:见上一种 BFS\n\t//if len(board) == 0 {\n\t//\treturn\n\t//}\n\t//m, n := len(board), len(board[0])\n\t//queue, di, dj := make([]Point, 0), [4]int{-1, 0, 0, 1}, [4]int{0, -1, 1, 0}\n\t//var bfs func()\n\t//bfs = func() {\n\t//\t//for idx := 0; idx < len(queue); idx++ {\t// out of memory(太多O),\n\t//\tfor len(queue) > 0 { // out of memory(太多O),那么就要换种写法\n\t//\t\tlength := len(queue)\n\t//\t\tfor idx := 0; idx < length; idx++ {\n\t//\t\t\ti, j := queue[idx].i, queue[idx].j\n\t//\t\t\tboard[i][j] = '!'\n\t//\t\t\tfor k := 0; k < 4; k++ {\n\t//\t\t\t\tnI, nJ := i+di[k], j+dj[k]\n\t//\t\t\t\tif nI < 0 || nI >= m || nJ < 0 || nJ >= n || board[nI][nJ] == 'X' || board[nI][nJ] == '!' {\n\t//\t\t\t\t\tcontinue\n\t//\t\t\t\t}\n\t//\t\t\t\tqueue = append(queue, Point{nI, nJ})\t// 作为 四连通 添加重复元素的案例\n\t//\t\t\t}\n\t//\t\t}\n\t//\t\tqueue = queue[length:]\n\t//\t}\n\t//}\n\t//for i := 0; i < m; i++ {\n\t//\tfor j := 0; j < n; j++ {\n\t//\t\tif board[i][j] == 'O' && (i == 0 || i == m-1 || j == 0 || j == n-1) {\n\t//\t\t\tqueue = append(queue, Point{i, j})\n\t//\t\t\tbfs()\n\t//\t\t}\n\t//\t}\n\t//}\n\t//for i := 0; i < m; i++ {\n\t//\tfor j := 0; j < n; j++ {\n\t//\t\tswitch board[i][j] {\n\t//\t\tcase '!':\n\t//\t\t\tboard[i][j] = 'O'\n\t//\t\tcase 'O':\n\t//\t\t\tboard[i][j] = 'X'\n\t//\t\t}\n\t//\t}\n\t//}\n\n\t// DFS\n\t//m := len(board) - 1\n\t//if m == -1 {\n\t//\treturn\n\t//}\n\t//n := len(board[0]) - 1\n\t//dx, dy := [4]int{-1, 0, 0, 1}, [4]int{0, -1, 1, 0}\n\t//var dfs func(i, j int)\n\t//dfs = func(i, j int) {\n\t//\tif i < 0 || i > m || j < 0 || j > n || board[i][j] == 'X' || board[i][j] == '!' {\n\t//\t\treturn\n\t//\t}\n\t//\tboard[i][j] = '!'\n\t//\tfor k := 0; k < 4; k++ {\n\t//\t\tdfs(i+dx[k], j+dy[k])\n\t//\t}\n\t//}\n\t//for i := 0; i <= m; i++ {\n\t//\tfor j := 0; j <= n; j++ {\n\t//\t\tif i == 0 || i == m || j == 0 || j == n && board[i][j] == 'O' { // 处理边界\n\t//\t\t\tdfs(i, j)\n\t//\t\t}\n\t//\t}\n\t//}\n\t//for i := 0; i <= m; i++ {\n\t//\tfor j := 0; j <= n; j++ {\n\t//\t\tswitch board[i][j] { // 处理中央和边界\n\t//\t\tcase '!':\n\t//\t\t\tboard[i][j] = 'O'\n\t//\t\tcase 'O':\n\t//\t\t\tboard[i][j] = 'X'\n\t//\t\t}\n\t//\t}\n\t//}\n\n\t// DFS:失败\n\t//if len(board) == 0 {\n\t//\treturn\n\t//}\n\t//r, c := len(board), len(board[0])\n\t//dx, dy := [4]int{-1, 0, 0, 1}, [4]int{0, -1, 1, 0}\n\t//visited := make([]bool, r*c) // 加 visited 也解决不了“封闭”的bug\n\t//var dfs func(i, j int) // 有返回值的情况,行不通,因为当 [i,j] 3面都是 X 时,进来的地方,进来的地方和 [i,j] 互相依赖,无法判断\n\t//dfs = func(i, j int) {\n\t//\tfmt.Println(i, j)\n\t//\tif board[i][j] == 'X' { // 这里也要判断 visited[i*c+j],因为前面可能提前触到边界返回了\n\t//\t\treturn\n\t//\t}\n\t//\tvisited[i*c+j] = true\n\t//\t//ans := false\n\t//\tfor k := 0; k < 4; k++ {\n\t//\t\tnI, nJ := i+dx[k], j+dy[k]\n\t//\t\tif nI < 0 || nI == r || nJ < 0 || nJ == c {\n\t//\t\t\treturn\n\t//\t\t}\n\t//\t\tif visited[i*c+j] {\n\t//\t\t\tcontinue\n\t//\t\t}\n\t//\t\tdfs(nI, nJ)\n\t//\t}\n\t//\tboard[i][j] = 'X'\n\t//}\n\t//for i := 0; i < r; i++ {\n\t//\tfor j := 0; j < c; j++ {\n\t//\t\tif board[i][j] == 'O' && !visited[i*c+j] {\n\t//\t\t\tdfs(i, j)\n\t//\t\t}\n\t//\t}\n\t//}\n}", "func (n *Node) ClonePuzzle() []int {\n\tp := make([]int, NumberColumns*NumberRows)\n\tfor i := 0; i < len(n.Puzzle); i++ {\n\t\tp[i] = n.Puzzle[i]\n\t}\n\treturn p\n}", "func slidingPuzzle(board [][]int) int {\n\n}", "func puzzle_to_board(puzzle Puzzle) (Board, error) {\n\t// The board to return\n\tvar board Board\n\n\t// allocate composed 2d array\n\trows := len(puzzle)\n\tcols := len(puzzle[0])\n\n\tif rows%2 != 0 || cols%2 != 0 {\n\t\treturn board, errors.New(fmt.Sprintf(\"rows[%v] or cols[%v] not a multiple of 2\", rows, cols))\n\t}\n\ta := make([][]Cell, rows)\n\te := make([]Cell, rows*cols)\n\tfor i := range a {\n\t\ta[i] = e[i*cols : (i+1)*cols]\n\t}\n\n\tfor y := 0; y < len(puzzle); y++ {\n\t\tfor x := 0; x < len(puzzle[y]); x++ {\n\t\t\t// put puzzle in board\n\t\t\tswitch puzzle[y][x] {\n\t\t\tcase X:\n\t\t\t\ta[y][x] = Cell{false, X}\n\t\t\tcase 0:\n\t\t\t\ta[y][x] = Cell{true, 0}\n\t\t\tcase 1:\n\t\t\t\ta[y][x] = Cell{true, 1}\n\t\t\tdefault: // invalid!\n\t\t\t\treturn board, errors.New(fmt.Sprintf(\"Cell [%v,%v] is not 0, 1 or X\", y, x))\n\t\t\t}\n\t\t}\n\t}\n\n\tboard.dim_y = len(puzzle)\n\tboard.dim_x = len(puzzle[0])\n\tboard.cells = a\n\treturn board, nil\n}", "func singleValueSolver(cluster []cell) (changes []cell) {\n\tfor _, each := range cluster {\n\t\t// skip this cell if it's already solved\n\t\tif each.actual != 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\t// should never happen - probably #TODO# to catch this\n\t\tif len(each.excluded) >= len(cluster) {\n\t\t\tpanic(\"Found an unsolved cell with all values excluded\")\n\t\t}\n\n\t\tif len(each.excluded) == len(cluster)-1 {\n\t\t\t// send back an update for this cell\n\t\t\tsolvedValue := subArr(fullArray, each.excluded)\n\t\t\tchanges = append(changes, cell{location: each.location,\n\t\t\t\tactual: solvedValue[0], possible: fullArray})\n\t\t}\n\t}\n\treturn\n}", "func (this *Solution) Reset() []int {\n\treturn this.nums\n}", "func (this *Solution) Reset() []int {\n\treturn this.nums\n}", "func (this *Solution) Reset() []int {\n\treturn this.current\n}", "func (is *ImmuneSystem) clonalSelection() []TCell {\n\t// create clones\n\tclones := [][]TCell{}\n\tnumCopies := len(is.Cells) * is.cloneSizeFactor\n\tfor i := 0; i < len(is.Cells); i++ {\n\t\tclonesOfIndex := make([]TCell, numCopies)\n\t\tfor j := 0; j < numCopies; j++ {\n\t\t\tclonesOfIndex[j] = is.Cells[i]\n\t\t\tcopy(clonesOfIndex[j].prices, is.Cells[i].prices) // deep copy array otherwise both will change\n\t\t}\n\t\tclones = append(clones, clonesOfIndex)\n\t}\n\n\t// mutation\n\tfor i := 0; i < len(clones); i++ {\n\t\tfor j := 0; j < len(clones[i]); j++ {\n\t\t\tmutationRate := math.Exp(-1 * clones[i][j].Revenue / bestFitness)\n\t\t\tif rand.Float64() <= mutationRate {\n\t\t\t\tclones[i][j] = is.contiguousHyperMutation(clones[i][j].prices) // cant change\n\t\t\t}\n\t\t}\n\t}\n\n\t// prepare for use in main population\n\treturnedClones := []TCell{}\n\tfor i := 0; i < len(clones); i++ {\n\t\treturnedClones = append(returnedClones, clones[i]...)\n\t}\n\treturn returnedClones\n}", "func (s *Solution) Clone() *Solution {\n\ttmp := s.encoding.Flip\n\tif tmp != nil {\n\t\ttmp = pi(*tmp)\n\t}\n\tclone := Solution{\n\t\tencoding: encoding{\n\t\t\tZeroCoin: s.encoding.ZeroCoin,\n\t\t\tFlip: s.encoding.Flip,\n\t\t},\n\t\tWeighings: [3]Weighing{},\n\t\tCoins: make([]int, len(s.Coins)),\n\t\tWeights: make([]Weight, len(s.Weights)),\n\t\tUnique: s.Unique,\n\t\tTriples: s.Triples,\n\t\tFailures: make([]Failure, len(s.Failures)),\n\t\tflags: s.flags,\n\t\torder: s.order,\n\t\tflips: s.flips,\n\t}\n\n\tcopy(clone.Pairs[0:], s.Pairs[0:])\n\tcopy(clone.Weighings[0:], s.Weighings[0:])\n\tcopy(clone.Coins[0:], s.Coins[0:])\n\tcopy(clone.Weights[0:], s.Weights[0:])\n\tcopy(clone.Failures[0:], s.Failures[0:])\n\tcopy(clone.Structure[0:], s.Structure[0:])\n\n\treturn &clone\n}", "func to_be_placed() []int {\n\tvar temp = make([]int, 0)\n\tfor x := 1; x <= board_size; x++ {\n\t\tif contains(x, board) == false {\n\t\t\ttemp = append(temp, x)\n\t\t}\n\t}\n\treturn temp\n}", "func (this *Solution) Reset() []int {\n\treturn this.ori\n}", "func SolveGrid(grid [][]int) ([][]int, CheckedGrid, error) {\n\t// previousNumSquares holds the previous loops count of how many empty squares exist\n\tpreviousNumSquares := 0\n\n\tcg := CheckedGrid{}\n\n\tfor {\n\t\tss, err := NewSquares(grid)\n\t\tif err != nil {\n\t\t\treturn nil, cg, err\n\t\t}\n\n\t\tif len(ss) == 0 || len(ss) == previousNumSquares {\n\t\t\tbreak\n\t\t}\n\t\tpreviousNumSquares = len(ss)\n\n\t\tfor _, s := range ss {\n\t\t\tif len(s.possibleNums) == 1 {\n\t\t\t\tgrid[s.pos.rowNumber][s.pos.colNumber] = s.possibleNums[0]\n\t\t\t}\n\t\t}\n\t\tss, err = NewSquares(grid)\n\t\tif err != nil {\n\t\t\treturn nil, cg, err\n\t\t}\n\t\tfor _, s := range ss {\n\t\t\tif err := traverseAdjacent(grid, s); err != nil {\n\t\t\t\treturn nil, cg, err\n\t\t\t}\n\t\t}\n\t}\n\tcg = CheckGrid(grid)\n\tif !cg.Valid {\n\t\treturn grid, cg, errors.New(\"the grid is invalid\")\n\t}\n\tif cg.Complete {\n\t\treturn grid, cg, nil\n\t}\n\tvar err error\n\tgrid, err = bruteForceGuess(grid)\n\tif err != nil {\n\t\treturn grid, cg, err\n\t}\n\tcg = CheckGrid(grid)\n\tif !cg.Valid {\n\t\treturn grid, cg, errors.New(\"the grid is invalid after brute forcing\")\n\t}\n\treturn grid, cg, err\n}", "func (this *Solution) Reset() []int {\n\treturn this.initial\n}", "func subsets(nums []int) [][]int {\n tempAns, result := []int{}, [][]int{}\n for sublen:=0; sublen<=len(nums);sublen++{\n backtracking(nums, 0, sublen, tempAns, &result)\n }\n return result\n}", "func solve(board [][]byte) {\n\t// 2020-08-20 15:12 @bingohuang\n\t// 算法:1、深度优先搜索\n\t// 复杂度:O(MxN)/O(MxN)\n\t// 效率:执行耗时:36 ms,击败了9.94% 的Go用户\n\t//\t\t\t内存消耗:6 MB,击败了38.39% 的Go用户\n\tif len(board) == 0 || len(board[0]) == 0 {\n\t\treturn\n\t}\n\tr, c := len(board), len(board[0])\n\tvar dfs func([][]byte, int, int)\n\tdfs = func(board [][]byte, x, y int) {\n\t\tif x < 0 || x >= r || y < 0 || y >= c || board[x][y] != 'O' {\n\t\t\treturn\n\t\t}\n\t\tboard[x][y] = 'A'\n\t\tdfs(board, x+1, y)\n\t\tdfs(board, x-1, y)\n\t\tdfs(board, x, y+1)\n\t\tdfs(board, x, y-1)\n\t}\n\t// 左右两列搜索\n\tfor i := 0; i < r; i++ {\n\t\tdfs(board, i, 0)\n\t\tdfs(board, i, c-1)\n\t}\n\n\t// 上下两行搜索\n\tfor i := 0; i < c; i++ {\n\t\tdfs(board, 0, i)\n\t\tdfs(board, r-1, i)\n\t}\n\n\t// 对 A 标记,重新标记为O,对O标记为X\n\tfor i := 0; i < r; i++ {\n\t\tfor j := 0; j < c; j++ {\n\t\t\tif board[i][j] == 'A' {\n\t\t\t\tboard[i][j] = 'O'\n\t\t\t} else if board[i][j] == 'O' {\n\t\t\t\tboard[i][j] = 'X'\n\t\t\t}\n\t\t}\n\t}\n\n}", "func Solve(input [][]float64) (float64, []int) {\n\n\tvar total float64\n\tlocal := arrayCopy(input)\n\tif len(input) != len(input[0]) {\n\t\tlocal = normalizeMatrix(local)\n\t}\n\n\tresult := make([]int, len(input[0]))\n\tif len(input) > len(input[0]) {\n\t\t//missing colunms\n\t\tlocal = zeroRows(local)\n\t\tlocal = zeroColumns(local)\n\t} else {\n\t\t// equals or missing rows\n\t\tlocal = zeroRows(local)\n\t\tlocal = zeroColumns(local)\n\t}\n\n\tmarked := makeArray(len(input))\n\n\tmarked = rowScanning(local, marked)\n\n\tlineRows, lineCols := checkLines(marked)\n\n\tfor len(lineRows)+len(lineCols) != len(input) {\n\t\tlocal = step4(local, lineRows, lineCols)\n\t\tmarked = zeroOutMatrix(marked)\n\t\tmarked = rowScanning(local, marked)\n\t\tlineRows, lineCols = checkLines(marked)\n\t\tbreak\n\t}\n\t//fmt.Printf(\"local:%v\\nr:%v\\nc:%v\\nmarked:%v\\n\", local, lineRows, lineCols, marked)\n\n\tresult = resultDecider(marked)[:len(input[0])]\n\n\tfor row := range input {\n\t\ttotal += input[row][result[row]]\n\t}\n\treturn total, result\n}", "func singleCellSolver(index indexedCluster, cluster []cell) (changes []cell) {\n\tfor val, section := range index {\n\t\tif len(section) < 1 {\n\t\t\t// something went terribly wrong here - #TODO# add panic catch?\n\t\t\tpanic(\"Found a value with no possible cells\")\n\t\t} else if len(section) == 1 {\n\t\t\tchanges = append(changes, cell{\n\t\t\t\tlocation: cluster[section[0]].location,\n\t\t\t\tactual: val,\n\t\t\t\texcluded: fullArray,\n\t\t\t})\n\t\t}\n\t}\n\treturn\n}", "func GenerateProblem() (*SudokuSquare, error) {\n\tsud := randomFilledSudoku()\n\t// removing is more efficient than adding because of the way backtracking\n\t// works.\n\terr := removeCellsWhileSolvable(sud)\n\treturn sud, err\n}", "func (s *Sudoku) solveBasingOnMarkers() bool { \n someSolutionFound := false\n for a := range s.markerTable {\n for b := range s.markerTable[a] {\n if s.solution[a][b] == 0 {\n var solutionFound uint8 = 0\n for c := range s.markerTable[a][b] {\n if s.markerTable[a][b][c] == true {\n if solutionFound != 0 {\n solutionFound = 0\n break\n } \n solutionFound = uint8(c + 1)\n } \n }\n if solutionFound != 0 {\n //fmt.Printf(\"based on markers: new solution found, for a = %d, b = %d, and it is %d\\n\", a+1, b+1, solutionFound)\n s.fillSolutionCell(uint8(a), uint8(b), solutionFound)\n someSolutionFound = true\n } \n }\n }\n }\n return someSolutionFound\n}", "func newBoard(b []int, x int) []int {\n\tnew := make([]int, len(b)+1)\n\tfor i := 0; i < len(b); i++ {\n\t\tnew[i] = b[i]\n\t}\n\tnew[len(new)-1] = x\n\treturn new\n}", "func get_local_box_numbers(row, col int, matrix [][]int) []int {\n var nums = make([]int, 9, 9)\n\n start_row, start_col := (row / 3) * 3, (col / 3) * 3\n count := 0\n for i := 0; i < 3; i++ {\n for j := 0; j < 3; j++ {\n nums[count] = matrix[start_row + i][start_col + j]\n count++\n }\n }\n return nums\n}", "func TestSimplify(t *testing.T) {\n\n\ttestPuzzle := NewPuzzle()\n\tsc := func() {\n\t\tresult := testPuzzle.SelfCheck()\n\t\tif result != nil {\n\t\t\tlog.Fatal(\"Self check fail\", result)\n\t\t}\n\t}\n\tsc()\n\n\t// Set Value,Col,Row\n\t// numbered from 0\n\ttestPuzzle.setValC(3, 1, 0)\n\ttestPuzzle.setValC(4, 3, 0)\n\ttestPuzzle.setValC(8, 4, 0)\n\ttestPuzzle.setValC(6, 6, 0)\n\ttestPuzzle.setValC(9, 8, 0)\n\ttestPuzzle.setValC(2, 4, 1)\n\ttestPuzzle.setValC(7, 5, 1)\n\ttestPuzzle.setValC(8, 0, 2)\n\ttestPuzzle.setValC(3, 3, 2)\n\ttestPuzzle.setValC(1, 1, 3)\n\ttestPuzzle.setValC(9, 2, 3)\n\ttestPuzzle.setValC(7, 0, 4)\n\ttestPuzzle.setValC(8, 1, 4)\n\ttestPuzzle.setValC(2, 5, 4)\n\ttestPuzzle.setValC(9, 7, 4)\n\ttestPuzzle.setValC(3, 8, 4)\n\ttestPuzzle.setValC(4, 5, 5)\n\ttestPuzzle.setValC(8, 6, 5)\n\ttestPuzzle.setValC(7, 7, 5)\n\ttestPuzzle.setValC(5, 5, 6)\n\ttestPuzzle.setValC(6, 8, 6)\n\ttestPuzzle.setValC(1, 3, 7)\n\ttestPuzzle.setValC(3, 4, 7)\n\ttestPuzzle.setValC(9, 0, 8)\n\ttestPuzzle.setValC(2, 2, 8)\n\ttestPuzzle.setValC(4, 4, 8)\n\ttestPuzzle.setValC(8, 5, 8)\n\ttestPuzzle.setValC(1, 7, 8)\n\t//log.Println(\"Row 7\\n\",testPuzzle)\n\tsc()\n\n\ttestPuzzle.Solve()\n\tsc()\n\t// This is a minimal puzzle so:\n\t// Give is an extra solved location\n\ttestPuzzle.setValC(2, 0, 0)\n\tdifficultPuz := testPuzzle.MaxDifficulty()\n\t//log.Println(difficultPuz)\n\tif difficultPuz.roughCheck(*testPuzzle) {\n\t\t// all is good\n\t\t// every solved cell in testPuzzle\n\t\t// exists as a value in difficultPuz\n\t} else {\n\t\tlog.Fatal(\"Missing Cells\")\n\t}\n\n\t// if MaxDifficulty has worked\n\t// there will be some cells marked as solved in testPuzzle\n\t// that are not solved in difficultPuz\n\tif testPuzzle.lessRoughCheck(difficultPuz) {\n\t\t// If this is true\n\t\t// then every solved difficultPuz cell is solved in testPuzzle\n\t\tlog.Fatal(\"MaxDifficulty has done nothing\")\n\t}\n}", "func main() {\n\tarr := []int{17, 18, 5, 4, 6, 1}\n\tresult := solution(arr)\n\tfmt.Println(result)\n}", "func main() {\n\n\tpuzzle := PUZZLE{\n\t\t{0, 3, 0, 4, 8, 0, 6, 0, 9},\n\t\t{0, 0, 0, 0, 2, 7, 0, 0, 0},\n\t\t{8, 0, 0, 3, 0, 0, 0, 0, 0},\n\t\t{0, 1, 9, 0, 0, 0, 0, 0, 0},\n\t\t{7, 8, 0, 0, 0, 2, 0, 9, 3},\n\t\t{0, 0, 0, 0, 0, 4, 8, 7, 0},\n\t\t{0, 0, 0, 0, 0, 5, 0, 0, 6},\n\t\t{0, 0, 0, 1, 3, 0, 0, 0, 0},\n\t\t{9, 0, 2, 0, 4, 8, 0, 1, 0},\n\t}\n\n\tprintln(\"Start of Puzzle\")\n\tprintPuzzle(&puzzle)\n\n\tprintln(\"Solving...\")\n\tsolved := solve(puzzle)\n\n\tprintln(\"Done.\")\n\tprintPuzzle(solved)\n}", "func solve(nQueens int) []board {\n\tstop := startTimer(fmt.Sprintf(\"%d Queens\", nQueens))\n\tdefer stop()\n\t// place initial queen\n\tboards := make([]board, nQueens)\n\tfor i := 0; i < nQueens; i++ {\n\t\tboards[i] = []int{i}\n\t}\n\t// place remaining nQueens-1 queens\n\tfor i := 1; i < nQueens; i++ {\n\t\tvar grow []board\n\t\tfor _, b := range boards {\n\t\t\texpanded := expand(b, nQueens)\n\t\t\tgrow = append(grow, expanded...)\n\t\t}\n\t\tboards = grow\n\t}\n\treturn boards\n}", "func (b board) Copy() Board {\r\n\tc := make([][]int, len(b))\r\n\tfor i := range c {\r\n\t\tc[i] = make([]int, len(b[i]))\r\n\t\tcopy(c[i], b[i])\r\n\t}\r\n\treturn board(c)\r\n}", "func getMatrix(matrix [][][]int) [][]int {\n\n\tvar new_matrix [][]int\n\n\tnew_matrix = make([][]int, len(matrix))\n\n\tfor i := range new_matrix {\n\t\tnew_matrix[i] = make([]int, len(matrix[0]))\n\t}\n\n\tfor i := 0; i < len(matrix); i++ {\n\t\tfor j := 0; j < len(matrix[0]); j++ {\n\t\t\tnew_matrix[i][j] = matrix[i][j][0]\n\t\t}\n\t}\n\n\treturn new_matrix\n}", "func SolvedCubieCorners() CubieCorners {\n\tvar res CubieCorners\n\tfor i := 0; i < 8; i++ {\n\t\tres[i].Piece = i\n\t\tres[i].Orientation = 1\n\t}\n\treturn res\n}", "func (this *Solution) Reset() []int {\n\treturn this.NumOrigin\n}", "func (board *Board) Solve() (solved bool, err error) {\n\tcounter := 0\n\tx, y := 0, 0\n\tsolved = false\n\tfor solved == false {\n\t\tif counter%10000000 == 0 {\n\t\t\tfmt.Printf(\"(%v), At [%v,%v]\\n\", counter, x, y)\n\t\t\tfmt.Print(board.Show())\n\t\t}\n\t\tcounter++\n\t\tvalid := board.setNextValue(x, y)\n\t\t// valid is true when cell fixed or cell not fixed but set to 0 or 1\n\t\tif valid && board.isBoardStillValid(x, y) {\n\t\t\t// fmt.Println(\"isBoardStillValid is true\")\n\t\t\tx, y, err = board.getNextXY(x, y)\n\t\t\tif err != nil {\n\t\t\t\t// Fell of the end of the board... solved !!!\n\t\t\t\tfmt.Println(\"Solved!\")\n\t\t\t\tsolved = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else {\n\t\t\t//fmt.Println(\"isBoardStillValid is false\")\n\t\t\tif valid && !board.cells[y][x].fixed {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tx, y, err = board.getPreviousXY(x, y)\n\t\t\tif err != nil {\n\t\t\t\t// Fell of the beginning of the board... NO solution\n\t\t\t\tsolved = false\n\t\t\t\tfmt.Println(\"No solution found\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Printf(\"counter=%v, solved=%v \\n\", counter, solved)\n\treturn solved, err\n}", "func (arr *Array) Copy() *Array {\n\tcpy := make([]int, len(arr.elems))\n\tcopy(cpy, arr.hashs)\n\treturn &Array{\n\t\telems: termSliceCopy(arr.elems),\n\t\thashs: cpy,\n\t\thash: arr.hash,\n\t\tground: arr.IsGround()}\n}", "func (this *SolutionShuffle) Reset() []int {\n\treturn this.origin\n}", "func bruteForceGuess(grid [][]int) ([][]int, error) {\n\tss, err := NewSquares(grid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// poss := getEmptyPositions(grid)\n\tcopyGrid := func(grid [][]int) [][]int {\n\t\ttempGrid := make([][]int, len(grid))\n\t\tfor i := range grid {\n\t\t\ttempGrid[i] = make([]int, len(grid[i]))\n\t\t\tcopy(tempGrid[i], grid[i])\n\t\t}\n\t\treturn tempGrid\n\t}\n\n\ttempGrid := copyGrid(grid)\n\n\tfor _, s := range ss {\n\t\tif len(s.possibleNums) == 1 {\n\t\t\ttempGrid[s.pos.rowNumber][s.pos.colNumber] = s.possibleNums[0]\n\t\t}\n\n\t\tif err := traverseAdjacent(tempGrid, s); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcg := CheckGrid(tempGrid)\n\t\tif !cg.Valid {\n\t\t\ttempGrid = copyGrid(grid)\n\t\t\tcontinue\n\t\t}\n\t\tif cg.Complete {\n\t\t\treturn tempGrid, nil\n\t\t}\n\t}\n\treturn grid, nil\n}", "func solvedNoPossible(cluster []cell) (changes []cell) {\n\tfor id, each := range cluster {\n\t\tif each.actual != 0 && len(each.excluded) < len(fullArray) {\n\t\t\tnewExclusion := subArr(fullArray, each.excluded)\n\t\t\tchanges = append(changes, cell{location: each.location, excluded: newExclusion})\n\t\t}\n\t}\n\treturn\n}", "func TestSudoku(t *testing.T) {\n\n\t// initialize variables\n\tvars := make(Variables[int], 0)\n\tconstraints := make(Constraints[int], 0)\n\n\tletters := [9]string{\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\"}\n\ttenDomain := IntRange(1, 10)\n\n\t// configure variables and block constraints\n\tfor _, letter := range letters {\n\t\tletterVars := make(VariableNames, 0)\n\t\tfor i := 1; i <= 9; i++ {\n\t\t\tvarName := VariableName(letter + strconv.Itoa(i))\n\t\t\t// add vars like A1, A2, A3 ... A9, B1, B2, B3 ... B9 ... I9\n\t\t\tvars = append(vars, NewVariable(varName, tenDomain))\n\t\t\tletterVars = append(letterVars, varName)\n\t\t}\n\t\t// for each block, add uniqueness constraint within block\n\t\tconstraints = append(constraints, AllUnique[int](letterVars...)...)\n\t}\n\n\t// add horizontal constraints\n\trowLetterSets := [3][3]string{{\"A\", \"B\", \"C\"}, {\"D\", \"E\", \"F\"}, {\"G\", \"H\", \"I\"}}\n\trowNumberSets := [3][3]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}\n\tfor _, letterSet := range rowLetterSets {\n\t\tfor _, numberSet := range rowNumberSets {\n\t\t\trowVarNames := make(VariableNames, 0)\n\t\t\tfor _, letter := range letterSet {\n\t\t\t\tfor _, number := range numberSet {\n\t\t\t\t\tvarName := VariableName(letter + strconv.Itoa(number))\n\t\t\t\t\trowVarNames = append(rowVarNames, varName)\n\t\t\t\t}\n\t\t\t}\n\t\t\t// add uniqueness constraints\n\t\t\tconstraints = append(constraints, AllUnique[int](rowVarNames...)...)\n\t\t}\n\t}\n\n\t// add vertical constraints\n\tcolumnLetterSets := [3][3]string{{\"A\", \"D\", \"G\"}, {\"B\", \"E\", \"H\"}, {\"C\", \"F\", \"I\"}}\n\tcolumnNumberSets := [3][3]int{{1, 4, 7}, {2, 5, 8}, {3, 6, 9}}\n\tfor _, letterSet := range columnLetterSets {\n\t\tfor _, numberSet := range columnNumberSets {\n\t\t\tcolumnVarNames := make(VariableNames, 0)\n\t\t\tfor _, letter := range letterSet {\n\t\t\t\tfor _, number := range numberSet {\n\t\t\t\t\tvarName := VariableName(letter + strconv.Itoa(number))\n\t\t\t\t\tcolumnVarNames = append(columnVarNames, varName)\n\t\t\t\t}\n\t\t\t}\n\t\t\t// add uniqueness constraints\n\t\t\tconstraints = append(constraints, AllUnique[int](columnVarNames...)...)\n\t\t}\n\t}\n\t// set values already known\n\tvars.SetValue(\"A1\", 5)\n\tvars.SetValue(\"A2\", 3)\n\tvars.SetValue(\"A4\", 6)\n\tvars.SetValue(\"A8\", 9)\n\tvars.SetValue(\"A9\", 8)\n\tvars.SetValue(\"B2\", 7)\n\tvars.SetValue(\"B4\", 1)\n\tvars.SetValue(\"B5\", 9)\n\tvars.SetValue(\"B6\", 5)\n\tvars.SetValue(\"C8\", 6)\n\tvars.SetValue(\"D1\", 8)\n\tvars.SetValue(\"D4\", 4)\n\tvars.SetValue(\"D7\", 7)\n\tvars.SetValue(\"E2\", 6)\n\tvars.SetValue(\"E4\", 8)\n\tvars.SetValue(\"E6\", 3)\n\tvars.SetValue(\"E8\", 2)\n\tvars.SetValue(\"F3\", 3)\n\tvars.SetValue(\"F6\", 1)\n\tvars.SetValue(\"F9\", 6)\n\tvars.SetValue(\"G2\", 6)\n\tvars.SetValue(\"H4\", 4)\n\tvars.SetValue(\"H5\", 1)\n\tvars.SetValue(\"H6\", 9)\n\tvars.SetValue(\"H8\", 8)\n\tvars.SetValue(\"I1\", 2)\n\tvars.SetValue(\"I2\", 8)\n\tvars.SetValue(\"I6\", 5)\n\tvars.SetValue(\"I8\", 7)\n\tvars.SetValue(\"I9\", 9)\n\n\t// create solver\n\tsolver := NewBackTrackingCSPSolver(vars, constraints)\n\n\t// simplify variable domains following initial assignment\n\tsolver.State.MakeArcConsistent(context.TODO())\n\tsuccess, err := solver.Solve(context.TODO()) // run the solution\n\tassert.Nil(t, err)\n\n\tassert.True(t, success)\n\n\t// check that we have a valid sudoku solution\n\n\tfor _, letterSet := range rowLetterSets {\n\t\tfor _, numberSet := range rowNumberSets {\n\t\t\tsum := 0\n\t\t\tfor _, letter := range letterSet {\n\t\t\t\tfor _, number := range numberSet {\n\t\t\t\t\tvarName := VariableName(letter + strconv.Itoa(number))\n\t\t\t\t\tvariable := solver.State.Vars.Find(varName)\n\t\t\t\t\tsum += variable.Value\n\t\t\t\t}\n\t\t\t}\n\t\t\tassert.Equal(t, 45, sum)\n\t\t}\n\t}\n\n\tfor _, letterSet := range columnLetterSets {\n\t\tfor _, numberSet := range columnNumberSets {\n\t\t\tsum := 0\n\t\t\tfor _, letter := range letterSet {\n\t\t\t\tfor _, number := range numberSet {\n\t\t\t\t\tvarName := VariableName(letter + strconv.Itoa(number))\n\t\t\t\t\tvariable := solver.State.Vars.Find(varName)\n\t\t\t\t\tsum += variable.Value\n\t\t\t\t}\n\t\t\t}\n\t\t\tassert.Equal(t, 45, sum)\n\t\t}\n\t}\n\n\tfor _, letter := range letters {\n\t\tsum := 0\n\t\tfor num := 1; num <= 9; num++ {\n\t\t\tvarName := VariableName(letter + strconv.Itoa(num))\n\t\t\tvariable := solver.State.Vars.Find(varName)\n\t\t\tsum += variable.Value\n\t\t}\n\t\tassert.Equal(t, 45, sum)\n\t}\n\n}", "func updateMatrix(matrix [][]int) [][]int {\n if len(matrix) == 0 {\n return matrix\n }\n\n q := [][]int{}\n\n push := func(x,y int) {\n q = append(q,[]int{x,y})\n }\n\n pull := func() (int,int) {\n if len(q) == 0 {\n return -1,-1\n }\n\n out := q[0]\n q = q[1:]\n return out[0],out[1]\n }\n\n out := make([][]int,len(matrix))\n for i := range matrix {\n out[i] = make([]int,len(matrix[i]))\n for j := range matrix[i] {\n if matrix[i][j] == 0 {\n out[i][j] = 0\n push(i,j)\n } else {\n out[i][j] = -1\n }\n }\n }\n\n for len(q) > 0 {\n i,j := pull()\n if i + 1 < len(out) && out[i+1][j] == -1 {\n out[i+1][j] = out[i][j] + 1\n push(i+1,j)\n }\n if i > 0 && out[i-1][j] == -1 {\n out[i-1][j] = out[i][j] + 1\n push(i-1,j)\n }\n if j + 1 < len(out[i]) && out[i][j+1] == -1 {\n out[i][j+1] = out[i][j] + 1\n push(i,j+1)\n }\n if j > 0 && out[i][j-1] == -1 {\n out[i][j-1] = out[i][j] + 1\n push(i,j-1)\n }\n }\n\n return out\n}", "func (s *Sudoku) fillSolutionCell(a, b, solution uint8) {\n s.solution[a][b] = solution\n fillFalse9(&s.markerTable[a][b])\n s.correctMarkersBasedOnCellSolution(a, b)\n}", "func (s *Solver) Solve(cap currency.Value) []Entry {\n\tvar soln []Entry\n\n\tns := s.init(cap)\n\tfor i, col := range s.table {\n\t\tif ns > 0 {\n\t\t\tsoln = append(soln, s.entries[i].take(ns))\n\t\t}\n\t\tns = col[ns].Next\n\t}\n\tif ns != 0 {\n\t\tpanic(\"nonzero offset at end\")\n\t}\n\treturn soln\n}", "func (this *Solution) Shuffle() []int {\n\tvar temp []int\n\tresult := []int{}\n\tif len(this.changed) == 0 {\n\t\ttemp = this.initial\n\t} else {\n\t\ttemp = this.changed\n\t}\n\tfor i, d := range temp {\n\t\tif i == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, d)\n\t}\n\tresult = append(result, temp[0])\n\tthis.changed = result\n\treturn result\n}", "func Test_isValidSudoku1(t *testing.T) {\n\tboard := [][]byte{\n\t\t{'8','3','.', '.','7','.', '.','.','.'},\n\t\t{'6','.','.', '1','9','5', '.','.','.'},\n\t\t{'.','9','8', '.','.','.', '.','6','.'},\n\t\t{'8','.','.', '.','6','.', '.','.','3'},\n\t\t{'4','.','.', '8','.','3', '.','.','1'},\n\t\t{'7','.','.', '.','2','.', '.','.','6'},\n\t\t{'.','6','.', '.','.','.', '2','8','.'},\n\t\t{'.','.','.', '4','1','9', '.','.','5'},\n\t\t{'.','.','.', '.','8','.', '.','7','9'},\n\t}\n\tgot := isValidSudoku(board)\n\tfmt.Println(fmt.Sprintf(\"isValidSudoku result is %v\", got))\n\ttime.Sleep(1 * time.Second)\n}", "func runSolver(cmd *cobra.Command, args []string) error {\n\tvar matrix [][]int\n\n\tif filename != \"\" {\n\t\tf, err := os.Open(filename)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\n\t\te := json.NewDecoder(f)\n\t\tif err := e.Decode(&matrix); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else if interactive == true {\n\t\tvar err error\n\t\tm, err := NewInteractiveMatrixGenerator()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tm.Run()\n\t\tmatrix = m.Matrix\n\t} else if cmd.Flag(\"size\").Changed {\n\t\tt := Random\n\t\tif constness == \"constant\" {\n\t\t\tt = Constant\n\t\t}\n\n\t\tm := NewManualMatrixGenerator(size, t)\n\t\tm.Run()\n\t\tmatrix = m.Matrix\n\t} else {\n\t\t// Stdin will be used.\n\t\te := json.NewDecoder(os.Stdin)\n\t\tif err := e.Decode(&matrix); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ts := lapjv.Lapjv(matrix)\n\tfmt.Printf(\"Matrix resolution : \\n\\tCost : \\t\\t%d\\n\\tRow solution : \\t%v\\n\\tCol solution : \\t%v\\n\", s.Cost, s.InRow, s.InCol)\n\n\treturn nil\n}", "func (sudoku *Sudoku) solve() bool {\n\n\t// Step 1: Try deduction. Use mulitple mechanisms and repeat them until none of them\n\t// yield any result.\n\tfor {\n\t\tnakedSingleCouldProgress := sudoku.deduce_nakedSingle()\n\t\thiddenSingleCouldProgress := sudoku.deduce_hiddenSingle()\n\n\t\tif !nakedSingleCouldProgress && !hiddenSingleCouldProgress {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// otherwise we tryAndError\n\tsudoku.tryAndError()\n\n\tif sudoku.hasZeros() == false {\n\n\t\tif sudoku.hasConflict() == false {\n\t\t\tsudoku.solved = true\n\t\t\treturn false\n\t\t}\n\n\t\treturn true\n\t}\n\n\n\treturn true\n}", "func buildArray(nums []int) []int {\n\t// TODO (tai): slow, solve with O(1) space\n\tans := make([]int, len(nums))\n\tfor i, v := range nums {\n\t\tans[i] = nums[v]\n\t}\n\treturn ans\n}", "func buildArray(nums []int) []int {\n\tvar outArr []int\n\tfor k := range nums {\n\t\toutArr = append(outArr, nums[nums[k]])\n\t}\n\ta := 7\n\tb := 2\n\to := a / b\n\tfmt.Println(\"--->ans\", o)\n\n\treturn outArr\n}", "func (this *Solution) Shuffle() []int {\n\tarrLen := len(this.Arr)\n\tna := make([]int, arrLen, arrLen)\n\tcopy(na, this.Arr)\n\trand.Shuffle(arrLen, func(i, j int) {\n\t\tna[i], na[j] = na[j], na[i]\n\t})\n\treturn na\n}", "func get_row(row int, matrix [][]int) []int {\n var nums = make([]int, 9, 9)\n\n count := 0\n for i := 0; i < 9; i++ {\n nums[count] = matrix[row][i]\n count++\n }\n return nums\n}", "func example_box_of_squares() {\n\n // print_board(\"unsolved/board_easy_1.csv\")\n // fmt.Println()\n\n m := make_board(\"unsolved/board_easy_1.csv\")\n\n print_matrix(m)\n\n fmt.Println()\n lb := get_local_box_numbers(3, 5, m)\n fmt.Println(lb)\n\n fmt.Println()\n r := get_row(3, m)\n fmt.Println(r)\n\n fmt.Println()\n c := get_col(3, m)\n fmt.Println(c)\n\n}", "func validateSolution(b Game) {\n\tfor row := 0; row < DIM; row++ {\n\t\tfor col := 0; col < DIM; col++ {\n\t\t\t// Hold on to the move for this cell\n\t\t\texpect := b.board[row][col]\n\t\t\t// Reset move and check that the expected move is in the candidate list\n\t\t\tb.board[row][col] = 0\n\t\t\tcandidates := b.CellCandidates(row, col)\n\t\t\tif !candidates[expect] {\n\t\t\t\tfmt.Printf(\"Invalid value %v at row %v, col %v\\n\", expect, row+1, col+1)\n\t\t\t}\n\t\t}\n\t}\n}", "func cloneArray(source []int) []int {\n\tn := len(source)\n\tdestination := make([]int, n, n)\n\tcopy(source, destination)\n\treturn destination\n}", "func (this *Solution) Reset() []int {\n\treturn this.seq\n}", "func (b Board) deepCopy() Board {\n\tc := new(Board)\n\tfor x := startSquare; x <= endSquare; x++ {\n\t\tfor y := startSquare; y <= endSquare; y++ {\n\t\t\tif b.squares[x][y] == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc.squares[x][y] = b.squares[x][y].deepCopy(c)\n\t\t}\n\t}\n\n\treturn *c\n}", "func (s *Solver) Solve(m [][]types.Distance) ([]types.Index, types.Distance, error) {\n\tsize := len(m)\n\n\tif size == 0 {\n\t\treturn nil, 0, errors.New(\"Distance matrix is empty\")\n\t}\n\n\tfor i := range m {\n\t\tif len(m[i]) != size {\n\t\t\treturn nil, 0, errors.New(\"Distance matrix is not square\")\n\t\t}\n\t}\n\n\ts.matrix = m\n\ts.bestSolution = []types.Index{}\n\ts.bestSolutionDistance = 0\n\ts.taskQueue = tasks.NewHeapQueue()\n\n\trootTask := tasks.Task{\n\t\tPath: []types.Index{0},\n\t\tDistance: 0,\n\t\tEstimate: 0,\n\t}\n\ts.taskQueue.Insert([]tasks.Task{rootTask})\n\n\ts.solveParallel()\n\n\treturn s.bestSolution, s.bestSolutionDistance, nil\n}", "func (b *Board) copy() *Board {\n\tnewBoard := &Board{\n\t\tPlayer1: make([]Square, len(b.Player1)),\n\t\tPlayer2: make([]Square, len(b.Player2)),\n\t\tresult: b.result,\n\t}\n\tfor i := range b.Player1 {\n\t\tnewBoard.Player1[i] = b.Player1[i]\n\t}\n\tfor i := range b.Player2 {\n\t\tnewBoard.Player2[i] = b.Player2[i]\n\t}\n\treturn newBoard\n}", "func Solution(A []int, K int) []int {\n lengthA := len(A)\n result := make([]int, lengthA)\n \n if K < 1 || len(A) == 0{\n return A\n }else{\n result[0] = A[lengthA-1] \n counter := 1\n //Iterate throught the original array, append to result array\n for x := 0; x < lengthA -1; x++{\n result[counter] = A[x]\n counter ++\n }\n result = Solution(result, K -1)\n \n }\n \n return result\n}", "func Solve(params Parameters, chunks [][]byte, goal []byte) ([]byte, uint32, error) {\n\tif err := params.Validate(); err != nil {\n\t\treturn nil, 0, errors.Wrap(err, \"invalid parameters\")\n\t}\n\tif len(chunks) == 0 {\n\t\treturn nil, 0, errors.New(\"must have at least one chunk\")\n\t}\n\tif len(goal) != sha512.Size384 {\n\t\treturn nil, 0, errors.New(\"goal value must be a SHA-384 digest; its length is wrong\")\n\t}\n\tif params.Rounds*uint32(len(chunks)) <= 1 {\n\t\t// XXX: Using a single round and a single cache is a silly idea, but `runPuzzle` will fail with those inputs.\n\t\treturn nil, 0, errors.New(\"must use at least two puzzle iterations; increase number of rounds or caches\")\n\t}\n\n\tgetBlockFn := func(chunkIdx, offset uint32) ([]byte, error) {\n\t\toffset = offset % uint32(len(chunks[chunkIdx])/aes.BlockSize)\n\t\treturn chunks[chunkIdx][offset*aes.BlockSize : (offset+1)*aes.BlockSize], nil\n\t}\n\n\t// Try all possible starting offsets and look for one that produces the result/goal value we're looking for.\n\tfor offset := uint32(0); offset < uint32(len(chunks[0])/aes.BlockSize); offset++ {\n\t\tresult, secret, err := runPuzzle(params.Rounds, uint32(len(chunks)), offset, getBlockFn)\n\t\tif err != nil {\n\t\t\treturn nil, 0, errors.Wrap(err, \"failed to run puzzle\")\n\t\t}\n\t\tif bytes.Equal(goal, result) {\n\t\t\treturn secret, offset, nil\n\t\t}\n\t}\n\n\treturn nil, 0, errors.New(\"no solution found\")\n\n}", "func (s *Solution) Reset() *Solution {\n\tr := s.Clone()\n\tr.reset()\n\tr.Coins = []int{}\n\tr.Weights = []Weight{}\n\tr.flags = INVALID\n\tr.encoding.Flip = nil\n\treturn r\n}", "func solve(n string, k int) int {\n\t//var dp [102][4][2]int\n\tl := len(n)\n\tdp := make([][][]int, l+1)\n\tfor i := range dp {\n\t\tdp[i] = make([][]int, 4)\n\t\tfor j := range dp[i] {\n\t\t\tdp[i][j] = make([]int, 2)\n\t\t}\n\t}\n\tdp[0][0][0] = 1\n\tfor i := 0; i < l; i++ {\n\t\tfor j := 0; j < 4; j++ {\n\t\t\tfor p := 0; p < 2; p++ {\n\t\t\t\tf := int(n[i] - '0')\n\t\t\t\tfor d := 0; d < 10; d++ {\n\t\t\t\t\tni, nj, np := i+1, j, p\n\t\t\t\t\tif d > 0 {\n\t\t\t\t\t\tnj++\n\t\t\t\t\t}\n\t\t\t\t\tif nj > k {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif p == 0 {\n\t\t\t\t\t\tswitch {\n\t\t\t\t\t\tcase d < f:\n\t\t\t\t\t\t\tnp = 1\n\t\t\t\t\t\tcase d > f:\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdp[ni][nj][np] += dp[i][j][p]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tdebugf(\"%v\\n\", dp)\n\n\treturn dp[l][k][0] + dp[l][k][1]\n}", "func (c *Cuckoo) PoW(siphashKey []byte) ([]uint32, bool) {\n\tfor i := 0; i < c.ncpu; i++ {\n\t\tfor x := 0; x < nx; x++ {\n\t\t\tc.m2[i][x] = c.m2[i][x][:0]\n\t\t}\n\t}\n\t//fmt.Printf(\"PoW() c.m2 = %v\\n\",c.m2)\n\n\tfor x := 0; x < nx; x++ {\n\t\tfor y := 0; y < nx; y++ {\n\t\t\tc.matrix[x][y] = c.matrix[x][y][:0]\n\t\t}\n\t}\n\t//fmt.Printf(\"PoW() c.matrix = %v\\n\",c.matrix)\n\n\tfor i := range c.cuckoo {\n\t\tc.cuckoo[i] = 0\n\t}\n\n\t//\n\tc.sip = siphash.Newsip(siphashKey)\n\n\t//fmt.Printf(\"before buildU() c.matrix = %v\\n\",c.matrix)\n\tc.buildU()\n\t//fmt.Printf(\"after buildU() c.matrix = %v\\n\",c.matrix)\n\tc.buildV()\n\t//fmt.Printf(\"after buildV() c.matrix = %v\\n\",c.matrix)\n\n\tc.trimmimng()\n\n\tfor _, ux := range c.matrix {\n\t\tfor _, m := range ux {\n\t\t\tfor _, uv := range m {\n\t\t\t\tu := uint32(uv>>32) << 1\n\t\t\t\tv := (uint32(uv) << 1) | 1\n\t\t\t\tus, err1 := c.path(u, c.us)\n\t\t\t\tvs, err2 := c.path(v, c.vs)\n\t\t\t\tif err1 != nil || err2 != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif us[len(us)-1] == vs[len(vs)-1] {\n\t\t\t\t\tif ans, ok := c.solution(us, vs); ok {\n\t\t\t\t\t\treturn ans, true\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif len(us) < len(vs) {\n\t\t\t\t\tfor nu := len(us) - 2; nu >= 0; nu-- {\n\t\t\t\t\t\tc.cuckoo[us[nu+1]&xycomp1mask] = us[nu]\n\t\t\t\t\t}\n\t\t\t\t\tc.cuckoo[u&xycomp1mask] = v\n\t\t\t\t} else {\n\t\t\t\t\tfor nv := len(vs) - 2; nv >= 0; nv-- {\n\t\t\t\t\t\tc.cuckoo[vs[nv+1]&xycomp1mask] = vs[nv]\n\t\t\t\t\t}\n\t\t\t\t\tc.cuckoo[v&xycomp1mask] = u\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, false\n}", "func loop_map(index int, res *[][]int, nums []int) {\n\n}", "func (m Array) Clone() Node {\n\tout := make(Array, 0, len(m))\n\tfor _, v := range m {\n\t\tout = append(out, v.Clone())\n\t}\n\treturn out\n}", "func getSquares(num int, sum bool) []Square {\n /*\n num: how many squares to make\n sum: whether or not to use the \"summation\" method described in Part 2 of the problem\n */\n grid := make([]Square, num)\n direction := [2]int{0, -1}\n // the change in coordinates + or - 1 or 0\n var x, y, value int\n // x and y are the locations of the squares, value is the number it displays\n distance := 1\n // distance is how long it will keep going that direction\n distance_counter := 0\n // how long it has been going in that direction so far.\n\n\n for i, _ := range grid {\n // if value - 1 (or i) is a square number, distance will be increased and direction will change\n root := math.Sqrt(float64(i))\n if root == float64(int(root)) {\n // if that square is odd, direction will be ->, and if it's even direction will be <-\n // also the distance will go up (or is this in the other case? )\n direction = getNextDirection(direction)\n distance_counter = 0\n } else if distance == distance_counter {\n distance++\n direction = getNextDirection(direction)\n distance_counter = 0\n // change direction\n }\n\n\n if sum {\n if i == 0 {\n value = 1\n } else {\n for j := 0; j < i - 1; j++ {\n compare := grid[j]\n if (compare.X >= x - 1 && compare.X <= x + 1) && (compare.Y >= y - 1 && compare.Y <= y + 1) {\n value += compare.Value\n }\n }\n }\n } else {\n value = i + 1\n }\n grid[i] = Square{x, y, value}\n\n if sum && value > num {\n grid := grid[0:i+1]\n return grid\n }\n\n // change x and y appropriately\n x += direction[0]\n y += direction[1]\n distance_counter++\n }\n return grid\n}", "func sol2(nums []int, target int) []int {\n\tmemo := make(map[int]int)\n\tfor i, n := range nums {\n\t\tmemo[n] = i\n\t}\n\tfor i, n := range nums {\n\t\tif _, ok := memo[target-n]; ok && i != memo[target-n] {\n\t\t\treturn []int{i, memo[target-n]}\n\t\t}\n\t}\n\treturn nil\n}", "func (f *Field) Solve() bool {\n\t// if newly solved, return true\n\tif !f.Solvable() {\n\t\treturn false\n\t}\n\tfor i := 1; i <= f.sudoku.MaxValue; i++ {\n\t\tif !f.NonValues.Contains(i) {\n\t\t\tf.sudoku.addSolution(f, i)\n\t\t\tbreak\n\t\t}\n\t}\n\treturn true\n}", "func sol1(nums []int, target int) []int {\n\tfor i, n := range nums {\n\t\tfor j, m := range nums {\n\t\t\tif i == j {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif n+m == target {\n\t\t\t\treturn []int{i, j}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func main() {\n\n\tinput := []int{1, 1, 0, 1, 1, 1}\n\n\tresult := solution(input)\n\tfmt.Println(result)\n\n}", "func (p *Puzzle) reset() {\n\tfor i, _ := range p.Board {\n\t\tp.Board[i] = 0\n\t}\n}", "func restoreMatrix(rowSum []int, colSum []int) [][]int {\n\tm := len(rowSum)\n\tn := len(colSum)\n\n\tarr := make([][]int, 0, m)\n\tfor i := 0; i < m; i++ {\n\t\tarr = append(arr, make([]int, n))\n\t}\n\n\tx, y := 0, 0\n\tfor x < n && y < m {\n\t\ta := colSum[x]\n\t\tb := rowSum[y]\n\t\tt := a\n\t\tif t > b {\n\t\t\tt = b\n\t\t}\n\n\t\tarr[y][x] = t\n\t\tcolSum[x] -= t\n\t\trowSum[y] -= t\n\t\tif colSum[x] == 0 {\n\t\t\tx++\n\t\t}\n\n\t\tif rowSum[y] == 0 {\n\t\t\ty++\n\t\t}\n\t}\n\n\treturn arr\n}", "func Solve(words, puzzle []string) (map[string][2][2]int, error) {\n\t// search looks for word w starting at position (i, j).\n\tsearch := func(w string, i, j int) (bool, int, int) {\n\t\tfor dI := -1; dI < 2; dI++ {\n\t\t\tfor dJ := -1; dJ < 2; dJ++ {\n\t\t\t\t// If they're both zero, we're not searching for anything.\n\t\t\t\tif dI == 0 && dJ == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// Copy i and j so I can mess with them, and make a word index.\n\t\t\t\ttI, tJ := i, j\n\t\t\t\twI := 0\n\t\t\t\tfor ; wI < len(w); wI, tI, tJ = wI+1, tI+dI, tJ+dJ {\n\t\t\t\t\t// Make sure tI and tJ are valid puzzle positions.\n\t\t\t\t\tif tI < 0 || tI >= len(puzzle) || tJ < 0 || tJ >= len(puzzle[0]) {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tif w[wI] != puzzle[tI][tJ] {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif wI == len(w) {\n\t\t\t\t\treturn true, tI - dI, tJ - dJ\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false, 0, 0\n\t}\n\n\t// Make the map I'll return, and loop through the words searching for them.\n\tret := make(map[string][2][2]int)\n\tfor _, w := range words {\n\t\tvar sI, sJ, eI, eJ int\n\t\tfound := false\n\t\tfor i := 0; i < len(puzzle) && !found; i++ {\n\t\t\tfor j := 0; j < len(puzzle[0]) && !found; j++ {\n\t\t\t\tsI, sJ = i, j\n\t\t\t\tfound, eI, eJ = search(w, i, j)\n\t\t\t}\n\t\t}\n\t\tif found {\n\t\t\tret[w] = [2][2]int{[2]int{sJ, sI}, [2]int{eJ, eI}}\n\t\t} else {\n\t\t\tret[w] = [2][2]int{[2]int{-1, -1}, [2]int{-1, -1}}\n\t\t}\n\t}\n\treturn ret, nil\n}", "func copyMatrix(m [][]int) [][]int {\n\tvar matrix [][]int\n\tfor _, row := range m {\n\t\tnewRow := make([]int, len(row))\n\t\tcopy(newRow, row)\n\t\tmatrix = append(matrix, newRow)\n\t}\n\treturn matrix\n}", "func (s *square) getPossibleNumbers(grid [][]int) error {\n\ts.possibleNums = []int{}\n\tpossibleNumbers := map[int]bool{}\n\tfor i := 1; i <= 9; i++ {\n\t\tpossibleNumbers[i] = true\n\t}\n\n\t// check the row it is on\n\tfor col := 0; col <= 8; col++ {\n\t\tpossibleNumbers[grid[s.pos.rowNumber][col]] = false\n\t}\n\n\t// check the column it is in\n\tfor row := 0; row <= 8; row++ {\n\t\tpossibleNumbers[grid[row][s.pos.colNumber]] = false\n\t}\n\n\t// Check the grid it is in\n\tfor row := s.reg.minRowNumber; row <= s.reg.maxRowNumber; row++ {\n\t\tfor col := s.reg.minColNumber; col <= s.reg.maxColNumber; col++ {\n\t\t\tpossibleNumbers[grid[row][col]] = false\n\t\t}\n\t}\n\n\tfor num, stillPossible := range possibleNumbers {\n\t\tif stillPossible {\n\t\t\ts.possibleNums = append(s.possibleNums, num)\n\t\t}\n\t}\n\treturn nil\n}", "func formingMagicSquare(s [][]int32) int32 {\n\tmagicSquares := []*magicSquare{}\n\tmagicSquares = append(magicSquares, &magicSquare{\n\t\tmatrix: [][]int32{\n\t\t\t{8, 1, 6},\n\t\t\t{3, 5, 7},\n\t\t\t{4, 9, 2},\n\t\t},\n\t})\n\tmagicSquares = append(magicSquares, &magicSquare{\n\t\tmatrix: [][]int32{\n\t\t\t{6, 1, 8},\n\t\t\t{7, 5, 3},\n\t\t\t{2, 9, 4},\n\t\t},\n\t})\n\tmagicSquares = append(magicSquares, &magicSquare{\n\t\tmatrix: [][]int32{\n\t\t\t{4, 9, 2},\n\t\t\t{3, 5, 7},\n\t\t\t{8, 1, 6},\n\t\t},\n\t})\n\tmagicSquares = append(magicSquares, &magicSquare{\n\t\tmatrix: [][]int32{\n\t\t\t{2, 9, 4},\n\t\t\t{7, 5, 3},\n\t\t\t{6, 1, 8},\n\t\t},\n\t})\n\tmagicSquares = append(magicSquares, &magicSquare{\n\t\tmatrix: [][]int32{\n\t\t\t{8, 3, 4},\n\t\t\t{1, 5, 9},\n\t\t\t{6, 7, 2},\n\t\t},\n\t})\n\tmagicSquares = append(magicSquares, &magicSquare{\n\t\tmatrix: [][]int32{\n\t\t\t{4, 3, 8},\n\t\t\t{9, 5, 1},\n\t\t\t{2, 7, 6},\n\t\t},\n\t})\n\tmagicSquares = append(magicSquares, &magicSquare{\n\t\tmatrix: [][]int32{\n\t\t\t{6, 7, 2},\n\t\t\t{1, 5, 9},\n\t\t\t{8, 3, 4},\n\t\t},\n\t})\n\tmagicSquares = append(magicSquares, &magicSquare{\n\t\tmatrix: [][]int32{\n\t\t\t{2, 7, 6},\n\t\t\t{9, 5, 1},\n\t\t\t{4, 3, 8},\n\t\t},\n\t})\n\n\tminCost := int32(1000)\n\n\tfor _, v := range magicSquares {\n\t\tcost := int32(0)\n\t\tfor i := 0; i < 3; i++ {\n\t\t\tfor j := 0; j < 3; j++ {\n\t\t\t\tcost += int32(math.Abs(float64(s[i][j]) - float64(v.matrix[i][j])))\n\t\t\t}\n\t\t}\n\t\tif cost < minCost {\n\t\t\tminCost = cost\n\t\t}\n\t}\n\n\treturn minCost\n}", "func (s *Smart) Solve(g *Grid) (string, error) {\n\treturn \"Smart Solution\", nil\n}", "func (this *Solution) Shuffle() []int {\n\t// 随机交换元素的位置\n\ttmp := make([]int, len(this.a))\n\tcopy(tmp, this.a)\n\tfor i := 0; i < len(tmp); i++ {\n\t\tr := rand.Intn(len(tmp))\n\t\ttmp[i], tmp[r] = tmp[r], tmp[i]\n\t}\n\treturn tmp\n}", "func makeSquare(arr []int) []int {\n\tn := len(arr)\n\tsquares := make([]int, n)\n\tleftPoint, rightPoint, highestIndex := 0, n-1, n-1\n\tfor leftPoint <= rightPoint {\n\t\tleftSquare := arr[leftPoint] * arr[leftPoint]\n\t\trightSquare := arr[rightPoint] * arr[rightPoint]\n\n\t\tif leftSquare > rightSquare {\n\t\t\tsquares[highestIndex] = leftSquare\n\t\t\tleftPoint++\n\t\t} else {\n\t\t\tsquares[highestIndex] = rightSquare\n\t\t\trightPoint--\n\t\t}\n\t\thighestIndex--\n\t}\n\treturn squares\n}", "func Sudoku(line string) (time.Duration, string) {\n\tstartTime := time.Now()\n\tgrid := generateGrid()\n\tconvertToGrid(grid, line)\n\tfor !solved(grid) {\n\t\tfindMissingValuesAtEachCell(grid)\n\t\tcleanUpEachRow(grid)\n\t\tfindMissingValuesAtEachCell(grid)\n\t\tcleanUpEachColumn(grid)\n\t\tfindMissingValuesAtEachCell(grid)\n\t\tcleanUpGrid(grid)\n\t}\n\t// displayGridRowBsyRow(grid)\n\t// displayGrid(grid)\n\treturn time.Now().Sub(startTime), convertToLine(grid)\n}", "func makeMatrix(x, y int) [][]score {\n\tmatrix := make([][]score, y)\n\tfor i := range matrix {\n\t\trow := make([]score, x)\n\t\tmatrix[i] = row\n\t}\n\treturn matrix\n}", "func isValidSudoku(board [][]byte) bool {\n\trow := [9][9]int{[9]int{}, [9]int{}, [9]int{}, [9]int{}, [9]int{}, [9]int{}, [9]int{}, [9]int{}, [9]int{}}\n\tcol := [9][9]int{[9]int{}, [9]int{}, [9]int{}, [9]int{}, [9]int{}, [9]int{}, [9]int{}, [9]int{}, [9]int{}}\n\tsub := [9][9]int{[9]int{}, [9]int{}, [9]int{}, [9]int{}, [9]int{}, [9]int{}, [9]int{}, [9]int{}, [9]int{}}\n\n\tfor i := 0; i < 9; i++ {\n\t\tfor j := 0; j < 9; j++ {\n\t\t\tif board[i][j] == '.' {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvalue := board[i][j] - '1'\n\t\t\tsubBox := (i/3)*3 + (j / 3)\n\t\t\tif row[i][value] == 0 && col[j][value] == 0 && sub[subBox][value] == 0 {\n\t\t\t\trow[i][value] += 1\n\t\t\t\tcol[j][value] += 1\n\t\t\t\tsub[subBox][value] += 1\n\t\t\t} else {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}", "func (i *iteration) solve() error {\n\tfor cellIndex := i.index; ; cellIndex++ {\n\t\tcell := i.cells[cellIndex]\n\t\tif cell.fixed {\n\t\t\tcontinue\n\t\t}\n\t\ti.index = cellIndex\n\n\t\tnextValue, err := i.findNextValue(cell, i.minValue)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ti.minValue = nextValue\n\t\tcell.value = nextValue\n\t\treturn nil\n\t}\n}", "func newIteration(items []int, puzzleSize int, sectionSize int) *iteration {\n\trows := make([][]int, puzzleSize)\n\tcolumns := make([][]int, puzzleSize)\n\tsections := make([][]int, puzzleSize)\n\n\tit := &iteration{\n\t\tpuzzleSize: puzzleSize,\n\t\tsectionSize: sectionSize,\n\t\tcells: make(group, len(items)),\n\t\trows: rows,\n\t\tcolumns: columns,\n\t\tsections: sections,\n\t}\n\tfor i, item := range items {\n\t\tc := cell{\n\t\t\tfixed: item > 0,\n\t\t\tvalue: item,\n\t\t\tindex: i,\n\t\t}\n\t\tit.cells[i] = &c\n\n\t\trowIndex := getRowFromIndex(c.index, it.puzzleSize)\n\t\tif it.rows[rowIndex] == nil {\n\t\t\tit.rows[rowIndex] = make([]int, 0, it.puzzleSize)\n\t\t}\n\t\tit.rows[rowIndex] = append(it.rows[rowIndex], c.index)\n\n\t\tcolumnIndex := getColumnFromIndex(c.index, it.puzzleSize)\n\t\tif it.columns[columnIndex] == nil {\n\t\t\tit.columns[columnIndex] = make([]int, 0, it.puzzleSize)\n\t\t}\n\t\tit.columns[columnIndex] = append(it.columns[columnIndex], c.index)\n\n\t\tsectionIndex := getSectionFromIndex(c.index, it.puzzleSize, it.sectionSize)\n\t\tif it.sections[sectionIndex] == nil {\n\t\t\tit.sections[sectionIndex] = make([]int, 0, it.puzzleSize)\n\t\t}\n\t\tit.sections[sectionIndex] = append(it.sections[sectionIndex], c.index)\n\t}\n\treturn it\n}", "func combinationSum2(candidates []int, target int) [][]int {\n \n}", "func (sudoku *Sudoku) tryAndError() {\n\tif sudoku.hasZeros() == false {\n\t\treturn\n\t}\n\n\tmaxNumOfPossibilities := 2\n\n\t// this is \n\tvar iTry, jTry int\n\tvar possibleNumsTry []int\n\n\tdoBreak := false\n\n\tfor {\n\n\t\tfor i := 1; i<=9; i++ {\n\t\t\tfor j := 1; j<=9; j++ {\n\t\t\t\tif sudoku.grid[rowCol(i,j)] == 0 {\n\n\t\t\t\t\tpossibleNums := sudoku.getNumberPossibilities(i,j)\n\n\t\t\t\t\tif len(possibleNums) == maxNumOfPossibilities {\n\t\t\t\t\t\tpossibleNumsTry = possibleNums\n\t\t\t\t\t\tiTry = i\n\t\t\t\t\t\tjTry = j\n\t\t\t\t\t\tdoBreak = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t} else if len(possibleNums) == 0 {\n\t\t\t\t\t\t// this is conflicted then\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\tif doBreak {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif doBreak {\n\t\t\tbreak\n\t\t} else {\n\t\t\tmaxNumOfPossibilities++\n\t\t}\n\t}\n\t\n\t// we have a field we will bruteforce\n\tfor _, numToTry := range possibleNumsTry {\n\t\t// Step 1. Setup a test sudoku\n\t\tvar testSudoku Sudoku\n\t\ttestSudoku.grid = sudoku.grid\n\t\ttestSudoku.possibilities = sudoku.possibilities\n\n\t\t// Step 2. Set the number to try and let it solve\n\t\ttestSudoku.setNumber(iTry, jTry, numToTry)\n\n\t\t// Step 3. Let it solve itself\n\t\tconflicted := testSudoku.solve()\n\n\t\tif conflicted == false && testSudoku.solved {\n\t\t\tsudoku.grid = testSudoku.grid\n\t\t\tbreak\n\t\t}\n\t}\n}", "func matrixClone(matrix [][]float64) (cloneMatrix [][]float64) {\n\tfor i := 0; i < len(matrix); i++ {\n\t\tfor j := 0; j < len(matrix[i]); j++ {\n\t\t\tfor x := len(cloneMatrix); x <= i; x++ {\n\t\t\t\tcloneMatrix = append(cloneMatrix, []float64{})\n\t\t\t}\n\t\t\tfor k := len(cloneMatrix[i]); k <= j; k++ {\n\t\t\t\tcloneMatrix[i] = append(cloneMatrix[i], 0)\n\t\t\t}\n\t\t\tcloneMatrix[i][j] = matrix[i][j]\n\t\t}\n\t}\n\treturn\n}", "func (this *Solution) Shuffle() []int {\ntmp:=make([]int,len(this.arr))\ncopy(tmp,this.arr)\nfor i:=0;i<len(tmp);i++{\n\tr:=rand.Intn(len(tmp))\n\ttmp[i],tmp[r] = tmp[r],tmp[i]\n}\nreturn tmp\n}" ]
[ "0.67193305", "0.64270633", "0.62536854", "0.61941683", "0.6049497", "0.6033678", "0.58965313", "0.589649", "0.58708674", "0.5849783", "0.579723", "0.5719005", "0.56586736", "0.56038004", "0.55810887", "0.55595493", "0.5537374", "0.54805875", "0.5387022", "0.53836954", "0.53430265", "0.5314474", "0.5309684", "0.5309684", "0.5229077", "0.5212409", "0.52081454", "0.52048796", "0.51950186", "0.51942515", "0.5180996", "0.51706994", "0.5141239", "0.5135042", "0.5122647", "0.51172096", "0.5097158", "0.5079947", "0.5064798", "0.505865", "0.50574344", "0.5042901", "0.502665", "0.50183004", "0.50020206", "0.49948907", "0.4973079", "0.4968933", "0.4960454", "0.4955845", "0.4952318", "0.494948", "0.4898022", "0.48940167", "0.4892295", "0.4886761", "0.48855788", "0.48838437", "0.4877214", "0.48745662", "0.4861616", "0.48527753", "0.48505315", "0.48435104", "0.4842685", "0.48386756", "0.48244542", "0.48241752", "0.48134485", "0.4806003", "0.48041984", "0.4792047", "0.47858682", "0.47789344", "0.47785065", "0.4771534", "0.47562692", "0.4753264", "0.4750025", "0.4746778", "0.4715329", "0.47122043", "0.47073498", "0.46998727", "0.46928024", "0.46900183", "0.46894905", "0.46798572", "0.46792734", "0.46671015", "0.46635863", "0.4655045", "0.46529806", "0.46417657", "0.46414176", "0.46384954", "0.4634511", "0.46343035", "0.46283966", "0.46255735", "0.46220523" ]
0.0
-1
Index of first array matches the column number, then the second array contains all indexs of restrictions that match
func buildColumnToPossibleRestrictions(tickets []Ticket, restrictions []FieldDef) [][]int { numberOfColumns := len(restrictions) rowToRestrictions := make([][]int, numberOfColumns) for i := 0; i < numberOfColumns; i++ { rowToRestrictions[i] = buildPossibleRestrictionsForColumn(getColumn(tickets, i), restrictions) } return rowToRestrictions }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func IndexFindAllIndex(x *suffixarray.Index, r *regexp.Regexp, n int) [][]int", "func indexDiff(a, b []string) []int {\n\tm := make(map[string]bool)\n\tdiff := []int{}\n\n\tfor _, item := range b {\n\t\t m[item] = true\n\t}\n\n\tfor i, item := range a {\n\t\tif _, ok := m[item]; !ok {\n\t\t\tdiff = append(diff, i)\n\t\t}\n\t}\n\treturn diff\n}", "func containVirus(grid [][]int) int {\n \n}", "func findCandidateIndices(data [][]float64, findMinima bool) (candidates []int){\n\t//a coordinate is considered a candidate if both of its adjacent points have y-values\n\t//that are greater or less (depending on whether we want local minima or local maxima)\n\tfor i := 1; i < len(data) - 1; i++{\n\t\tprev := data[i-1][1]\n\t\tcur := data[i][1]\n\t\tnext := data[i+1][1]\n\t\tvar isCandidate bool\n\t\tif findMinima == true{\n\t\t\tisCandidate = prev > cur && next > cur\n\t\t} else {\n\t\t\tisCandidate = prev < cur && next < cur\n\t\t}\n\t\tif(isCandidate){\n\t\t\tcandidates = append(candidates, i)\n\t\t}\n\t}\n\treturn\n}", "func (params Params) ExtractMatches(matrix [][]float64) [][2]int {\n\tif len(matrix) == 0 || len(matrix[0]) == 0 {\n\t\treturn nil\n\t}\n\n\t// get max probability and index over columns along each row\n\ttype Candidate struct {\n\t\tRow int\n\t\tCol int\n\t\tScore float64\n\t}\n\trowMax := make([]Candidate, len(matrix))\n\tfor i := range matrix {\n\t\trowMax[i] = Candidate{-1, -1, params.GetMinIOU()}\n\t\tfor j := range matrix[i] {\n\t\t\tprob := matrix[i][j]\n\t\t\tif prob > rowMax[i].Score {\n\t\t\t\trowMax[i] = Candidate{i, j, prob}\n\t\t\t}\n\t\t}\n\t}\n\n\t// now make sure each row picked a unique column\n\t// in cases of conflicts, resolve via max probability\n\t// the losing row in the conflict would then match to nothing\n\tcolMax := make([]Candidate, len(matrix[0]))\n\tfor i := 0; i < len(matrix[0]); i++ {\n\t\tcolMax[i] = Candidate{-1, -1, 0}\n\t}\n\tfor _, candidate := range rowMax {\n\t\tif candidate.Col == -1 {\n\t\t\tcontinue\n\t\t}\n\t\tif candidate.Score > colMax[candidate.Col].Score {\n\t\t\tcolMax[candidate.Col] = candidate\n\t\t}\n\t}\n\n\t// finally we can enumerate the matches\n\tvar matches [][2]int\n\tfor _, candidate := range colMax {\n\t\tif candidate.Col == -1 {\n\t\t\tcontinue\n\t\t}\n\t\tmatches = append(matches, [2]int{candidate.Row, candidate.Col})\n\t}\n\treturn matches\n}", "func ColumnIndices(c Config) (icolIdxs, fcolIdxs []int) {\n\tisInt := func(x int64) bool {\n\t\tfor _, col := range c.IntColumns {\n\t\t\tif col == x { return true }\n\t\t}\n\t\treturn false\n\t}\n\n\tfor i := int64(0); i < c.Columns; i++ {\n\t\tif isInt(i) {\n\t\t\ticolIdxs = append(icolIdxs, int(i))\n\t\t} else {\n\t\t\tfcolIdxs = append(fcolIdxs, int(i))\n\t\t}\n\t}\n\n\treturn icolIdxs, fcolIdxs\n}", "func intSliceIncludesOther(a, b []int) bool {\n\tif len(b) > len(a) {\n\t\treturn false\n\t}\n\tfor _, n := range b {\n\t\tvar isMatch bool\n\t\tfor _, m := range a {\n\t\t\tif n == m {\n\t\t\t\tisMatch = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !isMatch {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func findIndices(n int) [][]int {\n\tvar indices [][]int\n\tfor _, target := range \"012\" {\n\t\tvar found []int\n\t\tfor i, x := range strconv.Itoa(n) {\n\t\t\tif x == target {\n\t\t\t\tfound = append(found, i)\n\t\t\t}\n\t\t}\n\t\tindices = append(indices, found)\n\t}\n\treturn indices\n}", "func Int2dArrayFindNeighbors(rowsAndCols [][]int, rowIndex int, colIndex int, directions []Direction) (neighbors []Int2dArrayNeighbor) {\n\tfor _, direction := range directions {\n\t\trow, col := direction.Translate(rowIndex, colIndex)\n\t\tvalue, isFound := Int2dArrayHasValueAtPos(rowsAndCols, row, col)\n\t\tif isFound {\n\t\t\tneighbors = append(neighbors, Int2dArrayNeighbor{Row: row, Col: col, Value: value, Direction: direction})\n\t\t}\n\t}\n\treturn\n}", "func (x *Index) FindAllIndex(r *regexp.Regexp, n int) (result [][]int)", "func ColumnSliceIsIntersect(s1, s2 []*Column) bool {\n\ttrace_util_0.Count(_util_00000, 171)\n\tintSet := map[int64]struct{}{}\n\tfor _, col := range s1 {\n\t\ttrace_util_0.Count(_util_00000, 174)\n\t\tintSet[col.UniqueID] = struct{}{}\n\t}\n\ttrace_util_0.Count(_util_00000, 172)\n\tfor _, col := range s2 {\n\t\ttrace_util_0.Count(_util_00000, 175)\n\t\tif _, ok := intSet[col.UniqueID]; ok {\n\t\t\ttrace_util_0.Count(_util_00000, 176)\n\t\t\treturn true\n\t\t}\n\t}\n\ttrace_util_0.Count(_util_00000, 173)\n\treturn false\n}", "func smallGridIndices(i, j int) (int, int) {\n\tvar smallGrid_i, smallGrid_j int\n\tif i <= 3 {\n\t\tsmallGrid_i = 1\n\t} else if i <= 6 {\n\t\tsmallGrid_i = 2\n\t} else {\n\t\tsmallGrid_i = 3\n\t}\n\n\tif j <= 3 {\n\t\tsmallGrid_j = 1\n\t} else if j <= 6 {\n\t\tsmallGrid_j = 2\n\t} else {\n\t\tsmallGrid_j = 3\n\t}\n\n\treturn smallGrid_i, smallGrid_j\n}", "func splitMatrix(X [][]float64, split float64, attribute int, ind []int) ([]int, []int) {\n\n\tsmaller := make([]int, 0)\n\tbigger := make([]int, 0)\n\n\tfor _, val := range ind {\n\t\tif X[val][attribute] < split {\n\t\t\tsmaller = append(smaller, val)\n\t\t} else {\n\t\t\tbigger = append(bigger, val)\n\t\t}\n\t}\n\n\treturn smaller, bigger\n}", "func indexCluster(in []cell) (out indexedCluster) {\n\n\t// add the fullArray to every value location\n\tfor i, _ := range in {\n\t\tcopy(out[i], fullArray)\n\t}\n\n\t// I can simply delete known values from the array\n\tfor _, each := range in {\n\t\tif each.actual != 0{\n\t\t\tdelete(out, each.actual)\n\t\t}\n\t}\n\n\t// remove all exclusions\n\tfor id, each := range in {\n\t\tfor _, exclusion := range each.excluded {\n\t\t\tout[exclusion] = subArr(out[exclusion], []int{exclusion})\n\t\t}\n\t}\n\n\treturn out\n}", "func diffIdsTupleSlices(a []IdsTuple, b []IdsTuple) []IdsTuple {\n\tindex := 0\n\tdiff := []IdsTuple(nil)\n\tfor _, n := range a {\n\t\tfor index < len(b) && CompareIdsTuple(&n, &b[index]) == 1 {\n\t\t\tindex++\n\t\t}\n\t\tif index >= len(b) || CompareIdsTuple(&n, &b[index]) == -1 {\n\t\t\tdiff = append(diff, n)\n\t\t}\n\t}\n\treturn diff\n}", "func eqCols(eqIndices []exec.NodeColumnOrdinal, planToColMap []int) []uint32 {\n\teqCols := make([]uint32, len(eqIndices))\n\tfor i, planCol := range eqIndices {\n\t\teqCols[i] = uint32(planToColMap[planCol])\n\t}\n\n\treturn eqCols\n}", "func rowScanning(input [][]float64, marked [][]float64) [][]float64 {\n\tfor row := range input {\n\n\t\tfor col := range input {\n\t\t\tif input[row][col] == 0 && marked[row][col] == 0 {\n\n\t\t\t\tmarked[row][col] = 1\n\t\t\t\tfor i := col; i < len(input); i++ {\n\t\t\t\t\tif input[row][i] == 0 && marked[row][i] == 0 {\n\t\t\t\t\t\t// cross out all left in the row\n\t\t\t\t\t\tmarked[row][i] = -1\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor row2 := range input {\n\t\t\t\t\t// cross all in the same column\n\t\t\t\t\tif input[row2][col] == 0 && row != row2 {\n\t\t\t\t\t\tmarked[row2][col] = -1\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn marked\n}", "func compareIndexes(schemaName, tableName string, from, to []Index, conn Conn) string {\n\tvar ret, tmp string\n\tvar err error\n\tvar toIndex Index\n\tfor j, i := range from {\n\t\tSetIndexName(schemaName, tableName, &i)\n\t\tfrom[j] = i\n\t\tif toIndex, err = findIndex(i.Name, to); err == nil {\n\t\t\ttoIndex.Columns = strings.Replace(toIndex.Columns, \", \", \",\", -1)\n\t\t\ti.Columns = strings.Replace(i.Columns, \", \", \",\", -1)\n\t\t\tif toIndex.Columns != i.Columns {\n\t\t\t\tlog.Fatal(schemaName, tableName, toIndex, i)\n\t\t\t\ttmp = conn.DropIndexSQL(schemaName, tableName, i.Name)\n\t\t\t\ttmp += \"\\n\" + conn.CreateIndexSQL(schemaName, tableName, &i)\n\t\t\t\tif len(ret) > 0 {\n\t\t\t\t\tret += \"\\n\"\n\t\t\t\t}\n\t\t\t\tret += tmp\n\t\t\t}\n\t\t} else {\n\t\t\ttmp = conn.CreateIndexSQL(schemaName, tableName, &i)\n\t\t\tif len(ret) > 0 {\n\t\t\t\tret += \"\\n\"\n\t\t\t}\n\t\t\tret += tmp\n\t\t}\n\t}\n\tfor _, i := range to {\n\t\tif toIndex, err = findIndex(i.Name, from); err != nil {\n\t\t\tif len(ret) > 0 {\n\t\t\t\tret += \"\\n\"\n\t\t\t}\n\t\t\tret += conn.DropIndexSQL(schemaName, tableName, i.Name)\n\t\t}\n\t}\n\treturn ret\n}", "func PairsSumNearToTarget(arr1, arr2 []int, target int) (arr1Idx, arr2Idx int) {\n\tvalueToPosition := make(map[int]int, len(arr2))\n\n\tclosest, ci, cj := 999, 0, 0\n\n\tfor i := 0; i < len(arr1); i++ {\n\t\t// Speed up: Is the current element's exact complement wrt target in the map?\n\t\tcomp := target - arr1[i]\n\t\t// If comp is in map, return it\n\t\tif idx, ok := valueToPosition[comp]; ok {\n\t\t\treturn i, idx\n\t\t}\n\n\t\t// Scan the second array\n\t\tfor j := 0; j < len(arr2); j++ {\n\t\t\t// Core check\n\t\t\tif arr1[i]+arr2[j] == target {\n\t\t\t\treturn i, j\n\t\t\t}\n\t\t\t// Is it the closest?\n\t\t\tif cl := math.Abs(float64(target - arr1[i] - arr2[j])); cl < float64(closest) {\n\t\t\t\tclosest, ci, cj = int(cl), i, j\n\t\t\t}\n\n\t\t\t// On first scan store arr2 values -> arr2 index in the map\n\t\t\tif i == 0 {\n\t\t\t\tvalueToPosition[arr2[j]] = j\n\t\t\t}\n\t\t}\n\t}\n\n\t// We didn't find an exact match so just return the closest\n\tprintln(\"closest indices\", ci, cj, \"diff:\", closest)\n\treturn ci, cj\n}", "func twoSum01(nums []int, target int) []int {\n\tnumMap := map[int]int{}\n\tfor i, v := range nums {\n\t\tnumMap[v] = i\n\t}\n\n\tfor i, v := range nums {\n\t\tif index, ok := numMap[target-v]; ok && index != i {\n\t\t\treturn []int{i, index}\n\t\t}\n\t}\n\n\treturn nil\n}", "func magicIndexBruteForce(A []int) (bool, int) {\n\tfor idx, val := range A {\n\t\tif idx == val {\n\t\t\treturn true, idx\n\t\t}\n\t}\n\treturn false, 0\n}", "func sol2(nums1 []int, nums2 []int, k int) [][]int {\n if len(nums1) == 0 || len(nums2) == 0 {\n return nil\n }\n\n cursors := make([]int, len(nums1))\n var res [][]int\n for len(res) < k && len(res) < len(nums1) * len(nums2) {\n min := nums1[len(nums1)-1] + nums2[len(nums2)-1] + 1\n next := -1\n for i, j := range cursors {\n if j >= len(nums2) {\n continue\n }\n t := nums1[i] + nums2[j]\n if min > t {\n min = t\n next = i\n }\n // todo: skip condition\n }\n res = append(res, []int{nums1[next], nums2[cursors[next]]})\n cursors[next]++\n }\n\n return res\n}", "func combinationSum2(candidates []int, target int) [][]int {\n \n}", "func Int2dArrayWalk(rowsAndCols [][]int, startRowIndex int, startColIndex int, direction Direction) (walkedValues []int) {\n\trowIndex := startRowIndex\n\tcolIndex := startColIndex\n\tfor {\n\t\trowIndex, colIndex = direction.Translate(rowIndex, colIndex)\n\t\tif !isValidPoint(rowsAndCols, rowIndex, colIndex) {\n\t\t\tbreak\n\t\t}\n\t\twalkedValues = append(walkedValues, rowsAndCols[rowIndex][colIndex])\n\t}\n\treturn walkedValues\n}", "func Layer2DRepIdxs(ly Layer, maxSize int) (idxs, shape []int) {\n\tsh := ly.Shape()\n\tmy := ints.MinInt(maxSize, sh.Dim(0))\n\tmx := ints.MinInt(maxSize, sh.Dim(1))\n\tshape = []int{my, mx}\n\tidxs = make([]int, my*mx)\n\ti := 0\n\tfor y := 0; y < my; y++ {\n\t\tfor x := 0; x < mx; x++ {\n\t\t\tidxs[i] = sh.Offset([]int{y, x})\n\t\t\ti++\n\t\t}\n\t}\n\treturn\n}", "func (g grid) diagonalSlice2(startRow, startCol int) []int {\n\tvar res []int\n\trow := startRow\n\tcol := startCol\n\tfor row < rows && col >= 0 {\n\t\tres = append(res, g[row][col])\n\t\trow++\n\t\tcol--\n\t}\n\treturn res\n}", "func DetachIndexConditions(conditions []expression.Expression, cols []*expression.Column,\n\tlengths []int) (accessConds []expression.Expression, filterConds []expression.Expression) {\n\taccessConds = make([]expression.Expression, len(cols))\n\tvar equalOrInCount int\n\tfor _, cond := range conditions {\n\t\toffset := getEqOrInColOffset(cond, cols)\n\t\tif offset != -1 {\n\t\t\taccessConds[offset] = cond\n\t\t}\n\t}\n\tfor i, cond := range accessConds {\n\t\tif cond == nil {\n\t\t\taccessConds = accessConds[:i]\n\t\t\tequalOrInCount = i\n\t\t\tbreak\n\t\t}\n\t\tif lengths[i] != types.UnspecifiedLength {\n\t\t\tfilterConds = append(filterConds, cond)\n\t\t}\n\t\tif i == len(accessConds)-1 {\n\t\t\tequalOrInCount = len(accessConds)\n\t\t}\n\t}\n\t// We should remove all accessConds, so that they will not be added to filter conditions.\n\tconditions = removeAccessConditions(conditions, accessConds)\n\tif equalOrInCount == len(cols) {\n\t\t// If curIndex equals to len of index columns, it means the rest conditions haven't been appended to filter conditions.\n\t\tfilterConds = append(filterConds, conditions...)\n\t\treturn accessConds, filterConds\n\t}\n\treturn extractAccessAndFilterConds(conditions, accessConds, filterConds, cols[equalOrInCount], lengths[equalOrInCount])\n}", "func EditDist(a, b string) int {\n\tlen1, len2 := len(a), len(b)\n\tif len1 < len2 {\n\t\treturn EditDist(b, a)\n\t}\n\trow1, row2 := make([]int, len2+1), make([]int, len2+1)\n\n\tfor i := 0; i < len2+1; i++ {\n\t\trow2[i] = i\n\t}\n\n\tfor i := 0; i < len1; i++ {\n\t\trow1[0] = i + 1\n\n\t\tfor j := 0; j < len2; j++ {\n\t\t\tx := min(row2[j+1]+1, row1[j]+1)\n\t\t\ty := row2[j] + invBool2int(a[i] == b[j])\n\t\t\trow1[j+1] = min(x, y)\n\t\t}\n\n\t\trow1, row2 = row2, row1\n\t}\n\treturn row2[len2]\n}", "func lookupCol(arr formulaArg, idx int) []formulaArg {\n\tcol := arr.List\n\tif arr.Type == ArgMatrix {\n\t\tcol = nil\n\t\tfor _, r := range arr.Matrix {\n\t\t\tif len(r) > 0 {\n\t\t\t\tcol = append(col, r[idx])\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcol = append(col, newEmptyFormulaArg())\n\t\t}\n\t}\n\treturn col\n}", "func getIndices(b []byte) [16]int {\n\n\tif len(b) != 6 {\n\t\tpanic(\"invalid index array size\")\n\t}\n\n\tdata := binary.BigEndian.Uint64(append([]byte{0, 0}, b...))\n\n\tix := [16]int{}\n\tfor i := 0; i < 16; i++ {\n\t\t//Bit shift data right by i*3 and & with 0x0111 to get index\n\t\tix[i] = int((data >> uint(i*3)) & 7)\n\t}\n\treturn ix\n}", "func canFormArray(arr []int, pieces [][]int) bool {\n\tfirstPos := make(map[int]int, len(pieces))\n\tfor i, slice := range pieces {\n\t\tfirstPos[slice[0]] = i\n\t}\n\t//fmt.Println(firstPos)\n\tfor i := 0; i < len(arr); {\n\t\tcur_ele := arr[i]\n\t\t//fmt.Println(cur_ele)\n\t\tif pos, ok := firstPos[cur_ele]; !ok {\n\t\t\treturn false\n\t\t} else {\n\n\t\t\tfor j := 1; j < len(pieces[pos]); j++ {\n\t\t\t\t//println(arr[i+j],pieces[pos][j])\n\t\t\t\tif arr[i+j] != pieces[pos][j] {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\ti += len(pieces[pos])\n\t\t}\n\t}\n\treturn true\n}", "func (res *Result) CheckAt(cols []int, expected [][]interface{}) {\n\tfor _, e := range expected {\n\t\tres.require.Equal(len(e), len(cols))\n\t}\n\n\trows := make([][]string, 0, len(expected))\n\tfor i := range res.rows {\n\t\trow := make([]string, 0, len(cols))\n\t\tfor _, r := range cols {\n\t\t\trow = append(row, res.rows[i][r])\n\t\t}\n\t\trows = append(rows, row)\n\t}\n\tgot := fmt.Sprintf(\"%s\", rows)\n\tneed := fmt.Sprintf(\"%s\", expected)\n\tres.require.Equal(need, got, res.comment)\n}", "func fix_min_indices(matrix [][]int, min_indices []int, rem_row int, rem_col int) []int {\n\tvar new_min_ind []int\n\n\tnew_min_ind = make([]int, len(min_indices)-1)\n\tvar count int = 0\n\n\tfor i := 0; i < len(min_indices); i++ {\n\t\tif i != rem_row {\n\t\t\tif min_indices[i] == rem_col {\n\t\t\t\tnew_min_ind[count] = min_index(matrix[count])\n\t\t\t} else if min_indices[i] > rem_col {\n\t\t\t\tnew_min_ind[count] = min_indices[i] - 1\n\t\t\t} else {\n\t\t\t\tnew_min_ind[count] = min_indices[i]\n\t\t\t}\n\t\t\tcount = count + 1\n\t\t}\n\t}\n\n\treturn new_min_ind\n}", "func getColumn(block [][]float32, index int) []float32 {\n\tcolumn := make([]float32, 8)\n\t//alternative := block[:][index]\n\tfor i := range column {\n\t\tcolumn[i] = block[i][index]\n\t}\n\treturn column\n}", "func (fn *formulaFuncs) index(array formulaArg, rowIdx, colIdx int) formulaArg {\n\tvar cells []formulaArg\n\tif array.Type == ArgMatrix {\n\t\tcellMatrix := array.Matrix\n\t\tif rowIdx < -1 || rowIdx >= len(cellMatrix) {\n\t\t\treturn newErrorFormulaArg(formulaErrorREF, \"INDEX row_num out of range\")\n\t\t}\n\t\tif rowIdx == -1 {\n\t\t\tif colIdx >= len(cellMatrix[0]) {\n\t\t\t\treturn newErrorFormulaArg(formulaErrorREF, \"INDEX col_num out of range\")\n\t\t\t}\n\t\t\tvar column [][]formulaArg\n\t\t\tfor _, cells = range cellMatrix {\n\t\t\t\tcolumn = append(column, []formulaArg{cells[colIdx]})\n\t\t\t}\n\t\t\treturn newMatrixFormulaArg(column)\n\t\t}\n\t\tcells = cellMatrix[rowIdx]\n\t}\n\tif colIdx < -1 || colIdx >= len(cells) {\n\t\treturn newErrorFormulaArg(formulaErrorREF, \"INDEX col_num out of range\")\n\t}\n\treturn newListFormulaArg(cells)\n}", "func WhichValuesInIntSlice(Slice1, Slice2 []int) (map[int][]int, bool) {\n\tvalues := make(map[int][]int)\n\tif len(Slice1) == 0 || len(Slice2) == 0 {\n\t\treturn values, false\n\t}\n\n\t// Remove dulpicated elements from Slice 1 (not from Slice 2!)\n\tif !IsUniqueIntSlice(Slice1) {\n\t\tSlice1 = UniqueIntSlice(Slice1)\n\t}\n\n\tfor _, valueInSlice1 := range Slice1 {\n\t\tif IsValueInIntSlice(valueInSlice1, Slice2) {\n\t\t\tfor index, valueInSlice2 := range Slice2 {\n\t\t\t\tif valueInSlice1 == valueInSlice2 && !IsValueInIntSlice(index, values[valueInSlice1]) {\n\t\t\t\t\tvalues[valueInSlice1] = append(values[valueInSlice1], index)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn values, len(values) > 0\n}", "func cmpEq(a []uint8, b []uint8, idx int) int { // THIS\n\tif a[idx] < b[idx] {\n\t\treturn -1\n\t} else if a[idx] > b[idx] {\n\t\treturn 1\n\t} else if a[idx] != 0 {\n\t\treturn 0\n\t}\n\treturn 0\n}", "func getHeaderIndices(fields []string, headers []string) []int {\n\tvar indices []int\n\tfor key, header := range headers {\n\t\tif inSlice(header, fields) {\n\t\t\tindices = append(indices, key)\n\t\t}\n\t}\n\treturn indices\n}", "func twoSum(arr []int, target int) []int {\n\tfor i := 0; i < len(arr); i++ {\n\t\tfor j := i + 1; j < len(arr); j++ {\n\t\t\tif arr[i]+arr[j] == target {\n\t\t\t\treturn []int{i, j}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func formulaIfsMatch(args []formulaArg) (cellRefs []cellRef) {\n\tfor i := 0; i < len(args)-1; i += 2 {\n\t\tvar match []cellRef\n\t\tmatrix, criteria := args[i].Matrix, formulaCriteriaParser(args[i+1].Value())\n\t\tif i == 0 {\n\t\t\tfor rowIdx, row := range matrix {\n\t\t\t\tfor colIdx, col := range row {\n\t\t\t\t\tif ok, _ := formulaCriteriaEval(col.Value(), criteria); ok {\n\t\t\t\t\t\tmatch = append(match, cellRef{Col: colIdx, Row: rowIdx})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfor _, ref := range cellRefs {\n\t\t\t\tvalue := matrix[ref.Row][ref.Col]\n\t\t\t\tif ok, _ := formulaCriteriaEval(value.Value(), criteria); ok {\n\t\t\t\t\tmatch = append(match, ref)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif len(match) == 0 {\n\t\t\treturn\n\t\t}\n\t\tcellRefs = match[:]\n\t}\n\treturn\n}", "func Intersection(nums1 []int, nums2 []int) []int {\n\tres := make([]int, 0)\n\tseen := make(map[int]bool)\n\t// Sort the smallest one\n\tif len(nums1) < len(nums2) {\n\t\tsort.Ints(nums1)\n\t\t// Search every element of bigger array in smaller array\n\t\t// and print the element if found\n\t\tfor _, v := range nums2 {\n\t\t\tif Search(nums1, v) != -1 && !seen[v] {\n\t\t\t\tres = append(res, v)\n\t\t\t\tseen[v] = true\n\t\t\t}\n\t\t}\n\t} else {\n\t\tsort.Ints(nums2)\n\t\t// Search every element of bigger array in smaller array\n\t\t// and print the element if found\n\t\tfor _, v := range nums1 {\n\t\t\tif Search(nums2, v) != -1 && !seen[v] {\n\t\t\t\tres = append(res, v)\n\t\t\t\tseen[v] = true\n\t\t\t}\n\t\t}\n\t}\n\treturn res\n}", "func checkCols(game Game) []int {\n\tvar out []int\n\n\tfor i, card := range game.Cards {\n\t\tfor j := 0; j <= 4; j++ {\n\t\t\tif card.Rows[0].Squares[j].Called && card.Rows[1].Squares[j].Called && card.Rows[2].Squares[j].Called && card.Rows[3].Squares[j].Called && card.Rows[4].Squares[j].Called {\n\t\t\t\tout = append(out, i)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn out\n}", "func EqualsSliceOfRefOfIndexColumn(a, b []*IndexColumn) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(a); i++ {\n\t\tif !EqualsRefOfIndexColumn(a[i], b[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func TestGetBoardColumnSlice(t *testing.T) {\n\tgameBoard := CreateGameBoard(5)\n\texpectedColumnSlice := []string{\"04\", \"09\", \"14\", \"19\", \"24\"} // last column\n\texpectedColumnSlice2 := []string{\"02\", \"07\", \"12\", \"17\", \"22\"}\n\n\tcolumnSlice := GetBoardColumnSlice(4, gameBoard)\n\n\tfor i, val := range columnSlice {\n\t\tif val != expectedColumnSlice[i] {\n\t\t\tt.Errorf(\"Unexpected element at column slice. actual: %s, expected: %s, index: %d\", val, expectedColumnSlice[i], i)\n\t\t}\n\t}\n\n\tcolumnSlice2 := GetBoardColumnSlice(2, gameBoard)\n\n\tfor i, val := range columnSlice2 {\n\t\tif val != expectedColumnSlice2[i] {\n\t\t\tt.Errorf(\"Unexpected element at column slice. actual: %s, expected: %s, index: %d\", val, expectedColumnSlice2[i], i)\n\t\t}\n\t}\n}", "func sol1(nums []int, target int) []int {\n\tfor i, n := range nums {\n\t\tfor j, m := range nums {\n\t\t\tif i == j {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif n+m == target {\n\t\t\t\treturn []int{i, j}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func loop_map(index int, res *[][]int, nums []int) {\n\n}", "func (self *PhysicsP2) BoundsCollidesWith() []interface{}{\n\tarray00 := self.Object.Get(\"boundsCollidesWith\")\n\tlength00 := array00.Length()\n\tout00 := make([]interface{}, length00, length00)\n\tfor i00 := 0; i00 < length00; i00++ {\n\t\tout00[i00] = array00.Index(i00)\n\t}\n\treturn out00\n}", "func querySubset(q, s []int) [][]int {\n\n\tif len(q) != len(s) {\n\t\tpanic(\"size mismatch\")\n\t}\n\tvar result [][]int\n\n\tswitch {\n\tcase len(s) == 1 && q[0] >= 0:\n\t\tresult = [][]int{[]int{q[0]}}\n\n\tcase len(s) == 1 && q[0] < 0:\n\t\tresult = make([][]int, s[0], s[0])\n\t\tfor k := range result {\n\t\t\tresult[k] = []int{k}\n\t\t}\n\n\tcase q[0] >= 0:\n\t\tx := querySubset(q[1:], s[1:])\n\t\tfor _, v := range x {\n\t\t\tvar sl []int\n\t\t\tsl = append(sl, q[0])\n\t\t\tsl = append(sl, v...)\n\t\t\tresult = append(result, sl)\n\t\t}\n\n\tcase q[0] < 0:\n\t\tfor i := 0; i < s[0]; i++ {\n\t\t\tx := querySubset(q[1:], s[1:])\n\t\t\tfor _, v := range x {\n\t\t\t\tvar sl []int\n\t\t\t\tsl = append(sl, i)\n\t\t\t\tsl = append(sl, v...)\n\t\t\t\tresult = append(result, sl)\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}", "func Retind(inslice []float64, elems []float64) []int {\n\tif len(inslice) < 1 || len(elems) != 2 {\n\t\terr := errors.New(\"Array of more than one element is required for inslice while a tuple is required for elems.\")\n\t\tpanic(err)\n\t}\n\tvar inind []int\n\tfor i, v := range inslice {\n\t\tif v == elems[0] || v == elems[1] {\n\t\t\tinind = append(inind, i)\n\t\t}\n\t}\n\tif inind[1] > inind[0] {\n\t\tinind[0], inind[1] = inind[1], inind[0]\n\t}\n\treturn inind\n}", "func (dr *DataRow) selectByIndices(columnIndices []int) DataRow {\n\toutItems := make([]DataItem, 0, len(columnIndices))\n\n\tfor _, index := range columnIndices {\n\t\toutItems = append(outItems, dr.Items[index])\n\t}\n\n\treturn DataRow{\n\t\tItems: outItems,\n\t}\n}", "func intersection(nums1 []int, nums2 []int) []int {\n\tvar ret []int\n\tmapping := map[int]bool{}\n\tfor _, e := range nums1 {\n\t\tmapping[e] = true\n\t}\n\tfor _, e := range nums2 {\n\t\tif _, ok := mapping[e]; ok {\n\t\t\tret = append(ret, e)\n\t\t\tdelete(mapping, e)\n\t\t}\n\t}\n\treturn ret\n}", "func check(nums []int, otherTarget int) (bool, int) {\n for i := range nums {\n if nums[i] == otherTarget {\n return true, i\n }\n }\n return false, 0\n}", "func isInColumnNames(key string, col []string) int {\n\tfor i, n := range col {\n\t\tif n == key {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func adjacentRowsAndCols(reg region, pos position) adjacentToCheck {\n\tr := adjacentToCheck{}\n\n\tswitch reg.maxRowNumber - pos.rowNumber {\n\tcase 0:\n\t\tr.adjacentRows = append(r.adjacentRows, pos.rowNumber-1)\n\t\tr.adjacentRows = append(r.adjacentRows, pos.rowNumber-2)\n\tcase 1:\n\t\tr.adjacentRows = append(r.adjacentRows, pos.rowNumber+1)\n\t\tr.adjacentRows = append(r.adjacentRows, pos.rowNumber-1)\n\tcase 2:\n\t\tr.adjacentRows = append(r.adjacentRows, pos.rowNumber+1)\n\t\tr.adjacentRows = append(r.adjacentRows, pos.rowNumber+2)\n\t}\n\n\tswitch reg.maxColNumber - pos.colNumber {\n\tcase 0:\n\t\tr.adjacentCols = append(r.adjacentCols, pos.colNumber-1)\n\t\tr.adjacentCols = append(r.adjacentCols, pos.colNumber-2)\n\tcase 1:\n\t\tr.adjacentCols = append(r.adjacentCols, pos.colNumber+1)\n\t\tr.adjacentCols = append(r.adjacentCols, pos.colNumber-1)\n\tcase 2:\n\t\tr.adjacentCols = append(r.adjacentCols, pos.colNumber+1)\n\t\tr.adjacentCols = append(r.adjacentCols, pos.colNumber+2)\n\t}\n\n\treturn r\n}", "func lt(index index.Int, column []int, comp int, bIndex index.Bool) {\n\tfor i, x := range bIndex {\n\t\tif !x {\n\t\t\tbIndex[i] = column[index[i]] < comp\n\t\t}\n\t}\n}", "func getLuckyIndices(isTwice bool) []int {\n\tconst len = 10\n\t// Field for the indices, either two, or three\n\tindices := make([]int, 3)\n\n\tindex1, _ := rand.Int(rand.Reader, big.NewInt(len))\n\tindices[0] = int(index1.Uint64())\n\n\tindex2, _ := rand.Int(rand.Reader, big.NewInt(len))\n\tfor index1.Cmp(index2) == 0 {\n\t\tindex2, _ = rand.Int(rand.Reader, big.NewInt(len))\n\t}\n\tindices[1] = int(index2.Uint64())\n\n\tif !isTwice {\n\t\tindex3, _ := rand.Int(rand.Reader, big.NewInt(len))\n\n\t\ti1 := index1.Uint64()\n\t\ti2 := index2.Uint64()\n\t\ti3 := index3.Uint64()\n\n\t\tindicesAreNeighbours := checkIndicesForBeingNeighbours(i1, i2, i3)\n\n\t\tfor index1.Cmp(index3) == 0 || index2.Cmp(index3) == 0 || indicesAreNeighbours {\n\t\t\tindex3, _ = rand.Int(rand.Reader, big.NewInt(len))\n\t\t\ti3 = index3.Uint64()\n\t\t\tindicesAreNeighbours = checkIndicesForBeingNeighbours(i1, i2, i3)\n\t\t}\n\t\tindices[2] = int(index3.Uint64())\n\t} else {\n\t\tindices[2] = -1\n\t}\n\n\treturn indices\n}", "func search() {\n\tvar lowerMatchedList = list.New() // the list which stores the lower-matched index\n\tfor i := 0; i < indexSize; i++ { // scan each index item (lower)\n\t\tvar isMatched bool = false\n\t\tfor j := 0; j < 32/blockSize; j++ { // scan each block\n\t\t\tfor k := 0; k < int(subIndexSize); k++ { // scan all the blocks which their tags are the same as the query's\n\t\t\t\tif index[i].blockCipher[j].subIndex[queryCipher.lower.blockCipher[j].subIndex][k] == 100 { // if all the items with the same sub-index in one block have been checked\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ttargetItem := index[i].blockCipher[j].subIndex[queryCipher.lower.blockCipher[j].subIndex][k] // get the item's index\n\n\t\t\t\t// perform the hash operation to check if this item is matched by the query lower-bound block\n\t\t\t\tk1Byte := F(new(big.Int).SetBytes(queryCipher.lower.blockCipher[j].cipher), index[i].gamma)\n\t\t\t\tk2Byte := index[i].blockCipher[j].ciphers[targetItem]\n\n\t\t\t\tif bytes.Equal(k1Byte, k2Byte) {\n\t\t\t\t\tisMatched = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif isMatched == true { // if one item in a block matches, the whole index item matches\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif isMatched == true { // lowerMatchedList will store all the indexes' positions which match the lower-bound\n\t\t\tlowerMatchedList.PushBack(i)\n\t\t}\n\t}\n\n\tfor e := lowerMatchedList.Front(); e != nil; e = e.Next() { // find which one matches the upper bound from the list whose item matches the lower bound\n\t\tvar (\n\t\t\ti = e.Value.(int)\n\t\t\tisMatched bool = false\n\t\t)\n\t\tfor j := 0; j < 32/blockSize; j++ { // scan each block\n\t\t\tfor k := 0; k < int(subIndexSize); k++ { // scan all the blocks which their tags are the same as the query's\n\t\t\t\tif index[i].blockCipher[j].subIndex[queryCipher.upper.blockCipher[j].subIndex][k] == 100 { // if all the items with the same sub-index in one block have been checked\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ttargetItem := index[i].blockCipher[j].subIndex[queryCipher.upper.blockCipher[j].subIndex][k] // get the item's index\n\n\t\t\t\t// perform the hash operation to check if this item is matched by the query lower-bound block\n\t\t\t\tk1Byte := F(new(big.Int).SetBytes(queryCipher.upper.blockCipher[j].cipher), index[i].gamma)\n\t\t\t\tk2Byte := index[i].blockCipher[j].ciphers[targetItem]\n\n\t\t\t\tif bytes.Equal(k1Byte, k2Byte) {\n\t\t\t\t\tisMatched = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif isMatched == true { // if one item in a block matches, the whole index item matches\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif isMatched == true { // insert the matched index into the result list\n\t\t\tres.PushBack(index[i].note)\n\t\t}\n\t}\n}", "func deriveIntersect(this, that []int) []int {\n\tintersect := make([]int, 0, deriveMin(len(this), len(that)))\n\tfor i, v := range this {\n\t\tif deriveContains(that, v) {\n\t\t\tintersect = append(intersect, this[i])\n\t\t}\n\t}\n\treturn intersect\n}", "func (db *calcDatabase) columnIndex(database [][]formulaArg, field formulaArg) int {\n\tnum := field.ToNumber()\n\tif num.Type != ArgNumber && len(database) > 0 {\n\t\tfor i := 0; i < len(database[0]); i++ {\n\t\t\tif title := database[0][i]; strings.EqualFold(title.Value(), field.Value()) {\n\t\t\t\treturn i\n\t\t\t}\n\t\t}\n\t\treturn -1\n\t}\n\treturn int(num.Number - 1)\n}", "func ruleParaIx(prMap map[int][]int) map[int]int {\n\truleParaIx := make(map[int]int)\n\n\tfor i:=0; i<len(prMap); i++ {\n\n\t\t// this loop is a clunky way to find the\n\t\t// solution with exactly i+1 rules \n\t\t// a possible optimization could be some kind of sorting\n\t\tfor pix, rls := range prMap {\n\t\t\tif len(rls) == i+1 {\n\t\t\t\tfor _, r := range rls {\n\t\t\t\t\tif _, exists := ruleParaIx[r]; !exists {\n\t\t\t\t\t\truleParaIx[r] = pix\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn ruleParaIx\n}", "func twoSum(nums []int, target int) []int {\n\t//var ans []int\n\tfor i, first := range nums{\n\t\tfor j, second := range nums[1:]{\n\t\t\tif first + second == target{\n\t\t\t\t//return append(ans, i, j)\n\t\t\t\treturn []int{i,j+1}\n\t\t\t}\n\t\t}\n\n\t}\n\treturn nil\n}", "func twoSum(nums []int, target int) (out []int) {\n\tN := len(nums)\n\tfor i, n := range nums {\n\t\tt := target - n\n\t\tfor j := i + 1; j < N; j ++ {\n\t\t\tif nums[j] == t {\n\t\t\t\tout = []int{i, j}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func commonElementsInKSortedArrays644(arrs [][]int) []int {\n\tif arrs == nil || len(arrs) == 0 {\n\t\treturn []int{}\n\t}\n\tif len(arrs) == 1 {\n\t\treturn arrs[0]\n\t}\n\tmid := len(arrs) / 2\n\tleft := commonElementsInKSortedArrays644(arrs[0:mid])\n\tright := commonElementsInKSortedArrays644(arrs[mid:len(arrs)])\n\treturn merge644(left, right)\n}", "func get_col(col int, matrix [][]int) []int {\n var nums = make([]int, 9, 9)\n\n count := 0\n for i := 0; i < 9; i++ {\n nums[count] = matrix[i][col]\n count++\n }\n return nums\n}", "func aliasInts(x, y []int) bool {\n\treturn cap(x) > 0 && cap(y) > 0 && &x[0:cap(x)][cap(x)-1] == &y[0:cap(y)][cap(y)-1]\n}", "func EditDistEx(a, b string) int {\n\tlen1, len2 := len(a), len(b)\n\tif len1 == 0 {\n\t\treturn len2\n\t}\n\tif len2 == 0 {\n\t\treturn len1\n\t}\n\tif len1 < len2 {\n\t\treturn EditDistEx(b, a)\n\t}\n\tcurr, next := 0, 0\n\trow := make([]int, len2+1)\n\n\tfor i := 0; i < len2+1; i++ {\n\t\trow[i] = i\n\t}\n\n\tfor i := 0; i < len1; i++ {\n\t\tcurr = i + 1\n\n\t\tfor j := 0; j < len2; j++ {\n\t\t\tcost := invBool2int(a[i] == b[j] || (i > 0 && j > 0 && a[i-1] == b[j] && a[i] == b[j-1]))\n\t\t\tfmt.Printf(\"%v %v == %v\\n\", a[i], b[j], cost)\n\n\t\t\tnext = min(min(\n\t\t\t\trow[j+1]+1,\n\t\t\t\trow[j]+cost),\n\t\t\t\tcurr+1)\n\n\t\t\trow[j], curr = curr, next\n\t\t}\n\t\trow[len2] = next\n\t\tfmt.Printf(\"%v\\n\", row)\n\t}\n\tfmt.Printf(\"\\n\")\n\tfmt.Printf(\"\\n\")\n\treturn next\n}", "func randPartialIndexPredicateFromCols(\n\trng *rand.Rand, columnTableDefs []*tree.ColumnTableDef, tableName *tree.TableName,\n) tree.Expr {\n\t// Shuffle the columns.\n\tcpy := make([]*tree.ColumnTableDef, len(columnTableDefs))\n\tcopy(cpy, columnTableDefs)\n\trng.Shuffle(len(cpy), func(i, j int) { cpy[i], cpy[j] = cpy[j], cpy[i] })\n\n\t// Select a random number of columns (at least 1). Loop through the columns\n\t// to find columns with types that are currently supported for generating\n\t// partial index expressions.\n\tnCols := rng.Intn(len(cpy)) + 1\n\tcols := make([]*tree.ColumnTableDef, 0, nCols)\n\tfor _, col := range cpy {\n\t\tif isAllowedPartialIndexColType(col) {\n\t\t\tcols = append(cols, col)\n\t\t}\n\t\tif len(cols) == nCols {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Build a boolean expression tree with containing a reference to each\n\t// column.\n\tvar e tree.Expr\n\tfor _, columnTableDef := range cols {\n\t\texpr := randBoolColumnExpr(rng, columnTableDef, tableName)\n\t\t// If an expression has already been built, combine the previous and\n\t\t// current expression with an AndExpr or OrExpr.\n\t\tif e != nil {\n\t\t\texpr = randAndOrExpr(rng, e, expr)\n\t\t}\n\t\te = expr\n\t}\n\treturn e\n}", "func compareVC(leftVC []int, rightVC []int, view []string) []int {\r\n\tleftSum := 0\r\n\trightSum := 0\r\n\tfor i := 0; i < len(view); i++ {\r\n\t\tleftSum += leftVC[i]\r\n\t\trightSum += rightVC[i]\r\n\t}\r\n\tif leftSum > rightSum {\r\n\t\treturn leftVC\r\n\t}\r\n\treturn rightVC\r\n}", "func main() {\n\n\t//We might have points between which we want to calculate distance, in that case we can use struct\n\n\tv1 := Vertex1{2,3}\n\tv2 := Vertex1{6,6}\n\n\n\tans := calculateDistance(v1,v2)\n\tfmt.Printf(\"The distance between the 2 points is %f \\n\",ans)\n\n\n\tpointerToV1 := &v1\n\n\tfmt.Println(pointerToV1)\n\tpointerToV1.Y = 23\n\tfmt.Println(*pointerToV1)\n\tfmt.Println(pointerToV1)\n\n\tarray := [6]int{1,2,3,4,5,6}\n\t//for i:=0;i<6;i++ {\n\t//\tfmt.Println(array[i])\n\t//}\n\tfmt.Println(array)\n\n\ts := array[4:5]\n\t//for i:=0;i<len(s);i++ {\n\t//\tfmt.Println(s[i])\n\t//}\n\tfmt.Println(s)\n\tfmt.Println(cap(s),\" \",len(s))\n\n\tfmt.Println(&s[0])\n\tfmt.Println(&array[1])\n\n\tvar s1 []int\n\tfmt.Println(cap(s1),\" \",len(s1))\n\n\ta := make([]int,5,10)\n\tfmt.Println(cap(a),len(a))\n\tb := a[3:5]\n\tfmt.Println(cap(b),len(b))\n\n\n\t// Understanding slices of slices\n\t\tboard := [][]string {\n\t\t\t[]string{\"_\",\"_\",\"_\"},\n\t\t\t[]string{\"_\",\"_\",\"_\"},\n\t\t\t[]string{\"_\",\"_\",\"_\"},\n\t\t}\n\t\tfor i:= range board{\n\t\t\tfor j:= range board[0] {\n\t\t\t\tfmt.Print(board[i][j]+\" \")\n\t\t\t}\n\t\t\tfmt.Println()\n\t\t}\n\n\t\tarr := []int {1,2,3,4,5}\n\t\tfor i,j := range arr {\n\t\t\tfmt.Println(i,j)\n\t\t}\n\n\tvar s3 []int\n\tfmt.Println(s3)\n\ts3 = append(s3,0,2,2)\n\tfmt.Println(s3)\n\n\tvar arr3 = [8]int {6,5,4,3,2,1,0,-1}\n\ts5 := arr3[1:6]\n\tincreaseByOne(s5)\n\tfmt.Println(s5)\n\tfmt.Println(arr3)\n}", "func main() {\n\t\n\tvar arr [5]string =[\"Lunes\", \"Martes\", \"Miercoles\", \"Jueves\", \"Viernes\"]\n\tvar arr [3]string =[\"Dia\", \"Tarde\", \"Noche\"]\n\n\tfor i := 0; i < len(arr); i++ {\n\t\tfor x := 0; x < len(arr2); i++ {\n\t\t\tfmt.Println(arr[x])\n\t\t}\n\t}", "func getColumns(grid [][]int) [][]int {\n\tcols := [][]int{}\n\n\tif len(grid) == 0 {\n\t\treturn cols\n\t}\n\n\tfor colIndex := 0; colIndex < len(grid[0]); colIndex++ {\n\t\tcols = append(cols, []int{})\n\t\tfor rowIndex := 0; rowIndex < len(grid); rowIndex++ {\n\t\t\tcols[colIndex] = append(cols[colIndex], grid[rowIndex][colIndex])\n\t\t}\n\t}\n\n\treturn cols\n}", "func compare2DSlices(A, B []int) bool {\n\tif len(A) != len(B) {\n\t\treturn false\n\t}\n\n\tif len(A) == 0 {\n\t\treturn true // empty slices is equal\n\t}\n\n\tsort.Ints(A)\n\tsort.Ints(B)\n\n\tfor i, a := range A {\n\t\tif a != B[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func comparator(resultA []int64, resultB []int64) (numberofMatches int) {\n\n\tdefer measureTime(time.Now(), \"comparator\")\n\tnumberofMatches = 0\n\n\tfor ic := 0; ic < numberofPairs; ic++ { //\tComparator Code here =>\n\n\t\tresultA16LSB := resultA[ic] & 0x0000FFFF\n\t\tresultB16LSB := resultB[ic] & 0x0000FFFF\n\t\t/*\n\t\t\tif ic < 5 {\n\t\t\t\tfmt.Printf(\"resultA bits: => %032b\\n\", resultA[ic])\n\t\t\t\tfmt.Printf(\"resultB bits: => %032b\\n\", resultB[ic])\n\t\t\t\tfmt.Println(\"--------------------------------------------------\")\n\n\t\t\t\tfmt.Printf(\"resultA16LSB: => %032b\\n\", resultA16LSB)\n\t\t\t\tfmt.Printf(\"resultB16LSB: => %032b\\n\", resultB16LSB)\n\t\t\t\tfmt.Println(\"--------------------------------------------------\")\n\t\t\t}\n\t\t*/\n\t\tif resultB16LSB == resultA16LSB {\n\t\t\tnumberofMatches++\n\t\t\t//\tfmt.Println(numberofMatches)\n\t\t}\n\t}\n\treturn numberofMatches\n}", "func mergeMe(inAr1 []int, inAr2 []int) {\n\t// Flag to drive the processing\n\tprocFlag := true\n\n\t// Variable to track inAr1's index value\n\tind1 := 0\n\tind2 := 0\n\n\tfor procFlag {\n\t\tfmt.Printf(\"In loop with ind1: %v, ind2: %v, and procFlag: %v\\n\", ind1, ind2, procFlag)\n\t\t// Check if we've exhausted the inAr1 array\n\t\tif ind1 < len(inAr1) {\n\n\t\t\tswitch {\n\n\t\t\tcase inAr2[ind2] > inAr1[ind1]:\n\t\t\t\t// inAr1's element is less than inAr2's element, append it (inAr1 element) to the new array\n\t\t\t\tnewArr = append(newArr, inAr1[ind1])\n\t\t\t\t// Handled the current inAr1 element, move to the next element in inAr1\n\t\t\t\tind1++\n\t\t\tcase inAr2[ind2] < inAr1[ind1]:\n\t\t\t\t// inAr2's element is less than inAr2's element, append it (inAr2 element) to the new array\n\t\t\t\tnewArr = append(newArr, inAr2[ind2])\n\t\t\t\t// Handled the current inAr2 element, move to the next element in inAr2\n\t\t\t\tind2++\n\t\t\tcase inAr2[ind2] == inAr1[ind1]:\n\t\t\t\t// inAr2's element is less than inAr2's element, append it (inAr2 element) to the new array\n\t\t\t\tnewArr = append(newArr, inAr1[ind1])\n\t\t\t\tnewArr = append(newArr, inAr2[ind2])\n\t\t\t\t// Handled the current inAr2 element, move to the next element in inAr2\n\t\t\t\tind1++\n\t\t\t\tind2++\n\t\t\t}\n\n\t\t} else {\n\t\t\t// No more inAr1 elements to check, append the inAr2 element to the new array\n\t\t\tnewArr = append(newArr, inAr2[ind2])\n\t\t\tind2++\n\t\t}\n\n\t\t// Check if we've exhausted inAr2\n\t\tif ind2 >= len(inAr2) {\n\t\t\t// Stop the iterations\n\t\t\tprocFlag = false\n\t\t}\n\t}\n\n\t// Check to see if there are any remaining elements in inAr1\n\t// if so, simply append those to the new array\n\tif ind1 < len(inAr1) {\n\t\tnewArr = append(newArr, inAr1[ind1:len(inAr1)]...)\n\t}\n\n\treturn\n}", "func OtherMultipleOfIndex(ints []int) []int {\n\t// good luck\n\tret := make([]int, 0)\n\n\tfor i := 1; i < len(ints); i++ {\n\t\tif ints[i]%i == 0 {\n\t\t\tret = append(ret, ints[i])\n\t\t}\n\t}\n\treturn ret\n}", "func intersectB(nums1 []int, nums2 []int) []int {\n\tif len(nums2) > len(nums1) {\n\t\tnums1, nums2 = nums2, nums1\n\t}\n\n\ttaken := make([]bool, len(nums2))\n\tresp := []int{}\n\tfor i := 0; i < len(nums1); i++ {\n\t\tfor j := 0; j < len(nums2); j++ {\n\t\t\tif nums1[i] == nums2[j] && !taken[j] {\n\t\t\t\tresp = append(resp, nums1[i])\n\t\t\t\ttaken[j] = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn resp\n}", "func (rg Range) Columns(x0, x1 int) Range {\n\tnrg := rg\n\tnrg.Min.X = rg.Min.X + x0\n\tnrg.Max.X = rg.Min.X + x1\n\treturn rg.Intersect(nrg)\n}", "func intervalIntersection(A [][]int, B [][]int) [][]int {\n\tia := 0\n\tib := 0\n\tmerged := [][]int{}\n\tfor {\n\t\tif ia >= len(A) || ib >= len(B) {\n\t\t\tbreak\n\t\t}\n\t\tvar a, b []int\n\t\tif ia != len(A) {\n\t\t\ta = A[ia]\n\t\t}\n\t\tif ib != len(B) {\n\t\t\tb = B[ib]\n\t\t}\n\n\t\tif a[0] < b[0] {\n\t\t\tif a[1] >= b[1] {\n\t\t\t\tmerged = append(merged, []int{b[0], b[1]})\n\t\t\t\tib++\n\t\t\t} else if a[1] >= b[0] {\n\t\t\t\tmerged = append(merged, []int{b[0], a[1]})\n\t\t\t\tia++\n\t\t\t} else {\n\t\t\t\tia++\n\t\t\t}\n\n\t\t} else if a[0] == b[0] {\n\t\t\t// a and b start together\n\t\t\tif a[1] > b[1] {\n\t\t\t\t// b contained in a\n\t\t\t\tmerged = append(merged, []int{a[0], b[1]})\n\n\t\t\t\tib++\n\t\t\t} else if a[1] == b[1] {\n\t\t\t\t// full overlap\n\t\t\t\tmerged = append(merged, []int{a[0], a[1]})\n\t\t\t\tia++\n\t\t\t\tib++\n\t\t\t} else /* a[1] < b[1] */ {\n\t\t\t\t// a contained in b\n\t\t\t\tmerged = append(merged, []int{a[0], b[1]})\n\t\t\t\tia++\n\t\t\t}\n\t\t} else {\n\t\t\t// a > b\n\t\t\tif b[1] >= a[1] {\n\t\t\t\t// containment: a in b\n\t\t\t\tmerged = append(merged, []int{a[0], a[1]})\n\t\t\t\tia++\n\t\t\t\tif b[1] == a[1] {\n\t\t\t\t\tib++\n\t\t\t\t}\n\t\t\t} else if b[1] >= a[0] {\n\t\t\t\tmerged = append(merged, []int{a[0], b[1]})\n\t\t\t\tib++\n\t\t\t} else {\n\t\t\t\t// no overlap\n\t\t\t\tib++\n\t\t\t}\n\t\t}\n\t}\n\treturn merged\n}", "func intersectPreferences(a []uint8, b []uint8) (intersection []uint8) {\n\tvar j int\n\tfor _, v := range a {\n\t\tfor _, v2 := range b {\n\t\t\tif v == v2 {\n\t\t\t\ta[j] = v\n\t\t\t\tj++\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn a[:j]\n}", "func twoSum1(nums []int, target int) []int {\n\tfor i, j := range nums {\n\t\tfor k := i + 1; k < len(nums); k++ {\n\t\t\tif nums[k]+j == target {\n\t\t\t\treturn []int{i, k}\n\t\t\t}\n\t\t}\n\t}\n\treturn []int{}\n}", "func (t *table) appendBounds(cr *colReader) {\n\tbounds := []execute.Time{t.bounds.Start, t.bounds.Stop}\n\tfor j := range []int{startColIdx, stopColIdx} {\n\t\tb := arrow.NewIntBuilder(t.alloc)\n\t\tb.Reserve(cr.l)\n\t\tfor i := 0; i < cr.l; i++ {\n\t\t\tb.UnsafeAppend(int64(bounds[j]))\n\t\t}\n\t\tcr.cols[j] = b.NewArray()\n\t\tb.Release()\n\t}\n}", "func twoSum(nums []int, target int) []int {\n\trecord := make(map[int]int)\n\n\tfor i, j := range nums {\n\t\tcomplement := target - j\n\t\tif res, ok := record[complement]; ok {\n\t\t\treturn []int{res, i}\n\t\t}\n\t\trecord[j] = i\n\t}\n\treturn []int{}\n}", "func BoolIdxRng(list []bool, indices []int, element bool) (int, int, bool) {\n\tleft := 0\n\tright := len(indices) - 1\n\tfor left <= right {\n\t\tmiddle := (left + right) / 2\n\t\tvalueIndex := indices[0]\n\t\tvalue := list[valueIndex]\n\t\tif element != value {\n\t\t\tif element {\n\t\t\t\tleft = middle + 1\n\t\t\t} else {\n\t\t\t\tright = middle - 1\n\t\t\t}\n\t\t} else {\n\t\t\tfrom := boolIdxRngL(list, indices, element, left, middle-1)\n\t\t\tto := boolIdxRngR(list, indices, element, middle+1, right)\n\t\t\treturn from, to, true\n\t\t}\n\t}\n\treturn left, left + 1, false\n}", "func twoSum(nums []int, target int) []int {\n\tvar record = make(map[int]int)\n\tfor i, v := range nums {\n\t\tif index, ok := record[target-nums[i]]; ok {\n\t\t\treturn []int{index, i}\n\t\t}\n\t\trecord[v] = i\n\t}\n\n\treturn nil\n}", "func Take(dst, src []float64, indices []int) []float64 {\n\n\tif len(indices) > len(src) {\n\t\tpanic(errLength)\n\t}\n\n\tif dst == nil {\n\t\tdst = make([]float64, len(indices))\n\t}\n\n\tif len(dst) != len(indices) {\n\t\tpanic(errLength)\n\t}\n\n\tif len(indices) == 0 {\n\t\treturn dst\n\t}\n\n\tdst[0] = src[indices[0]]\n\tfor i := 1; i < len(indices); i++ {\n\t\tv0 := indices[i-1]\n\t\tv1 := indices[i]\n\t\tswitch {\n\t\tcase v0 == v1:\n\t\t\tpanic(errDuplicateIndices)\n\t\tcase v0 > v1:\n\t\t\tpanic(errSortedIndices)\n\t\t}\n\t\tdst[i] = src[v1]\n\t}\n\n\treturn dst\n}", "func intersect(a, b []model.Fingerprint) []model.Fingerprint {\n\tif a == nil {\n\t\treturn b\n\t}\n\tresult := []model.Fingerprint{}\n\tfor i, j := 0, 0; i < len(a) && j < len(b); {\n\t\tif a[i] == b[j] {\n\t\t\tresult = append(result, a[i])\n\t\t}\n\t\tif a[i] < b[j] {\n\t\t\ti++\n\t\t} else {\n\t\t\tj++\n\t\t}\n\t}\n\treturn result\n}", "func index(vs []int, t int) int {\n\tfor i, v := range vs {\n\t\tif v == t {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func twoSum(nums []int, target int) []int {\n\n\tfor i, v := range nums {\n\t\tfor ii := i + 1; ii < len(nums); ii++ {\n\t\t\tif v+nums[ii] == target {\n\t\t\t\treturn []int{i, ii}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func checkLines(marked [][]float64) (map[int]bool, map[int]bool) {\n\tmarkedRows := make(map[int]bool)\n\tmarkedCols := make(map[int]bool)\n\n\t//Mark all rows having no assignments\n\tfor row := range marked {\n\t\tmarkedRows[row] = true\n\t\tfor col := range marked {\n\t\t\tif marked[row][col] == 1 {\n\t\t\t\tdelete(markedRows, row)\n\t\t\t}\n\t\t}\n\t}\n\n\tvar numMarkedRows int\n\tvar numMarkedCols int\n\tnewlyMarkedRows := markedRows\n\tnewlyMarkedCols := make(map[int]bool)\n\tfor numMarkedRows != len(markedRows) || numMarkedCols != len(markedCols) {\n\t\tnumMarkedRows = len(markedRows)\n\t\tnumMarkedCols = len(markedCols)\n\t\t//Mark all columns having zeros in newly marked row(s)\n\t\tfor markedRow := range newlyMarkedRows {\n\t\t\tfor col := range marked {\n\t\t\t\tif marked[markedRow][col] != 0 {\n\t\t\t\t\tnewlyMarkedCols[col] = true\n\t\t\t\t\tmarkedCols[col] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tnewlyMarkedRows = make(map[int]bool) // reset newly\n\t\t//Mark all rows having assignments in newly marked columns\n\t\tfor markedCol := range newlyMarkedCols {\n\t\t\tfor row := range marked {\n\t\t\t\tif marked[row][markedCol] == 1 {\n\t\t\t\t\tnewlyMarkedRows[row] = true\n\t\t\t\t\tmarkedRows[row] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tnewlyMarkedCols = make(map[int]bool) // reset newly\n\n\t}\n\t// return lines for the markedCols and for the UNmarkedRows\n\trowLines := make(map[int]bool)\n\tfor i := range marked {\n\t\tif !markedRows[i] {\n\t\t\trowLines[i] = true\n\t\t}\n\t}\n\tcolLines := markedCols\n\treturn rowLines, colLines\n}", "func checkIndexBounds(indices *Data, upperlimit uint64) error {\n\tif indices.length == 0 {\n\t\treturn nil\n\t}\n\n\tvar maxval uint64\n\tswitch indices.dtype.ID() {\n\tcase arrow.UINT8:\n\t\tmaxval = math.MaxUint8\n\tcase arrow.UINT16:\n\t\tmaxval = math.MaxUint16\n\tcase arrow.UINT32:\n\t\tmaxval = math.MaxUint32\n\tcase arrow.UINT64:\n\t\tmaxval = math.MaxUint64\n\t}\n\t// for unsigned integers, if the values array is larger than the maximum\n\t// index value (especially for UINT8/UINT16), then there's no need to\n\t// boundscheck. for signed integers we still need to bounds check\n\t// because a value could be < 0.\n\tisSigned := maxval == 0\n\tif !isSigned && upperlimit > maxval {\n\t\treturn nil\n\t}\n\n\tstart := indices.offset\n\tend := indices.offset + indices.length\n\n\t// TODO(ARROW-15950): lift BitSetRunReader from parquet to utils\n\t// and use it here for performance improvement.\n\n\tswitch indices.dtype.ID() {\n\tcase arrow.INT8:\n\t\tdata := arrow.Int8Traits.CastFromBytes(indices.buffers[1].Bytes())\n\t\tmin, max := utils.GetMinMaxInt8(data[start:end])\n\t\tif min < 0 || max >= int8(upperlimit) {\n\t\t\treturn fmt.Errorf(\"contains out of bounds index: min: %d, max: %d\", min, max)\n\t\t}\n\tcase arrow.UINT8:\n\t\tdata := arrow.Uint8Traits.CastFromBytes(indices.buffers[1].Bytes())\n\t\t_, max := utils.GetMinMaxUint8(data[start:end])\n\t\tif max >= uint8(upperlimit) {\n\t\t\treturn fmt.Errorf(\"contains out of bounds index: max: %d\", max)\n\t\t}\n\tcase arrow.INT16:\n\t\tdata := arrow.Int16Traits.CastFromBytes(indices.buffers[1].Bytes())\n\t\tmin, max := utils.GetMinMaxInt16(data[start:end])\n\t\tif min < 0 || max >= int16(upperlimit) {\n\t\t\treturn fmt.Errorf(\"contains out of bounds index: min: %d, max: %d\", min, max)\n\t\t}\n\tcase arrow.UINT16:\n\t\tdata := arrow.Uint16Traits.CastFromBytes(indices.buffers[1].Bytes())\n\t\t_, max := utils.GetMinMaxUint16(data[start:end])\n\t\tif max >= uint16(upperlimit) {\n\t\t\treturn fmt.Errorf(\"contains out of bounds index: max: %d\", max)\n\t\t}\n\tcase arrow.INT32:\n\t\tdata := arrow.Int32Traits.CastFromBytes(indices.buffers[1].Bytes())\n\t\tmin, max := utils.GetMinMaxInt32(data[start:end])\n\t\tif min < 0 || max >= int32(upperlimit) {\n\t\t\treturn fmt.Errorf(\"contains out of bounds index: min: %d, max: %d\", min, max)\n\t\t}\n\tcase arrow.UINT32:\n\t\tdata := arrow.Uint32Traits.CastFromBytes(indices.buffers[1].Bytes())\n\t\t_, max := utils.GetMinMaxUint32(data[start:end])\n\t\tif max >= uint32(upperlimit) {\n\t\t\treturn fmt.Errorf(\"contains out of bounds index: max: %d\", max)\n\t\t}\n\tcase arrow.INT64:\n\t\tdata := arrow.Int64Traits.CastFromBytes(indices.buffers[1].Bytes())\n\t\tmin, max := utils.GetMinMaxInt64(data[start:end])\n\t\tif min < 0 || max >= int64(upperlimit) {\n\t\t\treturn fmt.Errorf(\"contains out of bounds index: min: %d, max: %d\", min, max)\n\t\t}\n\tcase arrow.UINT64:\n\t\tdata := arrow.Uint64Traits.CastFromBytes(indices.buffers[1].Bytes())\n\t\t_, max := utils.GetMinMaxUint64(data[indices.offset : indices.offset+indices.length])\n\t\tif max >= upperlimit {\n\t\t\treturn fmt.Errorf(\"contains out of bounds value: max: %d\", max)\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid type for bounds checking: %T\", indices.dtype)\n\t}\n\n\treturn nil\n}", "func (s VectOp) IndexesOf(p fs.Predicate) []int {\n\tvar indexes []int\n\tfor i, val := range s {\n\t\tif p(val) {\n\t\t\tindexes = append(indexes, i)\n\t\t}\n\t}\n\treturn indexes\n}", "func sliceSubset(a, b []string) []string {\n\tresults := []string{}\n\n\tfor _, aValue := range a {\n\t\tif !existsInList(b, aValue) {\n\t\t\tresults = append(results, aValue)\n\t\t}\n\t}\n\n\treturn results\n}", "func TwoPointPerm(a, b []int) []int {\n\tif len(a) != len(b) {\n\t\tpanic(\"expected inputs to have same length\")\n\t}\n\tc := make([]int, len(a))\n\tstart, end := rand.Intn(len(c)), rand.Intn(len(c))\n\tif start > end {\n\t\tstart, end = end, start\n\t}\n\t// take every value between start and end from a\n\ttaken := map[int]bool{}\n\tfor i := range c {\n\t\tif start <= i && i < end {\n\t\t\tc[i] = a[i]\n\t\t\ttaken[a[i]] = true\n\t\t}\n\t}\n\t// return index of next untaken value in b\n\tnextFromB := func() int {\n\t\tfor bindex := 0; bindex < len(b); bindex++ {\n\t\t\t_, exists := taken[b[bindex]]\n\t\t\tif !exists {\n\t\t\t\treturn bindex\n\t\t\t}\n\t\t}\n\t\tpanic(\"No untaken values in b left but another value was requested. Verify that the inputs have unique contents.\")\n\t}\n\t// fill gaps in c with untaken values from b\n\tfor i := range c {\n\t\tif i < start || end <= i {\n\t\t\tnextBIndex := nextFromB()\n\t\t\ttaken[b[nextBIndex]] = true\n\t\t\tc[i] = b[nextBIndex]\n\t\t}\n\t}\n\treturn c\n}", "func inTabuList(candidate []int, tabuList [][]int) bool {\r\n\tfor _, val := range tabuList {\r\n\t\tif IntsEquals(candidate, val) {\r\n\t\t\treturn true\r\n\t\t}\r\n\t}\r\n\treturn false\r\n}", "func markerIndexComparator(a, b interface{}) int {\n\taCasted := a.(markers.Index)\n\tbCasted := b.(markers.Index)\n\n\tswitch {\n\tcase aCasted < bCasted:\n\t\treturn -1\n\tcase aCasted > bCasted:\n\t\treturn 1\n\tdefault:\n\t\treturn 0\n\t}\n}", "func getChildIndices(pos int) (int, int) {\n\treturn (2 * pos) + 1, (2 * pos) + 2\n}", "func indexCombinations(n int) [][]int {\n\tresultMap := make(map[int][]int)\n\tnextResultMapKey := 0\n\tfirstCombination := make([]int, n)\n\n\tindexCombinationsRecursive(n, firstCombination, 0, resultMap, &nextResultMapKey)\n\n\tret := make([][]int, len(resultMap))\n\tfor k, v := range resultMap {\n\t\tret[k] = v\n\t}\n\n\treturn ret\n}", "func find(s [][]int, e []int) int {\n\tfor i, n := range s {\n\t\tif equals(n, e) {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func CalcSliceIntDifference(a, b []int) []int {\n\tmb := map[int]bool{}\n\tfor _, x := range b {\n\t\tmb[x] = true\n\t}\n\tab := []int{}\n\tfor _, x := range a {\n\t\tif _, ok := mb[x]; !ok {\n\t\t\tab = append(ab, x)\n\t\t}\n\t}\n\treturn ab\n}", "func firstTwoSlice(array []int) ([]int, error) {\n\n\tif len(array) < 3 {\n\t\treturn nil, errors.New(\"Array needs to have 3 of more elements\")\n\t}\n\n\t// s is []int\n\t// A slice is formed by specifying two indices, a low and high bound, separated by a colon:\n\t// a[low : high]\n\t// This selects a half-open range which includes the first element, but excludes the last one.\n\ts := array[1:3]\n\treturn s, nil\n}" ]
[ "0.5408901", "0.5372722", "0.51973224", "0.5108608", "0.5081069", "0.5075441", "0.5071634", "0.49702466", "0.4949031", "0.49230248", "0.48864025", "0.48742807", "0.4862145", "0.48436132", "0.4823846", "0.47946924", "0.47935823", "0.47839373", "0.4770979", "0.4752496", "0.4733612", "0.4718815", "0.4691528", "0.4682155", "0.46709582", "0.46653047", "0.46501932", "0.4648609", "0.46423608", "0.46397913", "0.46329045", "0.46117303", "0.4604372", "0.4592998", "0.4592709", "0.45908394", "0.4588254", "0.45796683", "0.45785525", "0.45702678", "0.45688897", "0.4564749", "0.45513132", "0.4551055", "0.45382673", "0.45332825", "0.45268723", "0.4524833", "0.45213282", "0.45168278", "0.45117915", "0.45069838", "0.45057237", "0.45052642", "0.45013243", "0.4491819", "0.44904497", "0.44839904", "0.448249", "0.4465623", "0.44497916", "0.443808", "0.44330347", "0.44297165", "0.44237208", "0.442184", "0.44192392", "0.4418459", "0.44150367", "0.44031104", "0.4396575", "0.4389672", "0.438826", "0.43832177", "0.43768084", "0.43759257", "0.4373243", "0.43729192", "0.436246", "0.43616438", "0.43611816", "0.43607485", "0.43576118", "0.43562338", "0.43554127", "0.43507087", "0.4347676", "0.43474138", "0.43453908", "0.43435517", "0.4342449", "0.4341102", "0.4338212", "0.43372998", "0.4336922", "0.433653", "0.4334644", "0.43338674", "0.43320113", "0.4315879" ]
0.5508602
0
Serialize implement Serializable interface serialize a variable bytes array into format below: variable length + bytes[]
func (vb *VarBytes) Serialize(w io.Writer) error { var varlen = VarUint{UintType: GetUintTypeByValue(vb.Len), Value: vb.Len} if err := varlen.Serialize(w); err != nil { return err } return binary.Write(w, binary.LittleEndian, vb.Bytes) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *RecBytes) Serialize() []byte {\n\tres := make([]byte, 0, len(r.Path)+len(r.Time)+len(r.Val)+3)\n\tres = append(res, r.Path...)\n\tres = append(res, ' ')\n\tres = append(res, r.Val...)\n\tres = append(res, ' ')\n\tres = append(res, r.Time...)\n\tres = append(res, '\\n')\n\n\treturn res\n}", "func (n ByteArray) Serialize() *bytes.Buffer {\n\tbuffer := bytes.NewBuffer([]byte{})\n\twriteByteArray([]byte(n), buffer)\n\treturn buffer\n}", "func Pack(data []interface{}) []byte {\n\tbuf := new(bytes.Buffer)\n\tfor _, v := range data {\n\t\terr := binary.Write(buf, binary.BigEndian, v)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"failed packing bytes:\", err)\n\t\t}\n\t}\n\treturn buf.Bytes()\n}", "func (enc *Encoder) EncodeFixedByteArray(v []byte) (int, error) {\n\treturn enc.w.Write(v)\n}", "func encodeByteSlice(w io.Writer, bz []byte) (err error) {\n\terr = encodeVarint(w, int64(len(bz)))\n\tif err != nil {\n\t\treturn\n\t}\n\t_, err = w.Write(bz)\n\treturn\n}", "func sliceEncoder(e *encodeState, v reflect.Value) {\n\tif v.IsNil() {\n\t\te.WriteString(\"le\")\n\t\treturn\n\t}\n\tif v.Type().Elem().Kind() == reflect.Uint8 {\n\t\ts := v.Bytes()\n\t\tb := strconv.AppendInt(e.scratch[:0], int64(len(s)), 10)\n\t\te.Write(b)\n\t\te.WriteString(\":\")\n\t\te.Write(s)\n\t}\n}", "func (enc *Encoder) EncodeByteArray(v []byte) (int, error) {\n\tinputLen, err := enc.EncodeUInt32(uint32(len(v)))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tdataLen, err := enc.EncodeFixedByteArray(v)\n\tinputLen += dataLen\n\n\treturn inputLen, err\n}", "func encodeBytes(data []byte) []byte {\n\t// Allocate more space to avoid unnecessary slice growing.\n\t// Assume that the byte slice size is about `(len(data) / encGroupSize + 1) * (encGroupSize + 1)` bytes,\n\t// that is `(len(data) / 8 + 1) * 9` in our implement.\n\tdLen := len(data)\n\tresult := make([]byte, 0, (dLen/encGroupSize+1)*(encGroupSize+1))\n\tfor idx := 0; idx <= dLen; idx += encGroupSize {\n\t\tremain := dLen - idx\n\t\tpadCount := 0\n\t\tif remain >= encGroupSize {\n\t\t\tresult = append(result, data[idx:idx+encGroupSize]...)\n\t\t} else {\n\t\t\tpadCount = encGroupSize - remain\n\t\t\tresult = append(result, data[idx:]...)\n\t\t\tresult = append(result, pads[:padCount]...)\n\t\t}\n\n\t\tmarker := encMarker - byte(padCount)\n\t\tresult = append(result, marker)\n\t}\n\treturn result\n}", "func Write(w io.Writer, byteorder binary.ByteOrder, data interface{}) error {\n\n\tswitch data.(type) {\n\tcase uint8, uint16, uint32, uint64, int8, int16, int32, int64, float32, float64:\n\t\treturn binary.Write(w, byteorder, data)\n\t}\n\n\tv := reflect.ValueOf(data)\n\n\tswitch v.Kind() {\n\tcase reflect.Array, reflect.Slice:\n\t\tif v.Kind() == reflect.Slice && v.Type().Elem().Kind() == reflect.Uint8 {\n\t\t\t_, err := w.Write(v.Bytes())\n\t\t\treturn err\n\t\t}\n\n\t\tl := v.Len()\n\t\tfor i := 0; i < l; i++ {\n\t\t\terr := Write(w, byteorder, v.Index(i).Interface())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\tcase reflect.Struct:\n\t\t// write all public fields in order\n\t\ttyp := v.Type()\n\t\tl := typ.NumField()\n\t\tfor i := 0; i < l; i++ {\n\t\t\tf := typ.Field(i)\n\t\t\tif f.PkgPath != \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfval := v.Field(i)\n\n\t\t\topts := parseTag(f.Tag)\n\t\t\tvar bOrder binary.ByteOrder = byteorder\n\t\t\tif opts.endian != nil {\n\t\t\t\tbOrder = opts.endian\n\t\t\t}\n\n\t\t\t// if we have a slice embedded in a struct, get the struct tag that tells us how to write the (unknown) length before the contents\n\t\t\tif f.Type.Kind() == reflect.Slice {\n\t\t\t\tslen := uint64(fval.Len())\n\n\t\t\t\tif opts.lenprefix == \"\" {\n\t\t\t\t\treturn ErrMissingLenPrefix\n\t\t\t\t}\n\n\t\t\t\tmaxlen, ok := maxSliceLen[opts.lenprefix]\n\t\t\t\tif !ok {\n\t\t\t\t\treturn ErrUnknownLenPrefix\n\t\t\t\t}\n\n\t\t\t\tif slen > maxlen {\n\t\t\t\t\treturn ErrSliceTooLarge\n\t\t\t\t}\n\n\t\t\t\tvar err error\n\t\t\t\tswitch opts.lenprefix {\n\t\t\t\tcase \"uint8\":\n\t\t\t\t\terr = binary.Write(w, bOrder, uint8(slen))\n\n\t\t\t\tcase \"uint16\":\n\t\t\t\t\terr = binary.Write(w, bOrder, uint16(slen))\n\n\t\t\t\tcase \"uint32\":\n\t\t\t\t\terr = binary.Write(w, bOrder, uint32(slen))\n\n\t\t\t\tcase \"uint64\":\n\t\t\t\t\terr = binary.Write(w, bOrder, slen)\n\n\t\t\t\tcase \"int8\":\n\t\t\t\t\terr = binary.Write(w, bOrder, int8(slen))\n\n\t\t\t\tcase \"int16\":\n\t\t\t\t\terr = binary.Write(w, bOrder, int16(slen))\n\n\t\t\t\tcase \"int32\":\n\t\t\t\t\terr = binary.Write(w, bOrder, int32(slen))\n\n\t\t\t\tcase \"int64\":\n\t\t\t\t\terr = binary.Write(w, bOrder, int64(slen))\n\t\t\t\t}\n\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr := Write(w, bOrder, v.Field(i).Interface())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n\n}", "func MarshalBytes(dst, b []byte) []byte {\n\tdst = MarshalVarUint64(dst, uint64(len(b)))\n\tdst = append(dst, b...)\n\treturn dst\n}", "func (c *uint8Type) SerializeFixedT(v uint8, dest []byte) error {\n\tdest[0] = v\n\treturn nil\n}", "func encodeUxArray(obj *UxArray) ([]byte, error) {\n\tn := encodeSizeUxArray(obj)\n\tbuf := make([]byte, n)\n\n\tif err := encodeUxArrayToBuffer(buf, obj); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf, nil\n}", "func (e *Event) packBytes() ([]byte, error) {\n\tdata := make([]interface{}, 2)\n\tdata[0] = e.Header\n\tdata[1] = e.Name\n\n\tfor _, a := range e.Args {\n\t\tdata = append(data, a)\n\t}\n\n\tvar buf []byte\n\n\tenc := codec.NewEncoderBytes(&buf, &mh)\n\tif err := enc.Encode(data); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf, nil\n}", "func encodeByteSequence(v [][]byte) []byte {\n\tvar hexstrings []string\n\tfor _, a := range v {\n\t\thexstrings = append(hexstrings, hexutil.Encode(a))\n\t}\n\treturn []byte(strings.Join(hexstrings, \",\"))\n}", "func WriteBytes(wtr io.Writer, bs []byte) (err error) {\n\tsz := int64(len(bs))\n\tif sz <= int64(constants.MaxInt32) {\n\t\terr = EncodeAndWriteVarInt32(wtr, int32(sz))\n\t} else {\n\t\terr = EncodeAndWriteVarInt64(wtr, sz)\n\t}\n\tif err != nil {\n\t\treturn oerror.NewTrace(err)\n\t}\n\n\tn, err := wtr.Write(bs)\n\tif err != nil {\n\t\treturn oerror.NewTrace(err)\n\t}\n\n\t// an encoded varint give the length of the remaining byte array\n\tif n != int(sz) {\n\t\treturn fmt.Errorf(\"Error in varint.WriteBytes: size of bytes written was less than byte slice size: %v\", n)\n\t}\n\treturn nil\n}", "func Marshal(val interface{}) ([]byte, error) {}", "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 (r *InterRecord) Bytes() []byte {\n\tif r.Types != 0 {\n\t\treturn r.Raw\n\t}\n\n\t// Collect the buffers to be recycled after generate the JSON\n\tvar buffs []*bytebufferpool.ByteBuffer\n\n\t// Interal function for compress\n\tcomp := func(o []byte) []byte {\n\t\t// Get a buffer from the pool\n\t\tb := compressPool.Get()\n\t\t// append to an slice of bytesbuffers to be recycled (check the defer some upper lines)\n\t\tbuffs = append(buffs, b)\n\n\t\t// Get a gzip from the pull, write in the buffer and return to the pool\n\t\tw := GetGzipWriter(b)\n\t\tw.Write(o)\n\t\tw.Close()\n\n\t\t// Unlink the buffer for the gzip before return to the pool, just in case..?\n\t\tPutGzipWriter(w)\n\n\t\treturn b.B\n\t}\n\n\t// After generate the JSON send the buffer to the pool\n\tdefer func() {\n\t\tif len(buffs) > 0 {\n\t\t\tfor _, b := range buffs {\n\t\t\t\tcompressPool.Put(b)\n\t\t\t}\n\t\t}\n\t}()\n\n\tif r.compressFields {\n\t\tfor k, v := range r.Data {\n\t\t\tswitch o := v.(type) {\n\t\t\tcase []byte:\n\t\t\t\tr.Data[k] = comp(o)\n\t\t\tcase []interface{}:\n\t\t\t\tfor _, iv := range o {\n\t\t\t\t\tswitch o := iv.(type) {\n\t\t\t\t\tcase []byte:\n\t\t\t\t\t\tiv = comp(o)\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase map[string]interface{}:\n\t\t\t\tfor _, iv := range o {\n\t\t\t\t\tswitch o := iv.(type) {\n\t\t\t\t\tcase []byte:\n\t\t\t\t\t\tiv = comp(o)\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\t// No changes\n\t\t\t}\n\t\t}\n\t}\n\n\tbuf, err := ffjson.Marshal(r)\n\tif err != nil {\n\t\tffjson.Pool(buf)\n\t\tlog.Printf(\"Error in ffjson: %s\", err)\n\t\treturn nil\n\t}\n\n\treturn buf\n}", "func (b ByteArray) Encode(w io.Writer) error {\n\terr := util.WriteVarInt(w, len(b))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = w.Write(b)\n\treturn err\n}", "func Encode(data interface{}) []byte {\n v := Value{data}\n return v.Encode()\n}", "func marshal(msgType uint8, msg interface{}) []byte {\n\tvar out []byte\n\tout = append(out, msgType)\n\n\tv := reflect.ValueOf(msg)\n\tstructType := v.Type()\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tfield := v.Field(i)\n\t\tt := field.Type()\n\t\tswitch t.Kind() {\n\t\tcase reflect.Bool:\n\t\t\tvar v uint8\n\t\t\tif field.Bool() {\n\t\t\t\tv = 1\n\t\t\t}\n\t\t\tout = append(out, v)\n\t\tcase reflect.Array:\n\t\t\tif t.Elem().Kind() != reflect.Uint8 {\n\t\t\t\tpanic(\"array of non-uint8\")\n\t\t\t}\n\t\t\tfor j := 0; j < t.Len(); j++ {\n\t\t\t\tout = append(out, byte(field.Index(j).Uint()))\n\t\t\t}\n\t\tcase reflect.Uint32:\n\t\t\tu32 := uint32(field.Uint())\n\t\t\tout = append(out, byte(u32>>24))\n\t\t\tout = append(out, byte(u32>>16))\n\t\t\tout = append(out, byte(u32>>8))\n\t\t\tout = append(out, byte(u32))\n\t\tcase reflect.String:\n\t\t\ts := field.String()\n\t\t\tout = append(out, byte(len(s)>>24))\n\t\t\tout = append(out, byte(len(s)>>16))\n\t\t\tout = append(out, byte(len(s)>>8))\n\t\t\tout = append(out, byte(len(s)))\n\t\t\tout = append(out, s...)\n\t\tcase reflect.Slice:\n\t\t\tswitch t.Elem().Kind() {\n\t\t\tcase reflect.Uint8:\n\t\t\t\tlength := field.Len()\n\t\t\t\tif structType.Field(i).Tag.Get(\"ssh\") != \"rest\" {\n\t\t\t\t\tout = append(out, byte(length>>24))\n\t\t\t\t\tout = append(out, byte(length>>16))\n\t\t\t\t\tout = append(out, byte(length>>8))\n\t\t\t\t\tout = append(out, byte(length))\n\t\t\t\t}\n\t\t\t\tfor j := 0; j < length; j++ {\n\t\t\t\t\tout = append(out, byte(field.Index(j).Uint()))\n\t\t\t\t}\n\t\t\tcase reflect.String:\n\t\t\t\tvar length int\n\t\t\t\tfor j := 0; j < field.Len(); j++ {\n\t\t\t\t\tif j != 0 {\n\t\t\t\t\t\tlength++ /* comma */\n\t\t\t\t\t}\n\t\t\t\t\tlength += len(field.Index(j).String())\n\t\t\t\t}\n\n\t\t\t\tout = append(out, byte(length>>24))\n\t\t\t\tout = append(out, byte(length>>16))\n\t\t\t\tout = append(out, byte(length>>8))\n\t\t\t\tout = append(out, byte(length))\n\t\t\t\tfor j := 0; j < field.Len(); j++ {\n\t\t\t\t\tif j != 0 {\n\t\t\t\t\t\tout = append(out, ',')\n\t\t\t\t\t}\n\t\t\t\t\tout = append(out, field.Index(j).String()...)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tpanic(\"slice of unknown type\")\n\t\t\t}\n\t\tcase reflect.Ptr:\n\t\t\tif t == bigIntType {\n\t\t\t\tvar n *big.Int\n\t\t\t\tnValue := reflect.ValueOf(&n)\n\t\t\t\tnValue.Elem().Set(field)\n\t\t\t\tneeded := intLength(n)\n\t\t\t\toldLength := len(out)\n\n\t\t\t\tif cap(out)-len(out) < needed {\n\t\t\t\t\tnewOut := make([]byte, len(out), 2*(len(out)+needed))\n\t\t\t\t\tcopy(newOut, out)\n\t\t\t\t\tout = newOut\n\t\t\t\t}\n\t\t\t\tout = out[:oldLength+needed]\n\t\t\t\tmarshalInt(out[oldLength:], n)\n\t\t\t} else {\n\t\t\t\tpanic(\"pointer to unknown type\")\n\t\t\t}\n\t\t}\n\t}\n\n\treturn out\n}", "func ConvertFixedDataIntoByteArray(data interface{}) []byte {\n\tbuff := new(bytes.Buffer)\n\terr := binary.Write(buff, binary.BigEndian, data)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\treturn buff.Bytes()\n}", "func toByteArray(data interface{}) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tenc := gob.NewEncoder(&buf)\n\terr := enc.Encode(data)\n\tif err != nil {\n\t\treturn nil, err\n\t} else {\n\t\treturn buf.Bytes(), nil\n\t}\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 ToByteArr(v interface{}) (result []byte) {\n\tresult = []byte(\"\")\n\tif v == nil {\n\t\treturn result\n\t}\n\n\tswitch v := v.(type) {\n\tcase string:\n\t\tresult = []byte(v)\n\tcase int:\n\t\tresult = []byte(strconv.Itoa(v))\n\tcase int64:\n\t\tresult = []byte(strconv.FormatInt(v, 10))\n\tcase bool:\n\t\tresult = []byte(strconv.FormatBool(v))\n\tcase float64:\n\t\tresult = []byte(strconv.FormatFloat(v, 'E', -1, 64))\n\tcase []uint8:\n\t\tresult = v\n\tdefault:\n\t\tresultJSON, err := json.Marshal(v)\n\t\tif err == nil {\n\t\t\tresult = resultJSON\n\t\t} else {\n\t\t\tlog.Println(\"func ToByteArr\", err)\n\t\t}\n\t}\n\n\treturn result\n}", "func (id ID) Bytes() []byte {\n\treturn proto.EncodeVarint(uint64(id))\n}", "func encodeSizeUxArray(obj *UxArray) uint64 {\n\ti0 := uint64(0)\n\n\t// obj.UxArray\n\ti0 += 4\n\t{\n\t\ti1 := uint64(0)\n\n\t\t// x.Head.Time\n\t\ti1 += 8\n\n\t\t// x.Head.BkSeq\n\t\ti1 += 8\n\n\t\t// x.Body.SrcTransaction\n\t\ti1 += 32\n\n\t\t// x.Body.Address.Version\n\t\ti1++\n\n\t\t// x.Body.Address.Key\n\t\ti1 += 20\n\n\t\t// x.Body.Coins\n\t\ti1 += 8\n\n\t\t// x.Body.Hours\n\t\ti1 += 8\n\n\t\ti0 += uint64(len(obj.UxArray)) * i1\n\t}\n\n\treturn i0\n}", "func (e *Encoder) Bytes() []byte { return e.buf }", "func (xd *ExtraData) AsBytes() []byte {\n\tvar length uint\n\tfor _, rec := range xd.Records {\n\t\trecLen := uint(len(rec.Bytes))\n\t\tlength += 4 + recLen\n\t}\n\n\tout := make([]byte, 0, length)\n\tfor _, rec := range xd.Records {\n\t\tvar tmp [2]byte\n\t\tbinary.LittleEndian.PutUint16(tmp[:], uint16(len(rec.Bytes)))\n\t\tout = append(out, rec.ID[0], rec.ID[1], tmp[0], tmp[1])\n\t\tout = append(out, rec.Bytes...)\n\t}\n\treturn out\n}", "func AsBytes(objs ...interface{}) []byte {\n\tbbuf, err := EncodeBytes(objs...)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn bbuf\n}", "func (a *Asset) FixedBytes() [common.AssetLength]byte {\n\tvar serialized [common.AssetLength]byte\n\tbinary.BigEndian.PutUint32(serialized[:], a.Property)\n\tbinary.BigEndian.PutUint64(serialized[4:], a.Id)\n\treturn serialized\n}", "func (v *Value) Bytes() []byte {\n switch d := v.data.(type) {\n case []byte:\n return d\n case string:\n return []byte(d)\n default:\n if j, e := json.Marshal(v.data); e == nil {\n return j\n }\n return []byte(fmt.Sprintf(\"%+v\", v.data))\n }\n}", "func WriteBytesStr(b []byte, w io.Writer, array bool) error {\n\tvar prefix string\n\tif array {\n\t\tprefix = \"[\" + strconv.Itoa(len(b)) + \"]byte{\"\n\t} else {\n\t\tprefix = \"[]byte{\"\n\t}\n\treturn writeBytesStr(b, prefix, w)\n}", "func (enc *Encoder) Encode(data interface{}) error {\n\tpadding := enc.offset - len(enc.Buf)\n\n\tif padding > 0 {\n\t\tenc.Buf = append(enc.Buf, make([]byte, padding)...)\n\t}\n\n\tif data, ok := data.(CMarshaler); ok {\n\t\traw, err := data.MarshalC()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tenc.Buf = append(enc.Buf, raw...)\n\n\t\treturn nil\n\t}\n\n\trv := reflect.Indirect(reflect.ValueOf(data))\n\tif !rv.IsValid() {\n\t\treturn fmt.Errorf(\"cmem: reflect.ValueOf returned invalid value for type %T\", data)\n\t}\n\n\trt := rv.Type()\n\n\tswitch rt.Kind() {\n\tcase reflect.Slice:\n\t\tvar tempBuf []byte\n\n\t\tfor i := 0; i < rv.Len(); i++ {\n\t\t\tvar myenc Encoder\n\t\t\tif err := myenc.Encode(rv.Index(i).Interface()); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tmypad := myenc.offset - len(myenc.Buf)\n\t\t\tif mypad > 0 {\n\t\t\t\tmyenc.Buf = append(myenc.Buf, make([]byte, mypad)...)\n\t\t\t}\n\t\t\ttempBuf = append(tempBuf, myenc.Buf...)\n\t\t}\n\n\t\tarraySize := C.size_t(len(tempBuf))\n\t\tvlArray := C.malloc(arraySize)\n\t\tC.bzero(vlArray, arraySize)\n\t\tC.memcpy(vlArray, unsafe.Pointer(&tempBuf[0]), C.size_t(arraySize))\n\t\tenc.pointerSlice = append(enc.pointerSlice, vlArray)\n\n\t\t// this is variable length data, it should follow hvl_t format\n\t\tif err := enc.Encode(C.size_t(rv.Len())); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := enc.Encode(C.size_t(uintptr(vlArray))); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\n\tcase reflect.Array:\n\t\tfor i := 0; i < rv.Len(); i++ {\n\t\t\tif err := enc.Encode(rv.Index(i).Interface()); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\n\tcase reflect.Struct:\n\t\toffset := enc.offset\n\t\tfor i := 0; i < rv.NumField(); i++ {\n\t\t\tsfv := rv.Field(i).Interface()\n\t\t\t// In order to keep the memory offset always correct, we use the\n\t\t\t// structs offset.\n\t\t\tenc.offset = offset + int(rt.Field(i).Offset)\n\t\t\tif err := enc.Encode(sfv); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// Reset the offset to the correct array size.\n\t\t\tenc.offset = offset + int(rt.Size())\n\t\t}\n\t\treturn nil\n\n\tcase reflect.String:\n\t\tstr := append([]byte(rv.String()), 0)\n\n\t\t// This direct machine conversion is only used\n\t\t// because HDF5 uses machine endianism.\n\t\t//\n\t\t// DO NOT DO THIS AT HOME.\n\t\t//\n\t\traw := (*[unsafe.Sizeof(uintptr(0))]byte)(unsafe.Pointer(&str))\n\t\tenc.Buf = append(enc.Buf, raw[:]...)\n\t\tenc.offset += len(raw)\n\n\tcase reflect.Ptr:\n\t\treturn enc.Encode(rv.Elem())\n\n\tcase reflect.Int8:\n\t\tenc.Buf = append(enc.Buf, byte(rv.Int()))\n\t\tenc.offset++\n\n\tcase reflect.Uint8:\n\t\tenc.Buf = append(enc.Buf, byte(rv.Uint()))\n\t\tenc.offset++\n\n\tcase reflect.Int16:\n\t\tvar raw [2]byte\n\t\tnativeEndian.PutUint16(raw[:], uint16(rv.Int()))\n\t\tenc.Buf = append(enc.Buf, raw[:]...)\n\t\tenc.offset += 2\n\n\tcase reflect.Uint16:\n\t\tvar raw [2]byte\n\t\tnativeEndian.PutUint16(raw[:], uint16(rv.Uint()))\n\t\tenc.Buf = append(enc.Buf, raw[:]...)\n\t\tenc.offset += 2\n\n\tcase reflect.Int32:\n\t\tvar raw [4]byte\n\t\tnativeEndian.PutUint32(raw[:], uint32(rv.Int()))\n\t\tenc.Buf = append(enc.Buf, raw[:]...)\n\t\tenc.offset += 4\n\n\tcase reflect.Uint32:\n\t\tvar raw [4]byte\n\t\tnativeEndian.PutUint32(raw[:], uint32(rv.Uint()))\n\t\tenc.Buf = append(enc.Buf, raw[:]...)\n\t\tenc.offset += 4\n\n\tcase reflect.Int64:\n\t\tvar raw [8]byte\n\t\tnativeEndian.PutUint64(raw[:], uint64(rv.Int()))\n\t\tenc.Buf = append(enc.Buf, raw[:]...)\n\t\tenc.offset += 8\n\n\tcase reflect.Uint64:\n\t\tvar raw [8]byte\n\t\tnativeEndian.PutUint64(raw[:], uint64(rv.Uint()))\n\t\tenc.Buf = append(enc.Buf, raw[:]...)\n\t\tenc.offset += 8\n\n\tcase reflect.Float32:\n\t\tvar raw [4]byte\n\t\tnativeEndian.PutUint32(raw[:], math.Float32bits(float32(rv.Float())))\n\t\tenc.Buf = append(enc.Buf, raw[:]...)\n\t\tenc.offset += 4\n\n\tcase reflect.Float64:\n\t\tvar raw [8]byte\n\t\tnativeEndian.PutUint64(raw[:], math.Float64bits(rv.Float()))\n\t\tenc.Buf = append(enc.Buf, raw[:]...)\n\t\tenc.offset += 8\n\n\tcase reflect.Bool:\n\t\tval := byte(0)\n\t\tif rv.Bool() {\n\t\t\tval = 1\n\t\t}\n\t\tenc.Buf = append(enc.Buf, val)\n\t\tenc.offset++\n\n\tdefault:\n\t\treturn fmt.Errorf(\"hdf5: PT Append does not support datatype (%s)\", rt.Kind())\n\t}\n\n\treturn nil\n}", "func (b *blockV1) Serialize(paddedBlockSize uint32) ([]byte, error) {\n\tblockSize := uint32(len(b.GetData()))\n\ttotalSize := blockHeaderLen + blockSize\n\tarrayBytes := totalSize\n\n\t// Padding turned on\n\tif paddedBlockSize > 0 {\n\t\tarrayBytes = paddedBlockSize\n\n\t\t// Each block can be at most \"paddedBlockSize\"\n\t\tif totalSize > paddedBlockSize {\n\t\t\treturn nil, NewBlockPaddingError(\n\t\t\t\t\"Block too large to pad to a fixed size\",\n\t\t\t\tpaddedBlockSize, totalSize, paddedBlockSize-8)\n\t\t}\n\t}\n\n\tserial := make([]byte, arrayBytes)\n\tbinary.BigEndian.PutUint32(serial[0:], b.GetID())\n\tbinary.BigEndian.PutUint32(serial[blockNumLen:], blockSize)\n\tcopy(serial[blockHeaderLen:], b.GetData())\n\n\t// Padding turned on\n\tif paddedBlockSize > 0 {\n\t\tif _, err := rand.Read(serial[totalSize:]); err != nil {\n\t\t\treturn nil, errors.New(err)\n\t\t}\n\t}\n\n\treturn serial, nil\n}", "func serialize(src interface{}) ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\tenc := gob.NewEncoder(buf)\n\tif err := enc.Encode(src); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (d *Decoder) Bytes() []byte {\n\tn := d.Varint()\n\tif n == 0 {\n\t\treturn nil\n\t}\n\tdata := make([]byte, n)\n\tnn, err := d.buf.Read(data)\n\tif int64(nn) != n || err != nil {\n\t\tlog.Panicf(\"unmarshalBytes: %d %d %v\", n, nn, err)\n\t}\n\treturn data\n}", "func (w *ByteWriter) Bytes() []byte { return w.buffer }", "func packBytes(bas... []byte) []byte {\n\tvar packed []byte\n\tfor _, ba := range bas {\n\t\tpacked = append(packed, ba...)\n\t}\n\treturn packed\n}", "func (m *Message) Serialize() []byte {\n\tif m == nil {\n\t\treturn make([]byte, 4)\n\t}\n\tlength := uint32(len(m.Payload) + 1) // +1 for id\n\tbuf := make([]byte, 4+length)\n\tbinary.BigEndian.PutUint32(buf[0:4], length)\n\tbuf[4] = byte(m.ID)\n\tcopy(buf[5:], m.Payload)\n\treturn buf\n}", "func (out *OutBuffer) WriteBytes(d []byte) {\n\tout.Append(d...)\n}", "func bytesToBinaryString(slice []byte) string {\n\t// Convert each byte to its bits representation as string\n\tvar strBuff bytes.Buffer\n\tfor _, b := range(slice) {\n\t\tstrBuff.WriteString(fmt.Sprintf(\"%.8b\", b))\n\t}\n\n\treturn strBuff.String()\n}", "func (f Fixed) MarshalBinary() (data []byte, err error) {\n\tvar buffer [binary.MaxVarintLen64]byte\n\tn := binary.PutVarint(buffer[:], f.fp)\n\treturn buffer[:n], nil\n}", "func (v Vector) MarshalBinary() ([]byte, error) {\n\tbufLen := int64(sizeInt64) + int64(v.n)*int64(sizeFloat64)\n\tif bufLen <= 0 {\n\t\t// bufLen is too big and has wrapped around.\n\t\treturn nil, errTooBig\n\t}\n\n\tp := 0\n\tbuf := make([]byte, bufLen)\n\tbinary.LittleEndian.PutUint64(buf[p:p+sizeInt64], uint64(v.n))\n\tp += sizeInt64\n\n\tfor i := 0; i < v.n; i++ {\n\t\tbinary.LittleEndian.PutUint64(buf[p:p+sizeFloat64], math.Float64bits(v.at(i)))\n\t\tp += sizeFloat64\n\t}\n\n\treturn buf, nil\n}", "func EncodeBytes(objs ...interface{}) (out []byte, err error) {\n\tvar buf bytes.Buffer\n\terr = Encode(&buf, objs...)\n\tif err != nil {\n\t\treturn\n\t}\n\tout = buf.Bytes()\n\treturn\n}", "func MarshalDBtoByte(batch *DataBatch) []byte {\n\n\tdata := make([]byte, 0)\n\n\t//intSize := unsafe.Sizeof(batch.CubeId)\n\t//uintSize := unsafe.Sizeof(batch.Capacity) // capacity(uint) and Dims(utin[])\n\t//float64Size := unsafe.Sizeof(float64(0))\n\tdimLength := len(batch.Dims)\n\tminsLength := len(batch.Mins)\n\tmaxsLength := len(batch.Maxs)\n\tdPointLength := len(batch.DPoints)\n\t// first intSize byte for cubeid\n\tbyteData, _ := json.Marshal(batch.CubeId)\n\tdata = append(data, byteData...)\n\t// next uintSize byte for capacity\n\tbyteData, _ = json.Marshal(batch.Capacity)\n\tdata = append(data, byteData...)\n\t// next intSize byte for lengof of Dims\n\tbyteData, _ = json.Marshal(dimLength)\n\tdata = append(data, byteData...)\n\t// next intSize byte for length of minslength\n\tbyteData, _ = json.Marshal(minsLength)\n\tdata = append(data, byteData...)\n\t// next intSize byte for length of maxslength\n\tbyteData, _ = json.Marshal(maxsLength)\n\tdata = append(data, byteData...)\n\t// next intSize byte for length of dPointLength\n\tbyteData, _ = json.Marshal(dPointLength)\n\tdata = append(data, byteData...)\n\n\t// trans dims into byte\n\tbyteData = marshalUintArray(batch.Dims)\n\tdata = append(data, byteData...)\n\n\t// trans mins into byte\n\tbyteData = marshalFloat64Array(batch.Mins)\n\tdata = append(data, byteData...)\n\n\t// trans maxs into byte\n\tbyteData = marshalFloat64Array(batch.Maxs)\n\tdata = append(data, byteData...)\n\n\t// trans dPoints into byte\n\tfor _, dp := range batch.DPoints {\n\t\theader, body := convertDPoint(dp)\n\t\tdata = append(data, header...)\n\t\tdata = append(data, body...)\n\t}\n\treturn data\n}", "func (b *Binary) Bytes(encoder, lenEncoder, l int) ([]byte, error) {\n\tlength := l\n\tif b.FixLen != -1 {\n\t\tlength = b.FixLen\n\t}\n\tif length == -1 {\n\t\treturn nil, errors.New(ERR_MISSING_LENGTH)\n\t}\n\tif len(b.Value) > length {\n\t\treturn nil, errors.New(fmt.Sprintf(ERR_VALUE_TOO_LONG, \"Binary\", length, len(b.Value)))\n\t}\n\tif len(b.Value) < length {\n\t\treturn append(b.Value, make([]byte, length-len(b.Value))...), nil\n\t}\n\treturn b.Value, nil\n}", "func CastToBytes(varName string, datatypeName string) string {\n\tswitch datatypeName {\n\tcase field.TypeString:\n\t\treturn fmt.Sprintf(\"%[1]vBytes := []byte(%[1]v)\", varName)\n\tcase field.TypeUint:\n\t\treturn fmt.Sprintf(`%[1]vBytes := make([]byte, 8)\n \t\tbinary.BigEndian.PutUint64(%[1]vBytes, %[1]v)`, varName)\n\tcase field.TypeInt:\n\t\treturn fmt.Sprintf(`%[1]vBytes := make([]byte, 4)\n \t\tbinary.BigEndian.PutUint32(%[1]vBytes, uint32(%[1]v))`, varName)\n\tcase field.TypeBool:\n\t\treturn fmt.Sprintf(`%[1]vBytes := []byte{0}\n\t\tif %[1]v {\n\t\t\t%[1]vBytes = []byte{1}\n\t\t}`, varName)\n\tcase field.TypeCustom:\n\t\treturn fmt.Sprintf(`%[1]vBufferBytes := new(bytes.Buffer)\n\t\tjson.NewEncoder(%[1]vBytes).Encode(%[1]v)\n\t\t%[1]vBytes := reqBodyBytes.Bytes()`, varName)\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unknown type %s\", datatypeName))\n\t}\n}", "func (b *Binary) Bytes(encoder, lenEncoder, l int) ([]byte, error) {\n\tlength := l\n\tif b.FixLen != -1 {\n\t\tlength = b.FixLen\n\t}\n\tif length == -1 {\n\t\treturn nil, errors.New(ErrMissingLength)\n\t}\n\tif len(b.Value) > length {\n\t\treturn nil, fmt.Errorf(ErrValueTooLong, \"Binary\", length, len(b.Value))\n\t}\n\tif len(b.Value) < length {\n\t\treturn append(b.Value, make([]byte, length-len(b.Value))...), nil\n\t}\n\treturn b.Value, nil\n}", "func (c *ChunkRef) EncodeBytes() ([]byte, error) {\n\tb, err := msgpack.Marshal(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}", "func (e *Encoder) MarshalSlice(v reflect.Value) (int, error) {\n\tswitch v.Type().Elem().Kind() {\n\tcase reflect.Uint8:\n\t\tn, err := e.Byte(VarBinColumn)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ti, err := e.Binary(v.Bytes())\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\treturn n + i, nil\n\tdefault:\n\t\tn, err := e.Byte(ArrayColumn)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tl := v.Len()\n\t\ts, err := e.Int16(int16(l))\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tsize := n + s\n\t\tfor i := 0; i < l; i++ {\n\t\t\tc, err := e.Marshal(v.Index(i).Interface())\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\tsize += c\n\t\t}\n\t\treturn size, nil\n\t}\n}", "func (bw *BufWriter) Array(slice []interface{}) {\n\tif bw.Error != nil {\n\t\treturn\n\t}\n\tbw.stringBuf, bw.Error = Array(slice, bw.stringBuf[:0])\n\tif bw.Error != nil {\n\t\treturn\n\t}\n\t_, bw.Error = bw.writer.Write(bw.stringBuf)\n}", "func WriteBytes(obj any) []byte {\n\tvar b bytes.Buffer\n\tenc := toml.NewEncoder(&b)\n\tenc.Encode(obj)\n\treturn b.Bytes()\n}", "func Serialize(data interface{}) (bytes []byte, err error) {\n\tswitch data.(type) {\n\tcase []byte:\n\t\treturn data.([]byte), nil\n\tcase string:\n\t\treturn []byte(data.(string)), nil\n\tdefault:\n\t\tif data != nil {\n\t\t\treturn []byte(fmt.Sprint(data)), nil\n\t\t}\n\t}\n\treturn nil, nil\n}", "func ToJSONByteSlice(message MessageInterface) []byte {\n\tmarshalled, err := json.Marshal(message)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn marshalled\n}", "func WriteBytes(buffer []byte, offset int, value []byte) {\n copy(buffer[offset:offset + len(value)], value)\n}", "func (f Float64Slice) Serialize() ([]byte, error) {\n\tvar w bytes.Buffer\n\tbinary.Write(&w, binary.LittleEndian, uint64(len(f)))\n\tbinary.Write(&w, binary.LittleEndian, []float64(f))\n\treturn w.Bytes(), nil\n}", "func (g G1) Bytes() []byte { return g.encodeBytes(false) }", "func (p *partitionImpl) ToBytes() ([]byte, error) {\n\tnumRows := p.GetNumRows()\n\tsvrd := make([]*pb.DPartition_DVarRow, numRows)\n\t// include deserialized var row data\n\tfor i := 0; i < numRows; i++ {\n\t\tsvrd[i] = &pb.DPartition_DVarRow{\n\t\t\tRowData: make(map[string][]byte),\n\t\t}\n\t\tvarData := p.GetVarRowData(i)\n\t\tfor k, v := range varData {\n\t\t\tif v == nil {\n\t\t\t\tsvrd[i].RowData[k] = nil\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// no need to serialize values for columns we've dropped\n\t\t\tif col, err := p.currentSchema.GetOffset(k); err == nil {\n\t\t\t\tif vcol, ok := col.Type().(sif.VarColumnType); ok {\n\t\t\t\t\tsdata, err := vcol.Serialize(v)\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\tsvrd[i].RowData[k] = sdata\n\t\t\t\t} else {\n\t\t\t\t\tlog.Panicf(\"Column %s is not a variable-length type\", k)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// transfer un-deserialized variable-length data (possible if never accessed after a reduction)// transfer un-deserialized variable-length data (possible if never accessed after a reduction)\n\t\tsvarData := p.GetSerializedVarRowData(i)\n\t\tfor k, v := range svarData {\n\t\t\tsvrd[i].RowData[k] = v\n\t\t}\n\t}\n\tdm := &pb.DPartition{\n\t\tId: p.id,\n\t\tNumRows: uint32(p.numRows),\n\t\tMaxRows: uint32(p.maxRows),\n\t\tIsKeyed: p.isKeyed,\n\t\tRowData: p.rows,\n\t\tRowMeta: p.rowMeta,\n\t\tKeys: p.keys,\n\t\tSerializedVarRowData: svrd,\n\t}\n\tdata, err := proto.Marshal(dm)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}", "func (enc *Encoder) EncodeFixedArray(v reflect.Value) (int, error) {\n\tif v.Type().Elem().Kind() == reflect.Uint8 {\n\t\t// Create a slice of the underlying array for better efficiency\n\t\t// when possible. Can't create a slice of an unaddressable\n\t\t// value.\n\t\tif v.CanAddr() {\n\t\t\treturn enc.EncodeFixedByteArray(v.Slice(0, v.Len()).Bytes())\n\t\t}\n\n\t\t// When the underlying array isn't addressable fall back to\n\t\t// copying the array into a new slice. This is rather ugly, but\n\t\t// the inability to create a constant slice from an\n\t\t// unaddressable array is a limitation of Go.\n\t\tslice := make([]byte, v.Len(), v.Len())\n\t\treflect.Copy(reflect.ValueOf(slice), v)\n\t\treturn enc.EncodeFixedByteArray(slice)\n\t}\n\n\tvar n int\n\tfor i := 0; i < v.Len(); i++ {\n\t\tn2, err := enc.encode(v.Index(i))\n\t\tn += n2\n\t\tif err != nil {\n\t\t\treturn n, err\n\t\t}\n\t}\n\n\treturn n, nil\n}", "func (n ByteArray) Bytes() []byte {\n\treturn byteArrayBytes([]byte(n))\n}", "func (tx *ReleaseFromEndowment) SignableBytes() []byte {\n\treturn sbOf(tx)\n}", "func SerializerToBytes(value interface{}) ([]byte, error) {\n\tbyte, err := json.Marshal(value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn byte, nil\n}", "func (r *Encoder) Array(data []byte) {\n\tr.VarInt(uint64(len(data)))\n\tr.Bytes(data)\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 (e *Encoder) PutBytes(data []byte) {\n\te.PutVarint(int64(len(data)))\n\te.write(data)\n}", "func (b Bytes) Serialize() ([]byte, error) {\n\treturn b, nil\n}", "func anyToBytes(i interface{}) []byte {\n\tif i == nil {\n\t\treturn nil\n\t}\n\tswitch value := i.(type) {\n\tcase string:\n\t\treturn []byte(value)\n\tcase []byte:\n\t\treturn value\n\tdefault:\n\t\treturn encode(i)\n\t}\n}", "func (f Fixed) MarshalBinary() (data []byte, err error) {\n\tvar buffer [binary.MaxVarintLen64]byte\n\tn := binary.PutUvarint(buffer[:], f.fp)\n\treturn buffer[:n], nil\n}", "func (tv *TypedBytes) ByteArray() []byte {\n\treturn tv.Bytes\n}", "func (b ByteSlice) MarshalJSON() ([]byte, error) {\n\tif !b.Valid {\n\t\treturn []byte(\"null\"), nil\n\t}\n\t// Because we're passing a []byte into json.Marshal, the json package will\n\t// handle any base64 decoding that needs to happen.\n\treturn json.Marshal(b.ByteSlice)\n}", "func ToSlice(v interface{}) ([]byte, error) {\n\tswitch b := v.(type) {\n\tcase []byte:\n\t\treturn b, nil\n\tcase string:\n\t\treturn []byte(b), nil\n\tcase Name:\n\t\treturn []byte(b), nil\n\tcase Byter:\n\t\treturn b.Bytes(), nil\n\t}\n\tvar buf bytes.Buffer\n\tif err := binary.Write(&buf, binary.BigEndian, v); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (id *Id) Bytes() []byte {\n\tb := make([]byte, 8)\n\tbinary.LittleEndian.PutUint64(b, uint64(*id))\n\treturn b\n}", "func packdataLen() int {\n\treturn 2*marshalBufLen + binary.MaxVarintLen64 + 1\n}", "func (w *Writer) RawBytes(data []byte) {\n\tw.buf = append(w.buf, data...)\n}", "func (r *Decoder) Array() []byte {\n\tlength := r.VarInt()\n\tdata := r.Bytes(int(length))\n\treturn data\n}", "func cat(bytethings ...interface{}) []byte {\n\tbuf := &bytes.Buffer{}\n\tfor _, thing := range bytethings {\n\t\tswitch x := thing.(type) {\n\t\tcase int64:\n\t\t\tcmpbin.WriteInt(buf, x)\n\t\tcase int:\n\t\t\tcmpbin.WriteInt(buf, int64(x))\n\t\tcase uint64:\n\t\t\tcmpbin.WriteUint(buf, x)\n\t\tcase uint:\n\t\t\tcmpbin.WriteUint(buf, uint64(x))\n\t\tcase float64:\n\t\t\tcmpbin.WriteFloat64(buf, x)\n\t\tcase byte:\n\t\t\tbuf.WriteByte(x)\n\t\tcase ds.PropertyType:\n\t\t\tbuf.WriteByte(byte(x))\n\t\tcase string:\n\t\t\tcmpbin.WriteString(buf, x)\n\t\tcase []byte:\n\t\t\tbuf.Write(x)\n\t\tcase time.Time:\n\t\t\tserialize.WriteTime(buf, x)\n\t\tcase ds.Key:\n\t\t\tserialize.WriteKey(buf, serialize.WithoutContext, x)\n\t\tcase *ds.IndexDefinition:\n\t\t\tserialize.WriteIndexDefinition(buf, *x)\n\t\tcase ds.Property:\n\t\t\tserialize.WriteProperty(buf, serialize.WithoutContext, x)\n\t\tdefault:\n\t\t\tpanic(fmt.Errorf(\"I don't know how to deal with %T: %#v\", thing, thing))\n\t\t}\n\t}\n\tret := buf.Bytes()\n\tif ret == nil {\n\t\tret = []byte{}\n\t}\n\treturn ret\n}", "func (n NodesID) Bytes() []byte {\n\treturn n[:]\n}", "func NewBytesPayload(v []byte) CoAPMessagePayload {\n\tif v == nil {\n\t\tv = []byte{}\n\t}\n\treturn &BytesPayload{\n\t\tcontent: v,\n\t}\n}", "func (this *fixedSize) MarshalBinary() (data []byte, err error) {\n\t// var addrs = map[uintptr]uint64{}\n\tbuf := bytes.NewBuffer(make([]byte, 0, 3384))\n\tif err = this.marshalTo(buf /*, addrs*/); err == nil {\n\t\tdata = buf.Bytes()\n\t}\n\treturn\n}", "func Serialize(input interface{}) (msg []byte, err error) {\n\tbuffer, err := json.Marshal(input)\n\treturn buffer, err\n\n\t// TODO: Do we really need wire here?\n\t/*\n\t\tvar count int\n\n\t\tbuffer := new(bytes.Buffer)\n\n\t\twire.WriteBinary(input, buffer, &count, &err)\n\n\t\treturn buffer.Bytes(), err\n\t*/\n}", "func EncodeParts(parts [][]byte) ([]byte, error) {\n\tb := make([]byte, 0)\n\n\tfor i, part := range parts {\n\t\tl := int64(len(part))\n\n\t\tif l <= 75 {\n\t\t\tb = append(b, byte(len(part)))\n\t\t\tb = append(b, part...)\n\n\t\t} else if l <= 0xFF {\n\t\t\tb = append(b, 0x4c) // OP_PUSHDATA1\n\t\t\tb = append(b, byte(len(part)))\n\t\t\tb = append(b, part...)\n\n\t\t} else if l <= 0xFFFF {\n\t\t\tb = append(b, 0x4d) // OP_PUSHDATA2\n\t\t\tlenBuf := make([]byte, 2)\n\t\t\tbinary.LittleEndian.PutUint16(lenBuf, uint16(len(part)))\n\t\t\tb = append(b, lenBuf...)\n\t\t\tb = append(b, part...)\n\n\t\t} else if l <= 0xFFFFFFFF {\n\t\t\tb = append(b, 0x4e) // OP_PUSHDATA4\n\t\t\tlenBuf := make([]byte, 4)\n\t\t\tbinary.LittleEndian.PutUint32(lenBuf, uint32(len(part)))\n\t\t\tb = append(b, lenBuf...)\n\t\t\tb = append(b, part...)\n\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"Part %d is too big\", i)\n\t\t}\n\t}\n\n\treturn b, nil\n}", "func (query *Query) Serialize() []byte {\n bytes := make([]byte, 32, 32)\n\n bytes[0] = query.action\n bytes[1] = query.empty\n binary.BigEndian.PutUint32(bytes[2:6], query.replyIp)\n binary.BigEndian.PutUint16(bytes[6:8], query.replyPort)\n binary.BigEndian.PutUint64(bytes[8:16], query.key)\n binary.BigEndian.PutUint64(bytes[16:24], query.value)\n binary.BigEndian.PutUint32(bytes[24:28], query.timeToLive)\n binary.BigEndian.PutUint32(bytes[28:32], query.requestId)\n\n return bytes\n}", "func (cb *codedBuffer) encodeRawBytes(b []byte) error {\n\tcb.encodeVarint(uint64(len(b)))\n\tcb.buf = append(cb.buf, b...)\n\treturn nil\n}", "func pack(args... interface{}) []byte {\n panic(\"not implemented!\")\n}", "func (c *uint8Type) SerializeFixed(v interface{}, dest []byte) error {\n\tvi, ok := v.(uint8)\n\tif !ok {\n\t\treturn fmt.Errorf(\"value %v is not a uint8\", v)\n\t}\n\treturn c.SerializeFixedT(vi, dest)\n}", "func _FencRF(___V interface{}) []byte {\n\n\t/*\n\t var __Vbyte []byte\n\t __Vbyte = *((*[]byte)(&___V))\n\n\t size := dataSize(v)\n\t*/\n\n\t//buf := make([]byte, size)\n\treturn nil\n}", "func (tx *Delegate) SignableBytes() []byte {\n\treturn sbOf(tx)\n}", "func (i IntSlice) Serialize() ([]byte, error) {\n\tints64 := make([]int64, len(i))\n\tfor j, x := range i {\n\t\tints64[j] = int64(x)\n\t}\n\tvar w bytes.Buffer\n\tbinary.Write(&w, binary.LittleEndian, uint64(len(i)))\n\tbinary.Write(&w, binary.LittleEndian, ints64)\n\treturn w.Bytes(), nil\n}", "func BuildBytes(bytes []byte) string {\n\tvar builder strings.Builder\n\tbuilder.WriteString(\"[\\n\")\n\tfor i, b := range bytes {\n\t\tbuilder.WriteString(fmt.Sprintf(\"0x%02x,\", b))\n\t\tif i%8 == 7 {\n\t\t\tbuilder.WriteString(\"\\n\")\n\t\t}\n\t}\n\tbuilder.WriteString(\"]\")\n\treturn builder.String()\n}", "func MarshalTinySlice(w io.Writer, v interface{}) error {\n\tval := reflect.ValueOf(v)\n\tswitch k := val.Kind(); k {\n\tcase reflect.Slice:\n\t\tl := val.Len()\n\t\tif l > math.MaxUint8 {\n\t\t\treturn fmt.Errorf(\"a tiny slice can have a maximum of %d elements\", math.MaxUint8)\n\t\t}\n\t\t// slices are variable length, so prepend the length\n\t\terr := MarshalUint8(w, uint8(l))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif l == 0 {\n\t\t\t// if length is 0, we are done\n\t\t\treturn nil\n\t\t}\n\t\t// special case for byte slices\n\t\tif val.Type().Elem().Kind() == reflect.Uint8 {\n\t\t\t// if the array is addressable, we can optimize a bit here\n\t\t\tif val.CanAddr() {\n\t\t\t\treturn marshalBytes(w, val.Slice(0, val.Len()).Bytes())\n\t\t\t}\n\t\t\t// otherwise we have to copy into a newly allocated slice\n\t\t\tslice := reflect.MakeSlice(reflect.SliceOf(val.Type().Elem()), val.Len(), val.Len())\n\t\t\treflect.Copy(slice, val)\n\t\t\treturn marshalBytes(w, slice.Bytes())\n\t\t}\n\t\t// create an encoder and encode all slice elements in the regular Sia-encoding way\n\t\te := NewEncoder(w)\n\t\t// normal slices are encoded by sequentially encoding their elements\n\t\tfor i := 0; i < l; i++ {\n\t\t\terr = e.Encode(val.Index(i).Interface())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\n\tcase reflect.String:\n\t\treturn MarshalTinySlice(w, []byte(val.String()))\n\n\tdefault:\n\t\treturn fmt.Errorf(\"MarshalTinySlice: non-slice type %s (kind: %s) is not supported\",\n\t\t\tval.Type().String(), k.String())\n\t}\n}", "func (h *HandShake) Serialize() []byte {\n\t// NOTE: Whenever we are sending a msg, it has to be in []byte type \n\tbuf := make([]byte, len(h.Pstr)+49)\n\tbuf[0] = byte(len(h.Pstr))\n\tcurr := 1\n\tcurr += copy(buf[curr:], h.Pstr)\n\tcurr += copy(buf[curr:], make([]byte, 8)) // 8 reserved bytes\n\tcurr += copy(buf[curr:], h.Info_hash[:])\n\tcurr += copy(buf[curr:], h.Peer_id[:])\n\treturn buf\n}", "func packdataLen() int {\n\treturn 2*marshalBufLen + binary.MaxVarintLen64 + sha256.Size + 1\n}", "func inputStructToBytes(v interface{}) (sb [][]byte, err error) {\n\n\te := reflect.Indirect(reflect.ValueOf(v))\n\tfor i := 0; i < e.NumField(); i++ {\n\t\tv := e.Field(i)\n\t\tif v.Type().Name() != \"string\" {\n\t\t\terr = fmt.Errorf(\"struct should contain only string values\")\n\t\t\treturn\n\t\t}\n\t\tvarValue := v.String()\n\t\tsb = append(sb, []byte(varValue))\n\t}\n\treturn\n\n}", "func (p *PayloadFrame) Bytes() []byte {\n\tlen := len(p.data)\n\tbuf := make([]byte, FrameLengthFieldSize)\n\n\tappendFrameLength(buf, len)\n\tbuf = append(buf, p.data...)\n\treturn buf\n}", "func (l *Label) data() []byte {\n Assert(nilLabel, l != nil)\n \n bytes, _ := util.Uint64ToBytes(l.value)\n refs, _ := util.Uint64ToBytes(l.refs)\n left, _ := util.Uint16ToBytes(l.l)\n right, _ := util.Uint16ToBytes(l.r)\n \n bytes = append(bytes, append(refs, append(left, append(right, l.h)...)...)...) // TODO ??\n return bytes\n \n}", "func encodeUxArrayToBuffer(buf []byte, obj *UxArray) error {\n\tif uint64(len(buf)) < encodeSizeUxArray(obj) {\n\t\treturn encoder.ErrBufferUnderflow\n\t}\n\n\te := &encoder.Encoder{\n\t\tBuffer: buf[:],\n\t}\n\n\t// obj.UxArray length check\n\tif uint64(len(obj.UxArray)) > math.MaxUint32 {\n\t\treturn errors.New(\"obj.UxArray length exceeds math.MaxUint32\")\n\t}\n\n\t// obj.UxArray length\n\te.Uint32(uint32(len(obj.UxArray)))\n\n\t// obj.UxArray\n\tfor _, x := range obj.UxArray {\n\n\t\t// x.Head.Time\n\t\te.Uint64(x.Head.Time)\n\n\t\t// x.Head.BkSeq\n\t\te.Uint64(x.Head.BkSeq)\n\n\t\t// x.Body.SrcTransaction\n\t\te.CopyBytes(x.Body.SrcTransaction[:])\n\n\t\t// x.Body.Address.Version\n\t\te.Uint8(x.Body.Address.Version)\n\n\t\t// x.Body.Address.Key\n\t\te.CopyBytes(x.Body.Address.Key[:])\n\n\t\t// x.Body.Coins\n\t\te.Uint64(x.Body.Coins)\n\n\t\t// x.Body.Hours\n\t\te.Uint64(x.Body.Hours)\n\n\t}\n\n\treturn nil\n}", "func Serialize(v interface{}) ([]byte, error) {\n\tbuf := bytes.NewBuffer(make([]byte, 0))\n\tif err := gob.NewEncoder(buf).Encode(v); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (f *PushNotice) Serialize(buffer []byte) []byte {\n\tbuffer[0] = byte(f.Flags)\n\tcopy(buffer[1:], f.Data)\n\treturn buffer\n}", "func (b *buffer) bytes(n int) []byte {\n\tdata := b.unsafeBytes(n)\n\tif !b.shared {\n\t\treturn data\n\t}\n\t// TODO(kortschak): Replace this with bytes.Clone when available.\n\t// See https://github.com/golang/go/issues/45038 for bytes.Clone.\n\treturn append(data[:0:0], data...)\n}" ]
[ "0.60886234", "0.6066471", "0.5919572", "0.573001", "0.55983853", "0.5585901", "0.55529904", "0.5549069", "0.553861", "0.5525328", "0.5523632", "0.5516", "0.54950243", "0.54753387", "0.5423635", "0.541514", "0.54085726", "0.53678983", "0.53493255", "0.53365976", "0.5331272", "0.5330848", "0.53295785", "0.5327973", "0.5327377", "0.53226936", "0.5321039", "0.5319736", "0.5317394", "0.5315986", "0.52931553", "0.5289345", "0.52842045", "0.5271351", "0.5266481", "0.526457", "0.52547723", "0.52455384", "0.5241507", "0.5241465", "0.5239208", "0.5237707", "0.523067", "0.52275854", "0.52260107", "0.5221694", "0.52139795", "0.52114266", "0.5210306", "0.5203998", "0.519832", "0.51921105", "0.5186511", "0.5184386", "0.5182259", "0.5180671", "0.51805127", "0.51771796", "0.5175597", "0.51697433", "0.5166614", "0.5165297", "0.51626694", "0.5162177", "0.51586825", "0.5155171", "0.51474565", "0.51275223", "0.51265854", "0.51131433", "0.50981855", "0.5094381", "0.50935066", "0.5092427", "0.5089725", "0.50791055", "0.5074186", "0.5072762", "0.50725925", "0.5066209", "0.50589573", "0.5058906", "0.5054507", "0.50514776", "0.50511223", "0.5050827", "0.50481313", "0.50472426", "0.50462943", "0.5042929", "0.50408685", "0.50393", "0.5038325", "0.5036544", "0.5032057", "0.50295734", "0.5028281", "0.50255376", "0.50248027", "0.50216275" ]
0.63819116
0
Deserialize implement Deserialiazable interface deserialize a variable bytes arrary from buffer see Serialize above as reference
func (vb *VarBytes) Deserialize(r io.Reader) error { var varlen VarUint if err := varlen.Deserialize(r); err != nil { return err } vb.Len = uint64(varlen.Value) vb.Bytes = make([]byte, vb.Len) return binary.Read(r, binary.LittleEndian, vb.Bytes) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func deserialize(src []byte, dst interface{}) error {\n\tdec := gob.NewDecoder(bytes.NewBuffer(src))\n\tif err := dec.Decode(dst); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Deserialize(buffer []byte) *block {\n\tvar b block\n\tdecoder := gob.NewDecoder(bytes.NewReader(buffer)) // convert []byte to io.Reader\n\terr := decoder.Decode(&b) // here b is the dest\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\treturn &b\n}", "func (f *PushNotice) Deserialize(buffer []byte, err *error) []byte {\n\tif *err != nil {\n\t\treturn nil\n\t}\n\tif len(buffer) < 1 {\n\t\t*err = errDeserialize\n\t\treturn nil\n\t}\n\tf.Flags = DataFlags(buffer[0])\n\tf.Data = buffer[1:]\n\treturn buffer\n}", "func deserialize(src *[]byte, obj interface{}) error {\n\tglog.Infof(\"Deserialization\")\n\n\t// make a copy of the bytes as this comes from bolt and the object will be used outside\n\t// of the transaction\n\tb := make([]byte, len(*src))\n\tcopy(b, *src)\n\n\tbuf := bytes.NewBuffer(b)\n\tdec := gob.NewDecoder(buf)\n\n\terr := dec.Decode(obj)\n\tif err != nil {\n\t\tglog.Infof(\"Failed to deserialize object: %s\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Deserialize(b []byte, out interface{}) error {\n\tautil.TODO(\"CBOR-deseriaization\")\n\treturn nil\n}", "func (f *OpenStreamReply) Deserialize(buffer []byte, err *error) []byte {\n\tif *err != nil {\n\t\treturn nil\n\t}\n\tif len(buffer) != 4 {\n\t\t*err = errDeserialize\n\t\treturn nil\n\t}\n\treturn buffer\n}", "func DeserializeBytes(d []byte) (Bytes, error) {\n\treturn d, nil\n}", "func ReadBytes(obj any, b []byte) error {\n\terr := toml.Unmarshal(b, obj)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func Deserialize(buffer []byte, destination interface{}) error {\n\treturn json.Unmarshal(buffer, &destination)\n}", "func (f *CloseNotice) Deserialize(buffer []byte, err *error) []byte {\n\tif *err != nil {\n\t\treturn nil\n\t}\n\tif len(buffer) != 0 {\n\t\t*err = errDeserialize\n\t\treturn nil\n\t}\n\treturn buffer\n}", "func Deserialize(packet [UDP_BUF_LEN]byte, n int) TCP_Segment {\n\ttemp := packet[0:n]\n\tb := bytes.NewBuffer(temp)\n\t//log.Println(\"Buffer:\", b.Bytes())\n\tvar segmentReceived TCP_Segment\n\tbinary.Read(b, binary.BigEndian, &segmentReceived)\n\t//log.Println(\"Segment Rec: \", segmentReceived)\n\treturn segmentReceived\n}", "func Deserialize(input []byte, output interface{}) (msg interface{}, err error) {\n\n\terr = json.Unmarshal(input, output)\n\treturn output, err\n\n\t// TODO: Do we really need wire here?\n\t/*\n\t\tvar count int\n\n\t\tbuffer := bytes.NewBuffer(input)\n\n\t\tvalueOf := reflect.ValueOf(output)\n\t\tif valueOf.Kind() == reflect.Ptr {\n\t\t\tmsg = wire.ReadBinaryPtr(output, buffer, len(input), &count, &err)\n\t\t\t//msg = wire.ReadBinaryPtr(output, buffer, 0, &count, &err)\n\t\t} else {\n\t\t\tmsg = wire.ReadBinary(output, buffer, len(input), &count, &err)\n\t\t\t//msg = wire.ReadBinary(output, buffer, 0, &count, &err)\n\t\t}\n\t\treturn msg, err\n\t*/\n}", "func Unmarshal([]byte) (WireMessage, error) { return nil, nil }", "func Deserialize(data []byte, value interface{}) error {\n\treturn rlp.DecodeBytes(data, value)\n}", "func (f *OpenStreamRequest) Deserialize(buffer []byte, err *error) []byte {\n\tif *err != nil {\n\t\treturn nil\n\t}\n\tbuffer = f.Stream.Deserialize(buffer, err)\n\treturn buffer\n}", "func (f *ReadRequest) Deserialize(buffer []byte, err *error) []byte {\n\tif *err != nil {\n\t\treturn nil\n\t}\n\tif len(buffer) != 1+8+8 {\n\t\t*err = errDeserialize\n\t\treturn nil\n\t}\n\tf.Seek = SeekFlags(buffer[0])\n\tf.Offset = int64(binary.LittleEndian.Uint64(buffer[1:]))\n\tf.Count = int64(binary.LittleEndian.Uint64(buffer[9:]))\n\treturn buffer\n}", "func unconvertData(data []byte) interface{} {\n\tif data == nil || string(data) == \"\" {\n\t\treturn nil\n\t}\n\n\tvar proto interface{}\n\tresult, err := serial.Deserialize(data, proto, serial.PERSISTENT)\n\tif err != nil {\n\t\tlog.Fatal(\"Persistent Deserialization Failed\", \"err\", err, \"data\", data)\n\t}\n\treturn result\n}", "func (f *CreateBundleReply) Deserialize(buffer []byte, err *error) []byte {\n\tif *err != nil {\n\t\treturn nil\n\t}\n\tif len(buffer) != 4 {\n\t\t*err = errDeserialize\n\t\treturn nil\n\t}\n\treturn buffer\n}", "func decodeByteArray(s *Stream, val reflect.Value) error {\n\t// getting detailed information on encoded data\n\tkind, size, err := s.Kind()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// getting the length of declared ByteArray\n\tvlen := val.Len()\n\n\tswitch kind {\n\t// put a byte in a byte array\n\tcase Byte:\n\t\tif vlen == 0 {\n\t\t\treturn &decodeError{msg: \"input string too long\", typ: val.Type()}\n\t\t}\n\t\tif vlen > 1 {\n\t\t\treturn &decodeError{msg: \"input string too short\", typ: val.Type()}\n\t\t}\n\n\t\t// get the content and stores in the index 0\n\t\tbv, _ := s.Uint()\n\t\tval.Index(0).SetUint(bv)\n\n\t// put string in a byte array\n\tcase String:\n\t\tif uint64(vlen) < size {\n\t\t\treturn &decodeError{msg: \"input string too long\", typ: val.Type()}\n\t\t}\n\t\tif uint64(vlen) > size {\n\t\t\treturn &decodeError{msg: \"input string too short\", typ: val.Type()}\n\t\t}\n\n\t\t// transfer the byte array to byte slice and place string content inside\n\t\tslice := val.Slice(0, vlen).Interface().([]byte)\n\t\tif err := s.readFull(slice); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// reject cases where single byte encoding should have been used\n\t\tif size == 1 && slice[0] < 128 {\n\t\t\treturn wrapStreamError(ErrCanonSize, val.Type())\n\t\t}\n\t// byte array should not contain any list\n\tcase List:\n\t\treturn wrapStreamError(ErrExpectedString, val.Type())\n\t}\n\treturn nil\n}", "func deserializeByteSequenceModel(model SerializedSequenceModel) *SequenceModel {\n\tsequence, err := hex.DecodeString(model.Sequence)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn &SequenceModel{Index: model.Index, Offset: model.Offset, Sequence: sequence, Length: model.Length}\n}", "func ReadProtoBuff(ctx *fasthttp.RequestCtx, data interface{}) error {\n\tif err := proto.UnmarshalBytes(ctx.PostBody(), data); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (f *ProgressNotice) Deserialize(buffer []byte, err *error) []byte {\n\tif *err != nil {\n\t\treturn nil\n\t}\n\tif len(buffer) < 8 {\n\t\t*err = errDeserialize\n\t\treturn nil\n\t}\n\tf.Offset = binary.LittleEndian.Uint64(buffer)\n\tbuffer = f.User.Deserialize(buffer[8:], err)\n\treturn buffer\n}", "func Deserialize(registerValue interface{}, data []byte, targetPointer interface{}) error {\n\tif registerValue != nil {\n\t\tgob.Register(registerValue)\n\t}\n\tdecoder := gob.NewDecoder(bytes.NewReader(data))\n\terr := decoder.Decode(targetPointer)\n\n\treturn err\n}", "func DeserializerFromBytes(value []byte, result interface{}) error {\n\tif json.Valid(value) {\n\t\treturn json.Unmarshal(value, result)\n\t}\n\treturn errors.New(\"invalid json byte array\")\n}", "func Deserialize(holder interface{}, data []byte) error {\n\tds := createDeserializer(data)\n\n\tt := reflect.ValueOf(holder)\n\tif t.Kind() != reflect.Ptr {\n\t\treturn fmt.Errorf(\"holder must set pointer value. but got: %t\", holder)\n\t}\n\n\tt = t.Elem()\n\tif t.Kind() == reflect.Ptr {\n\t\tt = t.Elem()\n\t}\n\n\t// byte to Struct\n\tif t.Kind() == reflect.Struct && !isDateTime(t) && !isDateTimeOffset(t) {\n\t\treturn ds.deserializeStruct(t)\n\t}\n\n\t// byte to primitive\n\t_, err := ds.deserialize(t, 0)\n\treturn err\n}", "func (pd *pymtData) Deserialize(b []byte) error {\n\terr := json.Unmarshal(b, pd)\n\tif err != nil {\n\t\treturn errors.Wrap(err, ErrInvalidFormatBlob)\n\t}\n\n\treturn nil\n}", "func decodeByteSlice(s *Stream, val reflect.Value) error {\n\t// b = byte slice contained string content\n\tb, err := s.Bytes()\n\tif err != nil {\n\t\treturn wrapStreamError(err, val.Type())\n\t}\n\tval.SetBytes(b)\n\treturn nil\n}", "func (d *Decoder) Bytes() []byte {\n\tn := d.Varint()\n\tif n == 0 {\n\t\treturn nil\n\t}\n\tdata := make([]byte, n)\n\tnn, err := d.buf.Read(data)\n\tif int64(nn) != n || err != nil {\n\t\tlog.Panicf(\"unmarshalBytes: %d %d %v\", n, nn, err)\n\t}\n\treturn data\n}", "func (f *DestReply) Deserialize(buffer []byte, err *error) []byte {\n\tif *err != nil {\n\t\treturn nil\n\t}\n\tif len(buffer) != 4 {\n\t\t*err = errDeserialize\n\t\treturn nil\n\t}\n\treturn buffer\n}", "func (e BinaryEncoding) Read(r io.Reader, objs ...interface{}) error {\n\tde := decoder{e.Constructor, r}\n\tfor i := 0; i < len(objs); i++ {\n\t\t// XXX check that it's a by-reference type\n\t\t// (pointer, slice, etc.) and complain if not,\n\t\t// to head of accidental misuse?\n\t\tif err := de.value(reflect.ValueOf(objs[i]), 0); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func bytesToStruct(elementBytes []byte, element interface{}) error {\n\treturn json.Unmarshal(elementBytes, &element)\n}", "func (f *WriteRequest) Deserialize(buffer []byte, err *error) []byte {\n\tif *err != nil {\n\t\treturn nil\n\t}\n\tif len(buffer) < 1 {\n\t\t*err = errDeserialize\n\t\treturn nil\n\t}\n\tf.Flags = WriteFlags(buffer[0])\n\tf.Data = buffer[1:]\n\treturn buffer\n}", "func (a *Buffer) UnmarshalJSON(b []byte) error {\n\tvar data BufferData\n\tif err := json.Unmarshal(b, &data); err != nil {\n\t\treturn err\n\t}\n\n\ta.isBinary = data.PlaceHolder\n\ta.Data = data.Data\n\ta.num = data.Num\n\n\treturn nil\n}", "func Deserialize(b []byte) (Message, error) {\n\tvar msg Message\n\tbuf := bytes.NewBuffer(b)\n\tdecoder := json.NewDecoder(buf)\n\terr := decoder.Decode(&msg)\n\treturn msg, err\n}", "func (c *uint8Type) Deserialize(sv []byte) (interface{}, error) {\n\treturn c.DeserializeT(sv)\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 (b *Buffer) Data() []byte { return b.data }", "func (c app) ReceiveBytes(byt []byte) {\n\tvar dat []interface{}\n\n\tif err := json.Unmarshal(byt, &dat); err != nil {\n\t\tInfo(\"Unable to unmarshal json! Message: \", dat)\n\t} else {\n\t\tif m, err := c.serializer.deserializeString(dat); err == nil {\n\t\t\tc.in <- m\n\t\t} else {\n\t\t\tInfo(\"Unable to unmarshal json string! Message: \", m)\n\t\t}\n\t}\n}", "func (this *Codec) deserialize(data string) *TreeNode {\n\ttmp := strings.Split(this.SerializeStr, \",\")\n\treturn d(&tmp)\n}", "func (i *DeserializerV1) Read() ([]interface{}, error) {\n\tif i.r == nil {\n\t\treturn nil, fmt.Errorf(\"io.Reader is not set yet\")\n\t}\n\n\tp, err := ioutil.ReadAll(i.r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tans, _, err := i.ReadAt(p, 0)\n\treturn ans, err\n}", "func DeSerializeQuery(bytes []byte) Query {\n if len(bytes) != 32 {\n fmt.Println(\"Error : bytes length is not 32. Its \", len(bytes))\n }\n\n return Query {\n action : bytes[0],\n empty : 0,\n replyIp : binary.BigEndian.Uint32(bytes[2:6]),\n replyPort : binary.BigEndian.Uint16(bytes[6:8]),\n key : binary.BigEndian.Uint64(bytes[8:16]),\n value : binary.BigEndian.Uint64(bytes[16:24]),\n timeToLive: binary.BigEndian.Uint32(bytes[24:28]),\n requestId : binary.BigEndian.Uint32(bytes[28:32]),\n }\n}", "func (q *Quote) Deserialize(b []byte) error {\n\tbuf := bytes.NewBuffer(b)\n\tdec := gob.NewDecoder(buf)\n\terr := dec.Decode(q)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"Deserialize: decoding failed for %s\", b)\n\t}\n\treturn nil\n}", "func BytesDecode(ctx context.Context, b []byte, obj interface{}) error {\n\tv := obj.(*[]byte)\n\t*v = b[:]\n\treturn nil\n}", "func (b *Buffer) Unserialize() error {\n\t// If either savecursor or saveundo is turned on, we need to load the serialized information\n\t// from ~/.config/micro/buffers\n\tif b.Path == \"\" {\n\t\treturn nil\n\t}\n\tfile, err := os.Open(filepath.Join(config.ConfigDir, \"buffers\", util.EscapePath(b.AbsPath)))\n\tif err == nil {\n\t\tdefer file.Close()\n\t\tvar buffer SerializedBuffer\n\t\tdecoder := gob.NewDecoder(file)\n\t\terr = decoder.Decode(&buffer)\n\t\tif err != nil {\n\t\t\treturn errors.New(err.Error() + \"\\nYou may want to remove the files in ~/.config/micro/buffers (these files\\nstore the information for the 'saveundo' and 'savecursor' options) if\\nthis problem persists.\\nThis may be caused by upgrading to version 2.0, and removing the 'buffers'\\ndirectory will reset the cursor and undo history and solve the problem.\")\n\t\t}\n\t\tif b.Settings[\"savecursor\"].(bool) {\n\t\t\tb.StartCursor = buffer.Cursor\n\t\t}\n\n\t\tif b.Settings[\"saveundo\"].(bool) {\n\t\t\t// We should only use last time's eventhandler if the file wasn't modified by someone else in the meantime\n\t\t\tif b.ModTime == buffer.ModTime {\n\t\t\t\tb.EventHandler = buffer.EventHandler\n\t\t\t\tb.EventHandler.cursors = b.cursors\n\t\t\t\tb.EventHandler.buf = b.SharedBuffer\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (tag *ByteArray) Read(reader io.Reader) error {\n\tvar length int32\n\n\tif err := binary.Read(reader, binary.BigEndian, &length); err != nil {\n\t\treturn err\n\t}\n\n\tvar i int32\n\tfor i = 0; i < length; i++ {\n\t\tvar b byte\n\n\t\tif err := binary.Read(reader, binary.BigEndian, &b); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttag.Value = append(tag.Value, b)\n\t}\n\n\treturn nil\n}", "func (msg *MsgTx) Deserialize(r io.Reader) error {\n\t// At the current time, there is no difference between the protos encoding\n\t// at protocol version 0 and the stable long-term storage format. As\n\t// a result, make use of VVSDecode.\n\treturn msg.VVSDecode(r, 0, BaseEncoding)\n}", "func Unserialize(data []byte, v interface{}) error {\n\treturn gob.NewDecoder(bytes.NewBuffer(data)).Decode(v)\n}", "func recordioUnmarshal(b []byte, v interface{}) error {\n\treturn proto.Unmarshal(b, v.(proto.Message))\n}", "func decodeUxArray(buf []byte, obj *UxArray) (uint64, error) {\n\td := &encoder.Decoder{\n\t\tBuffer: buf[:],\n\t}\n\n\t{\n\t\t// obj.UxArray\n\n\t\tul, err := d.Uint32()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tlength := int(ul)\n\t\tif length < 0 || length > len(d.Buffer) {\n\t\t\treturn 0, encoder.ErrBufferUnderflow\n\t\t}\n\n\t\tif length != 0 {\n\t\t\tobj.UxArray = make([]coin.UxOut, length)\n\n\t\t\tfor z1 := range obj.UxArray {\n\t\t\t\t{\n\t\t\t\t\t// obj.UxArray[z1].Head.Time\n\t\t\t\t\ti, err := d.Uint64()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn 0, err\n\t\t\t\t\t}\n\t\t\t\t\tobj.UxArray[z1].Head.Time = i\n\t\t\t\t}\n\n\t\t\t\t{\n\t\t\t\t\t// obj.UxArray[z1].Head.BkSeq\n\t\t\t\t\ti, err := d.Uint64()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn 0, err\n\t\t\t\t\t}\n\t\t\t\t\tobj.UxArray[z1].Head.BkSeq = i\n\t\t\t\t}\n\n\t\t\t\t{\n\t\t\t\t\t// obj.UxArray[z1].Body.SrcTransaction\n\t\t\t\t\tif len(d.Buffer) < len(obj.UxArray[z1].Body.SrcTransaction) {\n\t\t\t\t\t\treturn 0, encoder.ErrBufferUnderflow\n\t\t\t\t\t}\n\t\t\t\t\tcopy(obj.UxArray[z1].Body.SrcTransaction[:], d.Buffer[:len(obj.UxArray[z1].Body.SrcTransaction)])\n\t\t\t\t\td.Buffer = d.Buffer[len(obj.UxArray[z1].Body.SrcTransaction):]\n\t\t\t\t}\n\n\t\t\t\t{\n\t\t\t\t\t// obj.UxArray[z1].Body.Address.Version\n\t\t\t\t\ti, err := d.Uint8()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn 0, err\n\t\t\t\t\t}\n\t\t\t\t\tobj.UxArray[z1].Body.Address.Version = i\n\t\t\t\t}\n\n\t\t\t\t{\n\t\t\t\t\t// obj.UxArray[z1].Body.Address.Key\n\t\t\t\t\tif len(d.Buffer) < len(obj.UxArray[z1].Body.Address.Key) {\n\t\t\t\t\t\treturn 0, encoder.ErrBufferUnderflow\n\t\t\t\t\t}\n\t\t\t\t\tcopy(obj.UxArray[z1].Body.Address.Key[:], d.Buffer[:len(obj.UxArray[z1].Body.Address.Key)])\n\t\t\t\t\td.Buffer = d.Buffer[len(obj.UxArray[z1].Body.Address.Key):]\n\t\t\t\t}\n\n\t\t\t\t{\n\t\t\t\t\t// obj.UxArray[z1].Body.Coins\n\t\t\t\t\ti, err := d.Uint64()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn 0, err\n\t\t\t\t\t}\n\t\t\t\t\tobj.UxArray[z1].Body.Coins = i\n\t\t\t\t}\n\n\t\t\t\t{\n\t\t\t\t\t// obj.UxArray[z1].Body.Hours\n\t\t\t\t\ti, err := d.Uint64()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn 0, err\n\t\t\t\t\t}\n\t\t\t\t\tobj.UxArray[z1].Body.Hours = i\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\n\treturn uint64(len(buf) - len(d.Buffer)), nil\n}", "func FromJSONByteSlice(data []byte, message MessageInterface) error {\n\terr := json.Unmarshal(data, message)\n\treturn err\n}", "func (b *MicroBlock) Deserialize(r io.Reader) error {\n return readBlock(r, 0, b)\n}", "func (b ByteArray) Decode(r io.Reader) (interface{}, error) {\n\tl, err := util.ReadVarInt(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbuf := make([]byte, int(l))\n\t_, err = io.ReadFull(r, buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf, nil\n}", "func convertData(data interface{}) []byte {\n\tbuffer, err := serial.Serialize(data, serial.PERSISTENT)\n\tif err != nil {\n\t\tlog.Fatal(\"Persistent Serialization Failed\", \"err\", err, \"data\", data)\n\t}\n\treturn buffer\n}", "func (f *CommitNotice) Deserialize(buffer []byte, err *error) []byte {\n\tif *err != nil {\n\t\treturn nil\n\t}\n\tif len(buffer) != 4+8 {\n\t\t*err = errDeserialize\n\t\treturn nil\n\t}\n\tf.Error = ErrorCode(binary.LittleEndian.Uint32(buffer))\n\tf.Time = int64(binary.LittleEndian.Uint64(buffer[4:]))\n\treturn buffer\n}", "func DeserializeThrift(ctx context.Context, b []byte, s athrift.TStruct) error {\n\treader := bytes.NewReader(b)\n\ttransport := athrift.NewStreamTransportR(reader)\n\treturn s.Read(ctx, athrift.NewTBinaryProtocolTransport(transport))\n}", "func (*nopSerializer) Unmarshal([]byte, Message) error { return nil }", "func (c *app) ReceiveBytes(byt []byte) {\n\tvar dat []interface{}\n\n\tif err := json.Unmarshal(byt, &dat); err != nil {\n\t\tInfo(\"Unable to unmarshal json! Message: %v\", string(byt))\n\t} else {\n\t\tif m, err := c.serializer.deserializeString(dat); err == nil {\n\t\t\tc.ReceiveMessage(m)\n\t\t} else {\n\t\t\tInfo(\"Unable to unmarshal json string! Message: %v\", m)\n\t\t}\n\t}\n}", "func (c *ChunkRef) DecodeBytes(by []byte) error {\n\treturn msgpack.Unmarshal(by, c)\n}", "func (u *Uint256) Deserialize(r io.Reader) error {\n\treturn binary.Read(r, binary.LittleEndian, u)\n}", "func (g *Generic) DecodeFromBytes(b []byte) error {\n\tlog.Println(\"DEPRECATED: use UnmarshalBinary instead\")\n\treturn g.UnmarshalBinary(b)\n}", "func read(r *bufio.Reader, pb proto.Message) error {\n\ts, err := r.ReadString('\\n')\n\tif err != nil {\n\t\treturn err\n\t}\n\ts = strings.TrimRight(s, \"\\r\\n\")\n\tb, err := base64.StdEncoding.DecodeString(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn proto.Unmarshal(b, pb)\n}", "func (this *Codec) deserialize(data string) *TreeNode {\n\tints := strings.Split(data, \",\")\n\n\treturn dHelper(&ints)\n}", "func toInterface(bts []byte, data interface{}) error {\n\tbuf := bytes.NewBuffer(bts)\n\tdec := gob.NewDecoder(buf)\n\treturn dec.Decode(data)\n}", "func (rr *Reader) ReadSerialized(obj deserializable, sizes ...int) {\n\tif rr.Err != nil {\n\t\treturn\n\t}\n\tif obj == nil {\n\t\tpanic(\"nil deserializer\")\n\t}\n\tvar size int\n\tswitch len(sizes) {\n\tcase 0:\n\t\tsize = rr.ReadSize16()\n\tcase 1:\n\t\tlimit := sizes[0]\n\t\tif limit < 0 || limit > math.MaxInt32 {\n\t\t\tpanic(\"invalid deserialize limit\")\n\t\t}\n\t\tsize = rr.ReadSizeWithLimit(uint32(limit))\n\tcase 2:\n\t\tsize = sizes[1]\n\t\tif size < 0 || size > math.MaxInt32 {\n\t\t\tpanic(\"invalid deserialize size\")\n\t\t}\n\tdefault:\n\t\tpanic(\"too many deserialize params\")\n\t}\n\tdata := make([]byte, size)\n\trr.ReadN(data)\n\tif rr.Err == nil {\n\t\tvar n int\n\t\tn, rr.Err = obj.Deserialize(data, serializer.DeSeriModeNoValidation, nil)\n\t\tif n != len(data) && rr.Err == nil {\n\t\t\trr.Err = errors.New(\"unexpected deserialize size\")\n\t\t}\n\t}\n}", "func FromBytes(rawBytes []byte, p Packet) error {\n\t// interface smuggling\n\tif pp, ok := p.(encoding.BinaryUnmarshaler); ok {\n\t\treturn pp.UnmarshalBinary(rawBytes)\n\t}\n\treader := bytes.NewReader(rawBytes)\n\treturn binary.Read(reader, binary.BigEndian, p)\n}", "func decodeMsgPack(buf []byte, out interface{}) error {\n\treturn codec.NewDecoder(bytes.NewReader(buf), msgpackHandle).Decode(out)\n}", "func decodeMsgPack(buf []byte, out interface{}) error {\n\treturn codec.NewDecoder(bytes.NewReader(buf), msgpackHandle).Decode(out)\n}", "func (protocol *Protocol) UnMarshal(data []byte) (int, error) {\n if(len(data) < TypeEnd) {\n //不完整的数据 待下次再读\n return 0, fmt.Errorf(\"incomplete data\"); \n }\n \n idSplit := data[:IDEnd]\n ptypeSplit := data[IDEnd:TypeEnd]\n packSplit := data[TypeEnd:]\n \n protocol.ID = ProtoID(binary.LittleEndian.Uint32(idSplit))\n protocol.PType = ProtoType(binary.LittleEndian.Uint32(ptypeSplit))\n \n protocol.Packet = NewPBPacket(protocol.ID)\n \n if nil == protocol.Packet {\n return -1, fmt.Errorf(\"Invalid packetId, need Close client??? id = %d, data = %v\", protocol.ID, data)\n }\n \n ms, _ := protocol.Packet.(proto.Message);\n err := proto.Unmarshal(packSplit, ms)\n \n if nil != err {\n return 0, fmt.Errorf(\"PBMessage Unmarshal Error!!! incomplete packet or need close client\")\n }\n \n msLen := proto.Size(ms)\n\n packetLen := msLen + TypeEnd\n return packetLen, nil\n}", "func (cb *codedBuffer) decodeRawBytes(alloc bool) (buf []byte, err error) {\n\tn, err := cb.decodeVarint()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnb := int(n)\n\tif nb < 0 {\n\t\treturn nil, fmt.Errorf(\"proto: bad byte length %d\", nb)\n\t}\n\tend := cb.index + nb\n\tif end < cb.index || end > len(cb.buf) {\n\t\treturn nil, io.ErrUnexpectedEOF\n\t}\n\n\tif !alloc {\n\t\tbuf = cb.buf[cb.index:end]\n\t\tcb.index = end\n\t\treturn\n\t}\n\n\tbuf = make([]byte, nb)\n\tcopy(buf, cb.buf[cb.index:])\n\tcb.index = end\n\treturn\n}", "func DecodeBytes(in []byte, objs ...interface{}) (err error) {\n\tbuf := bytes.NewBuffer(in)\n\terr = Decode(buf, objs...)\n\treturn\n}", "func newDataFileReaderBytes(buf []byte, datumReader DatumReader) (reader *DataFileReader, err error) {\n\tif len(buf) < len(magic) || !bytes.Equal(magic, buf[0:4]) {\n\t\treturn nil, NotAvroFile\n\t}\n\n\tdec := NewBinaryDecoder(buf)\n\tblockDecoder := NewBinaryDecoder(nil)\n\treader = &DataFileReader{\n\t\tdata: buf,\n\t\tdec: dec,\n\t\tblockDecoder: blockDecoder,\n\t\tdatum: datumReader,\n\t}\n\n\tif reader.header, err = readObjFileHeader(dec); err != nil {\n\t\treturn nil, err\n\t}\n\n\tschema, err := ParseSchema(string(reader.header.Meta[schemaKey]))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treader.datum.SetSchema(schema)\n\treader.block = &DataBlock{}\n\n\tif reader.hasNextBlock() {\n\t\tif err := reader.NextBlock(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn reader, nil\n}", "func readBytes(dataBytes []byte, data interface{}, index int, size int64, numElements int64) error {\n\tstart := int64(index) * numElements * size\n\tbuf := bytes.NewBuffer(dataBytes[start : start+numElements*size])\n\treturn binary.Read(buf, binary.LittleEndian, data)\n}", "func unmarsharlYaml(byteArray []byte) Config {\n var cfg Config\n err := yaml.Unmarshal([]byte(byteArray), &cfg)\n if err != nil {\n log.Fatalf(\"error: %v\", err)\n }\n return cfg\n}", "func (r *InterRecord) Bytes() []byte {\n\tif r.Types != 0 {\n\t\treturn r.Raw\n\t}\n\n\t// Collect the buffers to be recycled after generate the JSON\n\tvar buffs []*bytebufferpool.ByteBuffer\n\n\t// Interal function for compress\n\tcomp := func(o []byte) []byte {\n\t\t// Get a buffer from the pool\n\t\tb := compressPool.Get()\n\t\t// append to an slice of bytesbuffers to be recycled (check the defer some upper lines)\n\t\tbuffs = append(buffs, b)\n\n\t\t// Get a gzip from the pull, write in the buffer and return to the pool\n\t\tw := GetGzipWriter(b)\n\t\tw.Write(o)\n\t\tw.Close()\n\n\t\t// Unlink the buffer for the gzip before return to the pool, just in case..?\n\t\tPutGzipWriter(w)\n\n\t\treturn b.B\n\t}\n\n\t// After generate the JSON send the buffer to the pool\n\tdefer func() {\n\t\tif len(buffs) > 0 {\n\t\t\tfor _, b := range buffs {\n\t\t\t\tcompressPool.Put(b)\n\t\t\t}\n\t\t}\n\t}()\n\n\tif r.compressFields {\n\t\tfor k, v := range r.Data {\n\t\t\tswitch o := v.(type) {\n\t\t\tcase []byte:\n\t\t\t\tr.Data[k] = comp(o)\n\t\t\tcase []interface{}:\n\t\t\t\tfor _, iv := range o {\n\t\t\t\t\tswitch o := iv.(type) {\n\t\t\t\t\tcase []byte:\n\t\t\t\t\t\tiv = comp(o)\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase map[string]interface{}:\n\t\t\t\tfor _, iv := range o {\n\t\t\t\t\tswitch o := iv.(type) {\n\t\t\t\t\tcase []byte:\n\t\t\t\t\t\tiv = comp(o)\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\t// No changes\n\t\t\t}\n\t\t}\n\t}\n\n\tbuf, err := ffjson.Marshal(r)\n\tif err != nil {\n\t\tffjson.Pool(buf)\n\t\tlog.Printf(\"Error in ffjson: %s\", err)\n\t\treturn nil\n\t}\n\n\treturn buf\n}", "func _messsageDecode(b *[]byte) (*Message, error) {\n\n\tmessage := Message{}\n\n\tmsg := bytes.Split(*b, elemSep)\n\t// if the length of msg slice is less than the message is invalid\n\tif len(msg) < 2 {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Invalid message : invalid msg len %d\", len(msg)))\n\t}\n\n\t// elemCount counts the number of elements added to the message like MsgType,Msg etc..\n\t// the elemCount should be equal to len(msg) after the loop coming\n\tvar elemCount int\n\n\t// loop until the last element\n\t// the last element is the payload\n\tfor index, element := range msg {\n\n\t\tif (index + 1) == len(msg) {\n\n\t\t\tmessage.Msg = element\n\t\t\telemCount++\n\t\t\tbreak\n\n\t\t}\n\n\t\telem := bytes.Split(element, keyValSep)\n\n\t\tif len(elem) < 2 {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Invalid message : invalid length %d elemCounted %d\",len(elem),elemCount))\n\t\t}\n\n\t\t// find the approprite elem of message\n\t\t// if unknown elem is sent then this is an errors\n\t\tswitch string(elem[0]) {\n\n\t\tcase \"ClientID\":\n\n\t\t\tmessage.ClientID = string(elem[1])\n\t\t\telemCount++\n\n\t\tcase \"ReceiverID\":\n\n\t\t\tmessage.ReceiverID = string(elem[1])\n\t\t\telemCount++\n\n\t\tcase \"RoomID\":\n\n\t\t\tmessage.RoomID = string(elem[1])\n\t\t\telemCount++\n\n\t\tcase \"Info\":\n\n\t\t\tmessage.Info = string(elem[1])\n\t\t\telemCount++\n\n\t\tcase \"MsgType\":\n\n\t\t\tmsgType, err := strconv.ParseInt(string(elem[1]), 10, 16)\n\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tmessage.MsgType = int(msgType)\n\t\t\telemCount++\n\n\t\tdefault: // unknown elemetn which is a error\n\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Invalid message : Unknown Elem(%s)\", string(elem[0])))\n\n\t\t} // switch case ends\n\n\t} // for loop ends\n\n\tif elemCount != len(msg) {\n\t\treturn nil, errors.New(\"Invalid message\")\n\t}\n\n\t// Now we have a valid message\n\n\treturn &message, nil\n\n}", "func (b *Buf) Bytes() []byte { return b.b }", "func (batch *BatchEncoder) Read() (keyByte []byte, valueByte []byte) {\n\tkeyByte = make([]byte, batch.keyBuf.Len())\n\t_, _ = batch.keyBuf.Read(keyByte)\n\n\tvalueByte = make([]byte, batch.valueBuf.Len())\n\t_, _ = batch.valueBuf.Read(valueByte)\n\treturn\n}", "func GobDecode(buffer []byte, value interface{}) error {\n buf := bytes.NewBuffer(buffer)\n decoder := gob.NewDecoder(buf)\n err := decoder.Decode(value)\n if err != nil {\n return gobDebug.Error(err)\n }\n return nil\n}", "func (b *Buffer) Bytes() []byte { return b.buf[:b.length] }", "func deserializeChannel(serialized []byte) (*StoredChannel, error) {\n\tbuffer := &bytes.Buffer{}\n\tdecoder := gob.NewDecoder(buffer)\n\tif _, err := buffer.Write(serialized); err != nil {\n\t\treturn nil, err\n\t}\n\n\tdec := &StoredChannel{}\n\terr := decoder.Decode(dec)\n\treturn dec, err\n}", "func Deserialize(data []byte, typ string, registry Registry) (interface{}, error) {\n\tif len(data) == 0 {\n\t\treturn nil, nil\n\t}\n\tserde, err := registry.GetSerde(typ)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn serde.Deserialize(data)\n}", "func (n *bigNumber) setBytes(in []byte) *bigNumber {\n\tif len(in) != fieldBytes {\n\t\treturn nil\n\t}\n\n\ts := serialized{}\n\tfor i, si := range in {\n\t\ts[len(s)-i-1] = si\n\t}\n\n\td, ok := deserialize(s)\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tfor i, di := range d {\n\t\tn[i] = di\n\t}\n\n\treturn n\n}", "func Unmarshal(b []byte, v interface{}) (err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tif je, ok := r.(error); ok {\n\t\t\t\terr = fmt.Errorf(\"%s, bianay %v, destType %T\", je.Error(), b, v)\n\t\t\t} else {\n\t\t\t\terr = fmt.Errorf(\"%v, bianay %v, destType %T\", r, b, v)\n\t\t\t}\n\t\t}\n\t}()\n\t// Get the decoder from the pool, reset it\n\td := decoders.Get().(*Decoder)\n\td.r.(*reader).Reset(b) // Reset the reader\n\n\t// Decode and set the buffer if successful and free the decoder\n\terr = d.Decode(v)\n\tdecoders.Put(d)\n\treturn\n}", "func (deserializer *batchDeserializer) parseBatchRecord(data []byte) (*batchRecord, error) {\n batchHeader, err := deserializer.deserializeBatchHeader(data)\n if err != nil {\n return nil, err\n }\n\n // 跳过batch header的部分\n data = data[batchRecordHeaderSize:]\n\n rawBuf, err := deserializer.decompressIfNeed(batchHeader, data)\n if err != nil {\n return nil, err\n }\n\n batch := &batchRecord{}\n reader := bytes.NewReader(rawBuf)\n batch.records = make([]*binaryRecord, 0, batchHeader.recordCount)\n for idx := 0; idx < batchHeader.recordCount; idx = idx + 1 {\n bRecord, err := deserializer.bSerializer.deserializeBinaryRecord(reader)\n if err != nil {\n return nil, err\n }\n batch.records = append(batch.records, bRecord)\n }\n\n return batch, nil\n}", "func (b *BundleIdent) Deserialize(buffer []byte, err *error) []byte {\n\tif *err != nil {\n\t\treturn nil\n\t}\n\tb.App, buffer = deserializeString(buffer, err)\n\tbuffer = b.User.Deserialize(buffer, err)\n\tb.Name, buffer = deserializeString(buffer, err)\n\tb.Incarnation, buffer = deserializeString(buffer, err)\n\treturn buffer\n}", "func PayloadFromBytes(b []byte) Payload {\n\treturn jsonPayload(b)\n}", "func ParseBytes(bytes []byte) (*JSONData, error) {\n\tdata := JSONData{}\n\treturn &data, json.Unmarshal(bytes, &data.value)\n}", "func Deserialize(r io.Reader, dser Deserializer) error {\n\tbufreader := bufio.NewReader(r)\n\tbuf, err := bufreader.Peek(1)\n\tif err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\tif err == io.EOF && len(buf) == 0 {\n\t\treturn nil\n\t}\n\tdec := json.NewDecoder(bufreader)\n\tdec.UseNumber()\n\ttoken := string(buf[0:1])\n\trunning := true\n\tfor running {\n\t\tswitch token {\n\t\tcase \"[\", \"{\":\n\t\t\t{\n\t\t\t\tif token == \"[\" {\n\t\t\t\t\t// advance the array token\n\t\t\t\t\tdec.Token()\n\t\t\t\t}\n\t\t\t\tvar line json.RawMessage\n\t\t\t\tfor dec.More() {\n\t\t\t\t\tif err := dec.Decode(&line); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tif err := dser(line); 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\t// consume the last token\n\t\t\t\tdec.Token()\n\t\t\t\t// check to see if we have more data in the buffer in case we\n\t\t\t\t// have concatenated streams together\n\t\t\t\trunning = dec.More()\n\t\t\t}\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"invalid json, expected either [ or {\")\n\t\t}\n\t}\n\treturn nil\n}", "func bytesToCmd(b []byte) interface{} {\n\tr := bytes.NewReader(b)\n\tdec := gob.NewDecoder(r)\n\tvar c Command\n\tif err := dec.Decode(&c); nil != err {\n\t\tlog.Fatalf(\"failed to decode command: %s\", err)\n\t\treturn Command{}\n\t}\n\treturn c.Cmd\n}", "func ReadConfigFromByteArray(configYaml []byte) *Config {\n\tc := &Config{}\n\n\terr := yaml.Unmarshal(configYaml, c)\n\tif err != nil {\n\t\tlog.Fatalf(\"Invalid configuration: %v\", err)\n\t\treturn nil\n\t}\n\n\tc.Vars.init()\n\treturn c\n}", "func DecodeBytes(b []byte, val interface{}) error {\n\t// initialize byte reader\n\tr := bytes.NewReader(b)\n\tif err := NewStream(r, uint64(len(b))).Decode(val); err != nil {\n\t\treturn err\n\t}\n\tif r.Len() > 0 {\n\t\treturn ErrMoreThanOneValue\n\t}\n\treturn nil\n}", "func ReadBytes(fourBytes []byte, v interface{}) error {\n\tbuf := bytes.NewBuffer(fourBytes)\n\n\tswitch v.(type) {\n\tcase *int8:\n\t\tv = v.(*int8)\n\tcase *int16:\n\t\tv = v.(*int16)\n\tcase *int32:\n\t\tv = v.(*int32)\n\tcase *float32:\n\t\tv = v.(*float32)\n\tcase *float64:\n\t\tv = v.(*float64)\n\tdefault:\n\t\treturn fmt.Errorf(\"cannot decode bytes to type %T\", v)\n\t}\n\n\tif err := binary.Read(buf, binary.LittleEndian, v); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (d RawDataDecoder) Decode(v interface{}) error {\n\tdata, err := ioutil.ReadAll(d.reader)\n\tif err != nil {\n\t\treturn err\n\t}\n\tswitch v.(type) {\n\tcase FromBytes:\n\t\t(v.(FromBytes)).SetBytes(data)\n\tdefault:\n\t\treturn errors.New(\"RawDataDecoder only admits FromBytes interface\")\n\t}\n\treturn nil\n}", "func Decode(buf []byte, out interface{}) error {\n\treturn codec.NewDecoder(bytes.NewReader(buf), msgpackHandle).Decode(out)\n}", "func Decode(buf []byte, out interface{}) error {\n\treturn codec.NewDecoder(bytes.NewReader(buf), msgpackHandle).Decode(out)\n}", "func Read(b []byte) { Reader.Read(b) }", "func (i *DeserializerV1) ReadAt(p []byte, begin int) ([]interface{}, int, error) {\n\tvar ans []interface{}\n\tvar j = begin\n\tvar err error\n\n\tfor ; j < len(p); j++ {\n\t\tch := p[j]\n\t\tswitch ch {\n\t\tdefault:\n\t\tcase 'c':\n\t\tcase 'r':\n\t\tcase 'f':\n\t\t\tvar args []interface{}\n\t\t\targs, j, err = i.ReadAt(p, j+1)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, j, err\n\t\t\t}\n\t\t\treturn nil, j, fmt.Errorf(\"Call Service Error, Exception: %s, Message: %s\", args[1].(string), args[3].(string))\n\t\tcase 'z':\n\t\t\treturn ans, j, nil\n\t\tcase 'T':\n\t\t\tans = append(ans, true)\n\t\tcase 'F':\n\t\t\tans = append(ans, false)\n\t\tcase 'N':\n\t\t\tans = append(ans, nil)\n\t\tcase 'B':\n\t\t\t// B b16 b8 byte-value\n\t\t\tvar val []byte\n\t\t\tval, j, err = i.ReadBytesAt(p, j+1)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, j, err\n\t\t\t}\n\t\t\tans = append(ans, val)\n\t\tcase 'S':\n\t\t\t// S b16 b8 string-value\n\t\t\tvar val string\n\t\t\tval, j, err = i.ReadStringAt(p, j+1)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, j, err\n\t\t\t}\n\t\t\tans = append(ans, val)\n\t\tcase 'I':\n\t\t\t// I b32 b24 b16 b8\n\t\t\tvar val int32\n\t\t\tval, j, err = i.ReadInt32At(p, j+1)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, j, err\n\t\t\t}\n\t\t\tans = append(ans, val)\n\t\tcase 'L':\n\t\t\t// L b64 b56 b48 b40 b32 b24 b16 b8\n\t\t\tvar val int64\n\t\t\tval, j, err = i.ReadInt64At(p, j+1)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, j, err\n\t\t\t}\n\t\t\tans = append(ans, val)\n\t\tcase 'D':\n\t\t\t// D b64 b56 b48 b40 b32 b24 b16 b8\n\t\t\tvar val float64\n\t\t\tval, j, err = i.ReadFloat64At(p, j+1)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, j, err\n\t\t\t}\n\t\t\tans = append(ans, val)\n\t\tcase 'd':\n\t\t\t// d b64 b56 b48 b40 b32 b24 b16 b8\n\t\t\tvar val time.Time\n\t\t\tval, j, err = i.ReadDateAt(p, j+1)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, j, err\n\t\t\t}\n\t\t\tans = append(ans, val)\n\t\tcase 'M':\n\t\t\tif p[j+1] == 't' {\n\t\t\t\tj++\n\t\t\t\tvar pkg string\n\t\t\t\tvar m = make(map[interface{}]interface{})\n\t\t\t\tpkg, j, err = i.ReadStringAt(p, j+1)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, j, err\n\t\t\t\t}\n\n\t\t\t\t// parse 'Mt' arguments\n\t\t\t\tm, j, err = i.ReadMapAt(p, j+1)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, j, err\n\t\t\t\t}\n\n\t\t\t\tif len(pkg) > 0 {\n\t\t\t\t\tobj, err := i.BuildObject(pkg, m)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tans = append(ans, nil)\n\t\t\t\t\t}\n\t\t\t\t\tans = append(ans, obj)\n\t\t\t\t} else {\n\t\t\t\t\tans = append(ans, m)\n\t\t\t\t}\n\t\t\t}\n\t\tcase 'V':\n\t\t\tif p[j+1] == 't' {\n\t\t\t\tj++\n\t\t\t\tvar arr []interface{}\n\n\t\t\t\tarr, j, err = i.ReadArrayAt(p, j+1)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, j, err\n\t\t\t\t}\n\n\t\t\t\tans = append(ans, arr)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ans, j, nil\n}", "func (f *CreateBundleRequest) Deserialize(buffer []byte, err *error) []byte {\n\tif *err != nil {\n\t\treturn nil\n\t}\n\tbuffer = f.Bundle.Deserialize(buffer, err)\n\treturn buffer\n}", "func (bm *BlockMeta) Deserialize(buf []byte) error {\n\tepochMetapb := &blockmetapb.BlockMeta{}\n\tif err := proto.Unmarshal(buf, epochMetapb); err != nil {\n\t\treturn errors.Wrap(err, \"failed to unmarshal blocklist\")\n\t}\n\treturn bm.LoadProto(epochMetapb)\n}", "func readDataToStruct(i2c *i2c.I2C, byteCount int,\n\tbyteOrder binary.ByteOrder, obj interface{}) error {\n\tbuf1 := make([]byte, byteCount)\n\t_, err := i2c.ReadBytes(buf1)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbuf := bytes.NewBuffer(buf1)\n\terr = binary.Read(buf, byteOrder, obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}" ]
[ "0.6612194", "0.6521848", "0.6435393", "0.63997245", "0.6359135", "0.633301", "0.62487584", "0.61810875", "0.6155041", "0.60449594", "0.6040225", "0.60215473", "0.5947103", "0.59352154", "0.59306705", "0.5907481", "0.5892002", "0.5888056", "0.5870201", "0.5865612", "0.58612597", "0.5856737", "0.58252674", "0.58178496", "0.5815367", "0.5778627", "0.5731261", "0.5720487", "0.56960636", "0.5672151", "0.562956", "0.56253487", "0.55635333", "0.55538505", "0.55470175", "0.5544667", "0.5522409", "0.55207705", "0.55106735", "0.5504633", "0.54984605", "0.5482871", "0.547824", "0.5475505", "0.54662067", "0.5462273", "0.5462021", "0.54610467", "0.54561687", "0.5451411", "0.54513675", "0.544169", "0.54367906", "0.5428881", "0.53910595", "0.5380359", "0.5368746", "0.5364583", "0.53637034", "0.5359406", "0.53425366", "0.53392303", "0.5334794", "0.53322685", "0.5330718", "0.53267324", "0.53267324", "0.5318763", "0.531368", "0.5305629", "0.52989405", "0.52842784", "0.5283924", "0.5276068", "0.5272941", "0.52724546", "0.5268631", "0.5265244", "0.5261875", "0.5246468", "0.5241431", "0.52382463", "0.52371335", "0.5230885", "0.52286434", "0.52244896", "0.5221216", "0.5218575", "0.52169615", "0.5216892", "0.52149653", "0.52142227", "0.5201971", "0.51988095", "0.51988095", "0.5198287", "0.5190279", "0.5182791", "0.517905", "0.51761913" ]
0.611553
9
Exec_Withdraw exec asset withdraw
func (z *zksync) Exec_Withdraw(payload *types.AssetsWithdraw, tx *types.Transaction, index int) (*types.Receipt, error) { action := NewAction(z, tx, index) return action.AssetWithdraw(payload, tx, index) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (_IWETH *IWETHTransactor) Withdraw(opts *bind.TransactOpts, arg0 *big.Int) (*types.Transaction, error) {\r\n\treturn _IWETH.contract.Transact(opts, \"withdraw\", arg0)\r\n}", "func (_PBridge *PBridgeTransactor) ExecuteWithdrawTx(opts *bind.TransactOpts, txKey string, to common.Address, amount *big.Int, isERC20 bool, ERC20 common.Address, signatures []byte) (*types.Transaction, error) {\n\treturn _PBridge.contract.Transact(opts, \"executeWithdrawTx\", txKey, to, amount, isERC20, ERC20, signatures)\n}", "func (_Smartchef *SmartchefTransactor) Withdraw(opts *bind.TransactOpts, _amount *big.Int) (*types.Transaction, error) {\n\treturn _Smartchef.contract.Transact(opts, \"withdraw\", _amount)\n}", "func (_WELV9 *WELV9Transactor) Withdraw(opts *bind.TransactOpts, wad *big.Int) (*types.Transaction, error) {\n\treturn _WELV9.contract.Transact(opts, \"withdraw\", wad)\n}", "func (_Token *TokenTransactor) ExecuteWithdrawal(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Token.contract.Transact(opts, \"executeWithdrawal\")\n}", "func (_PBridge *PBridgeSession) ExecuteWithdrawTx(txKey string, to common.Address, amount *big.Int, isERC20 bool, ERC20 common.Address, signatures []byte) (*types.Transaction, error) {\n\treturn _PBridge.Contract.ExecuteWithdrawTx(&_PBridge.TransactOpts, txKey, to, amount, isERC20, ERC20, signatures)\n}", "func (_PBridge *PBridgeTransactorSession) ExecuteWithdrawTx(txKey string, to common.Address, amount *big.Int, isERC20 bool, ERC20 common.Address, signatures []byte) (*types.Transaction, error) {\n\treturn _PBridge.Contract.ExecuteWithdrawTx(&_PBridge.TransactOpts, txKey, to, amount, isERC20, ERC20, signatures)\n}", "func (_Wmatic *WmaticTransactor) Withdraw(opts *bind.TransactOpts, wad *big.Int) (*types.Transaction, error) {\n\treturn _Wmatic.contract.Transact(opts, \"withdraw\", wad)\n}", "func (_IWETH *IWETHSession) Withdraw(arg0 *big.Int) (*types.Transaction, error) {\r\n\treturn _IWETH.Contract.Withdraw(&_IWETH.TransactOpts, arg0)\r\n}", "func (_IWETH *IWETHTransactorSession) Withdraw(arg0 *big.Int) (*types.Transaction, error) {\r\n\treturn _IWETH.Contract.Withdraw(&_IWETH.TransactOpts, arg0)\r\n}", "func (_BREMICO *BREMICOTransactor) Withdraw(opts *bind.TransactOpts, _value *big.Int) (*types.Transaction, error) {\n\treturn _BREMICO.contract.Transact(opts, \"withdraw\", _value)\n}", "func (_SingleAuto *SingleAutoTransactor) Withdraw(opts *bind.TransactOpts, _pid *big.Int, _wantAmt *big.Int) (*types.Transaction, error) {\n\treturn _SingleAuto.contract.Transact(opts, \"withdraw\", _pid, _wantAmt)\n}", "func (_Cakevault *CakevaultTransactor) Withdraw(opts *bind.TransactOpts, _shares *big.Int) (*types.Transaction, error) {\n\treturn _Cakevault.contract.Transact(opts, \"withdraw\", _shares)\n}", "func (_TokenStakingEscrow *TokenStakingEscrowTransactor) Withdraw(opts *bind.TransactOpts, operator common.Address) (*types.Transaction, error) {\n\treturn _TokenStakingEscrow.contract.Transact(opts, \"withdraw\", operator)\n}", "func (_ElvTradable *ElvTradableTransactor) Withdraw(opts *bind.TransactOpts, _amount *big.Int) (*types.Transaction, error) {\n\treturn _ElvTradable.contract.Transact(opts, \"withdraw\", _amount)\n}", "func (seele *SeeleContract) Withdraw(_contractId [32]byte, _preimage [32]byte) ([]byte, error) {\n\treturn getFuncByteCode(\"withdraw\", _contractId, _preimage)\n}", "func (_WandappETH *WandappETHTransactor) Withdraw(opts *bind.TransactOpts, proof []byte) (*types.Transaction, error) {\n\treturn _WandappETH.contract.Transact(opts, \"withdraw\", proof)\n}", "func (_Contract *ContractTransactor) Withdraw(opts *bind.TransactOpts, value *big.Int) (*types.Transaction, error) {\n\treturn _Contract.contract.Transact(opts, \"withdraw\", value)\n}", "func (_DelegateProfile *DelegateProfileTransactor) Withdraw(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _DelegateProfile.contract.Transact(opts, \"withdraw\")\n}", "func (_Wmatic *WmaticSession) Withdraw(wad *big.Int) (*types.Transaction, error) {\n\treturn _Wmatic.Contract.Withdraw(&_Wmatic.TransactOpts, wad)\n}", "func (_Token *TokenTransactorSession) ExecuteWithdrawal() (*types.Transaction, error) {\n\treturn _Token.Contract.ExecuteWithdrawal(&_Token.TransactOpts)\n}", "func (_Vault *VaultTransactorSession) Withdraw(inst []byte, heights *big.Int, instPaths [][32]byte, instPathIsLefts []bool, instRoots [32]byte, blkData [32]byte, sigIdxs []*big.Int, sigVs []uint8, sigRs [][32]byte, sigSs [][32]byte) (*types.Transaction, error) {\n\treturn _Vault.Contract.Withdraw(&_Vault.TransactOpts, inst, heights, instPaths, instPathIsLefts, instRoots, blkData, sigIdxs, sigVs, sigRs, sigSs)\n}", "func (_Wmatic *WmaticTransactorSession) Withdraw(wad *big.Int) (*types.Transaction, error) {\n\treturn _Wmatic.Contract.Withdraw(&_Wmatic.TransactOpts, wad)\n}", "func (sc stakingClient) Withdraw(fromInfo keys.Info, passWd, coinsStr, memo string, accNum, seqNum uint64) (\n\tresp sdk.TxResponse, err error) {\n\tif err = params.CheckKeyParams(fromInfo, passWd); err != nil {\n\t\treturn\n\t}\n\n\tcoin, err := sdk.ParseDecCoin(coinsStr)\n\tif err != nil {\n\t\treturn resp, fmt.Errorf(\"failed : parse Coins [%s] error: %s\", coinsStr, err)\n\t}\n\n\tmsg := types.NewMsgWithdraw(fromInfo.GetAddress(), coin)\n\n\treturn sc.BuildAndBroadcast(fromInfo.GetName(), passWd, memo, []sdk.Msg{msg}, accNum, seqNum)\n\n}", "func (_Vault *VaultSession) Withdraw(inst []byte, heights *big.Int, instPaths [][32]byte, instPathIsLefts []bool, instRoots [32]byte, blkData [32]byte, sigIdxs []*big.Int, sigVs []uint8, sigRs [][32]byte, sigSs [][32]byte) (*types.Transaction, error) {\n\treturn _Vault.Contract.Withdraw(&_Vault.TransactOpts, inst, heights, instPaths, instPathIsLefts, instRoots, blkData, sigIdxs, sigVs, sigRs, sigSs)\n}", "func (_Vault *VaultTransactor) Withdraw(opts *bind.TransactOpts, inst []byte, heights *big.Int, instPaths [][32]byte, instPathIsLefts []bool, instRoots [32]byte, blkData [32]byte, sigIdxs []*big.Int, sigVs []uint8, sigRs [][32]byte, sigSs [][32]byte) (*types.Transaction, error) {\n\treturn _Vault.contract.Transact(opts, \"withdraw\", inst, heights, instPaths, instPathIsLefts, instRoots, blkData, sigIdxs, sigVs, sigRs, sigSs)\n}", "func (_Token *TokenSession) ExecuteWithdrawal() (*types.Transaction, error) {\n\treturn _Token.Contract.ExecuteWithdrawal(&_Token.TransactOpts)\n}", "func (_XStaking *XStakingTransactor) Withdraw(opts *bind.TransactOpts, amount *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.contract.Transact(opts, \"withdraw\", amount)\n}", "func (_EtherDelta *EtherDeltaTransactor) Withdraw(opts *bind.TransactOpts, amount *big.Int) (*types.Transaction, error) {\n\treturn _EtherDelta.contract.Transact(opts, \"withdraw\", amount)\n}", "func (_Lmc *LmcTransactor) Withdraw(opts *bind.TransactOpts, _tokenAmount *big.Int) (*types.Transaction, error) {\n\treturn _Lmc.contract.Transact(opts, \"withdraw\", _tokenAmount)\n}", "func (_ElvTradableLocal *ElvTradableLocalTransactor) Withdraw(opts *bind.TransactOpts, _amount *big.Int) (*types.Transaction, error) {\n\treturn _ElvTradableLocal.contract.Transact(opts, \"withdraw\", _amount)\n}", "func (_Smartchef *SmartchefSession) Withdraw(_amount *big.Int) (*types.Transaction, error) {\n\treturn _Smartchef.Contract.Withdraw(&_Smartchef.TransactOpts, _amount)\n}", "func (_Smartchef *SmartchefTransactorSession) Withdraw(_amount *big.Int) (*types.Transaction, error) {\n\treturn _Smartchef.Contract.Withdraw(&_Smartchef.TransactOpts, _amount)\n}", "func (_DogsOfRome *DogsOfRomeTransactor) Withdraw(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _DogsOfRome.contract.Transact(opts, \"withdraw\")\n}", "func (_Contract *ContractTransactorSession) Withdraw(value *big.Int) (*types.Transaction, error) {\n\treturn _Contract.Contract.Withdraw(&_Contract.TransactOpts, value)\n}", "func (sc Funcs) Withdraw(ctx wasmlib.ScFuncClientContext) *WithdrawCall {\n\treturn &WithdrawCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncWithdraw)}\n}", "func withdraw(ctx iscp.Sandbox) (dict.Dict, error) {\n\tstate := ctx.State()\n\tmustCheckLedger(state, \"accounts.withdraw.begin\")\n\n\tif ctx.Caller().Address().Equals(ctx.ChainID().AsAddress()) {\n\t\t// if the caller is on the same chain, do nothing\n\t\treturn nil, nil\n\t}\n\ttokensToWithdraw, ok := GetAccountBalances(state, ctx.Caller())\n\tif !ok {\n\t\t// empty balance, nothing to withdraw\n\t\treturn nil, nil\n\t}\n\t// will be sending back to default entry point\n\ta := assert.NewAssert(ctx.Log())\n\t// bring balances to the current account (owner's account). It is needed for subsequent Send call\n\ta.Require(MoveBetweenAccounts(state, ctx.Caller(), commonaccount.Get(ctx.ChainID()), tokensToWithdraw),\n\t\t\"accounts.withdraw.inconsistency. failed to move tokens to owner's account\")\n\n\t// add incoming tokens (after fees) to the balances to be withdrawn. Otherwise they would end up in the common account\n\ttokensToWithdraw.AddAll(ctx.IncomingTransfer())\n\t// Send call assumes tokens are in the current account\n\ta.Require(ctx.Send(ctx.Caller().Address(), tokensToWithdraw, &iscp.SendMetadata{\n\t\tTargetContract: ctx.Caller().Hname(),\n\t}), \"accounts.withdraw.inconsistency: failed sending tokens \")\n\n\tctx.Log().Debugf(\"accounts.withdraw.success. Sent to address %s\", tokensToWithdraw.String())\n\n\tmustCheckLedger(state, \"accounts.withdraw.exit\")\n\treturn nil, nil\n}", "func (_WandappETH *WandappETHTransactorSession) Withdraw(proof []byte) (*types.Transaction, error) {\n\treturn _WandappETH.Contract.Withdraw(&_WandappETH.TransactOpts, proof)\n}", "func (_WandappETH *WandappETHSession) Withdraw(proof []byte) (*types.Transaction, error) {\n\treturn _WandappETH.Contract.Withdraw(&_WandappETH.TransactOpts, proof)\n}", "func (_SingleAuto *SingleAutoSession) Withdraw(_pid *big.Int, _wantAmt *big.Int) (*types.Transaction, error) {\n\treturn _SingleAuto.Contract.Withdraw(&_SingleAuto.TransactOpts, _pid, _wantAmt)\n}", "func (_SingleAuto *SingleAutoTransactorSession) Withdraw(_pid *big.Int, _wantAmt *big.Int) (*types.Transaction, error) {\n\treturn _SingleAuto.Contract.Withdraw(&_SingleAuto.TransactOpts, _pid, _wantAmt)\n}", "func (_DelegateProfile *DelegateProfileTransactorSession) Withdraw() (*types.Transaction, error) {\n\treturn _DelegateProfile.Contract.Withdraw(&_DelegateProfile.TransactOpts)\n}", "func (_Contract *ContractSession) Withdraw(value *big.Int) (*types.Transaction, error) {\n\treturn _Contract.Contract.Withdraw(&_Contract.TransactOpts, value)\n}", "func (_TokenStakingEscrow *TokenStakingEscrowSession) Withdraw(operator common.Address) (*types.Transaction, error) {\n\treturn _TokenStakingEscrow.Contract.Withdraw(&_TokenStakingEscrow.TransactOpts, operator)\n}", "func (_BREMICO *BREMICOTransactorSession) Withdraw(_value *big.Int) (*types.Transaction, error) {\n\treturn _BREMICO.Contract.Withdraw(&_BREMICO.TransactOpts, _value)\n}", "func (_EtherDelta *EtherDeltaTransactorSession) Withdraw(amount *big.Int) (*types.Transaction, error) {\n\treturn _EtherDelta.Contract.Withdraw(&_EtherDelta.TransactOpts, amount)\n}", "func (_BREMICO *BREMICOSession) Withdraw(_value *big.Int) (*types.Transaction, error) {\n\treturn _BREMICO.Contract.Withdraw(&_BREMICO.TransactOpts, _value)\n}", "func (_TokenStakingEscrow *TokenStakingEscrowTransactorSession) Withdraw(operator common.Address) (*types.Transaction, error) {\n\treturn _TokenStakingEscrow.Contract.Withdraw(&_TokenStakingEscrow.TransactOpts, operator)\n}", "func (_EtherDelta *EtherDeltaSession) Withdraw(amount *big.Int) (*types.Transaction, error) {\n\treturn _EtherDelta.Contract.Withdraw(&_EtherDelta.TransactOpts, amount)\n}", "func (m *controller) Withdraw(db weave.KVStore, escrow *Escrow, escrowID []byte, dest weave.Address, amounts coin.Coins) error {\n\tavailable := coin.Coins(escrow.Amount).Clone()\n\terr := m.moveCoins(db, Condition(escrowID).Address(), dest, amounts)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// remove coin from remaining balance\n\tfor _, c := range amounts {\n\t\tavailable, err = available.Subtract(*c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tescrow.Amount = available\n\t// if there is something left, just update the balance...\n\tif available.IsPositive() {\n\t\treturn m.bucket.Save(db, orm.NewSimpleObj(escrowID, escrow))\n\t}\n\t// otherwise we finished the escrow and can delete it\n\treturn m.bucket.Delete(db, escrowID)\n}", "func (_Vault *VaultTransactor) RequestWithdraw(opts *bind.TransactOpts, incognitoAddress string, token common.Address, amount *big.Int, signData []byte, timestamp []byte) (*types.Transaction, error) {\n\treturn _Vault.contract.Transact(opts, \"requestWithdraw\", incognitoAddress, token, amount, signData, timestamp)\n}", "func Withdraw(accID string, amount int64) error {\n\tif amount <= 0 {\n\t\treturn fmt.Errorf(\"invalid amount; %d\", amount)\n\t}\n\n\tvar accs []*share.Account\n\terr := client.GetByNames(ctx, share.KindAccount, []string{accID, \"Cash\"}, &accs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"get accounts error; %v\", err)\n\t}\n\n\tif accs[0].Balance < amount {\n\t\treturn fmt.Errorf(\"balance of account %s is %d, not enough for withdraw %d\", accID, accs[0].Balance, amount)\n\t}\n\n\taccs[0].Balance -= amount\n\taccs[1].Balance += amount\n\ttrans := []*share.Transaction{\n\t\t{Type: share.TransactionTypeWithdraw, AccountID: accID, Amount: -amount},\n\t\t{Type: share.TransactionTypeDeposit, AccountID: \"Cash\", Amount: amount},\n\t}\n\tfor _, tran := range trans {\n\t\ttran.NewKey(share.KindTransaction)\n\t}\n\terr = client.SaveModels(ctx, \"\", []interface{}{accs[0], accs[1], trans[0], trans[1]})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"save models error; %v\", err)\n\t}\n\treturn nil\n}", "func (_DelegateProfile *DelegateProfileSession) Withdraw() (*types.Transaction, error) {\n\treturn _DelegateProfile.Contract.Withdraw(&_DelegateProfile.TransactOpts)\n}", "func (s *StorageECR721Fixed) Withdraw() error {\n\tevmTr, err := s.session.Withdraw()\n\tif err != nil {\n\t\terr = errors.Wrapf(err, \"failed to execute %s\", Withdraw)\n\t\tLogger.Error(err)\n\t\treturn err\n\t}\n\n\tLogger.Info(\"Executed \", Withdraw, \" hash: \", evmTr.Hash())\n\n\treturn nil\n}", "func (_XStaking *XStakingSession) Withdraw(amount *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.Contract.Withdraw(&_XStaking.TransactOpts, amount)\n}", "func (_XStaking *XStakingTransactorSession) Withdraw(amount *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.Contract.Withdraw(&_XStaking.TransactOpts, amount)\n}", "func (_Cakevault *CakevaultTransactorSession) Withdraw(_shares *big.Int) (*types.Transaction, error) {\n\treturn _Cakevault.Contract.Withdraw(&_Cakevault.TransactOpts, _shares)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactor) Withdraw(opts *bind.TransactOpts, _member common.Address) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.contract.Transact(opts, \"withdraw\", _member)\n}", "func (u Usecase) Withdraw(ctx context.Context, accID vos.AccountID, amount vos.Money) error {\n\tconst operation = \"accounts.Usecase.Withdraw\"\n\n\tlog := logger.FromCtx(ctx).WithFields(logrus.Fields{\n\t\t\"accID\": accID,\n\t\t\"amount\": amount.Int(),\n\t})\n\n\tlog.Infoln(\"processing a withdrawal\")\n\n\tif amount <= 0 {\n\t\treturn ErrInvalidAmount\n\t}\n\n\tacc, err := u.GetAccountByID(ctx, accID)\n\tif err != nil {\n\t\treturn domain.Error(operation, err)\n\t}\n\n\tif acc.Balance < amount {\n\t\treturn ErrInsufficientBalance\n\t}\n\n\terr = u.accRepo.Withdraw(ctx, accID, amount)\n\n\tif err != nil {\n\t\treturn domain.Error(operation, err)\n\t}\n\n\tlog.Infoln(\"withdrawal successfully processed\")\n\n\treturn nil\n}", "func (_Cakevault *CakevaultSession) Withdraw(_shares *big.Int) (*types.Transaction, error) {\n\treturn _Cakevault.Contract.Withdraw(&_Cakevault.TransactOpts, _shares)\n}", "func (_IStakingRewards *IStakingRewardsTransactor) Withdraw(opts *bind.TransactOpts, amount *big.Int) (*types.Transaction, error) {\n\treturn _IStakingRewards.contract.Transact(opts, \"withdraw\", amount)\n}", "func (k Keeper) Withdraw(ctx sdk.Context, depositor sdk.AccAddress, amount sdk.Coin) error {\n\tdeposit, found := k.GetDeposit(ctx, depositor, amount.Denom)\n\tif !found {\n\t\treturn sdkerrors.Wrapf(types.ErrDepositNotFound, \"no %s deposit found for %s\", amount.Denom, depositor)\n\t}\n\tif !deposit.Amount.IsGTE(amount) {\n\t\treturn sdkerrors.Wrapf(types.ErrInvalidWithdrawAmount, \"%s>%s\", amount, deposit.Amount)\n\t}\n\n\terr := k.supplyKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleAccountName, depositor, sdk.NewCoins(amount))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeHarvestWithdrawal,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyDepositor, depositor.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyDepositDenom, amount.Denom),\n\t\t),\n\t)\n\n\tif deposit.Amount.IsEqual(amount) {\n\t\tctx.EventManager().EmitEvent(\n\t\t\tsdk.NewEvent(\n\t\t\t\ttypes.EventTypeDeleteHarvestDeposit,\n\t\t\t\tsdk.NewAttribute(types.AttributeKeyDepositor, depositor.String()),\n\t\t\t\tsdk.NewAttribute(types.AttributeKeyDepositDenom, amount.Denom),\n\t\t\t),\n\t\t)\n\t\tk.DeleteDeposit(ctx, deposit)\n\t\treturn nil\n\t}\n\n\tdeposit.Amount = deposit.Amount.Sub(amount)\n\tk.SetDeposit(ctx, deposit)\n\n\treturn nil\n}", "func (_DogsOfRome *DogsOfRomeTransactorSession) Withdraw() (*types.Transaction, error) {\n\treturn _DogsOfRome.Contract.Withdraw(&_DogsOfRome.TransactOpts)\n}", "func (_PBridge *PBridgeTransactor) ExecuteWithdrawTxERC721(opts *bind.TransactOpts, txKey string, ERC721 common.Address, to common.Address, tokenId *big.Int, tokenURI string, signatures []byte) (*types.Transaction, error) {\n\treturn _PBridge.contract.Transact(opts, \"executeWithdrawTxERC721\", txKey, ERC721, to, tokenId, tokenURI, signatures)\n}", "func (k Keeper) Withdraw(ctx sdk.Context, msg types.MsgWithdraw) error {\n\tstore := ctx.KVStore(k.storeKey)\n\tamount, err := sdk.ParseCoins(msg.Amount)\n\tif err != nil {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, err.Error())\n\t}\n\town, err := k.get(store, msg.ResourceHash)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif own == nil {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, \"resource %q does not have any ownership\", msg.ResourceHash)\n\t}\n\tif own.Owner != msg.Owner.String() {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, \"resource %q is not owned by you\", msg.ResourceHash)\n\t}\n\treturn k.bankKeeper.SendCoins(ctx, own.ResourceAddress, msg.Owner, amount)\n}", "func (c *Client) Withdraw(ctx context.Context, p *WithdrawRequestBody) (err error) {\n\t_, err = c.WithdrawEndpoint(ctx, p)\n\treturn\n}", "func (_DogsOfRome *DogsOfRomeSession) Withdraw() (*types.Transaction, error) {\n\treturn _DogsOfRome.Contract.Withdraw(&_DogsOfRome.TransactOpts)\n}", "func Withdraw(interactor account.Interactor) fiber.Handler {\n\n\treturn func(ctx *fiber.Ctx) error {\n\t\tvar userDetails = ctx.Locals(\"userDetails\").(map[string]string)\n\t\tuserId := userDetails[\"userId\"]\n\n\t\tvar p param\n\t\t_ = ctx.BodyParser(&p)\n\n\t\tbalance, err := interactor.Withdraw(uuid.FromStringOrNil(userId), p.Amount)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn ctx.JSON(map[string]interface{}{\n\t\t\t\"message\": fmt.Sprintf(\"Amount successfully withdrawn. New balance %v\", balance),\n\t\t\t\"balance\": balance,\n\t\t\t\"userId\": userId,\n\t\t})\n\t}\n}", "func (_BREMICO *BREMICOTransactor) ConfirmWithdraw(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BREMICO.contract.Transact(opts, \"confirmWithdraw\")\n}", "func (_Vault *VaultTransactorSession) RequestWithdraw(incognitoAddress string, token common.Address, amount *big.Int, signData []byte, timestamp []byte) (*types.Transaction, error) {\n\treturn _Vault.Contract.RequestWithdraw(&_Vault.TransactOpts, incognitoAddress, token, amount, signData, timestamp)\n}", "func (_Vault *VaultSession) RequestWithdraw(incognitoAddress string, token common.Address, amount *big.Int, signData []byte, timestamp []byte) (*types.Transaction, error) {\n\treturn _Vault.Contract.RequestWithdraw(&_Vault.TransactOpts, incognitoAddress, token, amount, signData, timestamp)\n}", "func (s *FundServer) Withdraw(amount int) {\n\ts.Transact(func(f *Fund) {\n\t\tf.Withdraw(amount)\n\t})\n}", "func (_Lmc *LmcTransactorSession) Withdraw(_tokenAmount *big.Int) (*types.Transaction, error) {\n\treturn _Lmc.Contract.Withdraw(&_Lmc.TransactOpts, _tokenAmount)\n}", "func AliceWithdrawFromTxAPIHandler(w http.ResponseWriter, r *http.Request) {\n\tLog := Logger.NewSessionLogger()\n\n\tvar plog PodLog\n\tplog.Result = LOG_RESULT_FAILED\n\tplog.Operation = LOG_OPERATION_TYPE_ALICE_WITHDRAW_FROM_TX\n\n\tdefer func() {\n\t\terr := insertLogToDB(plog)\n\t\tif err != nil {\n\t\t\tLog.Warnf(\"insert log error! %v\", err)\n\t\t\treturn\n\t\t}\n\t\tnodeRecovery(w, Log)\n\t}()\n\n\tsessionID := r.FormValue(\"session_id\")\n\tLog.Infof(\"start withdraw eth from transaction in contract...sessionID=%v\", sessionID)\n\tplog.Detail = fmt.Sprintf(\"sessionID=%v\", sessionID)\n\n\tif sessionID == \"\" {\n\t\tLog.Warnf(\"invalid sessionID. sessionID=%v\", sessionID)\n\t\tfmt.Fprintf(w, RESPONSE_INCOMPLETE_PARAM)\n\t\treturn\n\t}\n\ttx, rs, err := loadAliceFromDB(sessionID)\n\tif err != nil {\n\t\tLog.Warnf(\"failed to load transaction info from db. sessionID=%v, err=%v\", sessionID, err)\n\t\tfmt.Fprintf(w, RESPONSE_READ_DATABASE_FAILED)\n\t\treturn\n\t}\n\tif !rs {\n\t\tLog.Warnf(\"no transaction info loaded. sessionID=%v,\", sessionID)\n\t\tfmt.Fprintf(w, RESPONSE_NO_NEED_TO_WITHDRAW)\n\t\treturn\n\t}\n\tif tx.SubMode != TRANSACTION_SUB_MODE_COMPLAINT {\n\t\tLog.Warnf(\"the mode does not need withdraw eth.\")\n\t\tfmt.Fprintf(w, RESPONSE_NO_NEED_TO_WITHDRAW)\n\t\treturn\n\t}\n\tLog.Debugf(\"start send transaction to withdraw eth...sessionID=%v\", sessionID)\n\tt := time.Now()\n\ttxid, err := settleDealForComplaint(sessionID, tx.AliceAddr, tx.BobAddr)\n\tif err != nil {\n\t\tLog.Warnf(\"failed to withdraw eth for Alice from contract. err=%v\", err)\n\t\tfmt.Fprintf(w, RESPONSE_READ_CONTRACT_FAILED)\n\t\treturn\n\t}\n\tLog.Debugf(\"success to send transaction to withdraw eth...txid=%v, sessionID=%v, time cost=%v\", txid, sessionID, time.Since(t))\n\n\tplog.Result = LOG_RESULT_SUCCESS\n\tfmt.Fprintf(w, fmt.Sprintf(RESPONSE_SUCCESS, \"send transaction for withdrawing from contract...\"))\n\treturn\n}", "func (_PBridge *PBridgeTransactorSession) ExecuteWithdrawTxERC721(txKey string, ERC721 common.Address, to common.Address, tokenId *big.Int, tokenURI string, signatures []byte) (*types.Transaction, error) {\n\treturn _PBridge.Contract.ExecuteWithdrawTxERC721(&_PBridge.TransactOpts, txKey, ERC721, to, tokenId, tokenURI, signatures)\n}", "func (p *SharePool) Withdraw(tokenDst, shareSrc, shareAmount *quantity.Quantity) error {\n\ttokens, err := p.tokensForShares(shareAmount)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = shareSrc.Sub(shareAmount); err != nil {\n\t\treturn err\n\t}\n\n\tif err = p.TotalShares.Sub(shareAmount); err != nil {\n\t\treturn err\n\t}\n\n\tif err = quantity.Move(tokenDst, &p.Balance, tokens); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (_Lmc *LmcSession) Withdraw(_tokenAmount *big.Int) (*types.Transaction, error) {\n\treturn _Lmc.Contract.Withdraw(&_Lmc.TransactOpts, _tokenAmount)\n}", "func (_PBridge *PBridgeSession) ExecuteWithdrawTxERC721(txKey string, ERC721 common.Address, to common.Address, tokenId *big.Int, tokenURI string, signatures []byte) (*types.Transaction, error) {\n\treturn _PBridge.Contract.ExecuteWithdrawTxERC721(&_PBridge.TransactOpts, txKey, ERC721, to, tokenId, tokenURI, signatures)\n}", "func (_IStakingRewards *IStakingRewardsSession) Withdraw(amount *big.Int) (*types.Transaction, error) {\n\treturn _IStakingRewards.Contract.Withdraw(&_IStakingRewards.TransactOpts, amount)\n}", "func (_IStakingRewards *IStakingRewardsTransactorSession) Withdraw(amount *big.Int) (*types.Transaction, error) {\n\treturn _IStakingRewards.Contract.Withdraw(&_IStakingRewards.TransactOpts, amount)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactorSession) Withdraw(_member common.Address) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.Withdraw(&_BondedECDSAKeep.TransactOpts, _member)\n}", "func (_SmartTgStats *SmartTgStatsTransactor) CEOWithdraw(opts *bind.TransactOpts, _to common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _SmartTgStats.contract.Transact(opts, \"CEOWithdraw\", _to, _amount)\n}", "func (c *Client) AccountWithdraw(currency string, quantity *big.Float, address string, paymentID string) (TransactionID, error) {\r\n\tdefer c.clearError()\r\n\r\n\tparams := map[string]string{\r\n\t\t\"apikey\": c.apiKey,\r\n\t\t\"currency\": currency,\r\n\t\t\"quantity\": quantity.String(),\r\n\t\t\"address\": address,\r\n\t}\r\n\r\n\tif paymentID != \"\" {\r\n\t\tparams[\"paymentid\"] = paymentID\r\n\t}\r\n\r\n\tvar parsedResponse *baseResponse\r\n\r\n\tparsedResponse = c.sendRequest(\"account/withdraw\", params)\r\n\r\n\tif c.err != nil {\r\n\t\treturn TransactionID{}, c.err\r\n\t}\r\n\r\n\tif parsedResponse.Success != true {\r\n\t\tc.setError(\"api error - account/withdraw\", parsedResponse.Message)\r\n\t\treturn TransactionID{}, c.err\r\n\t}\r\n\r\n\tvar response TransactionID\r\n\tdefaultVal := TransactionID{}\r\n\r\n\tif err := json.Unmarshal(parsedResponse.Result, &response); err != nil {\r\n\t\tc.setError(\"api error - account/withdraw\", err.Error())\r\n\t\treturn defaultVal, c.err\r\n\t}\r\n\r\n\tif response == defaultVal {\r\n\t\tc.setError(\"validate response\", \"nil vals in withdraw response\")\r\n\t}\r\n\r\n\treturn response, nil\r\n}", "func (_WandappETH *WandappETHTransactor) OperatorWithdraw(opts *bind.TransactOpts, proof []byte) (*types.Transaction, error) {\n\treturn _WandappETH.contract.Transact(opts, \"operatorWithdraw\", proof)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) Withdraw(_member common.Address) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.Withdraw(&_BondedECDSAKeep.TransactOpts, _member)\n}", "func (_Cakevault *CakevaultTransactor) EmergencyWithdraw(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Cakevault.contract.Transact(opts, \"emergencyWithdraw\")\n}", "func (a *Account) Withdraw (amount int) error {\n\tif a.balance < amount {\n\t\treturn errNomoney\n\t}\n\ta.balance -= amount\n\treturn nil\n}", "func (s *Service) WithdrawSuccess(c context.Context, orderNo int64, tradeStatus int) (err error) {\n\tupWithdraw, err := s.dao.QueryUpWithdrawByID(c, orderNo)\n\tif err != nil {\n\t\tlog.Error(\"s.dao.QueryUpWithdrawByID error(%v)\", err)\n\t\treturn\n\t}\n\n\tif tradeStatus != _withdrawSuccess {\n\t\tlog.Info(\"param tradeStatus(%d) != withdraw success(2)\", tradeStatus)\n\t\treturn\n\t}\n\n\tif upWithdraw.State == _withdrawSuccess {\n\t\tlog.Info(\"withdraw has successed already\")\n\t\treturn\n\t}\n\n\ttx, err := s.dao.BeginTran(c)\n\tif err != nil {\n\t\tlog.Error(\"s.dao.BeginTran error(%v)\", err)\n\t\treturn\n\t}\n\n\t// update up_income_withdraw state\n\trows, err := s.dao.TxUpdateUpWithdrawState(tx, orderNo, _withdrawSuccess)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\tlog.Error(\"s.dao.UpdateUpWithdrawState error(%v)\", err)\n\t\treturn\n\t}\n\tif rows != 1 {\n\t\ttx.Rollback()\n\t\tlog.Error(\"s.dao.UpdateUpWithdrawState Update withdraw record error id(%d)\", orderNo)\n\t\treturn\n\t}\n\n\t// update up_account withdraw\n\trows, err = s.dao.TxUpdateUpAccountWithdraw(tx, upWithdraw.MID, upWithdraw.WithdrawIncome)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\tlog.Error(\"s.dao.UpdateUpAccountWithdraw error(%v)\", err)\n\t\treturn\n\t}\n\tif rows != 1 {\n\t\ttx.Rollback()\n\t\tlog.Error(\"s.dao.UpdateUpAccountWithdraw Update up account record error id(%d)\", orderNo)\n\t\treturn\n\t}\n\n\tmaxUpWithdrawDateVersion, err := s.dao.TxQueryMaxUpWithdrawDateVersion(tx, upWithdraw.MID)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\tlog.Error(\"s.dao.QueryMaxUpWithdrawDateVersion error(%v)\", err)\n\t\treturn\n\t}\n\n\ttime := 0\n\tvar version int64\n\tfor {\n\t\tversion, err = s.dao.TxQueryUpAccountVersion(tx, upWithdraw.MID)\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t\tlog.Error(\"s.dao.QueryUpAccountVersion error(%v)\", err)\n\t\t\treturn\n\t\t}\n\t\tif maxUpWithdrawDateVersion == \"\" {\n\t\t\tmaxUpWithdrawDateVersion = upWithdraw.DateVersion\n\t\t}\n\n\t\trows, err = s.dao.TxUpdateUpAccountUnwithdrawIncome(tx, upWithdraw.MID, maxUpWithdrawDateVersion, version)\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t\tlog.Error(\"s.dao.UpdateUpAccountUnwithdrawIncome error(%v)\", err)\n\t\t\treturn\n\t\t}\n\t\tif rows == 1 {\n\t\t\tif err = tx.Commit(); err != nil {\n\t\t\t\tlog.Error(\"tx.Commit error\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\ttime++\n\t\tif time >= 10 {\n\t\t\ttx.Rollback()\n\t\t\tlog.Info(\"try to synchronize unwithdraw income 10 times error mid(%d)\", upWithdraw.MID)\n\t\t\terr = fmt.Errorf(\"try to synchronize unwithdraw income 10 times error mid(%d)\", upWithdraw.MID)\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func (dcr *ExchangeWallet) withdraw(addr stdaddr.Address, val, feeRate uint64) (*wire.MsgTx, uint64, error) {\n\tif val == 0 {\n\t\treturn nil, 0, fmt.Errorf(\"cannot withdraw value = 0\")\n\t}\n\tenough := func(sum uint64, size uint32, unspent *compositeUTXO) bool {\n\t\treturn sum+toAtoms(unspent.rpc.Amount) >= val\n\t}\n\tcoins, _, _, _, err := dcr.fund(enough)\n\tif err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"unable to withdraw %s DCR to address %s with feeRate %d atoms/byte: %w\",\n\t\t\tamount(val), addr, feeRate, err)\n\t}\n\n\tmsgTx, sentVal, err := dcr.sendCoins(addr, coins, val, feeRate, true)\n\tif err != nil {\n\t\tif _, retErr := dcr.returnCoins(coins); retErr != nil {\n\t\t\tdcr.log.Errorf(\"Failed to unlock coins: %v\", retErr)\n\t\t}\n\t\treturn nil, 0, err\n\t}\n\treturn msgTx, sentVal, nil\n}", "func (user User) Withdraw(ctx context.Context, input *TransferInput, pin string) (*Snapshot, error) {\n\tif len(input.TraceID) == 0 {\n\t\tinput.TraceID = uuid.Must(uuid.NewV4()).String()\n\t}\n\tparas := utils.UnselectFields(input)\n\tdata, err := user.RequestWithPIN(ctx, \"POST\", \"/withdrawals\", paras, pin)\n\tif err != nil {\n\t\treturn nil, requestError(err)\n\t}\n\n\tvar resp struct {\n\t\tSnapshot *struct {\n\t\t\t*Snapshot\n\t\t\tMemo string `json:\"memo,omitempty\"`\n\t\t} `json:\"data,omitempty\"`\n\t\tError *Error `json:\"error,omitempty\"`\n\t}\n\tif err = json.Unmarshal(data, &resp); err != nil {\n\t\treturn nil, requestError(err)\n\t} else if resp.Error != nil {\n\t\treturn nil, resp.Error\n\t}\n\n\tresp.Snapshot.Data = resp.Snapshot.Memo\n\tif !input.verify(*resp.Snapshot.Snapshot) {\n\t\treturn nil, traceError()\n\t}\n\n\treturn resp.Snapshot.Snapshot, nil\n}", "func (h *HUOBI) Withdraw(ctx context.Context, c currency.Code, address, addrTag, chain string, amount, fee float64) (int64, error) {\n\tif c.IsEmpty() || address == \"\" || amount <= 0 {\n\t\treturn 0, errors.New(\"currency, address and amount must be set\")\n\t}\n\n\tresp := struct {\n\t\tWithdrawID int64 `json:\"data\"`\n\t}{}\n\n\tdata := struct {\n\t\tAddress string `json:\"address\"`\n\t\tAmount string `json:\"amount\"`\n\t\tCurrency string `json:\"currency\"`\n\t\tFee string `json:\"fee,omitempty\"`\n\t\tChain string `json:\"chain,omitempty\"`\n\t\tAddrTag string `json:\"addr-tag,omitempty\"`\n\t}{\n\t\tAddress: address,\n\t\tCurrency: c.Lower().String(),\n\t\tAmount: strconv.FormatFloat(amount, 'f', -1, 64),\n\t}\n\n\tif fee > 0 {\n\t\tdata.Fee = strconv.FormatFloat(fee, 'f', -1, 64)\n\t}\n\n\tif addrTag != \"\" {\n\t\tdata.AddrTag = addrTag\n\t}\n\n\tif chain != \"\" {\n\t\tdata.Chain = strings.ToLower(chain)\n\t}\n\n\terr := h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, huobiWithdrawCreate, nil, data, &resp, false)\n\treturn resp.WithdrawID, err\n}", "func (_BREMICO *BREMICOSession) ConfirmWithdraw() (*types.Transaction, error) {\n\treturn _BREMICO.Contract.ConfirmWithdraw(&_BREMICO.TransactOpts)\n}", "func (p *TDepositWithdrawServiceClient) AuditDepositWithdraw(ctx context.Context, traceId string, status string, mark string, withdrawId int32) (r bool, err error) {\n var _args5 TDepositWithdrawServiceAuditDepositWithdrawArgs\n _args5.TraceId = traceId\n _args5.Status = status\n _args5.Mark = mark\n _args5.WithdrawId = withdrawId\n var _result6 TDepositWithdrawServiceAuditDepositWithdrawResult\n if err = p.c.Call(ctx, \"auditDepositWithdraw\", &_args5, &_result6); err != nil {\n return\n }\n return _result6.GetSuccess(), nil\n}", "func (m *WithdrawManager) SubmitWithdrawal(ctx context.Context, req *withdraw.Request) (*withdraw.Response, error) {\n\tif m == nil {\n\t\treturn nil, ErrNilSubsystem\n\t}\n\tif req == nil {\n\t\treturn nil, withdraw.ErrRequestCannotBeNil\n\t}\n\n\texch, err := m.exchangeManager.GetExchangeByName(req.Exchange)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &withdraw.Response{\n\t\tExchange: withdraw.ExchangeResponse{\n\t\t\tName: req.Exchange,\n\t\t},\n\t\tRequestDetails: *req,\n\t}\n\n\t// Determines if the currency can be withdrawn from the exchange\n\terrF := exch.CanWithdraw(req.Currency, asset.Spot)\n\tif errF != nil && !errors.Is(errF, currencystate.ErrCurrencyStateNotFound) { // Suppress not found error\n\t\treturn nil, errF\n\t}\n\n\tif m.isDryRun {\n\t\tlog.Warnln(log.Global, \"Dry run enabled, no withdrawal request will be submitted or have an event created\")\n\t\tresp.ID = withdraw.DryRunID\n\t\tresp.Exchange.Status = \"dryrun\"\n\t\tresp.Exchange.ID = withdraw.DryRunID.String()\n\t} else {\n\t\tvar ret *withdraw.ExchangeResponse\n\t\tif req.Type == withdraw.Crypto {\n\t\t\tif !m.portfolioManager.IsWhiteListed(req.Crypto.Address) {\n\t\t\t\treturn nil, withdraw.ErrStrAddressNotWhiteListed\n\t\t\t}\n\t\t\tif !m.portfolioManager.IsExchangeSupported(req.Exchange, req.Crypto.Address) {\n\t\t\t\treturn nil, withdraw.ErrStrExchangeNotSupportedByAddress\n\t\t\t}\n\t\t}\n\t\tif req.Type == withdraw.Fiat {\n\t\t\tret, err = exch.WithdrawFiatFunds(ctx, req)\n\t\t\tif err != nil {\n\t\t\t\tresp.Exchange.Status = err.Error()\n\t\t\t} else {\n\t\t\t\tresp.Exchange.Status = ret.Status\n\t\t\t\tresp.Exchange.ID = ret.ID\n\t\t\t}\n\t\t} else if req.Type == withdraw.Crypto {\n\t\t\tret, err = exch.WithdrawCryptocurrencyFunds(ctx, req)\n\t\t\tif err != nil {\n\t\t\t\tresp.Exchange.Status = err.Error()\n\t\t\t} else {\n\t\t\t\tresp.Exchange.Status = ret.Status\n\t\t\t\tresp.Exchange.ID = ret.ID\n\t\t\t}\n\t\t}\n\t}\n\tdbwithdraw.Event(resp)\n\tif err == nil {\n\t\twithdraw.Cache.Add(resp.ID, resp)\n\t}\n\treturn resp, err\n}", "func (a *Account) Withdraw(amount int) error {\n\tif a.balance < amount {\n\t\treturn errorWithdraw\n\t}\n\ta.balance -= amount\n\treturn nil\n}", "func (_BREMICO *BREMICOTransactorSession) ConfirmWithdraw() (*types.Transaction, error) {\n\treturn _BREMICO.Contract.ConfirmWithdraw(&_BREMICO.TransactOpts)\n}", "func (_ArbSys *ArbSysTransactor) WithdrawEth(opts *bind.TransactOpts, dest common.Address) (*types.Transaction, error) {\n\treturn _ArbSys.contract.Transact(opts, \"withdrawEth\", dest)\n}", "func (w *Wallet) Withdraw(amount Bitcoin) error {\n\n\tif amount > w.balance {\n\t\treturn errors.New(\"cannot withdraw, insufficient funds\")\n\t}\n\tw.balance -= amount\n\treturn nil\n}", "func WithdrawRequest(uid int, amount float64, address string) bool {\n\tdb, err := sql.Open(\"sqlite3\", db_front)\n\tif !check_err(err) {\n\t\tLog(Log_Struct{\"error\", \"DB_Error_Line_551\", err})\n\t\treturn false\n\t}\n\tdefer db.Close()\n\n\tvar query string\n\ttx, err := db.Begin()\n\tif !check_err(err) {\n\t\tLog(Log_Struct{\"error\", \"DB_Error_Line_559\", err})\n\t\treturn false\n\t}\n\n\t// Insert into withdraw record\n\tquery = \"INSERT INTO withdraw(uid,amount,address,time) values(?,?,?,?)\"\n\tstmt, err := tx.Prepare(query)\n\tif !check_err(err) {\n\t\tLog(Log_Struct{\"error\", \"DB_Error_Line_567\", err})\n\t\treturn false\n\t}\n\tdefer stmt.Close()\n\t_, err = stmt.Exec(uid, amount, address, time.Now().Format(layout))\n\tif !check_err(err) {\n\t\tLog(Log_Struct{\"error\", \"DB_Error_Line_573\", err})\n\t\treturn false\n\t}\n\n\t// Update user info\n\tquery = fmt.Sprintf(\"UPDATE user SET balance = balance - %f WHERE id = %d\", amount, uid)\n\tstmt, err = tx.Prepare(query)\n\t_, err = stmt.Exec()\n\tif !check_err(err) {\n\t\tLog(Log_Struct{\"error\", \"DB_Error_Line_582\", err})\n\t\treturn false\n\t}\n\n\t// Commit\n\terr = tx.Commit()\n\tif !check_err(err) {\n\t\tLog(Log_Struct{\"error\", \"DB_Error_Line_589\", err})\n\t\ttx.Rollback()\n\t\treturn false\n\t}\n\n\treturn true\n\n}", "func (theAccount *Account) Withdraw(amount int) error {\n\tif theAccount.balance < amount {\n\t\treturn errNoMoney\n\t}\n\ttheAccount.balance -= amount\n\treturn nil\n}" ]
[ "0.7312641", "0.72754675", "0.71570385", "0.7136819", "0.7123336", "0.7105116", "0.71018606", "0.7083507", "0.7048111", "0.7032736", "0.70042676", "0.6964425", "0.6914816", "0.68968433", "0.68824387", "0.68595165", "0.68546516", "0.6827496", "0.6759343", "0.67280483", "0.6726812", "0.6719896", "0.6715899", "0.67155457", "0.6714606", "0.67009526", "0.6696139", "0.6670246", "0.66630304", "0.66351026", "0.65773046", "0.65762305", "0.6569026", "0.65191835", "0.6501336", "0.6500442", "0.64943606", "0.6491701", "0.6490281", "0.64866626", "0.64734334", "0.6449335", "0.6449103", "0.6409024", "0.63947797", "0.639259", "0.6379553", "0.6369034", "0.6363264", "0.63527024", "0.63516366", "0.6320013", "0.63139635", "0.631335", "0.6302838", "0.6290598", "0.62849194", "0.62844676", "0.6223032", "0.61979944", "0.6191482", "0.61277884", "0.61042005", "0.6098768", "0.60984945", "0.60973495", "0.6095589", "0.60898715", "0.6070253", "0.6031744", "0.6018714", "0.6004885", "0.59323424", "0.59270376", "0.5908921", "0.59044707", "0.5892009", "0.5890466", "0.5885574", "0.5845904", "0.5844928", "0.5839054", "0.58312273", "0.5825082", "0.5818895", "0.57995415", "0.57940596", "0.5782175", "0.5780172", "0.57781225", "0.57725203", "0.57645535", "0.5752569", "0.57493716", "0.5747663", "0.57395387", "0.5731661", "0.57284456", "0.57164454", "0.5698924" ]
0.80167997
0
Evaluate returns the input traits unmodified.
func (NullEvaluator) Evaluate(ctx context.Context, input *EvaluationInput) (*EvaluationOutput, error) { return &EvaluationOutput{ Traits: input.Traits, }, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *Strategy) Evaluate(pods []v1.Pod) []v1.Pod {\n\tlog.Printf(\"Evaluate called with %d pods\", len(pods))\n\tpods = s.eval(pods)\n\tlog.Printf(\"Evaluate exiting with %d pods\", len(pods))\n\treturn pods\n}", "func Evaluate(item interface{}, passedContext interface{}) map[string]float64 {\n\t//fmt.Fprintf(os.Stderr, \"eval:: %v %T\\n\", item, item)\n\n\tif item != nil {\n\t\tswitch passedContext.(type) {\n\t\tcase *DimContext:\n\t\t\t{\n\t\t\t\t//fmt.Fprintf(os.Stderr, \"here before processMember %v\\n\", item)\n\t\t\t\tprocessMember(item, passedContext)\n\t\t\t\t//fmt.Fprintf(os.Stderr, \"here after processMember %v %T\\n\", item, item)\n\t\t\t}\n\t\t}\n\t\tswitch v := item.(type) {\n\t\tcase hasResults:\n\t\t\t{\n\t\t\t\treturn v.Results()\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func Evaluate(thing interface{}, env Environment) (error, Value, Environment) {\n\tswitch thing.(type) {\n\tcase Value:\n\t\treturn EvaluateValue(thing.(Value), env)\n\tcase SExpression:\n\t\tsexp := thing.(SExpression)\n\t\tif isSpecialForm(sexp.FormName.Contained) {\n\t\t\treturn EvaluateSpecialForm(sexp, env)\n\t\t} else {\n\t\t\treturn EvaluateSexp(thing.(SExpression), env)\n\t\t}\n\tdefault:\n\t\treturn errors.New(fmt.Sprintf(\"No way to evaluate %v\\n\", thing)), Value{}, env\n\t}\n}", "func (t *TypeSystem) Evaluate(typename string, object interface{}, op string, value string) (bool, error) {\n\tswitch typename {\n\tcase String:\n\t\treturn t.stringts.Evaluate(object, op, value)\n\tcase Number:\n\t\treturn t.numberts.Evaluate(object, op, value)\n\tcase Boolean:\n\t\treturn t.boolts.Evaluate(object, op, value)\n\tcase Strings:\n\t\treturn t.stringsts.Evaluate(object, op, value)\n\tcase Date:\n\t\treturn t.datets.Evaluate(object, op, value)\n\tdefault:\n\t\treturn false, fmt.Errorf(\"type/golang/type.go: unsupport type, %s, %v, %s, %s\", typename, object, op, value)\n\t}\n}", "func (v Variable) Evaluate() Expression {\n\treturn v\n}", "func (f *functionQuery) Evaluate(t iterator) interface{} {\n\treturn f.Func(f.Input, t)\n}", "func (a *AlwaysReturn) Evaluate(r table.Row) (bool, error) {\n\treturn a.V, nil\n}", "func (session Runtime) Evaluate(code string, async bool, returnByValue bool) (interface{}, error) {\n\tresult, err := session.evaluate(code, session.currentContext(), async, returnByValue)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn result.Value, nil\n}", "func (this *Mod) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.BinaryEval(this, item, context)\n}", "func (this *ObjectValues) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.UnaryEval(this, item, context)\n}", "func (this *ObjectValues) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.UnaryEval(this, item, context)\n}", "func (this *Element) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.BinaryEval(this, item, context)\n}", "func (a Abstraction) Evaluate() Expression {\n\treturn Abstraction{a.Argument, a.Body.Evaluate()}\n}", "func Evaluate(c a.Context, s a.Sequence) a.Sequence {\n\treturn a.Map(c, compiler.Compile(c, s), evaluator)\n}", "func (c Chain) Evaluate(input Input) (string, string, bool) {\n\tfor _, policyFunc := range c {\n\t\treason, message, violationFound := policyFunc(input)\n\t\tif violationFound {\n\t\t\treturn reason, message, violationFound\n\t\t}\n\t}\n\treturn \"\", \"\", false\n}", "func (c Chain) Evaluate(input Input) (string, string, bool) {\n\tfor _, policyFunc := range c {\n\t\treason, message, violationFound := policyFunc(input)\n\t\tif violationFound {\n\t\t\treturn reason, message, violationFound\n\t\t}\n\t}\n\treturn \"\", \"\", false\n}", "func (m *Model) Evaluate(seq Sequence) {\n\tm.EvaluateAt(seq, 0)\n}", "func (_if If) Evaluate(environment map[string]expr.Expression) map[string]expr.Expression {\n\tswitch c := _if.Condition.Evaluate(environment); c {\n\tcase expr.Boolean{Value: true}:\n\t\treturn _if.Consequence.Evaluate(environment)\n\tcase expr.Boolean{Value: false}:\n\t\treturn _if.Alternative.Evaluate(environment)\n\tdefault:\n\t\treturn environment\n\t}\n}", "func (this *Self) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn item, nil\n}", "func (s *candidate) Evaluate() (float64, error) {\n\tr, err := s.Schedule()\n\treturn r.Evaluate(), err\n}", "func (state *KuhnGameState) Evaluate() float32 {\n\tcurrentActor := state.playerActor(state.CurrentActor().GetID())\n\tcurrentActorOpponent := state.playerActor(-state.CurrentActor().GetID())\n\tif state.causingAction.Name() == acting.Fold {\n\t\tcurrentActor.UpdateStack(currentActor.Stack + state.table.Pot)\n\t\treturn float32(currentActor.GetID()) * (state.table.Pot / 2)\n\t}\n\tcurrentActorHandValue := currentActor.EvaluateHand(state.table)\n\tcurrentActorOpponentHandValue := currentActorOpponent.EvaluateHand(state.table)\n\tif currentActorHandValue > currentActorOpponentHandValue {\n\t\tcurrentActor.UpdateStack(currentActor.Stack + state.table.Pot)\n\t\treturn float32(currentActor.GetID()) * (state.table.Pot / 2)\n\t} else {\n\t\tcurrentActorOpponent.UpdateStack(currentActorOpponent.Stack + state.table.Pot)\n\t\treturn float32(currentActorOpponent.GetID()) * (state.table.Pot / 2)\n\t}\n}", "func (this *ObjectUnwrap) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.UnaryEval(this, item, context)\n}", "func (this *ObjectInnerValues) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.UnaryEval(this, item, context)\n}", "func (e *Engine) Eval(ctx map[string]interface{}) ([]*model.DecisionValue, error) {\n\tinput := e.actPool.Get().(*activation)\n\tdefer e.actPool.Put(input)\n\tinput.vars = ctx\n\tvar decisions []*model.DecisionValue\n\tfor tmplName, insts := range e.instances {\n\t\trt, found := e.runtimes[tmplName]\n\t\tif !found {\n\t\t\t// Report an error\n\t\t\tcontinue\n\t\t}\n\t\tfor _, inst := range insts {\n\t\t\tif !e.selectInstance(inst, input) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdecs, err := rt.Eval(inst, input)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdecisions = append(decisions, decs...)\n\t\t}\n\t}\n\treturn decisions, nil\n}", "func (e *AccessorExpr) Evaluate(engine *Engine, input interface{}, args []*Statement) (interface{}, error) {\n\tin := reflect.ValueOf(input)\n\taccessor := e.Query[1:]\n\n\tif input == nil {\n\t\treturn nil, nil\n\t}\n\n\t// If it is a slice we need to Evaluate each one.\n\tif in.Kind() == reflect.Slice {\n\t\tt := TypeOfSliceElement(input)\n\t\tif t.Kind() == reflect.Ptr {\n\t\t\tt = t.Elem()\n\t\t}\n\t\treturnType := e.getReturnType(accessor, reflect.New(t).Interface())\n\n\t\tresults := reflect.MakeSlice(reflect.SliceOf(returnType), 0, 0)\n\n\t\tfor i := 0; i < in.Len(); i++ {\n\t\t\tresult, err := e.Evaluate(engine, in.Index(i).Interface(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tresults = reflect.Append(results, reflect.ValueOf(result))\n\t\t}\n\n\t\treturn results.Interface(), nil\n\t}\n\n\tvar err error\n\tinput, err = e.evaluateAccessor(accessor, input)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn input, nil\n}", "func (this *ObjectPut) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.TernaryEval(this, item, context)\n}", "func (ch *ClusterHost) Evaluate() (State, error) {\n\tstate := State{\n\t\tCurrent: \"unknown\",\n\t\tWant: ch.State,\n\t}\n\n\t_, err := ch.finder.HostSystem(ch.ctx, path.Join(ch.Path, ch.Name))\n\tif err != nil {\n\t\t// Host is absent\n\t\tif _, ok := err.(*find.NotFoundError); ok {\n\t\t\tstate.Current = \"absent\"\n\t\t\treturn state, nil\n\t\t}\n\n\t\t// Something else happened\n\t\treturn state, err\n\t}\n\n\tstate.Current = \"present\"\n\n\treturn state, nil\n}", "func Evaluate(tpl string, data interface{}) (string, error) {\n\tt, err := Parse(tpl)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn Execute(t, data)\n}", "func (p Print) Evaluate(vars map[string]interface{}, ctx interface{}, funcs FunctionMap, quotes []string) (map[string]interface{}, interface{}, error) {\n\tvars, v, err := p.Node.Evaluate(vars, ctx, funcs, quotes)\n\tif err != nil {\n\t\treturn vars, ctx, err\n\t}\n\tfmt.Println(TryFormatLiteral(v, quotes, false, 0))\n\treturn vars, ctx, nil\n}", "func (dn DoNothing) Evaluate(environment map[string]expr.Expression) map[string]expr.Expression {\n\treturn environment\n}", "func (b *BaseIntent) Evaluate(ctx context.Context, evaluateCtx *EvaluateContext) error {\n\treturn nil\n}", "func (in InHandler) Evaluate(key, value interface{}) bool {\n\tswitch typedKey := key.(type) {\n\tcase string:\n\t\treturn in.validateValueWithStringPattern(typedKey, value)\n\tcase int, int32, int64, float32, float64, bool:\n\t\treturn in.validateValueWithStringPattern(fmt.Sprint(typedKey), value)\n\tcase []interface{}:\n\t\tvar stringSlice []string\n\t\tfor _, v := range typedKey {\n\t\t\tstringSlice = append(stringSlice, v.(string))\n\t\t}\n\t\treturn in.validateValueWithStringSetPattern(stringSlice, value)\n\tdefault:\n\t\tin.log.V(2).Info(\"Unsupported type\", \"value\", typedKey, \"type\", fmt.Sprintf(\"%T\", typedKey))\n\t\treturn false\n\t}\n}", "func (r *RegexpOp) Evaluate(left, right EvalResult) (EvalResult, error) {\n\tpanic(\"implement me\")\n}", "func (r *Resolver) Evaluate(args struct{ Expr string }) (Result, error) {\n\tvar result Result\n\tamount, err := calc.CalculateAmount(args.Expr)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\tunitName := amount.Units\n\tunit, err := NewUnit(unitName)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\tresult = Result{amount.Value, unit, args.Expr}\n\tlog.Info(fmt.Sprintf(\"evaluate(%s) = %.2f %s\", args.Expr, result.value, result.units.pluralName))\n\treturn result, nil\n}", "func (e *Implementation) Evaluate(template string) (string, error) {\n\tp := tmpl.Parameters{\n\t\tTestNamespace: e.TestNamespace,\n\t\tDependencyNamespace: e.DependencyNamespace,\n\t}\n\n\treturn tmpl.Evaluate(template, p)\n}", "func (c *Context) Evaluate(language, code string, stdins []string) ([]string, Message) {\n\tstdinGlob := glob(stdins)\n\tresults, msg := c.run(language, code, stdinGlob)\n\n\treturn unglob(results), msg\n}", "func (o *OpenAI) Evaluate(stepsSinceReset int, obs gym.Obs, action interface{}) error {\n\tif err := o.Genomes[0].Evaluate(stepsSinceReset, obs, action); err != nil {\n\t\treturn err\n\t}\n\t// log.Printf(\"Evaluate: obs=%v, raw action=%v\", obs, action)\n\n\tswitch o.ActionSpace.Type {\n\t// case \"Discrete\":\n\tcase \"Tuple\":\n\t\tif vals, ok := action.(*[]int); ok {\n\t\t\tfor i, v := range *vals {\n\t\t\t\tif o.ActionSpace.Subspaces[i].Type == \"Discrete\" {\n\t\t\t\t\tif v < 0 {\n\t\t\t\t\t\tv = -v\n\t\t\t\t\t}\n\t\t\t\t\t(*vals)[i] = v % o.ActionSpace.Subspaces[i].N\n\t\t\t\t} else {\n\t\t\t\t\treturn fmt.Errorf(\"subspace %v not yet supported\", o.ActionSpace.Subspaces[i])\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"action type %T not yet supported\", action)\n\t\t}\n\t// case \"MultiBinary\":\n\t// case \"MultiDiscrete\":\n\t// case \"Box\":\n\tdefault:\n\t\treturn fmt.Errorf(\"ActionSpace type %v not yet implemented\", o.ActionSpace.Type)\n\t}\n\n\t// log.Printf(\"Evaluate: obs=%v, final action=%v\", obs, action)\n\n\treturn nil\n}", "func (l *LikeOp) Evaluate(left, right EvalResult) (EvalResult, error) {\n\tpanic(\"implement me\")\n}", "func (net *Network) Evaluate(inputValues []float64) float64 {\n\tinputLength := len(inputValues)\n\tfor i, n := range net.InputNodes {\n\t\tif i < inputLength {\n\t\t\tn.SetValue(inputValues[i])\n\t\t}\n\t}\n\tmaxIterationCounter := net.maxIterations\n\tif maxIterationCounter == 0 {\n\t\t// If max iterations has not been configured, use 100\n\t\tmaxIterationCounter = 100\n\t}\n\tresult, _ := net.OutputNode.evaluate(net.Weight, &maxIterationCounter)\n\treturn result\n}", "func (i *InOp) Evaluate(left, right EvalResult) (EvalResult, error) {\n\tpanic(\"implement me\")\n}", "func (f *CallExpression) Evaluate(ctx *Context) Value {\n\tcallable := f.Callable.Evaluate(ctx)\n\n\tif callable.Type == vtVariable {\n\t\tcallable = callable.Evaluate(ctx)\n\t}\n\n\tif callable.isCallable() {\n\t\tnewCtx := NewContext(\"\", nil)\n\t\targs := f.Args.EvaluateAll(ctx)\n\t\treturn callable.callable().Execute(newCtx, &args)\n\t}\n\n\tpanic(NewNotCallableError(callable))\n}", "func (a *AST) Evaluate(table ...map[string]ContextVar) *Expression {\n\tt := make(map[string]ContextVar)\n\tif len(table) > 0 && table[0] != nil {\n\t\tt = table[0]\n\t}\n\treturn a.Root.Evaluate(t)\n}", "func (p *prog) Eval(input any) (v ref.Val, det *EvalDetails, err error) {\n\t// Configure error recovery for unexpected panics during evaluation. Note, the use of named\n\t// return values makes it possible to modify the error response during the recovery\n\t// function.\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tswitch t := r.(type) {\n\t\t\tcase interpreter.EvalCancelledError:\n\t\t\t\terr = t\n\t\t\tdefault:\n\t\t\t\terr = fmt.Errorf(\"internal error: %v\", r)\n\t\t\t}\n\t\t}\n\t}()\n\t// Build a hierarchical activation if there are default vars set.\n\tvar vars interpreter.Activation\n\tswitch v := input.(type) {\n\tcase interpreter.Activation:\n\t\tvars = v\n\tcase map[string]any:\n\t\tvars = activationPool.Setup(v)\n\t\tdefer activationPool.Put(vars)\n\tdefault:\n\t\treturn nil, nil, fmt.Errorf(\"invalid input, wanted Activation or map[string]any, got: (%T)%v\", input, input)\n\t}\n\tif p.defaultVars != nil {\n\t\tvars = interpreter.NewHierarchicalActivation(p.defaultVars, vars)\n\t}\n\tv = p.interpretable.Eval(vars)\n\t// The output of an internal Eval may have a value (`v`) that is a types.Err. This step\n\t// translates the CEL value to a Go error response. This interface does not quite match the\n\t// RPC signature which allows for multiple errors to be returned, but should be sufficient.\n\tif types.IsError(v) {\n\t\terr = v.(*types.Err)\n\t}\n\treturn\n}", "func (s *Subtraction) Evaluate(left, right EvalResult) (EvalResult, error) {\n\treturn subtractNumericWithError(left, right)\n}", "func Evaluate(decision *Decision, maximiser bool) {\n\ts := whichStrategy(maximiser)\n\tdecision.Score = s.initial\n\tfor _, r := range decision.Responses {\n\t\tif r.Responses != nil {\n\t\t\t//\n\t\t\t// Evaluate the response from the opposite perspective.\n\t\t\t//\n\t\t\tEvaluate(r, !maximiser)\n\t\t}\n\t\tif s.compare(r.Score, decision.Score) {\n\t\t\tdecision.Score = r.Score\n\t\t}\n\t}\n}", "func Evaluate(expression *[]string, dispatchTable DispatchTable, stack *Stack) interface{} {\n\n\tfor idx, token := range *expression {\n\t\tvar dispatchFunction DispatchFunc\n\n\t\tif _, err := strconv.ParseFloat(token, 64); err == nil {\n\t\t\tdispatchFunction = dispatchTable[\"FLOAT\"]\n\t\t} else {\n\t\t\tvar evalsOk bool\n\t\t\tif dispatchFunction, evalsOk = dispatchTable[token]; !evalsOk {\n\t\t\t\tdispatchFunction = dispatchTable[\"__DEFAULT__\"]\n\t\t\t\t// delete token from expression\n\t\t\t\tcopy((*expression)[idx:], (*expression)[idx+1:])\n\t\t\t\t(*expression)[len(*expression)-1] = \"\"\n\t\t\t\t(*expression) = (*expression)[:len(*expression)-1]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tdispatchFunction(token, stack)\n\t}\n\treturn stack.Pop()\n}", "func (s *System) Evaluate(state []float32) []float32 {\n\tif len(state) > 0 {\n\t\treturn s.function(state, s.parametersVector)\n\t} else {\n\t\treturn s.function(s.stateVector, s.parametersVector)\n\t}\n}", "func (this *ObjectRemove) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.BinaryEval(this, item, context)\n}", "func (ap *AttestationPolicy) EvaluateResults(raw *checker.RawResults) (PolicyResult, error) {\n\tlogger := sclog.NewLogger(sclog.DefaultLevel)\n\tif ap.PreventBinaryArtifacts {\n\t\tcheckResult, err := CheckPreventBinaryArtifacts(ap.AllowedBinaryArtifacts, raw, logger)\n\t\tif !checkResult || err != nil {\n\t\t\treturn checkResult, err\n\t\t}\n\t}\n\n\tif ap.PreventUnpinnedDependencies {\n\t\tcheckResult, err := CheckNoUnpinnedDependencies(ap.AllowedUnpinnedDependencies, raw, logger)\n\t\tif !checkResult || err != nil {\n\t\t\treturn checkResult, err\n\t\t}\n\t}\n\n\tif ap.PreventKnownVulnerabilities {\n\t\tcheckResult, err := CheckNoVulnerabilities(raw, logger)\n\t\tif !checkResult || err != nil {\n\t\t\treturn checkResult, err\n\t\t}\n\t}\n\n\tif ap.EnsureCodeReviewed {\n\t\t// By default, if code review reqs. aren't specified, we assume\n\t\t// the user wants there to be atleast one reviewer\n\t\tif len(ap.CodeReviewRequirements.RequiredApprovers) == 0 &&\n\t\t\tap.CodeReviewRequirements.MinReviewers == 0 {\n\t\t\tap.CodeReviewRequirements.MinReviewers = 1\n\t\t}\n\n\t\tcheckResult, err := CheckCodeReviewed(ap.CodeReviewRequirements, raw, logger)\n\t\tif !checkResult || err != nil {\n\t\t\treturn checkResult, err\n\t\t}\n\t}\n\n\treturn Pass, nil\n}", "func (a Application) Evaluate() Expression {\n\tvar f = a.Function.Evaluate()\n\tif l, ok := f.(Abstraction); ok {\n\t\treturn l.Body.Substitute(l.Argument, a.Argument).Evaluate()\n\t}\n\treturn Application{f, a.Argument}\n}", "func (d *Division) Evaluate(left, right EvalResult) (EvalResult, error) {\n\treturn divideNumericWithError(left, right)\n}", "func (e *Evaluator) Evaluate(node ast.Node, env *object.Environment) object.Object {\n\te.Ctxt = node.Context()\n\tswitch node.(type) {\n\tcase *ast.Program:\n\t\tres := &object.StmtResults{}\n\t\tres.Results = []object.Object{}\n\n\t\t// adding statements\n\t\tfor _, stmt := range node.(*ast.Program).Statements {\n\t\t\tif ret, ok := stmt.(*ast.ReturnStatement); ok {\n\t\t\t\treturn e.Evaluate(ret, env)\n\t\t\t}\n\t\t\tresult := e.Evaluate(stmt, env)\n\t\t\tres.Results = append(res.Results, result)\n\t\t}\n\n\t\t// adding functions\n\t\t//todo: this should function differently than closures\n\t\tfor _, fn := range node.(*ast.Program).Functions {\n\t\t\tbody := fn.Body\n\t\t\tparams := fn.Params\n\t\t\tenv.Data[fn.Name.Value] = &object.Function{\n\t\t\t\tParams: params,\n\t\t\t\tBody: body,\n\t\t\t\tEnv: env,\n\t\t\t}\n\t\t}\n\n\t\t//todo: adding classes\n\n\t\treturn res\n\n\tcase ast.Statement:\n\t\tstmt := node.(ast.Statement)\n\n\t\tswitch node.(ast.Statement).(type) {\n\t\tcase *ast.LetStatement:\n\t\t\tletstmt := stmt.(*ast.LetStatement)\n\t\t\tval := e.Evaluate(letstmt.Value, env)\n\t\t\tenv.Set(letstmt.Name.Value, val)\n\t\t\treturn NULL\n\n\t\tcase *ast.ExprStatement:\n\t\t\texpr := stmt.(*ast.ExprStatement)\n\t\t\treturn e.Evaluate(expr.Expression, env)\n\n\t\tcase *ast.ReturnStatement:\n\t\t\tretstmt := stmt.(*ast.ReturnStatement)\n\t\t\tres := e.Evaluate(retstmt.Value, env)\n\t\t\treturn &object.Return{Inner: res}\n\n\t\tcase *ast.WhileStatement:\n\t\t\te.loopcount++\n\t\t\twhilestmt := stmt.(*ast.WhileStatement)\n\n\t\t\tvar result object.Object\n\n\t\t\tfor {\n\t\t\t\tval := e.Evaluate(whilestmt.Condition, env)\n\t\t\t\tif !evaluateTruthiness(val) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tresult = e.evalBlockStmt(whilestmt.Body, env)\n\t\t\t\tif object.IsErr(result) || object.IsBreak(result) {\n\t\t\t\t\tif object.IsBreak(result) {\n\t\t\t\t\t\te.loopcount--\n\t\t\t\t\t\treturn NULL\n\t\t\t\t\t}\n\t\t\t\t\treturn result\n\t\t\t\t}\n\t\t\t}\n\n\t\t\te.loopcount--\n\t\t\treturn result\n\n\t\tcase *ast.BreakStatement:\n\t\t\tif e.loopcount == 0 {\n\t\t\t\treturn &object.Exception{\n\t\t\t\t\tMsg: \"Cannot use break outside of loop\",\n\t\t\t\t\tCon: node.(ast.Statement).Context(),\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn &object.Break{}\n\n\t\tcase *ast.BlockStatement:\n\t\t\tblkstmt := stmt.(*ast.BlockStatement)\n\t\t\treturn e.evalBlockStmt(blkstmt, env)\n\n\t\tdefault:\n\t\t\treturn NULL\n\t\t}\n\n\tcase ast.Expression:\n\t\texpr := node.(ast.Expression)\n\n\t\tswitch node.(ast.Expression).(type) {\n\t\tcase *ast.Identifier:\n\t\t\tident := expr.(*ast.Identifier)\n\t\t\tif data, ok := env.Get(ident.Value); ok {\n\t\t\t\treturn data\n\t\t\t}\n\t\t\tif bltn, ok := builtins[ident.Value]; ok {\n\t\t\t\treturn bltn\n\t\t\t}\n\t\t\treturn &object.Exception{\n\t\t\t\tMsg: fmt.Sprintf(\"Could not find symbol %s\", ident.Value),\n\t\t\t\tCon: ident.Context(),\n\t\t\t}\n\n\t\tcase *ast.PrefixExpr:\n\t\t\tpexpr := expr.(*ast.PrefixExpr)\n\t\t\treturn e.evalPrefixExpr(pexpr, env)\n\n\t\tcase *ast.InfixExpr:\n\t\t\tiexpr := expr.(*ast.InfixExpr)\n\t\t\treturn e.evalInfixExpr(iexpr, env)\n\n\t\tcase *ast.IfExpression:\n\t\t\tifexpr := expr.(*ast.IfExpression)\n\t\t\tcondition := e.Evaluate(ifexpr.Condition, env)\n\t\t\tif condition == nil {\n\t\t\t\treturn &object.Exception{\n\t\t\t\t\tMsg: \"If condition returned nil\",\n\t\t\t\t\tCon: ifexpr.Context(),\n\t\t\t\t}\n\t\t\t}\n\t\t\tif evaluateTruthiness(condition) {\n\t\t\t\treturn e.Evaluate(ifexpr.Result, env)\n\t\t\t}\n\t\t\tif ifexpr.Alternative != nil {\n\t\t\t\tswitch ifexpr.Alternative.(type) {\n\t\t\t\tcase *ast.BlockStatement:\n\t\t\t\t\treturn e.Evaluate(ifexpr.Alternative.(*ast.BlockStatement), env)\n\t\t\t\tcase *ast.IfExpression:\n\t\t\t\t\treturn e.Evaluate(ifexpr.Alternative.(*ast.IfExpression), env)\n\t\t\t\tdefault:\n\t\t\t\t\treturn &object.Exception{\n\t\t\t\t\t\tMsg: \"Invalid else branch\",\n\t\t\t\t\t\tCon: ifexpr.Alternative.Context(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase *ast.FnLiteral:\n\t\t\tfnlit := expr.(*ast.FnLiteral)\n\t\t\tparams := fnlit.Params\n\t\t\tbody := fnlit.Body\n\t\t\treturn &object.Function{Params: params, Env: env, Body: body}\n\n\t\tcase *ast.FunctionCall:\n\t\t\t// asserting type\n\t\t\tfncall := expr.(*ast.FunctionCall)\n\n\t\t\t// resolving to object\n\t\t\tfunction := e.Evaluate(fncall.Ident, env)\n\t\t\tif object.IsErr(function) {\n\t\t\t\treturn function\n\t\t\t}\n\n\t\t\targs := e.evalExpressions(fncall.Params, env)\n\t\t\tif len(args) == 1 && object.IsErr(args[0]) {\n\t\t\t\treturn args[0]\n\t\t\t}\n\n\t\t\treturn e.applyFunction(function, args)\n\n\t\tcase *ast.DotExpression:\n\t\t\t//todo\n\t\t\treturn &object.Exception{\n\t\t\t\tMsg: \"DotExpr: unimplemented\",\n\t\t\t\tCon: node.Context(),\n\t\t\t}\n\n\t\tcase *ast.Int:\n\t\t\tintexpr := node.(ast.Expression).(*ast.Int)\n\t\t\treturn &object.Integer{Value: intexpr.Inner}\n\t\tcase *ast.Flt:\n\t\t\tfltexpr := node.(ast.Expression).(*ast.Flt)\n\t\t\treturn &object.Float{Value: fltexpr.Inner}\n\t\tcase *ast.Str:\n\t\t\tstrexpr := node.(ast.Expression).(*ast.Str)\n\t\t\treturn &object.String{Value: strexpr.Inner}\n\t\tcase *ast.Bool:\n\t\t\tboolexpr := node.(ast.Expression).(*ast.Bool)\n\t\t\treturn nativeBooltoObj(boolexpr.Inner)\n\t\tcase *ast.Array:\n\t\t\tarray := node.(ast.Expression).(*ast.Array)\n\t\t\tarr := &object.Array{}\n\n\t\t\t// preallocating so we don't have to waste cycles\n\t\t\t// reallocating every time we append\n\t\t\telements := make([]object.Object, 0, len(array.Elements))\n\n\t\t\tfor _, elem := range array.Elements {\n\t\t\t\telements = append(elements, e.Evaluate(elem, env))\n\t\t\t}\n\t\t\tarr.Elements = elements\n\n\t\t\treturn arr\n\n\t\tcase *ast.Map:\n\t\t\thash := node.(ast.Expression).(*ast.Map)\n\t\t\tnewmap := &object.Map{}\n\t\t\tnewmap.Elements = make(map[object.HashKey]object.Object)\n\n\t\t\tfor key, val := range hash.Elements {\n\t\t\t\tnkey, nval := e.Evaluate(key, env), e.Evaluate(val, env)\n\n\t\t\t\tif object.IsErr(nkey) {\n\t\t\t\t\treturn nkey\n\t\t\t\t}\n\t\t\t\tif object.IsErr(nval) {\n\t\t\t\t\treturn nval\n\t\t\t\t}\n\n\t\t\t\thashable, ok := nkey.(object.Hashable)\n\n\t\t\t\tif !ok {\n\t\t\t\t\treturn &object.Exception{\n\t\t\t\t\t\tMsg: fmt.Sprintf(\"Cannot use type %T as key for Map\", nkey),\n\t\t\t\t\t\tCon: hash.Context(),\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tnewmap.Elements[hashable.HashKey()] = nval\n\t\t\t}\n\n\t\t\treturn newmap\n\n\t\tcase *ast.IndexExpr:\n\t\t\tidx := node.(ast.Expression).(*ast.IndexExpr)\n\t\t\treturn e.evalIndexExpr(idx, env)\n\n\t\tdefault:\n\t\t\treturn NULL\n\t\t}\n\tdefault:\n\t\treturn &object.Exception{\n\t\t\tMsg: \"Unimplemented type\",\n\t\t\tCon: node.Context(),\n\t\t}\n\t}\n\treturn &object.Exception{\n\t\tMsg: fmt.Sprintf(\"Evaluate: unreachable code, got %T\", node),\n\t\tCon: node.Context(),\n\t}\n}", "func (e *ExpressionAtom) Evaluate() (reflect.Value, error) {\n\tvar val reflect.Value\n\tvar err error\n\tif e.Variable != nil {\n\t\tval, err = e.Variable.Evaluate()\n\t} else if e.FunctionCall != nil {\n\t\tval, err = e.FunctionCall.Evaluate()\n\t} else if e.MethodCall != nil {\n\t\tval, err = e.MethodCall.Evaluate()\n\t} else if e.Constant != nil {\n\t\tval, err = e.Constant.Evaluate()\n\t}\n\tif err == nil {\n\t\te.Value = val\n\t}\n\treturn val, err\n}", "func (this *ObjectLength) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.UnaryEval(this, item, context)\n}", "func (this *ObjectLength) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.UnaryEval(this, item, context)\n}", "func Evaluate(expr string, contextVars map[string]logol.Match) bool {\n\tlogger.Debugf(\"Evaluate expression: %s\", expr)\n\n\tre := regexp.MustCompile(\"[$@#]+\\\\w+\")\n\tres := re.FindAllString(expr, -1)\n\t// msg, _ := json.Marshal(contextVars)\n\t// logger.Errorf(\"CONTEXT: %s\", msg)\n\tparameters := make(map[string]interface{}, 8)\n\tvarIndex := 0\n\tfor _, val := range res {\n\t\tt := strconv.Itoa(varIndex)\n\t\tvarName := \"VAR\" + t\n\t\tr := strings.NewReplacer(val, varName)\n\t\texpr = r.Replace(expr)\n\t\tvarIndex++\n\t\tcValue, cerr := getValueFromExpression(val, contextVars)\n\t\tif cerr {\n\t\t\tlogger.Debugf(\"Failed to get value from expression %s\", val)\n\t\t\treturn false\n\t\t}\n\t\tparameters[varName] = cValue\n\t}\n\tlogger.Debugf(\"New expr: %s with params %v\", expr, parameters)\n\n\texpression, err := govaluate.NewEvaluableExpression(expr)\n\tif err != nil {\n\t\tlogger.Errorf(\"Failed to evaluate expression %s\", expr)\n\t\treturn false\n\t}\n\tresult, _ := expression.Evaluate(parameters)\n\tif result == true {\n\t\treturn true\n\t}\n\treturn false\n}", "func (p *Policy) Evaluate(c *Context) (allow bool, match bool, err error) {\n\tfor _, statement := range p.Statements {\n\t\tstatementMatch, err := statement.match(c)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif statementMatch {\n\t\t\tmatch = true\n\t\t\tif statement.Effect == Deny {\n\t\t\t\tallow = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif statement.Effect == Allow {\n\t\t\t\tallow = true\n\t\t\t}\n\t\t}\n\t}\n\treturn allow, match, err\n}", "func (e *Evaluator) Eval(expr string) (interface{}, error) {\n\tn := e.n.Copy()\n\t_expr, err := xpath.Compile(expr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"expr cannot compile: %w\", err)\n\t}\n\n\tv := _expr.Evaluate(n)\n\tswitch v := v.(type) {\n\tcase *xpath.NodeIterator:\n\t\tns := nodes(v)\n\t\tvs := make([]interface{}, 0, len(ns))\n\t\tfor i := range ns {\n\t\t\tswitch n := ns[i].(type) {\n\t\t\tcase attr:\n\t\t\t\tvs = append(vs, n.val)\n\t\t\t}\n\t\t}\n\t\tif len(vs) == len(ns) {\n\t\t\treturn vs, nil\n\t\t}\n\t\treturn ns, nil\n\t}\n\n\treturn v, nil\n}", "func (p *Pool) Evaluate() {\n\tvar wg sync.WaitGroup\n\tfor i := 0; i < POOL_SIZE; i++ {\n\t\twg.Add(1)\n\t\tgo func(i int, track []tracks.Element) {\n\t\t\tp.Members[i].Score, p.Members[i].ScoreData = GetScore(track)\n\t\t\twg.Done()\n\t\t}(i, p.Members[i].Track)\n\t}\n\twg.Wait()\n\n\t// Assign fitness for every member. In the future, consider a smarter\n\t// algorithm higher score members a better chance of reproducing.\n\tfor i := 0; i < POOL_SIZE; i++ {\n\t\tp.Members[i].Fitness = float64(p.Members[i].Score)\n\t}\n}", "func Evaluate(enode *lang.ExprNode, env *E) (*Value, error) {\n\tval, err := evalExpr(enode, env)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif enode.ResultVar != nil {\n\t\tif val.VType == MVar && enode.ResultVar.TType == lang.TTSVar {\n\t\t\treturn nil, fmt.Errorf(\"cannot assign a matrix value to a scalar variable\")\n\t\t}\n\n\t\tif val.VType == SVar && enode.ResultVar.TType == lang.TTMVar {\n\t\t\treturn nil, fmt.Errorf(\"cannot assign a scalar value to a matrix variable\")\n\t\t}\n\n\t\tv := rune(enode.ResultVar.Literal[0])\n\n\t\tswitch val.VType {\n\t\tcase MVar:\n\t\t\tenv.SetMVar(v, val.MValue)\n\t\tcase SVar:\n\t\t\tenv.SetSVar(v, val.SValue)\n\t\t}\n\t}\n\n\treturn val, nil\n}", "func (this *ObjectPairs) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.UnaryEval(this, item, context)\n}", "func (this *ObjectPairs) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.UnaryEval(this, item, context)\n}", "func (c *Contract) Evaluate(ctx TransactionContextInterface, jeweler string, paperNumber string, evaluator string, evalDateTime string) (*InventoryFinancingPaper, error) {\r\n\tpaper, err := ctx.GetPaperList().GetPaper(jeweler, paperNumber)\r\n\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\tif paper.GetEvaluator() == \"\" {\r\n\t\tpaper.SetEvaluator(evaluator)\r\n\t}\r\n\r\n\tif paper.IsReceived() {\r\n\t\tpaper.SetEvaluated()\r\n\t}\r\n\r\n\tif !paper.IsEvaluated() {\r\n\t\treturn nil, fmt.Errorf(\"inventory paper %s:%s is not yet evaluated, Current state = %s\", jeweler, paperNumber, paper.GetState())\r\n\t}\r\n\r\n\terr = ctx.GetPaperList().UpdatePaper(paper)\r\n\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\tfmt.Printf(\"The evluator %q has evaluated the inventory financing paper %q:%q,the evaluate date is %q..\\n Current State is %q\", paper.GetEvaluator(), jeweler, paperNumber, evalDateTime, paper.GetState())\r\n\treturn paper, nil\r\n}", "func Evaluate(e ast.Node, genCtx *GenCtx) parser_driver.ValueExpr {\n\tswitch t := e.(type) {\n\tcase *ast.ParenthesesExpr:\n\t\treturn Evaluate(t.Expr, genCtx)\n\tcase *ast.BinaryOperationExpr:\n\t\tres, err := operator.BinaryOps.Eval(t.Op.String(), Evaluate(t.L, genCtx), Evaluate(t.R, genCtx))\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"error occurred on eval: %+v\", err))\n\t\t}\n\t\treturn res\n\tcase *ast.UnaryOperationExpr:\n\t\tres, err := operator.UnaryOps.Eval(t.Op.String(), Evaluate(t.V, genCtx))\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"error occurred on eval: %+v\", err))\n\t\t}\n\t\treturn res\n\tcase *ast.IsNullExpr:\n\t\tsubResult := Evaluate(t.Expr, genCtx)\n\t\tc := ConvertToBoolOrNull(subResult)\n\t\tr := parser_driver.ValueExpr{}\n\t\tr.SetInt64(0)\n\t\tif c == -1 {\n\t\t\tr.SetInt64(1)\n\t\t}\n\t\treturn r\n\tcase *ast.ColumnNameExpr:\n\t\tfor key, value := range genCtx.unwrapPivotRows {\n\t\t\toriginTableName := t.Name.Table.L\n\t\t\tfor k, v := range genCtx.TableAlias {\n\t\t\t\tif v == originTableName {\n\t\t\t\t\toriginTableName = k\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\toriginColumnName := t.Name.Name.L\n\t\t\tif key == fmt.Sprintf(\"%s.%s\", originTableName, originColumnName) {\n\t\t\t\tv := parser_driver.ValueExpr{}\n\t\t\t\tv.SetValue(value)\n\t\t\t\tif tmpTable, ok := genCtx.TableAlias[t.Name.Table.L]; ok {\n\t\t\t\t\tt.Name.Table = model.NewCIStr(tmpTable)\n\t\t\t\t}\n\t\t\t\treturn v\n\t\t\t}\n\t\t}\n\t\tpanic(fmt.Sprintf(\"no such col %s in table %s\", t.Name, t.Name.Table))\n\tcase ast.ValueExpr:\n\t\tv := parser_driver.ValueExpr{}\n\t\tv.SetValue(t.GetValue())\n\t\tv.SetType(t.GetType())\n\t\treturn v\n\t}\n\n\t// is useless?\n\t// if e == nil {\n\t// \treturn trueValueExpr()\n\t// }\n\n\tpanic(\"not reachable\")\n\tv := parser_driver.ValueExpr{}\n\tv.SetNull()\n\treturn v\n}", "func (m *Manager) Evaluate(t *register.Transaction) (bool, error) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tvar matched []*Rule\n\tfor _, r := range m.rules {\n\t\tif r.Evaluate(t) {\n\t\t\tmatched = append(matched, r)\n\t\t}\n\t}\n\tif len(matched) == 0 {\n\t\treturn false, nil\n\t}\n\tif len(matched) > 1 {\n\t\tvar rules []string\n\t\tfor _, r := range matched {\n\t\t\trules = append(rules, r.Name)\n\t\t}\n\t\treturn false, fmt.Errorf(\"transaction %s matched multiple rules: %s\", t.ID, strings.Join(rules, \", \"))\n\t}\n\tif len(t.Category) > 0 {\n\t\treturn false, nil\n\t}\n\tt.Category = append(t.Category, &register.Category{Name: matched[0].Category, Amount: t.Amount})\n\treturn true, nil\n}", "func (me *BoolType) Evaluate(obj interface{}, operator string, values string) (bool, error) {\n\tvar pobj string\n\tvar err error\n\tvar object bool\n\n\tif obj != nil {\n\t\tif _, ok := obj.(bool); ok {\n\t\t\tif obj.(bool) {\n\t\t\t\tobj = \"true\"\n\t\t\t} else {\n\t\t\t\tobj = \"false\"\n\t\t\t}\n\t\t}\n\t\tvar ok bool\n\t\tpobj, ok = obj.(string)\n\t\tif !ok {\n\t\t\treturn false, fmt.Errorf(\"type/golang/bool.go: obj must be a string or a bool, got `%v`\", obj)\n\t\t}\n\n\t\tobject, err = strconv.ParseBool(pobj)\n\t\tif err != nil {\n\t\t\treturn false, fmt.Errorf(\"type/golang/bool.go: %v unable to parse value `%s` to bool\", err, pobj)\n\t\t}\n\t}\n\tswitch operator {\n\tcase Nab:\n\t\treturn err != nil, nil\n\tcase Ab:\n\t\treturn err == nil, nil\n\tcase Empty:\n\t\treturn obj == nil, nil\n\tcase NotEmpty:\n\t\treturn obj != nil, nil\n\tcase True:\n\t\tif obj == nil {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn object, nil\n\tcase False:\n\t\tif obj == nil {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn !object, nil\n\tdefault:\n\t\treturn false, fmt.Errorf(\"type/golang/bool.go: unsupport operator, %v, %s, %s\", obj, operator, values)\n\t}\n}", "func (e *ExpressionAtom) Evaluate(dataContext IDataContext, memory *WorkingMemory) (reflect.Value, error) {\n\tif e.Evaluated == true {\n\t\treturn e.Value, nil\n\t}\n\tif e.Variable != nil {\n\t\tval, err := e.Variable.Evaluate(dataContext, memory)\n\t\tif err != nil {\n\t\t\treturn reflect.Value{}, err\n\t\t}\n\t\te.Value = val\n\t\te.Evaluated = true\n\t\treturn val, err\n\t}\n\tif e.FunctionCall != nil {\n\t\tvalueNode := dataContext.Get(\"DEFUNC\")\n\t\targs, err := e.FunctionCall.EvaluateArgumentList(dataContext, memory)\n\t\tif err != nil {\n\t\t\treturn reflect.Value{}, err\n\t\t}\n\t\tret, err := valueNode.CallFunction(e.FunctionCall.FunctionName, args...)\n\t\tif err != nil {\n\t\t\treturn reflect.Value{}, err\n\t\t}\n\t\te.Value = ret\n\t\te.Evaluated = true\n\t\treturn ret, err\n\t}\n\tpanic(\"should not be reached\")\n}", "func (this *ObjectNames) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.UnaryEval(this, item, context)\n}", "func (this *ObjectNames) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.UnaryEval(this, item, context)\n}", "func (a *Ant) Evaluate() float64 {\n\tscore := 0.0\n\tfor i := 1; i < len(a.tour); i++ {\n\t\tscore += a.tour[i].Position.DistanceTo(&a.tour[i-1].Position)\n\t}\n\treturn score\n}", "func (c *chainACL) Evaluate(signatureSet []*protoutil.SignedData) error {\n\tpolicy, ok := c.policyManager.GetPolicy(policies.ChannelWriters)\n\tif !ok {\n\t\treturn fmt.Errorf(\"could not find policy %s\", policies.ChannelWriters)\n\t}\n\n\terr := policy.EvaluateSignedData(signatureSet)\n\tif err != nil {\n\t\tc.Logger.Debugf(\"SigFilter evaluation failed: %s, policyName: %s\", err.Error(), policies.ChannelWriters)\n\t\treturn errors.Wrap(errors.WithStack(msgprocessor.ErrPermissionDenied), err.Error())\n\t}\n\treturn nil\n}", "func (m *MockFloatTexture) Evaluate(si *SurfaceInteraction) float64 {\n\tret := m.ctrl.Call(m, \"Evaluate\", si)\n\tret0, _ := ret[0].(float64)\n\treturn ret0\n}", "func (this *ObjectAdd) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.TernaryEval(this, item, context)\n}", "func Eval(ctx context.Context, e Expr, vs Values) (interface{}, error) {\r\n\tfn, err := FuncOf(ctx, e, vs)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\treturn fn.Call(ctx, vs)\r\n}", "func (b *Behavior) Evaluate(ev *slack.MessageEvent, bot *bot.Bot) error {\n\tif ev.BotID != \"\" {\n\t\treturn nil\n\t}\n\n\tverses := b.parseText(ev.Text)\n\tif len(verses) == 0 {\n\t\treturn nil\n\t}\n\n\tbot.MessageChannel(ev.Channel, b.buildMessage(verses))\n\treturn nil\n}", "func (n *NotLikeOp) Evaluate(left, right EvalResult) (EvalResult, error) {\n\tpanic(\"implement me\")\n}", "func (this *Not) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.UnaryEval(this, item, context)\n}", "func (this *ObjectInnerPairs) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.UnaryEval(this, item, context)\n}", "func (tsf *traceStateFilter) Evaluate(_ context.Context, _ pcommon.TraceID, trace *TraceData) (Decision, error) {\n\ttrace.Lock()\n\tdefer trace.Unlock()\n\tbatches := trace.ReceivedBatches\n\n\treturn hasSpanWithCondition(batches, func(span ptrace.Span) bool {\n\t\ttraceState, err := tracesdk.ParseTraceState(span.TraceState().AsRaw())\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\tif ok := tsf.matcher(traceState.Get(tsf.key)); ok {\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}), nil\n}", "func (p *ApprovalPoll) Evaluate() ([]string, []CScore, error) {\n\tif p.candidates == nil || p.ballots == nil {\n\t\treturn []string{}, []CScore{}, errors.New(\"no candidates or no ballots\")\n\t}\n\twinners, ranks := p.getWinners()\n\treturn winners, ranks, nil\n}", "func (*SetVolumeTecLite) Evaluate(room base.PublicRoom, requestor string) ([]base.ActionStructure, int, error) {\n\t//call the default set volume to get the list of actions, then go through and remap them\n\t//for the new volme level\n\tdefaultSetVolume := &SetVolumeDefault{}\n\tactions, count, err := defaultSetVolume.Evaluate(room, requestor)\n\n\tif err != nil {\n\t\treturn actions, count, err\n\t}\n\n\tfor i := range actions {\n\t\toldLevel, err := strconv.Atoi(actions[i].Parameters[\"level\"])\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"[command_evaluators] Could not parse parameter 'level' for an integer: %s\", err.Error())\n\t\t\tlog.L.Errorf(\"%s\", err.Error())\n\t\t\treturn actions, count, err\n\t\t}\n\t\tactions[i].Parameters[\"level\"] = strconv.Itoa(calculateNewLevel(oldLevel, 65))\n\t}\n\treturn actions, count, nil\n}", "func (this *Version) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn _VERSION_VALUE, nil\n}", "func (n *aliasPlanExpression) Evaluate(currentRow []interface{}) (interface{}, error) {\n\treturn n.expr.Evaluate(currentRow)\n}", "func (o BoolOperand) Evaluate(cxt interface{}) (bool, error) {\n\treturn o.Value, nil\n}", "func (r RuleSet) Evaluate(packet Packet) (*Rule, []Rule, error) {\n\tmatches := []Rule{}\n\n\tfor _, rule := range r {\n\t\tif rule.Matches(packet) {\n\t\t\tmatches = append(matches, rule)\n\n\t\t\tif rule.Quick {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(matches) < 1 {\n\t\treturn nil, []Rule{}, nil\n\t}\n\n\treturn &matches[len(matches)-1], matches, nil\n}", "func (expr *Expr) Evaluate(root NodeNavigator) interface{} {\n\tval := expr.q.Evaluate(iteratorFunc(func() NodeNavigator { return root }))\n\tswitch val.(type) {\n\tcase query:\n\t\treturn &NodeIterator{query: expr.q.Clone(), node: root}\n\t}\n\treturn val\n}", "func (n *NullSafeEqualOp) Evaluate(left, right EvalResult) (EvalResult, error) {\n\tpanic(\"implement me\")\n}", "func (m *Multiplication) Evaluate(left, right EvalResult) (EvalResult, error) {\n\treturn multiplyNumericWithError(left, right)\n}", "func (n *NotRegexpOp) Evaluate(left, right EvalResult) (EvalResult, error) {\n\tpanic(\"implement me\")\n}", "func (a *Addition) Evaluate(left, right EvalResult) (EvalResult, error) {\n\treturn addNumericWithError(left, right)\n}", "func evaluate(expression []string, actions ActionTable, stack *Stack) interface{} {\n\tfor _, t := range expression {\n\t\tvar action ActionFunc\n\t\tif _, err := strconv.ParseFloat(t, 64); err == nil {\n\t\t\taction = actions[\"NUMBER\"]\n\t\t} else {\n\t\t\tvar ok bool\n\t\t\tif action, ok = actions[t]; !ok {\n\t\t\t\taction = actions[\"__DEFAULT__\"]\n\t\t\t}\n\t\t}\n\t\taction(t, stack)\n\t}\n\treturn stack.Pop()\n}", "func (m *MockSpectrumTexture) Evaluate(si *SurfaceInteraction) Spectrum {\n\tret := m.ctrl.Call(m, \"Evaluate\", si)\n\tret0, _ := ret[0].(Spectrum)\n\treturn ret0\n}", "func (cl CardList) Evaluate() uint16 {\n\tif len(cl) == 5 {\n\t\treturn evalFiveFast(cl[0], cl[1], cl[2], cl[3], cl[4])\n\t}\n\tif len(cl) < 5 || len(cl) > 7 {\n\t\treturn math.MaxUint16\n\t}\n\n\treturn cl.evalMore()\n}", "func (c constructedSchedule) Evaluate() float64 {\n\tvar score time.Duration\n\tfor _, attendee := range c.eventsByAttendee {\n\t\t// First event as early as possible.\n\t\tscore += attendee.Scheduled[0].Start.Sub(c.earliest)\n\n\t\t// All events packed as tight as possible.\n\t\tfor i, nextEvent := range attendee.Scheduled[1:] {\n\t\t\tcurEvent := attendee.Scheduled[i]\n\t\t\tscore += nextEvent.Start.Sub(curEvent.End)\n\t\t}\n\t}\n\n\t// TODO: Convert to seconds to not work with giant numbers?\n\treturn float64(score)\n}", "func Evaluate(query string, values map[string]interface{}) interface{} {\n\ttokens := Parser(query)\n\trpn := ToPostfix(tokens)\n\touts := SolvePostfix(rpn, values)\n\treturn outs\n}", "func (n *NotInOp) Evaluate(left, right EvalResult) (EvalResult, error) {\n\tpanic(\"implement me\")\n}", "func (o NotOperator) Evaluate(ctx interface{}) (bool, error) {\n\t// fmt.Println(\"Not.Evaluate()\")\n\tresult, err := o.Operand.Evaluate(ctx)\n\treturn !result, err\n}", "func (this *AggregateBase) evaluate(agg Aggregate, item value.Value,\n\tcontext expression.Context) (result value.Value, err error) {\n\tdefer func() {\n\t\tr := recover()\n\t\tif r != nil {\n\t\t\terr = fmt.Errorf(\"Error evaluating aggregate: %v.\", r)\n\t\t}\n\t}()\n\n\tav := item.(value.AnnotatedValue)\n\taggregates := av.GetAttachment(\"aggregates\")\n\tif aggregates != nil {\n\t\taggs := aggregates.(map[string]value.Value)\n\t\tresult = aggs[agg.String()]\n\t}\n\n\tif result == nil {\n\t\terr = fmt.Errorf(\"Aggregate %s not found.\", agg.String())\n\t}\n\n\treturn\n}", "func (indis Individuals) Evaluate(parallel bool) error {\n\tif !parallel {\n\t\tvar err error\n\t\tfor i := range indis {\n\t\t\terr = indis[i].Evaluate()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\tvar (\n\t\tnWorkers = runtime.GOMAXPROCS(-1)\n\t\tn = len(indis)\n\t\tchunkSize = (n + nWorkers - 1) / nWorkers\n\t\tg errgroup.Group\n\t)\n\n\tfor a := 0; a < n; a += chunkSize {\n\t\ta := a // https://golang.org/doc/faq#closures_and_goroutines\n\t\tvar b = minInt(a+chunkSize, n)\n\t\tg.Go(func() error {\n\t\t\treturn indis[a:b].Evaluate(false)\n\t\t})\n\t}\n\n\treturn g.Wait()\n}", "func (e *EqualOp) Evaluate(left, right EvalResult) (EvalResult, error) {\n\tif out, err := e.IsTrue(left, right); err != nil || !out {\n\t\treturn resultFalse, err\n\t}\n\treturn resultTrue, nil\n}" ]
[ "0.6244661", "0.612793", "0.6052038", "0.5920062", "0.5904791", "0.57955474", "0.5789945", "0.57720846", "0.5768817", "0.57387304", "0.57387304", "0.5710845", "0.56974244", "0.56859833", "0.5674682", "0.5674682", "0.56727636", "0.5640962", "0.56262887", "0.56128746", "0.55172443", "0.5483333", "0.5478223", "0.54745907", "0.54368037", "0.5427969", "0.5420867", "0.5416218", "0.540934", "0.53965896", "0.5393646", "0.5364132", "0.5357864", "0.53549826", "0.53423667", "0.5324198", "0.5312629", "0.52864146", "0.5275956", "0.52679807", "0.526142", "0.525179", "0.52469546", "0.5239549", "0.5236642", "0.5229065", "0.5205258", "0.5192732", "0.51873326", "0.5180826", "0.5173344", "0.51698536", "0.5152673", "0.5119122", "0.5119122", "0.5098494", "0.50894284", "0.50817174", "0.50732243", "0.5068983", "0.50560963", "0.50560963", "0.5040219", "0.50339156", "0.5033056", "0.50321186", "0.502493", "0.5011014", "0.5011014", "0.49930128", "0.49668655", "0.49640223", "0.4952997", "0.49263284", "0.49262202", "0.4916666", "0.48890886", "0.48732415", "0.486011", "0.48583856", "0.48527333", "0.4851106", "0.48306695", "0.4827129", "0.4808499", "0.48083037", "0.47968838", "0.479436", "0.47911447", "0.47890687", "0.47877106", "0.47833562", "0.47470272", "0.4746604", "0.47456914", "0.47299597", "0.4725722", "0.4720394", "0.47180358", "0.4715651" ]
0.6993517
0
NewConfigMapReplicator creates a new config map replicator
func NewConfigMapReplicator(client kubernetes.Interface, resyncPeriod time.Duration, allowAll bool) Replicator { repl := objectReplicator{ replicatorProps: replicatorProps{ Name: "config map", allowAll: allowAll, client: client, targetsFrom: make(map[string][]string), targetsTo: make(map[string][]string), watchedTargets: make(map[string][]string), watchedPatterns: make(map[string][]targetPattern), }, replicatorActions: ConfigMapActions, } namespaceStore, namespaceController := cache.NewInformer( &cache.ListWatch{ ListFunc: func(lo metav1.ListOptions) (runtime.Object, error) { list, err := client.CoreV1().Namespaces().List(lo) if err != nil { return list, err } // populate the store already, to avoid believing some items are deleted copy := make([]interface{}, len(list.Items)) for index := range list.Items { copy[index] = &list.Items[index] } repl.namespaceStore.Replace(copy, "init") return list, err }, WatchFunc: func(lo metav1.ListOptions) (watch.Interface, error) { return client.CoreV1().Namespaces().Watch(lo) }, }, &v1.Namespace{}, resyncPeriod, cache.ResourceEventHandlerFuncs{ AddFunc: repl.NamespaceAdded, UpdateFunc: func(old interface{}, new interface{}) {}, DeleteFunc: func(obj interface{}) {}, }, ) repl.namespaceStore = namespaceStore repl.namespaceController = namespaceController objectStore, objectController := cache.NewInformer( &cache.ListWatch{ ListFunc: func(lo metav1.ListOptions) (runtime.Object, error) { list, err := client.CoreV1().ConfigMaps("").List(lo) if err != nil { return list, err } // populate the store already, to avoid believing some items are deleted copy := make([]interface{}, len(list.Items)) for index := range list.Items { copy[index] = &list.Items[index] } repl.objectStore.Replace(copy, "init") return list, err }, WatchFunc: func(lo metav1.ListOptions) (watch.Interface, error) { return client.CoreV1().ConfigMaps("").Watch(lo) }, }, &v1.ConfigMap{}, resyncPeriod, cache.ResourceEventHandlerFuncs{ AddFunc: repl.ObjectAdded, UpdateFunc: func(old interface{}, new interface{}) { repl.ObjectAdded(new) }, DeleteFunc: repl.ObjectDeleted, }, ) repl.objectStore = objectStore repl.objectController = objectController return &repl }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newConfigMap(configMapName, namespace string, labels map[string]string,\n\tkibanaIndexMode, esUnicastHost, rootLogger, nodeQuorum, recoverExpectedShards, primaryShardsCount, replicaShardsCount string) *v1.ConfigMap {\n\n\terr, data := renderData(kibanaIndexMode, esUnicastHost, nodeQuorum, recoverExpectedShards, primaryShardsCount, replicaShardsCount, rootLogger)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn &v1.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"ConfigMap\",\n\t\t\tAPIVersion: v1.SchemeGroupVersion.String(),\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: configMapName,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tData: data,\n\t}\n}", "func newConfigmap(customConfigmap *customConfigMapv1alpha1.CustomConfigMap) *corev1.ConfigMap {\n\tlabels := map[string]string{\n\t\t\"name\": customConfigmap.Spec.ConfigMapName,\n\t\t\"customConfigName\": customConfigmap.Name,\n\t\t\"latest\": \"true\",\n\t}\n\tname := fmt.Sprintf(\"%s-%s\", customConfigmap.Spec.ConfigMapName, RandomSequence(5))\n\tconfigName := NameValidation(name)\n\treturn &corev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: configName,\n\t\t\tNamespace: customConfigmap.Namespace,\n\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\t*metav1.NewControllerRef(customConfigmap, customConfigMapv1alpha1.SchemeGroupVersion.WithKind(\"CustomConfigMap\")),\n\t\t\t},\n\t\t\tLabels: labels,\n\t\t},\n\t\tData: customConfigmap.Spec.Data,\n\t\tBinaryData: customConfigmap.Spec.BinaryData,\n\t}\n}", "func newConfigMapStore(c kubernetes.Interface) configMapStore {\n\treturn &APIServerconfigMapStore{\n\t\tconfigMapStore: cache.NewStore(cache.MetaNamespaceKeyFunc),\n\t\tclient: c,\n\t}\n}", "func NewConfigMap(namespace, cmName, originalFilename string, generatedKey string,\n\ttextData string, binaryData []byte) *corev1.ConfigMap {\n\timmutable := true\n\tcm := corev1.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"ConfigMap\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cmName,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: map[string]string{\n\t\t\t\tConfigMapOriginalFileNameLabel: originalFilename,\n\t\t\t\tConfigMapAutogenLabel: \"true\",\n\t\t\t},\n\t\t},\n\t\tImmutable: &immutable,\n\t}\n\tif textData != \"\" {\n\t\tcm.Data = map[string]string{\n\t\t\tgeneratedKey: textData,\n\t\t}\n\t}\n\tif binaryData != nil {\n\t\tcm.BinaryData = map[string][]byte{\n\t\t\tgeneratedKey: binaryData,\n\t\t}\n\t}\n\treturn &cm\n}", "func NewConfigMap(configmapName string, namespace string, data map[string]string) *core.ConfigMap {\n\treturn &core.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"ConfigMap\",\n\t\t\tAPIVersion: core.SchemeGroupVersion.String(),\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: configmapName,\n\t\t\tNamespace: namespace,\n\t\t},\n\t\tData: data,\n\t}\n}", "func newConfigMapForCR(cr *storagev1.CSIPowerMaxRevProxy) (*v1.ConfigMap, error) {\n\tconfig := cr.Spec.RevProxy\n\tif config.Mode == \"\" {\n\t\tconfig.Mode = DefaultMode\n\t}\n\tif config.Port == 0 {\n\t\tconfig.Port = DefaultPort\n\t}\n\tout, err := yaml.Marshal(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfigMapData := make(map[string]string)\n\tconfigMapData[ConfigFileName] = string(out)\n\tlabels := map[string]string{\n\t\t\"name\": ReverseProxyName,\n\t}\n\treturn &v1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: ConfigMapName,\n\t\t\tNamespace: cr.Namespace,\n\t\t\tLabels: labels,\n\t\t\tOwnerReferences: getOwnerReferences(cr),\n\t\t},\n\t\tData: configMapData,\n\t}, nil\n}", "func createConfigMap() *v1.ConfigMap {\n\treturn &v1.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"ConfigMap\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"descheduler-policy-configmap\",\n\t\t\tNamespace: \"kube-system\",\n\t\t},\n\t\t// strategies:\\n \\\"RemoveDuplicates\\\":\\n enabled: true\n\t\tData: map[string]string{\n\t\t\t\"policy.yaml\": \"apiVersion: \\\"descheduler/v1alpha1\\\"\\nkind: \\\"DeschedulerPolicy\\\"\\nstrategies:\\n \\\"RemoveDuplicates\\\":\\n enabled: true\\n\",\n\t\t},\n\t}\n}", "func NewConfigMapWatcher(logger *zap.Logger, dir string, updateConfig swappable.UpdateConfig) (*configMapWatcher, error) {\n\tconf, err := readConfigMap(logger, dir)\n\tif err != nil {\n\t\tlogger.Error(\"Unable to read configMap\", zap.Error(err))\n\t\treturn nil, err\n\t}\n\n\tlogger.Info(\"Read initial configMap\", zap.Any(\"conf\", conf))\n\n\terr = updateConfig(conf)\n\tif err != nil {\n\t\tlogger.Error(\"Unable to use the initial configMap: %v\", zap.Error(err))\n\t\treturn nil, err\n\t}\n\n\tcmw := &configMapWatcher{\n\t\tlogger: logger,\n\t\tdir: dir,\n\t\tconfigUpdated: updateConfig,\n\t}\n\treturn cmw, nil\n}", "func newConfigMapToUpdate(current, desired *corev1.ConfigMap) *corev1.ConfigMap {\n\tmerged := current.DeepCopy()\n\n\tmerged.Annotations = desired.Annotations\n\tmerged.Labels = desired.Labels\n\n\tmerged.BinaryData = desired.BinaryData\n\tmerged.Data = desired.Data\n\n\tif reflect.DeepEqual(current, merged) {\n\t\treturn nil\n\t}\n\n\treturn merged\n}", "func NewConfigMapController(kclient *kubernetes.Clientset, g grafana.APIInterface) *ConfigMapController {\n\tconfigmapWatcher := &ConfigMapController{}\n\n\t// Create informer for watching ConfigMaps\n\tconfigmapInformer := cache.NewSharedIndexInformer(\n\t\t&cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\treturn kclient.Core().ConfigMaps(metav1.NamespaceAll).List(options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\treturn kclient.Core().ConfigMaps(metav1.NamespaceAll).Watch(options)\n\t\t\t},\n\t\t},\n\t\t&v1.ConfigMap{},\n\t\t3*time.Minute,\n\t\tcache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},\n\t)\n\n\tconfigmapInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: configmapWatcher.CreateDashboards,\n\t})\n\n\tconfigmapWatcher.kclient = kclient\n\tconfigmapWatcher.configmapInformer = configmapInformer\n\tconfigmapWatcher.g = g\n\n\treturn configmapWatcher\n}", "func newJiraConfigMap(j *v1alpha1.Jira) error {\n\tcm := &v1.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"ConfigMap\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: j.Spec.ConfigMapName,\n\t\t\tNamespace: j.Namespace,\n\t\t\tOwnerReferences: ownerRef(j),\n\t\t\tLabels: jiraLabels(j),\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"dbconfig.xml\": DefaultDatabaseConfig,\n\t\t},\n\t}\n\treturn createResource(j, cm)\n}", "func newReconciler(mgr manager.Manager) reconcile.Reconciler {\n\treturn &ReconcileConfigMap{client: mgr.GetClient(), scheme: mgr.GetScheme()}\n}", "func NewReplicator(serviceName string, sVice common.SCommon, metadataClient metadata.TChanMetadataService, replicatorClientFactory ClientFactory, config configure.CommonAppConfig) (*Replicator, []thrift.TChanServer) {\n\tdeployment := strings.ToLower(sVice.GetConfig().GetDeploymentName())\n\tzone, tenancy := common.GetLocalClusterInfo(deployment)\n\tallZones := getAllZones(config.GetReplicatorConfig().GetReplicatorHosts())\n\tlogger := (sVice.GetConfig().GetLogger()).WithFields(bark.Fields{\n\t\tcommon.TagReplicator: common.FmtOut(sVice.GetHostUUID()),\n\t\tcommon.TagDplName: common.FmtDplName(deployment),\n\t\tcommon.TagZoneName: common.FmtZoneName(zone),\n\t\tcommon.TagTenancy: common.FmtTenancy(tenancy),\n\t})\n\n\tr := &Replicator{\n\t\tlogger: logger,\n\t\tm3Client: metrics.NewClient(sVice.GetMetricsReporter(), metrics.Replicator),\n\t\tSCommon: sVice,\n\t\tAppConfig: config,\n\t\tallZones: allZones,\n\t\tlocalZone: zone,\n\t\tdefaultAuthoritativeZone: config.GetReplicatorConfig().GetDefaultAuthoritativeZone(),\n\t\ttenancy: tenancy,\n\t\treplicatorclientFactory: replicatorClientFactory,\n\t\tremoteReplicatorConn: make(map[string]*outConnection),\n\t\tstorehostConn: make(map[string]*outConnection),\n\t}\n\n\tr.metaClient = mm.NewMetadataMetricsMgr(metadataClient, r.m3Client, r.logger)\n\n\tr.uconfigClient = sVice.GetDConfigClient()\n\tr.dynamicConfigManage()\n\n\treturn r, []thrift.TChanServer{rgen.NewTChanReplicatorServer(r)}\n}", "func (r *ReconcileDescheduler) createConfigMap(descheduler *deschedulerv1alpha1.Descheduler) (*v1.ConfigMap, error) {\n\tlog.Printf(\"Creating config map\")\n\tcm := &v1.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"ConfigMap\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: descheduler.Name,\n\t\t\tNamespace: descheduler.Namespace,\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"policy.yaml\": \"apiVersion: \\\"descheduler/v1alpha1\\\"\\nkind: \\\"DeschedulerPolicy\\\"\\nstrategies:\\n \\\"RemoveDuplicates\\\":\\n enabled: true\\n\",\n\t\t},\n\t}\n\terr := controllerutil.SetControllerReference(descheduler, cm, r.scheme)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error setting owner references %v\", err)\n\t}\n\treturn cm, nil\n}", "func NewConfigMapControl(client kubernetes.Interface,\n\tconfigMapInformer coreinformers.ConfigMapInformer) ConfigMapControlInterface {\n\n\tconfigMapControl := &ConfigMapControl{\n\t\tk8client: client,\n\t\tconfigMapLister: configMapInformer.Lister(),\n\t\tconfigMapListerSynced: configMapInformer.Informer().HasSynced,\n\t}\n\n\treturn configMapControl\n}", "func NewConfigMap(cr *databasev1alpha1.PostgreSQL) (*v1.ConfigMap, error) {\n\tlabels := utils.NewLabels(\"postgres\", cr.ObjectMeta.Name, \"postgres\")\n\tabsPath, _ := filepath.Abs(\"scripts/pre-stop.sh\")\n\tpreStop, err := ioutil.ReadFile(absPath)\n\n\tif err != nil {\n\t\tlog.Error(err, \"Unable to read file.\")\n\t\treturn nil, err\n\t}\n\tconfigMap := &v1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.ObjectMeta.Name + \"-postgresql-hooks-scripts\",\n\t\t\tLabels: labels,\n\t\t\tNamespace: cr.Spec.Namespace,\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"pre-stop.sh\": string(preStop),\n\t\t},\n\t}\n\n\treturn configMap, nil\n}", "func (c *controller) ApplyConfigMap(namespace string, configMap *ConfigMap) error {\n\tcm := apicorev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: configMap.Name,\n\t\t\tNamespace: namespace,\n\t\t},\n\t\tData: map[string]string{\n\t\t\tconfigMap.FileName: configMap.Data,\n\t\t},\n\t}\n\t_, err := c.k8sCoreClient.ConfigMaps(namespace).Get(cm.Name, metav1.GetOptions{})\n\tif err == nil {\n\t\t// exists, we update instead\n\t\t_, err = c.k8sCoreClient.ConfigMaps(namespace).Update(&cm)\n\t\treturn err\n\t}\n\t_, err = c.k8sCoreClient.ConfigMaps(namespace).Create(&cm)\n\treturn err\n}", "func addConfigMap(\n\tldr ifc.KvLoader,\n\tk *types.Kustomization,\n\tflags flagsAndArgs, rf *resource.Factory) error {\n\targs := findOrMakeConfigMapArgs(k, flags.Name)\n\tmergeFlagsIntoCmArgs(args, flags)\n\t// Validate by trying to create corev1.configmap.\n\targs.Options = types.MergeGlobalOptionsIntoLocal(\n\t\targs.Options, k.GeneratorOptions)\n\t_, err := rf.MakeConfigMap(ldr, args)\n\treturn err\n}", "func newCmdAddConfigMap(\n\tfSys filesys.FileSystem,\n\tldr ifc.KvLoader,\n\trf *resource.Factory) *cobra.Command {\n\tvar flags flagsAndArgs\n\tcmd := &cobra.Command{\n\t\tUse: \"configmap NAME [--behavior={create|merge|replace}] [--from-file=[key=]source] [--from-literal=key1=value1]\",\n\t\tShort: \"Adds a configmap to the kustomization file\",\n\t\tLong: \"\",\n\t\tExample: `\n\t# Adds a configmap to the kustomization file (with a specified key)\n\tkustomize edit add configmap my-configmap --from-file=my-key=file/path --from-literal=my-literal=12345\n\n\t# Adds a configmap to the kustomization file (key is the filename)\n\tkustomize edit add configmap my-configmap --from-file=file/path\n\n\t# Adds a configmap from env-file\n\tkustomize edit add configmap my-configmap --from-env-file=env/path.env\n\n\t# Adds a configmap from env-file with behavior merge\n\tkustomize edit add configmap my-configmap --behavior=merge --from-env-file=env/path.env\t\n`,\n\t\tRunE: func(_ *cobra.Command, args []string) error {\n\t\t\terr := flags.ExpandFileSource(fSys)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\terr = flags.Validate(args)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Load the kustomization file.\n\t\t\tmf, err := kustfile.NewKustomizationFile(fSys)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tkustomization, err := mf.Read()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Add the flagsAndArgs map to the kustomization file.\n\t\t\terr = addConfigMap(ldr, kustomization, flags, rf)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Write out the kustomization file with added configmap.\n\t\t\treturn mf.Write(kustomization)\n\t\t},\n\t}\n\n\tcmd.Flags().StringSliceVar(\n\t\t&flags.FileSources,\n\t\t\"from-file\",\n\t\t[]string{},\n\t\t\"Key file can be specified using its file path, in which case file basename will be used as configmap \"+\n\t\t\t\"key, or optionally with a key and file path, in which case the given key will be used. Specifying a \"+\n\t\t\t\"directory will iterate each named file in the directory whose basename is a valid configmap key.\")\n\tcmd.Flags().StringArrayVar(\n\t\t&flags.LiteralSources,\n\t\t\"from-literal\",\n\t\t[]string{},\n\t\t\"Specify a key and literal value to insert in configmap (i.e. mykey=somevalue)\")\n\tcmd.Flags().StringVar(\n\t\t&flags.EnvFileSource,\n\t\t\"from-env-file\",\n\t\t\"\",\n\t\t\"Specify the path to a file to read lines of key=val pairs to create a configmap (i.e. a Docker .env file).\")\n\tcmd.Flags().BoolVar(\n\t\t&flags.DisableNameSuffixHash,\n\t\t\"disableNameSuffixHash\",\n\t\tfalse,\n\t\t\"Disable the name suffix for the configmap\")\n\tcmd.Flags().StringVar(\n\t\t&flags.Behavior,\n\t\t\"behavior\",\n\t\t\"\",\n\t\t\"Specify the behavior for config map generation, i.e whether to create a new configmap (the default), \"+\n\t\t\t\"to merge with a previously defined one, or to replace an existing one. Merge and replace should be used only \"+\n\t\t\t\" when overriding an existing configmap defined in a base\")\n\n\treturn cmd\n}", "func createConfigMapFunc(f *framework.Framework, tc *nodeConfigTestCase) error {\n\ttc.configMap.ResourceVersion = \"\"\n\tcm, err := f.ClientSet.CoreV1().ConfigMaps(tc.configMap.Namespace).Create(tc.configMap)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// update tc.configMap's UID and ResourceVersion to match the new ConfigMap, this makes\n\t// sure our derived status checks have up-to-date information\n\ttc.configMap.UID = cm.UID\n\ttc.configMap.ResourceVersion = cm.ResourceVersion\n\treturn nil\n}", "func createConfigMap(hostClientSet internalclientset.Interface, config util.AdminConfig, fedSystemNamespace, federationName, joiningClusterName, targetClusterContext, kubeconfigPath string, dryRun bool) (*api.ConfigMap, error) {\n\tcmDep, err := getCMDeployment(hostClientSet, fedSystemNamespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdomainMap, ok := cmDep.Annotations[util.FedDomainMapKey]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"kube-dns config map data missing from controller manager annotations\")\n\t}\n\n\ttargetFactory := config.ClusterFactory(targetClusterContext, kubeconfigPath)\n\ttargetClientSet, err := targetFactory.ClientSet()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\texistingConfigMap, err := targetClientSet.Core().ConfigMaps(metav1.NamespaceSystem).Get(util.KubeDnsConfigmapName, metav1.GetOptions{})\n\tif isNotFound(err) {\n\t\tnewConfigMap := &api.ConfigMap{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: util.KubeDnsConfigmapName,\n\t\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\tfederation.FederationNameAnnotation: federationName,\n\t\t\t\t\tfederation.ClusterNameAnnotation: joiningClusterName,\n\t\t\t\t},\n\t\t\t},\n\t\t\tData: map[string]string{\n\t\t\t\tutil.FedDomainMapKey: domainMap,\n\t\t\t},\n\t\t}\n\t\tnewConfigMap = populateStubDomainsIfRequired(newConfigMap, cmDep.Annotations)\n\n\t\tif dryRun {\n\t\t\treturn newConfigMap, nil\n\t\t}\n\t\treturn targetClientSet.Core().ConfigMaps(metav1.NamespaceSystem).Create(newConfigMap)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif existingConfigMap.Data == nil {\n\t\texistingConfigMap.Data = make(map[string]string)\n\t}\n\tif _, ok := existingConfigMap.Data[util.FedDomainMapKey]; ok {\n\t\t// Append this federation info\n\t\texistingConfigMap.Data[util.FedDomainMapKey] = appendConfigMapString(existingConfigMap.Data[util.FedDomainMapKey], cmDep.Annotations[util.FedDomainMapKey])\n\n\t} else {\n\t\t// For some reason the configMap exists but this data is empty\n\t\texistingConfigMap.Data[util.FedDomainMapKey] = cmDep.Annotations[util.FedDomainMapKey]\n\t}\n\n\tif dryRun {\n\t\treturn existingConfigMap, nil\n\t}\n\treturn targetClientSet.Core().ConfigMaps(metav1.NamespaceSystem).Update(existingConfigMap)\n}", "func NewNamespacedConfigMapReflector(opts *options.NamespacedOpts) manager.NamespacedReflector {\n\tlocal := opts.LocalFactory.Core().V1().ConfigMaps()\n\tremote := opts.RemoteFactory.Core().V1().ConfigMaps()\n\n\t// Using opts.LocalNamespace for both event handlers so that the object will be put in the same workqueue\n\t// no matter the cluster, hence it will be processed by the handle function in the same way.\n\tlocal.Informer().AddEventHandler(opts.HandlerFactory(generic.NamespacedKeyer(opts.LocalNamespace)))\n\tremote.Informer().AddEventHandler(opts.HandlerFactory(RemoteConfigMapNamespacedKeyer(opts.LocalNamespace)))\n\n\treturn &NamespacedConfigMapReflector{\n\t\tNamespacedReflector: generic.NewNamespacedReflector(opts, ConfigMapReflectorName),\n\t\tlocalConfigMaps: local.Lister().ConfigMaps(opts.LocalNamespace),\n\t\tremoteConfigMaps: remote.Lister().ConfigMaps(opts.RemoteNamespace),\n\t\tremoteConfigMapsClient: opts.RemoteClient.CoreV1().ConfigMaps(opts.RemoteNamespace),\n\t}\n}", "func NewConfigMapScaler(kubeClient kubeclient.Interface, configNamespace, configmapName string,\n\tmaxBulkScaleUpCount int) Webhook {\n\tstopChannel := make(chan struct{})\n\tlister := kubernetes.NewConfigMapListerForNamespace(kubeClient, stopChannel, configNamespace)\n\treturn &ConfigMapScaler{client: kubeClient, namespace: configNamespace, name: configmapName,\n\t\tconfigmapLister: lister.ConfigMaps(configNamespace), maxBulkScaleUpCount: maxBulkScaleUpCount}\n}", "func (ts *tester) createConfigMap() error {\n\tts.cfg.Logger.Info(\"creating config map\")\n\n\tb, err := ioutil.ReadFile(ts.cfg.EKSConfig.KubeConfigPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), time.Minute)\n\t_, err = ts.cfg.K8SClient.KubernetesClientSet().\n\t\tCoreV1().\n\t\tConfigMaps(ts.cfg.EKSConfig.AddOnStresserRemote.Namespace).\n\t\tCreate(\n\t\t\tctx,\n\t\t\t&v1.ConfigMap{\n\t\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t\tKind: \"ConfigMap\",\n\t\t\t\t},\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: stresserKubeConfigConfigMapName,\n\t\t\t\t\tNamespace: ts.cfg.EKSConfig.AddOnStresserRemote.Namespace,\n\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\"name\": stresserKubeConfigConfigMapName,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tData: map[string]string{\n\t\t\t\t\tstresserKubeConfigConfigMapFileName: string(b),\n\t\t\t\t},\n\t\t\t},\n\t\t\tmetav1.CreateOptions{},\n\t\t)\n\tcancel()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tts.cfg.Logger.Info(\"created config map\")\n\tts.cfg.EKSConfig.Sync()\n\treturn nil\n}", "func createCustomConfigMap(c kubernetes.Interface, pluginPath string, subvolgrpInfo map[string]string) {\n\tpath := pluginPath + configMap\n\tcm := v1.ConfigMap{}\n\terr := unmarshal(path, &cm)\n\tExpect(err).Should(BeNil())\n\n\t// get mon list\n\tmons := getMons(rookNamespace, c)\n\t// get clusterIDs\n\tvar clusterID []string\n\tfor key := range subvolgrpInfo {\n\t\tclusterID = append(clusterID, key)\n\t}\n\tconmap := []util.ClusterInfo{\n\t\t{\n\t\t\tClusterID: clusterID[0],\n\t\t\tMonitors: mons,\n\t\t},\n\t\t{\n\t\t\tClusterID: clusterID[1],\n\t\t\tMonitors: mons,\n\t\t}}\n\tfor i := 0; i < len(subvolgrpInfo); i++ {\n\t\tconmap[i].CephFS.SubvolumeGroup = subvolgrpInfo[clusterID[i]]\n\t}\n\tdata, err := json.Marshal(conmap)\n\tExpect(err).Should(BeNil())\n\tcm.Data[\"config.json\"] = string(data)\n\tcm.Namespace = cephCSINamespace\n\t// since a configmap is already created, update the existing configmap\n\t_, updateErr := c.CoreV1().ConfigMaps(cephCSINamespace).Update(context.TODO(), &cm, metav1.UpdateOptions{})\n\tExpect(updateErr).Should(BeNil())\n}", "func newConfigFromMap(cfgMap map[string]string) (*configstore, error) {\n\tdata, ok := cfgMap[configdatakey]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"config data not present\")\n\t}\n\treturn &configstore{data}, nil\n}", "func (c *ContainerConfigMapSpec) Create() (client.Object, error) {\n\tcr := c.qserv\n\ttmplData := generateTemplateData(cr)\n\n\treqLogger := log.WithValues(\"Request.Namespace\", cr.Namespace, \"Request.Name\", cr.Name)\n\n\tname := c.GetName()\n\tnamespace := cr.Namespace\n\n\tlabels := util.GetContainerLabels(c.ContainerName, cr.Name)\n\troot := filepath.Join(\"/\", \"configmap\", string(c.ContainerName), c.Subdir)\n\n\tcm := &v1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tData: scanDir(root, reqLogger, &tmplData),\n\t}\n\treturn cm, nil\n}", "func (configMapTemplateFactory) New(def client.ResourceDefinition, c client.Interface, gc interfaces.GraphContext) interfaces.Resource {\n\tcm := parametrizeResource(def.ConfigMap, gc, configMapParamFields).(*v1.ConfigMap)\n\treturn report.SimpleReporter{BaseResource: newConfigMap{Base: Base{def.Meta}, ConfigMap: cm, Client: c.ConfigMaps()}}\n}", "func NewReplicator(\n\tclusterMetadata cluster.Metadata,\n\tmetadataManagerV2 persistence.MetadataManager,\n\tdomainCache cache.DomainCache,\n\tclientBean client.Bean,\n\tconfig *Config,\n\tclient messaging.Client,\n\tlogger log.Logger,\n\tmetricsClient metrics.Client,\n\thostInfo *membership.HostInfo,\n\tserviceResolver membership.ServiceResolver,\n) *Replicator {\n\n\tlogger = logger.WithTags(tag.ComponentReplicator)\n\treturn &Replicator{\n\t\thostInfo: hostInfo,\n\t\tserviceResolver: serviceResolver,\n\t\tdomainCache: domainCache,\n\t\tclusterMetadata: clusterMetadata,\n\t\tdomainReplicator: NewDomainReplicator(metadataManagerV2, logger),\n\t\tclientBean: clientBean,\n\t\thistoryClient: clientBean.GetHistoryClient(),\n\t\tconfig: config,\n\t\tclient: client,\n\t\tlogger: logger,\n\t\tmetricsClient: metricsClient,\n\t\thistorySerializer: persistence.NewPayloadSerializer(),\n\t}\n}", "func (rcmc *ConfigMapControl) PatchConfigMap(ndb *v1alpha1.Ndb) (*corev1.ConfigMap, error) {\n\n\t// Get the StatefulSet with the name specified in Ndb.spec, fetching from client not cache\n\tcmOrg, err := rcmc.k8client.CoreV1().ConfigMaps(ndb.Namespace).Get(ndb.GetConfigMapName(), metav1.GetOptions{})\n\n\t// If the resource doesn't exist\n\tif errors.IsNotFound(err) {\n\t}\n\n\tcmChg := cmOrg.DeepCopy()\n\tcmChg = resources.InjectUpdateToConfigMapObject(ndb, cmChg)\n\n\tj, err := json.Marshal(cmOrg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tj2, err := json.Marshal(cmChg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpatchBytes, err := strategicpatch.CreateTwoWayMergePatch(j, j2, corev1.ConfigMap{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result *corev1.ConfigMap\n\tupdateErr := wait.ExponentialBackoff(retry.DefaultBackoff, func() (ok bool, err error) {\n\n\t\tresult, err = rcmc.k8client.CoreV1().ConfigMaps(ndb.Namespace).Patch(cmOrg.Name,\n\t\t\ttypes.StrategicMergePatchType,\n\t\t\tpatchBytes)\n\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to patch config map: %v\", err)\n\t\t\treturn false, err\n\t\t}\n\n\t\treturn true, nil\n\t})\n\n\treturn result, updateErr\n}", "func NewConfigMapController(context *cluster.Context, namespace string, ref *metav1.OwnerReference, controller *TopolvmClusterReconciler) *ConfigMapController {\n\treturn &ConfigMapController{\n\t\tcontext: context,\n\t\tnamespace: namespace,\n\t\tref: ref,\n\t\tclusterCtr: controller,\n\t}\n}", "func NewConfigMapReflector(workers uint) manager.Reflector {\n\treturn generic.NewReflector(ConfigMapReflectorName, NewNamespacedConfigMapReflector,\n\t\tgeneric.WithoutFallback(), workers, generic.ConcurrencyModeLeader)\n}", "func NewReplicator(source *mysql.ConnParams, dest *mysql.ConnParams, kafkaParams *KafkaParams, filter *proto.Filter, rl *vo.RateLimit, stats *Stats, incrementalMode bool, serviceAddr string) (*Replicator, error) {\n\tstorageConnParams := config.MysqlConfigToConnParams(&config.Conf.Storage)\n\n\tmysqld := mysqlctl.NewMysqld(source)\n\t// TODO -- use common storage dbclient\n\tvar dbClient *DBClient\n\tif dest != nil {\n\t\tdbClient = NewDBClient(dest, stats)\n\t\terr := dbClient.Connect()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tstorage := NewDBClient(storageConnParams, stats)\n\terr := storage.Connect()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar kafkaWriter *kafka.Writer\n\tif kafkaParams != nil && kafkaParams.Addr != \"\" {\n\t\tkafkaWriter = &kafka.Writer{\n\t\t\tAddr: kafka.TCP(kafkaParams.Addr),\n\t\t\tBalancer: &kafka.LeastBytes{},\n\t\t\tBatchTimeout: 10 * time.Millisecond,\n\t\t\tBatchSize: 100,\n\t\t\tBatchBytes: 104857600,\n\t\t}\n\t}\n\n\tid, err := storage.CreateState(source, dest, kafkaParams, filter, serviceAddr, rl)\n\tif err != nil {\n\t\tlog.Warn(\"Create State error: %s\", err.Error())\n\t\treturn nil, err\n\t}\n\n\tdbnames := make(map[string]struct{})\n\tfor _, rule := range filter.Rules {\n\t\tif _, ok := dbnames[rule.Dbname]; !ok {\n\t\t\tdbnames[rule.Dbname] = struct{}{}\n\t\t}\n\t}\n\n\tvar mode ReplicatorMode\n\tif dbClient != nil && kafkaWriter != nil {\n\t\tmode = ModeBoth\n\t} else if dbClient != nil {\n\t\tmode = ModeOLTP\n\t} else {\n\t\tmode = ModeOLAP\n\t}\n\n\tr := Replicator{\n\t\tId: id,\n\t\tfilter: filter,\n\t\tsourceConnParams: source,\n\t\tdestConnParams: dest,\n\t\tkafkaParams: kafkaParams,\n\t\tdbnames: dbnames,\n\t\tstats: stats,\n\t\tdbClient: dbClient,\n\t\tkafkaWriter: kafkaWriter,\n\t\tstorage: storage,\n\t\tmysqld: mysqld,\n\t\tcfg: config.Conf,\n\t\tincrementalMode: incrementalMode,\n\t\tmode: mode,\n\t\tdone: make(chan struct{}),\n\t}\n\n\tif rl != nil {\n\t\tr.rateLimitCfg = rl\n\t\tr.bucket = ratelimit.NewBucketWithRate(float64(rl.Rate), int64(rl.Capacity))\n\t}\n\n\tctx := context.Background()\n\tpkInfo, tbFieldInfo, err := r.buildPkAndFieldInfoMap(ctx, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr.pkInfoMap = pkInfo\n\tr.tbFieldInfo = tbFieldInfo\n\n\tif !incrementalMode {\n\t\tif err := newCopier(&r).initTablesForCopy(ctx); err != nil {\n\t\t\tr.stats.ErrorCounts.Add([]string{\"Copy\"}, 1)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &r, nil\n}", "func ReconcileConfigMaps(ctx context.Context, namedGetters []NamedConfigMapCreatorGetter, namespace string, client ctrlruntimeclient.Client, objectModifiers ...ObjectModifier) error {\n\tfor _, get := range namedGetters {\n\t\tname, create := get()\n\t\tcreateObject := ConfigMapObjectWrapper(create)\n\t\tcreateObject = createWithNamespace(createObject, namespace)\n\t\tcreateObject = createWithName(createObject, name)\n\n\t\tfor _, objectModifier := range objectModifiers {\n\t\t\tcreateObject = objectModifier(createObject)\n\t\t}\n\n\t\tif err := EnsureNamedObject(ctx, types.NamespacedName{Namespace: namespace, Name: name}, createObject, client, &corev1.ConfigMap{}, false); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to ensure ConfigMap %s/%s: %v\", namespace, name, err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func CreateConfigMap(client kubernetes.Interface, namespace string, configmapName string, data string) (core_v1.ConfigMapInterface, error) {\n\tlogrus.Infof(\"Creating configmap\")\n\tconfigmapClient := client.CoreV1().ConfigMaps(namespace)\n\t_, err := configmapClient.Create(GetConfigmap(namespace, configmapName, data))\n\ttime.Sleep(10 * time.Second)\n\treturn configmapClient, err\n}", "func newDashboardGrafanaReconciler(\n\tmgr manager.Manager,\n\tlog *zap.SugaredLogger,\n\tnumWorkers int,\n\tworkerName string,\n\tversions kubermatic.Versions,\n\tdashboardGrafanaController *dashboardGrafanaController,\n) error {\n\tclient := mgr.GetClient()\n\n\treconciler := &dashboardGrafanaReconciler{\n\t\tClient: client,\n\n\t\tlog: log,\n\t\tworkerName: workerName,\n\t\trecorder: mgr.GetEventRecorderFor(ControllerName),\n\t\tversions: versions,\n\t\tdashboardGrafanaController: dashboardGrafanaController,\n\t}\n\n\tctrlOptions := controller.Options{\n\t\tReconciler: reconciler,\n\t\tMaxConcurrentReconciles: numWorkers,\n\t}\n\tc, err := controller.New(ControllerName, mgr, ctrlOptions)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tenqueueGrafanaConfigMap := handler.EnqueueRequestsFromMapFunc(func(a ctrlruntimeclient.Object) []reconcile.Request {\n\t\tif !strings.HasPrefix(a.GetName(), grafanaDashboardsConfigmapNamePrefix) {\n\t\t\treturn []reconcile.Request{}\n\t\t}\n\t\treturn []reconcile.Request{{NamespacedName: types.NamespacedName{Name: a.GetName(), Namespace: a.GetNamespace()}}}\n\t})\n\n\tif err := c.Watch(&source.Kind{Type: &corev1.ConfigMap{}}, enqueueGrafanaConfigMap, predicateutil.ByNamespace(dashboardGrafanaController.mlaNamespace)); err != nil {\n\t\treturn fmt.Errorf(\"failed to watch ConfigMap: %w\", err)\n\t}\n\n\treturn err\n}", "func InjectConfigMap(c kclientset.Interface, ns string, vars map[string]interface{}, config kapiv1.Pod) string {\n\tconfigMapName := ns + \"-configmap\"\n\tfreshConfigVars := convertVariablesToMap(vars)\n\tdirtyConfigVars := getClusterData(c, freshConfigVars)\n\tconfigMap := newConfigMap(ns, configMapName, dirtyConfigVars)\n\tframework.Logf(\"Creating configMap %v in namespace %v\", configMap.Name, ns)\n\tvar err error\n\tif configMap, err = c.CoreV1().ConfigMaps(ns).Create(configMap); err != nil {\n\t\tframework.Failf(\"Unable to create test configMap %s: %v\", configMap.Name, err)\n\t}\n\n\tfor i, envVar := range config.Spec.Containers[0].Env {\n\t\tif _, ok := dirtyConfigVars[envVar.Name]; ok {\n\t\t\tframework.Logf(\"Found match to replace: %+v\", envVar)\n\t\t\tconfig.Spec.Containers[0].Env[i] = kapiv1.EnvVar{\n\t\t\t\tName: envVar.Name,\n\t\t\t\tValueFrom: &kapiv1.EnvVarSource{\n\t\t\t\t\tConfigMapKeyRef: &kapiv1.ConfigMapKeySelector{\n\t\t\t\t\t\tLocalObjectReference: kapiv1.LocalObjectReference{\n\t\t\t\t\t\t\tName: configMapName,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tKey: envVar.Name,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t} else {\n\t\t\tframework.Logf(\"Environment variable %v is not defined in Pod file, skipping.\", envVar.Name)\n\t\t}\n\t}\n\treturn configMapName\n}", "func NewReplicator(client kubernetes.Interface, resyncPeriod time.Duration, allowAll bool) common.Replicator {\n\trepl := Replicator{\n\t\tGenericReplicator: common.NewGenericReplicator(common.ReplicatorConfig{\n\t\t\tKind: \"Secret\",\n\t\t\tObjType: &v1.Secret{},\n\t\t\tAllowAll: allowAll,\n\t\t\tResyncPeriod: resyncPeriod,\n\t\t\tClient: client,\n\t\t\tListFunc: func(lo metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\treturn client.CoreV1().Secrets(\"\").List(context.TODO(), lo)\n\t\t\t},\n\t\t\tWatchFunc: func(lo metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\treturn client.CoreV1().Secrets(\"\").Watch(context.TODO(), lo)\n\t\t\t},\n\t\t}),\n\t}\n\trepl.UpdateFuncs = common.UpdateFuncs{\n\t\tReplicateDataFrom: repl.ReplicateDataFrom,\n\t\tReplicateObjectTo: repl.ReplicateObjectTo,\n\t\tPatchDeleteDependent: repl.PatchDeleteDependent,\n\t\tDeleteReplicatedResource: repl.DeleteReplicatedResource,\n\t}\n\n\treturn &repl\n}", "func (regionEnv *RegionEnv) createConfigMap(deploymentName string) bool {\n\tgvk := schema.GroupVersionKind{Version: \"v1\", Kind: \"ConfigMap\"}\n\tmapping, _ := regionEnv.Mapper.RESTMapping(gvk.GroupKind(), gvk.Version)\n\tdynamicInterface := regionEnv.DynamicClient.Resource(mapping.Resource).Namespace(regionEnv.Cfg.Namespace)\n\tdata := make(map[string]interface{})\n\tfor _, envVar := range regionEnv.Vars {\n\t\tdata[envVar.Name] = envVar.Value\n\t}\n\t// Use Kubernetes labels to easily find and delete old configmaps.\n\tconfigMap := unstructured.Unstructured{\n\t\tObject: map[string]interface{}{\n\t\t\t\"apiVersion\": \"v1\",\n\t\t\t\"kind\": \"ConfigMap\",\n\t\t\t\"metadata\": map[string]interface{}{\n\t\t\t\t\"name\": fmt.Sprintf(\"%s-%s\", deploymentName, regionEnv.Cfg.SHA),\n\t\t\t\t\"labels\": map[string]interface{}{\n\t\t\t\t\t\"app\": deploymentName,\n\t\t\t\t\t\"sha\": regionEnv.Cfg.SHA,\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"data\": data,\n\t\t},\n\t}\n\n\t_, configMapGetErr := dynamicInterface.Get(regionEnv.Context, configMap.GetName(), metav1.GetOptions{})\n\n\t// ConfigMap may already exist if this is a rollback.\n\tif configMapGetErr == nil {\n\t\tregionEnv.Logger.Info(\"Config Map already exists\")\n\t\treturn true\n\t}\n\tif !errors.IsNotFound(configMapGetErr) {\n\t\tregionEnv.errf(\"Unexpected ConfigMap get error\\n%s\", configMapGetErr)\n\t\treturn false\n\t}\n\n\tconfigMapUploaded, configMapErr := dynamicInterface.Create(regionEnv.Context, &configMap,\n\t\tmetav1.CreateOptions{FieldManager: \"porter2k8s\"})\n\tif configMapErr != nil {\n\t\tregionEnv.Errors = append(regionEnv.Errors, configMapErr)\n\t\treturn false\n\t}\n\tregionEnv.Logger.Infof(\"Created Config Map\\n%+v\", configMapUploaded)\n\n\treturn true\n}", "func (r *HookRunner) configMap() (mp *core.ConfigMap, err error) {\n\tworkload, err := r.workload()\n\tif err != nil {\n\t\treturn\n\t}\n\tplaybook, err := r.playbook()\n\tif err != nil {\n\t\treturn\n\t}\n\tplan, err := r.plan()\n\tif err != nil {\n\t\treturn\n\t}\n\tmp = &core.ConfigMap{\n\t\tObjectMeta: meta.ObjectMeta{\n\t\t\tLabels: r.labels(),\n\t\t\tNamespace: r.Plan.Namespace,\n\t\t\tGenerateName: strings.ToLower(\n\t\t\t\tstrings.Join([]string{\n\t\t\t\t\tr.Plan.Name,\n\t\t\t\t\tr.vm.ID,\n\t\t\t\t\tr.vm.Phase},\n\t\t\t\t\t\"-\")) + \"-\",\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"workload.yml\": workload,\n\t\t\t\"playbook.yml\": playbook,\n\t\t\t\"plan.yml\": plan,\n\t\t},\n\t}\n\n\treturn\n}", "func newReconciler(mgr manager.Manager) reconcile.Reconciler {\n\treturn &ReconcileDeploymentConfig{Client: mgr.GetClient(), scheme: mgr.GetScheme()}\n}", "func (k *MockK8sClient) CreateConfigMap(namespace, configmap string, params map[string]string) (*v1.ConfigMap, error) {\n\tif k.CreateConfigMapFn != nil {\n\t\treturn k.CreateConfigMapFn(namespace, configmap, params)\n\t}\n\treturn nil, nil\n}", "func (c newConfigMap) Create() error {\n\tif err := checkExistence(c); err != nil {\n\t\tlog.Println(\"Creating\", c.Key())\n\t\tc.ConfigMap, err = c.Client.Create(c.ConfigMap)\n\t\treturn err\n\t}\n\treturn nil\n}", "func GenerateConfigMaps(instance *sfv1alpha1.SplunkForwarder, namespacedName types.NamespacedName, clusterid string) []*corev1.ConfigMap {\n\tret := []*corev1.ConfigMap{}\n\n\tmetadataCM := &corev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"osd-monitored-logs-metadata\",\n\t\t\tNamespace: namespacedName.Namespace,\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"app\": namespacedName.Name,\n\t\t\t},\n\t\t\tAnnotations: map[string]string{\n\t\t\t\t\"genVersion\": strconv.FormatInt(instance.Generation, 10),\n\t\t\t},\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"local.meta\": `\n[]\naccess = read : [ * ], write : [ admin ]\nexport = system\n`,\n\t\t},\n\t}\n\tret = append(ret, metadataCM)\n\n\tinputsStr := \"\"\n\n\tfor _, input := range instance.Spec.SplunkInputs {\n\t\t// No path passed in, skip it\n\t\tif input.Path == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tinputsStr += \"[monitor://\" + input.Path + \"]\\n\"\n\t\tif input.SourceType != \"\" {\n\t\t\tinputsStr += \"sourcetype = \" + input.SourceType + \"\\n\"\n\t\t} else {\n\t\t\tinputsStr += \"sourcetype = _json\\n\"\n\t\t}\n\n\t\tif input.Index != \"\" {\n\t\t\tinputsStr += \"index = \" + input.Index + \"\\n\"\n\t\t} else {\n\t\t\tinputsStr += \"index = main\\n\"\n\t\t}\n\n\t\tif input.WhiteList != \"\" {\n\t\t\tinputsStr += \"whitelist = \" + input.WhiteList + \"\\n\"\n\t\t}\n\n\t\tif input.BlackList != \"\" {\n\t\t\tinputsStr += \"blacklist = \" + input.BlackList + \"\\n\"\n\t\t}\n\n\t\tif clusterid != \"\" {\n\t\t\tinputsStr += \"_meta = clusterid::\" + clusterid + \"\\n\"\n\t\t}\n\n\t\tinputsStr += \"disabled = false\\n\"\n\t\tinputsStr += \"\\n\"\n\t}\n\n\tlocalCM := &corev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"osd-monitored-logs-local\",\n\t\t\tNamespace: namespacedName.Namespace,\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"app\": namespacedName.Name,\n\t\t\t},\n\t\t\tAnnotations: map[string]string{\n\t\t\t\t\"genVersion\": strconv.FormatInt(instance.Generation, 10),\n\t\t\t},\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"app.conf\": `\n[install]\nstate = enabled\n\n[package]\ncheck_for_updates = false\n\n[ui]\nis_visible = false\nis_manageable = false\n`,\n\t\t\t\"inputs.conf\": inputsStr,\n\t\t},\n\t}\n\n\tret = append(ret, localCM)\n\n\treturn ret\n}", "func ReconcileConfigMap(reqLogger logr.Logger, c client.Client, cm *corev1.ConfigMap) error {\n\tif err := SetCreationSpecAnnotation(&cm.ObjectMeta, cm); err != nil {\n\t\treturn err\n\t}\n\n\tfoundCM := &corev1.ConfigMap{}\n\tif err := c.Get(context.TODO(), types.NamespacedName{Name: cm.Name, Namespace: cm.Namespace}, foundCM); err != nil {\n\t\t// Return API error\n\t\tif client.IgnoreNotFound(err) != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Create the configmap\n\t\treqLogger.Info(\"Creating new configmap\", \"ConfigMap.Name\", cm.Name, \"ConfigMap.Namespace\", cm.Namespace)\n\t\tif err := c.Create(context.TODO(), cm); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\t// Check the found configmap data\n\tif !CreationSpecsEqual(cm.ObjectMeta, foundCM.ObjectMeta) {\n\t\t// We need to update the configmap\n\t\treqLogger.Info(\"Configmap data has changed, updating\", \"ConfigMap.Name\", cm.Name, \"ConfigMap.Namespace\", cm.Namespace)\n\t\tfoundCM.Data = cm.Data\n\t\tif err := c.Update(context.TODO(), foundCM); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func setupConfigMapReconciler(mgr manager.Manager, log logr.Logger) error {\n\n\tlog = log.WithName(\"secret-reconciler\")\n\n\terr := ctrl.NewControllerManagedBy(mgr).\n\t\tFor(&corev1.Secret{}, builder.OnlyMetadata).\n\t\tComplete(reconcile.Func(func(_ context.Context, r reconcile.Request) (reconcile.Result, error) {\n\t\t\tlog := log\n\t\t\tlog = log.WithValues(\"secret\", r.NamespacedName)\n\t\t\tlog.Info(\"start\")\n\t\t\tdefer log.Info(\"end\")\n\n\t\t\tsecret := &corev1.Secret{}\n\t\t\terr := mgr.GetClient().Get(context.Background(), r.NamespacedName, secret)\n\t\t\tswitch {\n\t\t\t// If the secret doesn't exist, the reconciliation is done.\n\t\t\tcase apierrors.IsNotFound(err):\n\t\t\t\tlog.Info(\"secret not found\")\n\t\t\t\treturn reconcile.Result{}, nil\n\t\t\tcase err != nil:\n\t\t\t\treturn reconcile.Result{}, fmt.Errorf(\"looking for Secret %s: %w\", r.NamespacedName, err)\n\t\t\t}\n\n\t\t\tif secret.Annotations != nil && secret.Annotations[\"secret-found\"] == \"yes\" {\n\t\t\t\treturn reconcile.Result{}, nil\n\t\t\t}\n\n\t\t\tif secret.Annotations == nil {\n\t\t\t\tsecret.Annotations = make(map[string]string)\n\t\t\t}\n\t\t\tsecret.Annotations[\"secret-found\"] = \"yes\"\n\t\t\terr = mgr.GetClient().Update(context.Background(), secret)\n\t\t\tif err != nil {\n\t\t\t\treturn reconcile.Result{}, err\n\t\t\t}\n\n\t\t\treturn reconcile.Result{}, nil\n\t\t}))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"while completing new controller: %w\", err)\n\t}\n\n\treturn nil\n}", "func (c client) CreateConfigMap(cm corev1.ConfigMap) error {\n\treturn c.Create(context.TODO(), &cm)\n}", "func FromConfigMap(ctx context.Context, clientSet kubernetes.Interface, namespace string) (*Config, error) {\n\tconfig, err := clientSet.CoreV1().ConfigMaps(namespace).Get(ctx, configMapName, metav1.GetOptions{})\n\tif err != nil {\n\t\tif k8errors.IsNotFound(err) {\n\t\t\tglog.Infof(\"cannot find launcher configmap: name=%q namespace=%q, will use default config\", configMapName, namespace)\n\t\t\t// LauncherConfig is optional, so ignore not found error.\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn &Config{data: config.Data}, nil\n}", "func CopyConfigMap(client kubernetes.Interface, srcNamespace, srcName, destNamespace, destName, destKey string) (string, error) {\n\tsrc, err := client.CoreV1().ConfigMaps(srcNamespace).Get(context.TODO(), srcName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif destName == \"\" {\n\t\tdestName = srcName + \"-\" + strings.ToLower(util.RandAlphaNum(8))\n\t}\n\n\tdst := &v1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: destName,\n\t\t},\n\t\tData: src.Data,\n\t}\n\n\t// Use this when overriding the default key when copying the configmap.\n\tif destKey != \"\" {\n\t\tdata := make(map[string]string, 0)\n\t\tfor _, v := range src.Data {\n\t\t\tdata[destKey] = v\n\t\t}\n\t\tdst.Data = data\n\t}\n\n\terr = client.CoreV1().ConfigMaps(destNamespace).Delete(context.TODO(), destName, metav1.DeleteOptions{})\n\tif err != nil && !errors.IsNotFound(err) {\n\t\treturn \"\", err\n\t}\n\n\t_, err = client.CoreV1().ConfigMaps(destNamespace).Create(context.TODO(), dst, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn destName, nil\n}", "func NewConfigMapObject(component *v3.Component, app *v3.Application) corev1.ConfigMap {\n\tvar stringmap map[string]string = make(map[string]string)\n\tfor _, i := range component.Containers {\n\t\tfor _, j := range i.Config {\n\t\t\tif j.FileName == \"\" {\n\t\t\t\tlog.Errorf(\"%s-%s's configmap configuration's filename is nil,please check configration\", component.Name, component.Version)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstringmap[j.FileName] = j.Value\n\t\t}\n\t}\n\tconfigmap := corev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tOwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(app, v3.SchemeGroupVersion.WithKind(\"Application\"))},\n\t\t\tNamespace: app.Namespace,\n\t\t\tName: app.Name + \"-\" + component.Name + \"-\" + component.Version + \"-\" + \"configmap\",\n\t\t},\n\t\tData: stringmap,\n\t}\n\treturn configmap\n}", "func CreateConfigMap(name string) *corev1.ConfigMap {\n\treturn &corev1.ConfigMap{\n\t\tTypeMeta: genTypeMeta(gvk.ConfigMap),\n\t\tObjectMeta: genObjectMeta(name, true),\n\t}\n}", "func (c *DotQservConfigMapSpec) Create() (client.Object, error) {\n\tcr := c.qserv\n\ttmplData := generateTemplateData(cr)\n\n\treqLogger := log.WithValues(\"Request.Namespace\", cr.Namespace, \"Request.Name\", cr.Name)\n\n\tname := c.GetName()\n\tnamespace := cr.Namespace\n\n\tlabels := util.GetComponentLabels(constants.Czar, cr.Name)\n\troot := filepath.Join(\"/\", \"configmap\", \"dot-qserv\")\n\n\tcm := &v1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tData: scanDir(root, reqLogger, &tmplData),\n\t}\n\n\treturn cm, nil\n}", "func recreateConfigMapFunc(f *framework.Framework, tc *nodeConfigTestCase) error {\n\t// need to ignore NotFound error, since there could be cases where delete\n\t// fails during a retry because the delete in a previous attempt succeeded,\n\t// before some other error occurred.\n\terr := deleteConfigMapFunc(f, tc)\n\tif err != nil && !apierrors.IsNotFound(err) {\n\t\treturn err\n\t}\n\treturn createConfigMapFunc(f, tc)\n}", "func createConfigMapWithNamespace(configMapName string, filePath string, namespace string, operation string) error {\n\tcmd := exec.Command(\n\t\tk8sUtils.Kubectl,\n\t\toperation,\n\t\t\"configmap\",\n\t\tconfigMapName,\n\t\t\"--from-file\",\n\t\tfilePath,\n\t\t\"-n\", namespace,\n\t)\n\t//print kubernetes error commands\n\tvar errBuf, outBuf bytes.Buffer\n\tcmd.Stderr = io.MultiWriter(os.Stderr, &errBuf)\n\tcmd.Stdout = io.MultiWriter(os.Stdout, &outBuf)\n\terr := cmd.Run()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func populateConfigOverrideConfigMap(clusterdContext *clusterd.Context, namespace string, ownerInfo *k8sutil.OwnerInfo, clusterMetadata metav1.ObjectMeta) error {\n\tctx := context.TODO()\n\n\texistingCM, err := clusterdContext.Clientset.CoreV1().ConfigMaps(namespace).Get(ctx, k8sutil.ConfigOverrideName, metav1.GetOptions{})\n\tif err != nil {\n\t\tif !kerrors.IsNotFound(err) {\n\t\t\tlogger.Warningf(\"failed to get cm %q to check labels and annotations\", k8sutil.ConfigOverrideName)\n\t\t\treturn nil\n\t\t}\n\n\t\tlabels := map[string]string{}\n\t\tannotations := map[string]string{}\n\t\tinitRequiredMetadata(clusterMetadata, labels, annotations)\n\n\t\t// Create the configmap since it doesn't exist yet\n\t\tplaceholderConfig := map[string]string{\n\t\t\tk8sutil.ConfigOverrideVal: \"\",\n\t\t}\n\t\tcm := &v1.ConfigMap{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: k8sutil.ConfigOverrideName,\n\t\t\t\tNamespace: namespace,\n\t\t\t\tLabels: labels,\n\t\t\t\tAnnotations: annotations,\n\t\t\t},\n\t\t\tData: placeholderConfig,\n\t\t}\n\n\t\terr := ownerInfo.SetControllerReference(cm)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to set owner reference to override configmap %q\", cm.Name)\n\t\t}\n\t\t_, err = clusterdContext.Clientset.CoreV1().ConfigMaps(namespace).Create(ctx, cm, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to create override configmap %s\", namespace)\n\t\t}\n\t\tlogger.Infof(\"created placeholder configmap for ceph overrides %q\", cm.Name)\n\t\treturn nil\n\t}\n\n\t// Ensure the annotations and labels are initialized\n\tif existingCM.Annotations == nil {\n\t\texistingCM.Annotations = map[string]string{}\n\t}\n\tif existingCM.Labels == nil {\n\t\texistingCM.Labels = map[string]string{}\n\t}\n\n\t// Add recommended labels and annotations to the existing configmap if it doesn't have any yet\n\tupdateRequired := initRequiredMetadata(clusterMetadata, existingCM.Labels, existingCM.Annotations)\n\tif updateRequired {\n\t\t_, err = clusterdContext.Clientset.CoreV1().ConfigMaps(namespace).Update(ctx, existingCM, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\tlogger.Warningf(\"failed to add recommended labels and annotations to configmap %q. %v\", existingCM.Name, err)\n\t\t} else {\n\t\t\tlogger.Infof(\"added expected labels and annotations to configmap %q\", existingCM.Name)\n\t\t}\n\t}\n\treturn nil\n}", "func (c *SQLConfigMapSpec) Create() (client.Object, error) {\n\tcr := c.qserv\n\ttmplData := generateTemplateData(cr)\n\n\treqLogger := log.WithValues(\"Request.Namespace\", cr.Namespace, \"Request.Name\", cr.Name)\n\t// reqLogger.Info(\"XXXXX %s\", \"tmplData\", tmplData)\n\n\tname := c.GetName()\n\tnamespace := cr.Namespace\n\n\tlabels := util.GetComponentLabels(c.Database, cr.Name)\n\troot := filepath.Join(\"/\", \"configmap\", \"initdb\", \"sql\", string(c.Database))\n\n\tconfigmap := &v1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tData: scanDir(root, reqLogger, &tmplData),\n\t}\n\treturn configmap, nil\n}", "func InjectConfigMap(podSpec *corev1.PodSpec, containerIdx int, configMapRef corev1.LocalObjectReference) string {\n\tconst (\n\t\t// cmVol is a configmap volume (with symlinks)\n\t\tcmVolName = \"cbi-cmcontext-tmp\"\n\t\tcmVolMountPath = \"/cbi-cmcontext-tmp\"\n\t\t// vol is an emptyDir volume (without symlinks)\n\t\tvolName = \"cbi-cmcontext\"\n\t\tvolMountPath = \"/cbi-cmcontext\"\n\t\tvolContextSubpath = \"context\"\n\t\t// initContainer is used for converting cmVol to vol so as to eliminate symlinks\n\t\tinitContainerName = \"cbi-cmcontext-init\"\n\t\tinitContainerImage = \"busybox\"\n\t)\n\tcontextPath := filepath.Join(volMountPath, volContextSubpath)\n\tcmVol := corev1.Volume{\n\t\tName: cmVolName,\n\t\tVolumeSource: corev1.VolumeSource{\n\t\t\tConfigMap: &corev1.ConfigMapVolumeSource{\n\t\t\t\tLocalObjectReference: configMapRef,\n\t\t\t},\n\t\t},\n\t}\n\tvol := corev1.Volume{\n\t\tName: volName,\n\t\tVolumeSource: corev1.VolumeSource{\n\t\t\tEmptyDir: &corev1.EmptyDirVolumeSource{},\n\t\t},\n\t}\n\tpodSpec.Volumes = append(podSpec.Volumes, cmVol, vol)\n\n\tinitContainer := corev1.Container{\n\t\tName: initContainerName,\n\t\tImage: initContainerImage,\n\t\tCommand: []string{\"cp\", \"-rL\", cmVolMountPath, contextPath},\n\t\tVolumeMounts: []corev1.VolumeMount{\n\t\t\t{\n\t\t\t\tName: volName,\n\t\t\t\tMountPath: volMountPath,\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: cmVolName,\n\t\t\t\tMountPath: cmVolMountPath,\n\t\t\t},\n\t\t},\n\t}\n\tpodSpec.InitContainers = append(podSpec.InitContainers, initContainer)\n\n\tpodSpec.Containers[containerIdx].VolumeMounts = append(podSpec.Containers[containerIdx].VolumeMounts,\n\t\tcorev1.VolumeMount{\n\t\t\tName: volName,\n\t\t\tMountPath: volMountPath,\n\t\t},\n\t)\n\treturn contextPath\n}", "func replaceClusterMembersConfigMap(ctx context.Context, centralClusterClient kubernetes.Interface, flags flags) error {\n\tmembers := corev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: defaultOperatorConfigMapName,\n\t\t\tNamespace: flags.centralClusterNamespace,\n\t\t\tLabels: multiClusterLabels(),\n\t\t},\n\t\tData: map[string]string{},\n\t}\n\n\taddToSet(flags.memberClusters, &members)\n\n\tfmt.Printf(\"Creating Member list Configmap %s/%s in cluster %s\\n\", flags.centralClusterNamespace, defaultOperatorConfigMapName, flags.centralCluster)\n\t_, err := centralClusterClient.CoreV1().ConfigMaps(flags.centralClusterNamespace).Create(ctx, &members, metav1.CreateOptions{})\n\n\tif err != nil && !errors.IsAlreadyExists(err) {\n\t\treturn xerrors.Errorf(\"failed creating secret: %w\", err)\n\t}\n\n\tif errors.IsAlreadyExists(err) {\n\t\tif _, err := centralClusterClient.CoreV1().ConfigMaps(flags.centralClusterNamespace).Update(ctx, &members, metav1.UpdateOptions{}); err != nil {\n\t\t\treturn xerrors.Errorf(\"error creating configmap: %w\", err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func NewConfigMapChecker(period time.Duration, labelSelectors, includeConfigMapsDataGlobs, excludeConfigMapsDataGlobs, annotationSelectors, namespaces []string, kubeconfigPath string, e *exporters.ConfigMapExporter) *PeriodicConfigMapChecker {\n\treturn &PeriodicConfigMapChecker{\n\t\tperiod: period,\n\t\tlabelSelectors: labelSelectors,\n\t\tannotationSelectors: annotationSelectors,\n\t\tnamespaces: namespaces,\n\t\tkubeconfigPath: kubeconfigPath,\n\t\texporter: e,\n\t\tincludeConfigMapsDataGlobs: includeConfigMapsDataGlobs,\n\t\texcludeConfigMapsDataGlobs: excludeConfigMapsDataGlobs,\n\t}\n}", "func New(kubeconfig *rest.Config, opa opa.Client, matcher func(*v1.ConfigMap) (bool, bool)) *Sync {\n\tcpy := *kubeconfig\n\tcpy.GroupVersion = &schema.GroupVersion{\n\t\tVersion: \"v1\",\n\t}\n\tcpy.APIPath = \"/api\"\n\tcpy.ContentType = runtime.ContentTypeJSON\n\tscheme := runtime.NewScheme()\n\tcpy.NegotiatedSerializer = serializer.WithoutConversionCodecFactory{CodecFactory: serializer.NewCodecFactory(scheme)}\n\tbuilder := runtime.NewSchemeBuilder(func(scheme *runtime.Scheme) error {\n\t\tscheme.AddKnownTypes(\n\t\t\t*cpy.GroupVersion,\n\t\t\t&metav1.ListOptions{},\n\t\t\t&metav1.Status{},\n\t\t\t&v1.ConfigMapList{},\n\t\t\t&v1.ConfigMap{})\n\t\treturn nil\n\t})\n\tbuilder.AddToScheme(scheme)\n\treturn &Sync{\n\t\tkubeconfig: &cpy,\n\t\topa: opa,\n\t\tmatcher: matcher,\n\t}\n}", "func (m *MockClientInterface) CreateConfigMap(arg0 *v10.ConfigMap) (*v10.ConfigMap, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateConfigMap\", arg0)\n\tret0, _ := ret[0].(*v10.ConfigMap)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockKubernetesClient) CreateConfigMap(namespace string, configMap *v1.ConfigMap, dryrun bool) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateConfigMap\", namespace, configMap, dryrun)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (c *Vrouter) CreateConfigMap(configMapName string,\n\tclient client.Client,\n\tscheme *runtime.Scheme,\n\trequest reconcile.Request) (*corev1.ConfigMap, error) {\n\treturn CreateConfigMap(configMapName,\n\t\tclient,\n\t\tscheme,\n\t\trequest,\n\t\t\"vrouter\",\n\t\tc)\n}", "func ApplyConfigMapFromFile(clientset *kubernetes.Clientset, namespace string, configmap *corev1.ConfigMap, path string) error {\n\tlog.Printf(\"📦 Reading contents of %s\", path)\n\t_, filename := filepath.Split(path)\n\tfileContents, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfigMapData := make(map[string]string)\n\tconfigMapData[filename] = string(fileContents)\n\tconfigmap.Data = configMapData\n\t// Check if deployment exists\n\tdeploymentExists, err := configMapExists(clientset, namespace, configmap.Name)\n\tif deploymentExists {\n\t\tlog.Printf(\"📦 Found existing deployment. Updating %s.\", configmap.Name)\n\t\t_, err = clientset.CoreV1().ConfigMaps(namespace).Update(configmap)\n\t\treturn err\n\t}\n\t_, err = clientset.CoreV1().ConfigMaps(namespace).Create(configmap)\n\treturn err\n}", "func NewConfigFromMap(data map[string]string) (*RedisConfig, error) {\n\trc := defaultConfig()\n\tif numC, ok := data[redisConfigKey]; ok {\n\t\trc.NumConsumers = numC\n\t}\n\treturn rc, nil\n}", "func CreateOrUpdateConfigMaps(dpl *v1alpha1.Elasticsearch) (err error) {\n\tkibanaIndexMode, err := kibanaIndexMode(\"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdataNodeCount := int((getDataCount(dpl)))\n\tmasterNodeCount := int((getMasterCount(dpl)))\n\n\tconfigmap := newConfigMap(\n\t\tdpl.Name,\n\t\tdpl.Namespace,\n\t\tdpl.Labels,\n\t\tkibanaIndexMode,\n\t\tesUnicastHost(dpl.Name, dpl.Namespace),\n\t\trootLogger(),\n\t\tstrconv.Itoa(masterNodeCount/2+1),\n\t\tstrconv.Itoa(dataNodeCount),\n\t\tstrconv.Itoa(dataNodeCount),\n\t\tstrconv.Itoa(calculateReplicaCount(dpl)),\n\t)\n\n\taddOwnerRefToObject(configmap, getOwnerRef(dpl))\n\n\terr = sdk.Create(configmap)\n\tif err != nil {\n\t\tif !errors.IsAlreadyExists(err) {\n\t\t\treturn fmt.Errorf(\"Failure constructing Elasticsearch ConfigMap: %v\", err)\n\t\t}\n\n\t\tif errors.IsAlreadyExists(err) {\n\t\t\t// Get existing configMap to check if it is same as what we want\n\t\t\tcurrent := configmap.DeepCopy()\n\t\t\terr = sdk.Get(current)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Unable to get Elasticsearch cluster configMap: %v\", err)\n\t\t\t}\n\n\t\t\tif configMapContentChanged(current, configmap) {\n\t\t\t\t// Cluster settings has changed, make sure it doesnt go unnoticed\n\t\t\t\tif err := updateConditionWithRetry(dpl, v1.ConditionTrue, updateUpdatingSettingsCondition); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\treturn retry.RetryOnConflict(retry.DefaultRetry, func() error {\n\t\t\t\t\tif getErr := sdk.Get(current); getErr != nil {\n\t\t\t\t\t\tlogrus.Debugf(\"Could not get Elasticsearch configmap %v: %v\", configmap.Name, getErr)\n\t\t\t\t\t\treturn getErr\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrent.Data = configmap.Data\n\t\t\t\t\tif updateErr := sdk.Update(current); updateErr != nil {\n\t\t\t\t\t\tlogrus.Debugf(\"Failed to update Elasticsearch configmap %v: %v\", configmap.Name, updateErr)\n\t\t\t\t\t\treturn updateErr\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}\n\t}\n\n\treturn nil\n}", "func NewConfigMapFactory(l ifc.Loader) *ConfigMapFactory {\n\treturn &ConfigMapFactory{ldr: l}\n}", "func (c existingConfigMap) Create() error {\n\treturn createExistingResource(c)\n}", "func (r *ConjurConfigReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n\t_ = r.Log.WithValues(\"conjurconfig\", req.NamespacedName)\n\n\t// Fetch the ConjurConfig instance\n\tconjurConfig := &conjurv1alpha1.ConjurConfig{}\n\terr := r.Get(ctx, req.NamespacedName, conjurConfig)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// Request object not found, could have been deleted after reconcile request.\n\t\t\t// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.\n\t\t\t// Return and don't requeue\n\t\t\tlog.Info(\"ConjurConfig resource not found. Ignoring since object must be deleted\")\n\t\t\treturn ctrl.Result{}, nil\n\t\t}\n\t\t// Error reading the object - requeue the request.\n\t\tlog.Error(err, \"Failed to get ConjurConfig\")\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t// Check if the ConfigMap already exists, if not create a new one\n\tfound := &v1.ConfigMap{}\n\tcmName := getConfigMapName(conjurConfig)\n\tcmNamespace := conjurConfig.Namespace\n\terr = r.Get(ctx, types.NamespacedName{Name: cmName, Namespace: cmNamespace}, found)\n\tif err != nil && errors.IsNotFound(err) {\n\t\t// Define a new ConfigMap\n\t\tcm := r.configMapForConjurConfig(conjurConfig, cmName)\n\t\tlog.Info(\"Creating a new ConfigMap, \", \"ConfigMap.Name: \", cmName,\n\t\t\t\"ConfigMap.Namespace: \", cmNamespace)\n\t\terr = r.Create(ctx, cm)\n\t\tif err != nil {\n\t\t\tlog.Error(err, \"Failed to create new ConfigMap, \", \"ConfigMap.Name: \", cm.Name, \"ConfigMap.Namespace: \", cm.Namespace)\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t\t// ConfigMap created successfully - return and requeue\n\t\treturn ctrl.Result{Requeue: true}, nil\n\t} else if err != nil {\n\t\tlog.Error(err, \"Failed to get ConfigMap\")\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t// TODO: Ensure ConfigMap has correct content\n\n\t// TODO: Add ConfigMap created and/or timestamp to status?\n\n\treturn ctrl.Result{}, nil\n}", "func BuildConfigMap(instance *operatorv1alpha1.AuditLogging, name string) (*corev1.ConfigMap, error) {\n\treqLogger := log.WithValues(\"ConfigMap.Namespace\", InstanceNamespace, \"ConfigMap.Name\", name)\n\tmetaLabels := LabelsForMetadata(FluentdName)\n\tdataMap := make(map[string]string)\n\tvar err error\n\tswitch name {\n\tcase FluentdDaemonSetName + \"-\" + ConfigName:\n\t\tdataMap[enableAuditLogForwardKey] = strconv.FormatBool(instance.Spec.Fluentd.EnableAuditLoggingForwarding)\n\t\ttype Data struct {\n\t\t\tValue string `yaml:\"fluent.conf\"`\n\t\t}\n\t\td := Data{}\n\t\terr = yaml.Unmarshal([]byte(fluentdMainConfigData), &d)\n\t\tdataMap[fluentdConfigKey] = d.Value\n\tcase FluentdDaemonSetName + \"-\" + SourceConfigName:\n\t\ttype DataS struct {\n\t\t\tValue string `yaml:\"source.conf\"`\n\t\t}\n\t\tds := DataS{}\n\t\tvar result string\n\t\tif instance.Spec.Fluentd.JournalPath != \"\" {\n\t\t\tresult = sourceConfigData1 + instance.Spec.Fluentd.JournalPath + sourceConfigData2\n\t\t} else {\n\t\t\tresult = sourceConfigData1 + journalPath + sourceConfigData2\n\t\t}\n\t\terr = yaml.Unmarshal([]byte(result), &ds)\n\t\tdataMap[sourceConfigKey] = ds.Value\n\tcase FluentdDaemonSetName + \"-\" + SplunkConfigName:\n\t\ttype DataSplunk struct {\n\t\t\tValue string `yaml:\"splunkHEC.conf\"`\n\t\t}\n\t\tdsplunk := DataSplunk{}\n\t\terr = yaml.Unmarshal([]byte(splunkConfigData), &dsplunk)\n\t\tif err != nil {\n\t\t\treqLogger.Error(err, \"Failed to unmarshall data for \"+name)\n\t\t}\n\t\tdataMap[splunkConfigKey] = dsplunk.Value\n\tcase FluentdDaemonSetName + \"-\" + QRadarConfigName:\n\t\ttype DataQRadar struct {\n\t\t\tValue string `yaml:\"remoteSyslog.conf\"`\n\t\t}\n\t\tdq := DataQRadar{}\n\t\terr = yaml.Unmarshal([]byte(qRadarConfigData), &dq)\n\t\tdataMap[qRadarConfigKey] = dq.Value\n\tdefault:\n\t\treqLogger.Info(\"Unknown ConfigMap name\")\n\t}\n\tif err != nil {\n\t\treqLogger.Error(err, \"Failed to unmarshall data for \"+name)\n\t\treturn nil, err\n\t}\n\tcm := &corev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: InstanceNamespace,\n\t\t\tLabels: metaLabels,\n\t\t},\n\t\tData: dataMap,\n\t}\n\treturn cm, nil\n}", "func TestDefaultConfigMap(t *testing.T) {\n\ttype args struct {\n\t\toperatorConfig *operatorv1.Console\n\t\tconsoleConfig *configv1.Console\n\t\tmanagedConfig *corev1.ConfigMap\n\t\tmonitoringSharedConfig *corev1.ConfigMap\n\t\tinfrastructureConfig *configv1.Infrastructure\n\t\trt *routev1.Route\n\t\tuseDefaultCAFile bool\n\t\tinactivityTimeoutSeconds int\n\t\tavailablePlugins []*v1.ConsolePlugin\n\t\tnodeArchitectures []string\n\t\tnodeOperatingSystems []string\n\t\tcopiedCSVsDisabled bool\n\t}\n\tt.Setenv(\"RELEASE_VERSION\", testReleaseVersion)\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twant *corev1.ConfigMap\n\t}{\n\t\t{\n\t\t\tname: \"Test default configmap, no customization\",\n\t\t\targs: args{\n\t\t\t\toperatorConfig: &operatorv1.Console{},\n\t\t\t\tconsoleConfig: &configv1.Console{},\n\t\t\t\tmanagedConfig: &corev1.ConfigMap{},\n\t\t\t\tinfrastructureConfig: &configv1.Infrastructure{\n\t\t\t\t\tStatus: configv1.InfrastructureStatus{\n\t\t\t\t\t\tAPIServerURL: mockAPIServer,\n\t\t\t\t\t\tControlPlaneTopology: configv1.HighlyAvailableTopologyMode,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\trt: &routev1.Route{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\tName: api.OpenShiftConsoleName,\n\t\t\t\t\t},\n\t\t\t\t\tSpec: routev1.RouteSpec{\n\t\t\t\t\t\tHost: host,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tuseDefaultCAFile: true,\n\t\t\t\tinactivityTimeoutSeconds: 0,\n\t\t\t},\n\t\t\twant: &corev1.ConfigMap{\n\t\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\t\tKind: \"ConfigMap\",\n\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t},\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: api.OpenShiftConsoleConfigMapName,\n\t\t\t\t\tNamespace: api.OpenShiftConsoleNamespace,\n\t\t\t\t\tLabels: map[string]string{\"app\": api.OpenShiftConsoleName},\n\t\t\t\t\tAnnotations: map[string]string{},\n\t\t\t\t},\n\t\t\t\tData: map[string]string{configKey: `kind: ConsoleConfig\napiVersion: console.openshift.io/v1\nauth:\n clientID: console\n clientSecretFile: /var/oauth-config/clientSecret\n oauthEndpointCAFile: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt\nclusterInfo:\n consoleBaseAddress: https://` + host + `\n masterPublicURL: ` + mockAPIServer + `\n controlPlaneTopology: HighlyAvailable\n releaseVersion: ` + testReleaseVersion + `\ncustomization:\n branding: ` + DEFAULT_BRAND + `\n documentationBaseURL: ` + DEFAULT_DOC_URL + `\nservingInfo:\n bindAddress: https://[::]:8443\n certFile: /var/serving-cert/tls.crt\n keyFile: /var/serving-cert/tls.key\nproviders: {}\n`,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Test configmap with oauth-serving-cert\",\n\t\t\targs: args{\n\t\t\t\toperatorConfig: &operatorv1.Console{},\n\t\t\t\tconsoleConfig: &configv1.Console{},\n\t\t\t\tmanagedConfig: &corev1.ConfigMap{},\n\t\t\t\tinfrastructureConfig: &configv1.Infrastructure{\n\t\t\t\t\tStatus: configv1.InfrastructureStatus{\n\t\t\t\t\t\tAPIServerURL: mockAPIServer,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\trt: &routev1.Route{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\tName: api.OpenShiftConsoleName,\n\t\t\t\t\t},\n\t\t\t\t\tSpec: routev1.RouteSpec{\n\t\t\t\t\t\tHost: host,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tuseDefaultCAFile: false,\n\t\t\t\tinactivityTimeoutSeconds: 0,\n\t\t\t},\n\t\t\twant: &corev1.ConfigMap{\n\t\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\t\tKind: \"ConfigMap\",\n\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t},\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: api.OpenShiftConsoleConfigMapName,\n\t\t\t\t\tNamespace: api.OpenShiftConsoleNamespace,\n\t\t\t\t\tLabels: map[string]string{\"app\": api.OpenShiftConsoleName},\n\t\t\t\t\tAnnotations: map[string]string{},\n\t\t\t\t},\n\t\t\t\tData: map[string]string{configKey: `kind: ConsoleConfig\napiVersion: console.openshift.io/v1\nauth:\n clientID: console\n clientSecretFile: /var/oauth-config/clientSecret\n oauthEndpointCAFile: /var/oauth-serving-cert/ca-bundle.crt\nclusterInfo:\n consoleBaseAddress: https://` + host + `\n masterPublicURL: ` + mockAPIServer + `\n releaseVersion: ` + testReleaseVersion + `\ncustomization:\n branding: ` + DEFAULT_BRAND + `\n documentationBaseURL: ` + DEFAULT_DOC_URL + `\nservingInfo:\n bindAddress: https://[::]:8443\n certFile: /var/serving-cert/tls.crt\n keyFile: /var/serving-cert/tls.key\nproviders: {}\n`,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Test managed config to override default config\",\n\t\t\targs: args{\n\t\t\t\toperatorConfig: &operatorv1.Console{},\n\t\t\t\tconsoleConfig: &configv1.Console{},\n\t\t\t\tmanagedConfig: &corev1.ConfigMap{\n\t\t\t\t\tData: map[string]string{configKey: `kind: ConsoleConfig\napiVersion: console.openshift.io/v1\ncustomization:\n branding: online\n documentationBaseURL: https://docs.okd.io/4.4/\n`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tinfrastructureConfig: &configv1.Infrastructure{\n\t\t\t\t\tStatus: configv1.InfrastructureStatus{\n\t\t\t\t\t\tAPIServerURL: mockAPIServer,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\trt: &routev1.Route{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\tName: api.OpenShiftConsoleName,\n\t\t\t\t\t},\n\t\t\t\t\tSpec: routev1.RouteSpec{\n\t\t\t\t\t\tHost: host,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tuseDefaultCAFile: true,\n\t\t\t\tinactivityTimeoutSeconds: 0,\n\t\t\t\tnodeArchitectures: []string{\"amd64\", \"arm64\"},\n\t\t\t},\n\t\t\twant: &corev1.ConfigMap{\n\t\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\t\tKind: \"ConfigMap\",\n\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t},\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: api.OpenShiftConsoleConfigMapName,\n\t\t\t\t\tNamespace: api.OpenShiftConsoleNamespace,\n\t\t\t\t\tLabels: map[string]string{\"app\": api.OpenShiftConsoleName},\n\t\t\t\t\tAnnotations: map[string]string{},\n\t\t\t\t},\n\t\t\t\tData: map[string]string{configKey: `kind: ConsoleConfig\napiVersion: console.openshift.io/v1\nauth:\n clientID: console\n clientSecretFile: /var/oauth-config/clientSecret\n oauthEndpointCAFile: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt\nclusterInfo:\n consoleBaseAddress: https://` + host + `\n masterPublicURL: ` + mockAPIServer + `\n releaseVersion: ` + testReleaseVersion + `\n nodeArchitectures:\n - amd64\n - arm64\ncustomization:\n branding: online\n documentationBaseURL: https://docs.okd.io/4.4/\nservingInfo:\n bindAddress: https://[::]:8443\n certFile: /var/serving-cert/tls.crt\n keyFile: /var/serving-cert/tls.key\nproviders: {}\n`,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Test nodeOperatingSystems config\",\n\t\t\targs: args{\n\t\t\t\toperatorConfig: &operatorv1.Console{},\n\t\t\t\tconsoleConfig: &configv1.Console{},\n\t\t\t\tmanagedConfig: &corev1.ConfigMap{\n\t\t\t\t\tData: map[string]string{configKey: `kind: ConsoleConfig\napiVersion: console.openshift.io/v1\ncustomization:\n branding: online\n documentationBaseURL: https://docs.okd.io/4.4/\n`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tinfrastructureConfig: &configv1.Infrastructure{\n\t\t\t\t\tStatus: configv1.InfrastructureStatus{\n\t\t\t\t\t\tAPIServerURL: mockAPIServer,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\trt: &routev1.Route{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\tName: api.OpenShiftConsoleName,\n\t\t\t\t\t},\n\t\t\t\t\tSpec: routev1.RouteSpec{\n\t\t\t\t\t\tHost: host,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tuseDefaultCAFile: true,\n\t\t\t\tinactivityTimeoutSeconds: 0,\n\t\t\t\tnodeOperatingSystems: []string{\"foo\", \"bar\"},\n\t\t\t},\n\t\t\twant: &corev1.ConfigMap{\n\t\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\t\tKind: \"ConfigMap\",\n\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t},\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: api.OpenShiftConsoleConfigMapName,\n\t\t\t\t\tNamespace: api.OpenShiftConsoleNamespace,\n\t\t\t\t\tLabels: map[string]string{\"app\": api.OpenShiftConsoleName},\n\t\t\t\t\tAnnotations: map[string]string{},\n\t\t\t\t},\n\t\t\t\tData: map[string]string{configKey: `kind: ConsoleConfig\napiVersion: console.openshift.io/v1\nauth:\n clientID: console\n clientSecretFile: /var/oauth-config/clientSecret\n oauthEndpointCAFile: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt\nclusterInfo:\n consoleBaseAddress: https://` + host + `\n masterPublicURL: ` + mockAPIServer + `\n releaseVersion: ` + testReleaseVersion + `\n nodeOperatingSystems:\n - foo\n - bar\ncustomization:\n branding: online\n documentationBaseURL: https://docs.okd.io/4.4/\nservingInfo:\n bindAddress: https://[::]:8443\n certFile: /var/serving-cert/tls.crt\n keyFile: /var/serving-cert/tls.key\nproviders: {}\n`,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Test operator config overriding default config and managed config\",\n\t\t\targs: args{\n\t\t\t\toperatorConfig: &operatorv1.Console{\n\t\t\t\t\tSpec: operatorv1.ConsoleSpec{\n\t\t\t\t\t\tOperatorSpec: operatorv1.OperatorSpec{},\n\t\t\t\t\t\tCustomization: operatorv1.ConsoleCustomization{\n\t\t\t\t\t\t\tBrand: operatorv1.BrandDedicated,\n\t\t\t\t\t\t\tDocumentationBaseURL: mockOperatorDocURL,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tStatus: operatorv1.ConsoleStatus{},\n\t\t\t\t},\n\t\t\t\tconsoleConfig: &configv1.Console{},\n\t\t\t\tmanagedConfig: &corev1.ConfigMap{\n\t\t\t\t\tData: map[string]string{configKey: `kind: ConsoleConfig\napiVersion: console.openshift.io/v1\ncustomization:\n branding: online\n documentationBaseURL: https://docs.okd.io/4.4/\n`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tinfrastructureConfig: &configv1.Infrastructure{\n\t\t\t\t\tStatus: configv1.InfrastructureStatus{\n\t\t\t\t\t\tAPIServerURL: mockAPIServer,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\trt: &routev1.Route{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\tName: api.OpenShiftConsoleName,\n\t\t\t\t\t},\n\t\t\t\t\tSpec: routev1.RouteSpec{\n\t\t\t\t\t\tHost: host,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tuseDefaultCAFile: true,\n\t\t\t\tinactivityTimeoutSeconds: 0,\n\t\t\t},\n\t\t\twant: &corev1.ConfigMap{\n\t\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\t\tKind: \"ConfigMap\",\n\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t},\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: api.OpenShiftConsoleConfigMapName,\n\t\t\t\t\tNamespace: api.OpenShiftConsoleNamespace,\n\t\t\t\t\tLabels: map[string]string{\"app\": api.OpenShiftConsoleName},\n\t\t\t\t\tAnnotations: map[string]string{},\n\t\t\t\t},\n\t\t\t\tData: map[string]string{configKey: `kind: ConsoleConfig\napiVersion: console.openshift.io/v1\nauth:\n clientID: console\n clientSecretFile: /var/oauth-config/clientSecret\n oauthEndpointCAFile: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt\nclusterInfo:\n consoleBaseAddress: https://` + host + `\n masterPublicURL: ` + mockAPIServer + `\n releaseVersion: ` + testReleaseVersion + `\ncustomization:\n branding: ` + string(operatorv1.BrandDedicatedLegacy) + `\n documentationBaseURL: ` + mockOperatorDocURL + `\nservingInfo:\n bindAddress: https://[::]:8443\n certFile: /var/serving-cert/tls.crt\n keyFile: /var/serving-cert/tls.key\nproviders: {}\n`,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Test operator config with Custom Branding Values\",\n\t\t\targs: args{\n\t\t\t\toperatorConfig: &operatorv1.Console{\n\t\t\t\t\tSpec: operatorv1.ConsoleSpec{\n\t\t\t\t\t\tOperatorSpec: operatorv1.OperatorSpec{},\n\t\t\t\t\t\tCustomization: operatorv1.ConsoleCustomization{\n\t\t\t\t\t\t\tBrand: operatorv1.BrandDedicated,\n\t\t\t\t\t\t\tDocumentationBaseURL: mockOperatorDocURL,\n\t\t\t\t\t\t\tCustomProductName: \"custom-product-name\",\n\t\t\t\t\t\t\tCustomLogoFile: configv1.ConfigMapFileReference{\n\t\t\t\t\t\t\t\tName: \"custom-logo-file\",\n\t\t\t\t\t\t\t\tKey: \"logo.svg\",\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\tStatus: operatorv1.ConsoleStatus{},\n\t\t\t\t},\n\t\t\t\tconsoleConfig: &configv1.Console{},\n\t\t\t\tmanagedConfig: &corev1.ConfigMap{\n\t\t\t\t\tData: map[string]string{configKey: `kind: ConsoleConfig\napiVersion: console.openshift.io/v1\ncustomization:\n branding: online\n documentationBaseURL: https://docs.okd.io/4.4/\n`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tinfrastructureConfig: &configv1.Infrastructure{\n\t\t\t\t\tStatus: configv1.InfrastructureStatus{\n\t\t\t\t\t\tAPIServerURL: mockAPIServer,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\trt: &routev1.Route{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\tName: api.OpenShiftConsoleName,\n\t\t\t\t\t},\n\t\t\t\t\tSpec: routev1.RouteSpec{\n\t\t\t\t\t\tHost: host,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tuseDefaultCAFile: true,\n\t\t\t\tinactivityTimeoutSeconds: 0,\n\t\t\t},\n\t\t\twant: &corev1.ConfigMap{\n\t\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\t\tKind: \"ConfigMap\",\n\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t},\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: api.OpenShiftConsoleConfigMapName,\n\t\t\t\t\tNamespace: api.OpenShiftConsoleNamespace,\n\t\t\t\t\tLabels: map[string]string{\"app\": api.OpenShiftConsoleName},\n\t\t\t\t\tAnnotations: map[string]string{},\n\t\t\t\t},\n\t\t\t\tData: map[string]string{configKey: `kind: ConsoleConfig\napiVersion: console.openshift.io/v1\nauth:\n clientID: console\n clientSecretFile: /var/oauth-config/clientSecret\n oauthEndpointCAFile: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt\nclusterInfo:\n consoleBaseAddress: https://` + host + `\n masterPublicURL: ` + mockAPIServer + `\n releaseVersion: ` + testReleaseVersion + `\ncustomization:\n branding: ` + string(operatorv1.BrandDedicatedLegacy) + `\n documentationBaseURL: ` + mockOperatorDocURL + `\n customLogoFile: /var/logo/logo.svg\n customProductName: custom-product-name\nservingInfo:\n bindAddress: https://[::]:8443\n certFile: /var/serving-cert/tls.crt\n keyFile: /var/serving-cert/tls.key\nproviders: {}\n`,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Test operator config with Statuspage pageID\",\n\t\t\targs: args{\n\t\t\t\toperatorConfig: &operatorv1.Console{\n\t\t\t\t\tSpec: operatorv1.ConsoleSpec{\n\t\t\t\t\t\tOperatorSpec: operatorv1.OperatorSpec{},\n\t\t\t\t\t\tCustomization: operatorv1.ConsoleCustomization{\n\t\t\t\t\t\t\tBrand: operatorv1.BrandDedicated,\n\t\t\t\t\t\t\tDocumentationBaseURL: mockOperatorDocURL,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tProviders: operatorv1.ConsoleProviders{\n\t\t\t\t\t\t\tStatuspage: &operatorv1.StatuspageProvider{\n\t\t\t\t\t\t\t\tPageID: \"id-1234\",\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\tStatus: operatorv1.ConsoleStatus{},\n\t\t\t\t},\n\t\t\t\tconsoleConfig: &configv1.Console{},\n\t\t\t\tmanagedConfig: &corev1.ConfigMap{\n\t\t\t\t\tData: map[string]string{configKey: `kind: ConsoleConfig\napiVersion: console.openshift.io/v1\ncustomization:\n branding: online\n documentationBaseURL: https://docs.okd.io/4.4/\n`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tinfrastructureConfig: &configv1.Infrastructure{\n\t\t\t\t\tStatus: configv1.InfrastructureStatus{\n\t\t\t\t\t\tAPIServerURL: mockAPIServer,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\trt: &routev1.Route{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\tName: api.OpenShiftConsoleName,\n\t\t\t\t\t},\n\t\t\t\t\tSpec: routev1.RouteSpec{\n\t\t\t\t\t\tHost: host,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tuseDefaultCAFile: true,\n\t\t\t\tinactivityTimeoutSeconds: 0,\n\t\t\t},\n\t\t\twant: &corev1.ConfigMap{\n\t\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\t\tKind: \"ConfigMap\",\n\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t},\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: api.OpenShiftConsoleConfigMapName,\n\t\t\t\t\tNamespace: api.OpenShiftConsoleNamespace,\n\t\t\t\t\tLabels: map[string]string{\"app\": api.OpenShiftConsoleName},\n\t\t\t\t\tAnnotations: map[string]string{},\n\t\t\t\t},\n\t\t\t\tData: map[string]string{configKey: `kind: ConsoleConfig\napiVersion: console.openshift.io/v1\nauth:\n clientID: console\n clientSecretFile: /var/oauth-config/clientSecret\n oauthEndpointCAFile: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt\nclusterInfo:\n consoleBaseAddress: https://` + host + `\n masterPublicURL: ` + mockAPIServer + `\n releaseVersion: ` + testReleaseVersion + `\ncustomization:\n branding: ` + string(operatorv1.BrandDedicatedLegacy) + `\n documentationBaseURL: ` + mockOperatorDocURL + `\nservingInfo:\n bindAddress: https://[::]:8443\n certFile: /var/serving-cert/tls.crt\n keyFile: /var/serving-cert/tls.key\nproviders:\n statuspageID: id-1234\n`,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Test operator config with custom route hostname\",\n\t\t\targs: args{\n\t\t\t\toperatorConfig: &operatorv1.Console{\n\t\t\t\t\tSpec: operatorv1.ConsoleSpec{\n\t\t\t\t\t\tRoute: operatorv1.ConsoleConfigRoute{\n\t\t\t\t\t\t\tHostname: customHostname,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tconsoleConfig: &configv1.Console{},\n\t\t\t\tmanagedConfig: &corev1.ConfigMap{},\n\t\t\t\tinfrastructureConfig: &configv1.Infrastructure{\n\t\t\t\t\tStatus: configv1.InfrastructureStatus{\n\t\t\t\t\t\tAPIServerURL: mockAPIServer,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\trt: &routev1.Route{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\tName: api.OpenshiftConsoleCustomRouteName,\n\t\t\t\t\t},\n\t\t\t\t\tSpec: routev1.RouteSpec{\n\t\t\t\t\t\tHost: customHostname,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tuseDefaultCAFile: false,\n\t\t\t\tinactivityTimeoutSeconds: 0,\n\t\t\t},\n\t\t\twant: &corev1.ConfigMap{\n\t\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\t\tKind: \"ConfigMap\",\n\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t},\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: api.OpenShiftConsoleConfigMapName,\n\t\t\t\t\tNamespace: api.OpenShiftConsoleNamespace,\n\t\t\t\t\tLabels: map[string]string{\"app\": api.OpenShiftConsoleName},\n\t\t\t\t\tAnnotations: map[string]string{},\n\t\t\t\t},\n\t\t\t\tData: map[string]string{configKey: `kind: ConsoleConfig\napiVersion: console.openshift.io/v1\nauth:\n clientID: console\n clientSecretFile: /var/oauth-config/clientSecret\n oauthEndpointCAFile: /var/oauth-serving-cert/ca-bundle.crt\nclusterInfo:\n consoleBaseAddress: https://` + customHostname + `\n masterPublicURL: ` + mockAPIServer + `\n releaseVersion: ` + testReleaseVersion + `\ncustomization:\n branding: ` + DEFAULT_BRAND + `\n documentationBaseURL: ` + DEFAULT_DOC_URL + `\nservingInfo:\n bindAddress: https://[::]:8443\n certFile: /var/serving-cert/tls.crt\n keyFile: /var/serving-cert/tls.key\n redirectPort: ` + strconv.Itoa(api.RedirectContainerPort) + `\nproviders: {}\n`,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Test operator config, with inactivityTimeoutSeconds set\",\n\t\t\targs: args{\n\t\t\t\toperatorConfig: &operatorv1.Console{},\n\t\t\t\tconsoleConfig: &configv1.Console{},\n\t\t\t\tmanagedConfig: &corev1.ConfigMap{},\n\t\t\t\tinfrastructureConfig: &configv1.Infrastructure{\n\t\t\t\t\tStatus: configv1.InfrastructureStatus{\n\t\t\t\t\t\tAPIServerURL: mockAPIServer,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\trt: &routev1.Route{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\tName: api.OpenShiftConsoleName,\n\t\t\t\t\t},\n\t\t\t\t\tSpec: routev1.RouteSpec{\n\t\t\t\t\t\tHost: host,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tuseDefaultCAFile: true,\n\t\t\t\tinactivityTimeoutSeconds: 60,\n\t\t\t},\n\t\t\twant: &corev1.ConfigMap{\n\t\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\t\tKind: \"ConfigMap\",\n\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t},\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: api.OpenShiftConsoleConfigMapName,\n\t\t\t\t\tNamespace: api.OpenShiftConsoleNamespace,\n\t\t\t\t\tLabels: map[string]string{\"app\": api.OpenShiftConsoleName},\n\t\t\t\t\tAnnotations: map[string]string{},\n\t\t\t\t},\n\t\t\t\tData: map[string]string{configKey: `kind: ConsoleConfig\napiVersion: console.openshift.io/v1\nauth:\n clientID: console\n clientSecretFile: /var/oauth-config/clientSecret\n inactivityTimeoutSeconds: 60\n oauthEndpointCAFile: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt\nclusterInfo:\n consoleBaseAddress: https://` + host + `\n masterPublicURL: ` + mockAPIServer + `\n releaseVersion: ` + testReleaseVersion + `\ncustomization:\n branding: ` + DEFAULT_BRAND + `\n documentationBaseURL: ` + DEFAULT_DOC_URL + `\nservingInfo:\n bindAddress: https://[::]:8443\n certFile: /var/serving-cert/tls.crt\n keyFile: /var/serving-cert/tls.key\nproviders: {}\n`,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Test operator config, with enabledPlugins set\",\n\t\t\targs: args{\n\t\t\t\toperatorConfig: &operatorv1.Console{},\n\t\t\t\tconsoleConfig: &configv1.Console{},\n\t\t\t\tmanagedConfig: &corev1.ConfigMap{},\n\t\t\t\tinfrastructureConfig: &configv1.Infrastructure{\n\t\t\t\t\tStatus: configv1.InfrastructureStatus{\n\t\t\t\t\t\tAPIServerURL: mockAPIServer,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\trt: &routev1.Route{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\tName: api.OpenShiftConsoleName,\n\t\t\t\t\t},\n\t\t\t\t\tSpec: routev1.RouteSpec{\n\t\t\t\t\t\tHost: host,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tuseDefaultCAFile: true,\n\t\t\t\tinactivityTimeoutSeconds: 0,\n\t\t\t\tavailablePlugins: []*v1.ConsolePlugin{\n\t\t\t\t\ttestPluginsWithProxy(\"plugin1\", \"service1\", \"service-namespace1\"),\n\t\t\t\t\ttestPluginsWithProxy(\"plugin2\", \"service2\", \"service-namespace2\"),\n\t\t\t\t\ttestPluginsWithI18nPreloadType(\"plugin3\", \"service3\", \"service-namespace3\"),\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: &corev1.ConfigMap{\n\t\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\t\tKind: \"ConfigMap\",\n\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t},\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: api.OpenShiftConsoleConfigMapName,\n\t\t\t\t\tNamespace: api.OpenShiftConsoleNamespace,\n\t\t\t\t\tLabels: map[string]string{\"app\": api.OpenShiftConsoleName},\n\t\t\t\t\tAnnotations: map[string]string{},\n\t\t\t\t},\n\t\t\t\tData: map[string]string{configKey: `kind: ConsoleConfig\napiVersion: console.openshift.io/v1\nauth:\n clientID: console\n clientSecretFile: /var/oauth-config/clientSecret\n oauthEndpointCAFile: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt\nclusterInfo:\n consoleBaseAddress: https://` + host + `\n masterPublicURL: ` + mockAPIServer + `\n releaseVersion: ` + testReleaseVersion + `\ncustomization:\n branding: ` + DEFAULT_BRAND + `\n documentationBaseURL: ` + DEFAULT_DOC_URL + `\ni18nNamespaces:\n- plugin__plugin3\nservingInfo:\n bindAddress: https://[::]:8443\n certFile: /var/serving-cert/tls.crt\n keyFile: /var/serving-cert/tls.key\nproviders: {}\nplugins:\n plugin1: https://service1.service-namespace1.svc.cluster.local:8443/\n plugin2: https://service2.service-namespace2.svc.cluster.local:8443/\n plugin3: https://service3.service-namespace3.svc.cluster.local:8443/\nproxy:\n services:\n - authorize: true\n caCertificate: '-----BEGIN CERTIFICATE-----` + \"\\n\" + `\nMIICRzCCAfGgAwIBAgIJAIydTIADd+yqMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNV` + \"\\n\" + `\nBAYTAkdCMQ8wDQYDVQQIDAZMb25kb24xDzANBgNVBAcMBkxvbmRvbjEYMBYGA1UE` + \"\\n\" + `\nCgwPR2xvYmFsIFNlY3VyaXR5MRYwFAYDVQQLDA1JVCBEZXBhcnRtZW50MRswGQYD` + \"\\n\" + `\nVQQDDBJ0ZXN0LWNlcnRpZmljYXRlLTIwIBcNMTcwNDI2MjMyNDU4WhgPMjExNzA0` + \"\\n\" + `\nMDIyMzI0NThaMH4xCzAJBgNVBAYTAkdCMQ8wDQYDVQQIDAZMb25kb24xDzANBgNV` + \"\\n\" + `\nBAcMBkxvbmRvbjEYMBYGA1UECgwPR2xvYmFsIFNlY3VyaXR5MRYwFAYDVQQLDA1J` + \"\\n\" + `\nVCBEZXBhcnRtZW50MRswGQYDVQQDDBJ0ZXN0LWNlcnRpZmljYXRlLTIwXDANBgkq` + \"\\n\" + `\nhkiG9w0BAQEFAANLADBIAkEAuiRet28DV68Dk4A8eqCaqgXmymamUEjW/DxvIQqH` + \"\\n\" + `\n3lbhtm8BwSnS9wUAajSLSWiq3fci2RbRgaSPjUrnbOHCLQIDAQABo1AwTjAdBgNV` + \"\\n\" + `\nHQ4EFgQU0vhI4OPGEOqT+VAWwxdhVvcmgdIwHwYDVR0jBBgwFoAU0vhI4OPGEOqT` + \"\\n\" + `\n+VAWwxdhVvcmgdIwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAANBALNeJGDe` + \"\\n\" + `\nnV5cXbp9W1bC12Tc8nnNXn4ypLE2JTQAvyp51zoZ8hQoSnRVx/VCY55Yu+br8gQZ` + \"\\n\" + `\n+tW+O/PoE7B3tuY=` + \"\\n\" + `\n-----END CERTIFICATE-----'\n consoleAPIPath: /api/proxy/plugin/plugin1/plugin1-alias/\n endpoint: https://proxy-service1.proxy-service-namespace1.svc.cluster.local:9991\n - authorize: true\n caCertificate: '-----BEGIN CERTIFICATE-----` + \"\\n\" + `\nMIICRzCCAfGgAwIBAgIJAIydTIADd+yqMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNV` + \"\\n\" + `\nBAYTAkdCMQ8wDQYDVQQIDAZMb25kb24xDzANBgNVBAcMBkxvbmRvbjEYMBYGA1UE` + \"\\n\" + `\nCgwPR2xvYmFsIFNlY3VyaXR5MRYwFAYDVQQLDA1JVCBEZXBhcnRtZW50MRswGQYD` + \"\\n\" + `\nVQQDDBJ0ZXN0LWNlcnRpZmljYXRlLTIwIBcNMTcwNDI2MjMyNDU4WhgPMjExNzA0` + \"\\n\" + `\nMDIyMzI0NThaMH4xCzAJBgNVBAYTAkdCMQ8wDQYDVQQIDAZMb25kb24xDzANBgNV` + \"\\n\" + `\nBAcMBkxvbmRvbjEYMBYGA1UECgwPR2xvYmFsIFNlY3VyaXR5MRYwFAYDVQQLDA1J` + \"\\n\" + `\nVCBEZXBhcnRtZW50MRswGQYDVQQDDBJ0ZXN0LWNlcnRpZmljYXRlLTIwXDANBgkq` + \"\\n\" + `\nhkiG9w0BAQEFAANLADBIAkEAuiRet28DV68Dk4A8eqCaqgXmymamUEjW/DxvIQqH` + \"\\n\" + `\n3lbhtm8BwSnS9wUAajSLSWiq3fci2RbRgaSPjUrnbOHCLQIDAQABo1AwTjAdBgNV` + \"\\n\" + `\nHQ4EFgQU0vhI4OPGEOqT+VAWwxdhVvcmgdIwHwYDVR0jBBgwFoAU0vhI4OPGEOqT` + \"\\n\" + `\n+VAWwxdhVvcmgdIwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAANBALNeJGDe` + \"\\n\" + `\nnV5cXbp9W1bC12Tc8nnNXn4ypLE2JTQAvyp51zoZ8hQoSnRVx/VCY55Yu+br8gQZ` + \"\\n\" + `\n+tW+O/PoE7B3tuY=` + \"\\n\" + `\n-----END CERTIFICATE-----'\n consoleAPIPath: /api/proxy/plugin/plugin2/plugin2-alias/\n endpoint: https://proxy-service2.proxy-service-namespace2.svc.cluster.local:9991\n`,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Test operator config, with 'External' ControlPlaneTopology\",\n\t\t\targs: args{\n\t\t\t\toperatorConfig: &operatorv1.Console{},\n\t\t\t\tconsoleConfig: &configv1.Console{},\n\t\t\t\tmanagedConfig: &corev1.ConfigMap{},\n\t\t\t\tinfrastructureConfig: &configv1.Infrastructure{\n\t\t\t\t\tStatus: configv1.InfrastructureStatus{\n\t\t\t\t\t\tAPIServerURL: mockAPIServer,\n\t\t\t\t\t\tControlPlaneTopology: configv1.ExternalTopologyMode,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\trt: &routev1.Route{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\tName: api.OpenShiftConsoleName,\n\t\t\t\t\t},\n\t\t\t\t\tSpec: routev1.RouteSpec{\n\t\t\t\t\t\tHost: host,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tuseDefaultCAFile: true,\n\t\t\t\tinactivityTimeoutSeconds: 0,\n\t\t\t},\n\t\t\twant: &corev1.ConfigMap{\n\t\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\t\tKind: \"ConfigMap\",\n\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t},\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: api.OpenShiftConsoleConfigMapName,\n\t\t\t\t\tNamespace: api.OpenShiftConsoleNamespace,\n\t\t\t\t\tLabels: map[string]string{\"app\": api.OpenShiftConsoleName},\n\t\t\t\t\tAnnotations: map[string]string{},\n\t\t\t\t},\n\t\t\t\tData: map[string]string{configKey: `kind: ConsoleConfig\napiVersion: console.openshift.io/v1\nauth:\n clientID: console\n clientSecretFile: /var/oauth-config/clientSecret\n oauthEndpointCAFile: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt\nclusterInfo:\n consoleBaseAddress: https://` + host + `\n masterPublicURL: ` + mockAPIServer + `\n controlPlaneTopology: External\n releaseVersion: ` + testReleaseVersion + `\ncustomization:\n branding: ` + DEFAULT_BRAND + `\n documentationBaseURL: ` + DEFAULT_DOC_URL + `\nservingInfo:\n bindAddress: https://[::]:8443\n certFile: /var/serving-cert/tls.crt\n keyFile: /var/serving-cert/tls.key\nproviders: {}\n`,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Test operator config, with CopiedCSVsDisabled\",\n\t\t\targs: args{\n\t\t\t\toperatorConfig: &operatorv1.Console{},\n\t\t\t\tconsoleConfig: &configv1.Console{},\n\t\t\t\tmanagedConfig: &corev1.ConfigMap{},\n\t\t\t\tinfrastructureConfig: &configv1.Infrastructure{\n\t\t\t\t\tStatus: configv1.InfrastructureStatus{\n\t\t\t\t\t\tAPIServerURL: mockAPIServer,\n\t\t\t\t\t\tControlPlaneTopology: configv1.ExternalTopologyMode,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tcopiedCSVsDisabled: true,\n\t\t\t\trt: &routev1.Route{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\tName: api.OpenShiftConsoleName,\n\t\t\t\t\t},\n\t\t\t\t\tSpec: routev1.RouteSpec{\n\t\t\t\t\t\tHost: host,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tuseDefaultCAFile: true,\n\t\t\t\tinactivityTimeoutSeconds: 0,\n\t\t\t},\n\t\t\twant: &corev1.ConfigMap{\n\t\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\t\tKind: \"ConfigMap\",\n\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t},\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: api.OpenShiftConsoleConfigMapName,\n\t\t\t\t\tNamespace: api.OpenShiftConsoleNamespace,\n\t\t\t\t\tLabels: map[string]string{\"app\": api.OpenShiftConsoleName},\n\t\t\t\t\tAnnotations: map[string]string{},\n\t\t\t\t},\n\t\t\t\tData: map[string]string{configKey: `kind: ConsoleConfig\napiVersion: console.openshift.io/v1\nauth:\n clientID: console\n clientSecretFile: /var/oauth-config/clientSecret\n oauthEndpointCAFile: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt\nclusterInfo:\n consoleBaseAddress: https://` + host + `\n masterPublicURL: ` + mockAPIServer + `\n controlPlaneTopology: External\n releaseVersion: ` + testReleaseVersion + `\n copiedCSVsDisabled: true\ncustomization:\n branding: ` + DEFAULT_BRAND + `\n documentationBaseURL: ` + DEFAULT_DOC_URL + `\nservingInfo:\n bindAddress: https://[::]:8443\n certFile: /var/serving-cert/tls.crt\n keyFile: /var/serving-cert/tls.key\nproviders: {}\n`,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Test default configmap with monitoring config\",\n\t\t\targs: args{\n\t\t\t\toperatorConfig: &operatorv1.Console{},\n\t\t\t\tconsoleConfig: &configv1.Console{},\n\t\t\t\tmanagedConfig: &corev1.ConfigMap{},\n\t\t\t\tinfrastructureConfig: &configv1.Infrastructure{\n\t\t\t\t\tStatus: configv1.InfrastructureStatus{\n\t\t\t\t\t\tAPIServerURL: mockAPIServer,\n\t\t\t\t\t\tControlPlaneTopology: configv1.HighlyAvailableTopologyMode,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\trt: &routev1.Route{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\tName: api.OpenShiftConsoleName,\n\t\t\t\t\t},\n\t\t\t\t\tSpec: routev1.RouteSpec{\n\t\t\t\t\t\tHost: host,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tuseDefaultCAFile: true,\n\t\t\t\tinactivityTimeoutSeconds: 0,\n\t\t\t\tmonitoringSharedConfig: &corev1.ConfigMap{\n\t\t\t\t\tData: map[string]string{\n\t\t\t\t\t\t\"alertmanagerUserWorkloadHost\": \"alertmanager-user-workload.openshift-user-workload-monitoring.svc:9094\",\n\t\t\t\t\t\t\"alertmanagerTenancyHost\": \"alertmanager-user-workload.openshift-user-workload-monitoring.svc:9092\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: &corev1.ConfigMap{\n\t\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\t\tKind: \"ConfigMap\",\n\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t},\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: api.OpenShiftConsoleConfigMapName,\n\t\t\t\t\tNamespace: api.OpenShiftConsoleNamespace,\n\t\t\t\t\tLabels: map[string]string{\"app\": api.OpenShiftConsoleName},\n\t\t\t\t\tAnnotations: map[string]string{},\n\t\t\t\t},\n\t\t\t\tData: map[string]string{configKey: `kind: ConsoleConfig\napiVersion: console.openshift.io/v1\nauth:\n clientID: console\n clientSecretFile: /var/oauth-config/clientSecret\n oauthEndpointCAFile: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt\nclusterInfo:\n consoleBaseAddress: https://` + host + `\n masterPublicURL: ` + mockAPIServer + `\n controlPlaneTopology: HighlyAvailable\n releaseVersion: ` + testReleaseVersion + `\ncustomization:\n branding: ` + DEFAULT_BRAND + `\n documentationBaseURL: ` + DEFAULT_DOC_URL + `\nmonitoringInfo:\n alertmanagerTenancyHost: alertmanager-user-workload.openshift-user-workload-monitoring.svc:9092\n alertmanagerUserWorkloadHost: alertmanager-user-workload.openshift-user-workload-monitoring.svc:9094\nservingInfo:\n bindAddress: https://[::]:8443\n certFile: /var/serving-cert/tls.crt\n keyFile: /var/serving-cert/tls.key\nproviders: {}\n`,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcm, _, _ := DefaultConfigMap(\n\t\t\t\ttt.args.operatorConfig,\n\t\t\t\ttt.args.consoleConfig,\n\t\t\t\ttt.args.managedConfig,\n\t\t\t\ttt.args.monitoringSharedConfig,\n\t\t\t\ttt.args.infrastructureConfig,\n\t\t\t\ttt.args.rt,\n\t\t\t\ttt.args.useDefaultCAFile,\n\t\t\t\ttt.args.inactivityTimeoutSeconds,\n\t\t\t\ttt.args.availablePlugins,\n\t\t\t\ttt.args.nodeArchitectures,\n\t\t\t\ttt.args.nodeOperatingSystems,\n\t\t\t\ttt.args.copiedCSVsDisabled,\n\t\t\t)\n\n\t\t\t// marshall the exampleYaml to map[string]interface{} so we can use it in diff below\n\t\t\tvar exampleConfig map[string]interface{}\n\t\t\texampleBytes := []byte(tt.want.Data[configKey])\n\t\t\terr := yaml.Unmarshal(exampleBytes, &exampleConfig)\n\t\t\tif err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\n\t\t\t// the reason we have to marshall blindly into map[string]interface{}\n\t\t\t// is that we don't have the definition for the console config struct.\n\t\t\t// it exists in the console repo under cmd/bridge/config.go and is not\n\t\t\t// available as an api object\n\t\t\tvar actualConfig map[string]interface{}\n\t\t\t// convert the string back into a []byte\n\t\t\tconfigBytes := []byte(cm.Data[configKey])\n\n\t\t\terr = yaml.Unmarshal(configBytes, &actualConfig)\n\t\t\tif err != nil {\n\t\t\t\tt.Error(\"Problem with consoleConfig.Data[console-config.yaml]\", err)\n\t\t\t}\n\n\t\t\t// compare the configs\n\t\t\tif diff := deep.Equal(exampleConfig, actualConfig); diff != nil {\n\t\t\t\tfmt.Printf(\"\\n EXAMPLE: %#v\\n\\n ACTUAL: %#v\\n\", exampleConfig, actualConfig)\n\t\t\t\tt.Error(diff)\n\t\t\t}\n\n\t\t\t// nil them out, we already compared them, and unfortunately we can't trust\n\t\t\t// that the ordering will be stable. this avoids a flaky test.\n\t\t\tcm.Data = nil\n\t\t\ttt.want.Data = nil\n\n\t\t\t// and then we can test the rest of the struct\n\t\t\tif diff := deep.Equal(cm, tt.want); diff != nil {\n\t\t\t\tt.Error(diff)\n\t\t\t}\n\t\t})\n\t}\n}", "func (c *ConfigMapConfig) ToConfigMap() corev1.ConfigMap {\n\treturn corev1.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: ApiVersion,\n\t\t\tKind: KindConfigMap,\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: c.Name,\n\t\t\tNamespace: c.Namespace,\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"csi.json\": c.JsonData,\n\t\t},\n\t}\n}", "func newReconciler(mgr manager.Manager) reconcile.Reconciler {\n\timageClient, err := imagev1.NewForConfig(mgr.GetConfig())\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Error getting image client: %v\", err))\n\t}\n\tbuildClient, err := buildv1.NewForConfig(mgr.GetConfig())\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Error getting build client: %v\", err))\n\t}\n\n\tclient := &kogitocli.Client{\n\t\tControlCli: mgr.GetClient(),\n\t\tBuildCli: buildClient,\n\t\tImageCli: imageClient,\n\t}\n\n\treturn &ReconcileKogitoApp{\n\t\tclient: client,\n\t\tscheme: mgr.GetScheme(),\n\t\tcache: mgr.GetCache(),\n\t}\n}", "func BuildConfigMapPlan(manifests map[string][]byte, namespace string) plan.Resource {\n\tb := plan.NewBuilder()\n\tfor name, manifest := range manifests {\n\t\tremoteName := fmt.Sprintf(\"config-map-%s\", name)\n\t\tb.AddResource(\"install:\"+remoteName, &resource.KubectlApply{Filename: object.String(remoteName), Manifest: manifest, Namespace: object.String(namespace)})\n\t}\n\tp, err := b.Plan()\n\tif err != nil {\n\t\tlog.Fatalf(\"%v\", err)\n\t}\n\treturn &p\n}", "func (a *APIServerconfigMapStore) Add(obj interface{}) error {\n\tcfg := obj.(*api_v1.ConfigMap)\n\t_, err := a.client.CoreV1().ConfigMaps(cfg.Namespace).Create(context.TODO(), cfg, metav1.CreateOptions{})\n\treturn err\n}", "func (f *ConfigMapFactory) MakeConfigMap(\n\targs *types.ConfigMapArgs, options *types.GeneratorOptions) (*corev1.ConfigMap, error) {\n\tvar all []kv.Pair\n\tvar err error\n\tcm := f.makeFreshConfigMap(args)\n\n\tpairs, err := keyValuesFromEnvFile(f.ldr, args.EnvSource)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, fmt.Sprintf(\n\t\t\t\"env source file: %s\",\n\t\t\targs.EnvSource))\n\t}\n\tall = append(all, pairs...)\n\n\tpairs, err = keyValuesFromLiteralSources(args.LiteralSources)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, fmt.Sprintf(\n\t\t\t\"literal sources %v\", args.LiteralSources))\n\t}\n\tall = append(all, pairs...)\n\n\tpairs, err = keyValuesFromFileSources(f.ldr, args.FileSources)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, fmt.Sprintf(\n\t\t\t\"file sources: %v\", args.FileSources))\n\t}\n\tall = append(all, pairs...)\n\n\tfor _, p := range all {\n\t\terr = addKvToConfigMap(cm, p.Key, p.Value)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif options != nil {\n\t\tcm.SetLabels(options.Labels)\n\t\tcm.SetAnnotations(options.Annotations)\n\t}\n\treturn cm, nil\n}", "func createSupportBundleSpecConfigMap(app apptypes.AppType, sequence int64, kotsKinds *kotsutil.KotsKinds, configMapName string, builtBundle *troubleshootv1beta2.SupportBundle, opts types.TroubleshootOptions, clientset kubernetes.Interface) error {\n\ts := serializer.NewYAMLSerializer(serializer.DefaultMetaFactory, scheme.Scheme, scheme.Scheme)\n\tvar b bytes.Buffer\n\tif err := s.Encode(builtBundle, &b); err != nil {\n\t\treturn errors.Wrap(err, \"failed to encode support bundle\")\n\t}\n\n\ttemplatedSpec := b.Bytes()\n\n\trenderedSpec, err := helper.RenderAppFile(app, &sequence, templatedSpec, kotsKinds, util.PodNamespace)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed render support bundle spec\")\n\t}\n\n\t// unmarshal the spec, look for image replacements in collectors and then remarshal\n\t// we do this after template rendering to support templating and then replacement\n\tsupportBundle, err := kotsutil.LoadSupportBundleFromContents(renderedSpec)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to unmarshal rendered support bundle spec\")\n\t}\n\n\tvar registrySettings registrytypes.RegistrySettings\n\tif !util.IsHelmManaged() {\n\t\ts, err := store.GetStore().GetRegistryDetailsForApp(app.GetID())\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to get registry settings for app\")\n\t\t}\n\t\tregistrySettings = s\n\t}\n\n\tcollectors, err := registry.UpdateCollectorSpecsWithRegistryData(supportBundle.Spec.Collectors, registrySettings, kotsKinds.Installation, kotsKinds.License, &kotsKinds.KotsApplication)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to update collectors\")\n\t}\n\tsupportBundle.Spec.Collectors = collectors\n\tb.Reset()\n\tif err := s.Encode(supportBundle, &b); err != nil {\n\t\treturn errors.Wrap(err, \"failed to encode support bundle\")\n\t}\n\trenderedSpec = b.Bytes()\n\n\texistingConfigMap, err := clientset.CoreV1().ConfigMaps(util.PodNamespace).Get(context.TODO(), configMapName, metav1.GetOptions{})\n\tlabels := kotstypes.MergeLabels(kotstypes.GetKotsadmLabels(), kotstypes.GetTroubleshootLabels())\n\tif err != nil {\n\t\tif kuberneteserrors.IsNotFound(err) {\n\t\t\tconfigMap := &corev1.ConfigMap{\n\t\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t\tKind: \"ConfigMap\",\n\t\t\t\t},\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: configMapName,\n\t\t\t\t\tNamespace: util.PodNamespace,\n\t\t\t\t\tLabels: labels,\n\t\t\t\t},\n\t\t\t\tData: map[string]string{\n\t\t\t\t\tSpecDataKey: string(renderedSpec),\n\t\t\t\t},\n\t\t\t}\n\n\t\t\t_, err = clientset.CoreV1().ConfigMaps(util.PodNamespace).Create(context.TODO(), configMap, metav1.CreateOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"failed to create support bundle secret\")\n\t\t\t}\n\n\t\t\tlogger.Debugf(\"created %q support bundle spec secret\", configMapName)\n\t\t} else {\n\t\t\treturn errors.Wrap(err, \"failed to read support bundle secret\")\n\t\t}\n\t} else {\n\t\tif existingConfigMap.Data == nil {\n\t\t\texistingConfigMap.Data = map[string]string{}\n\t\t}\n\t\texistingConfigMap.Data[SpecDataKey] = string(renderedSpec)\n\t\texistingConfigMap.ObjectMeta.Labels = labels\n\n\t\t_, err = clientset.CoreV1().ConfigMaps(util.PodNamespace).Update(context.TODO(), existingConfigMap, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to update support bundle secret\")\n\t\t}\n\t}\n\treturn nil\n}", "func (r *reconciler) createRouterCAConfigMap(cm *corev1.ConfigMap) error {\n\tif err := r.Client.Create(context.TODO(), cm); err != nil {\n\t\tif errors.IsAlreadyExists(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\tlogrus.Infof(\"created configmap %s/%s\", cm.Namespace, cm.Name)\n\treturn nil\n}", "func (w *worker) reconcileConfigMap(\n\tchi *chop.ClickHouseInstallation,\n\tconfigMap *core.ConfigMap,\n\tupdate bool,\n) error {\n\tw.a.V(2).M(chi).S().P()\n\tdefer w.a.V(2).M(chi).E().P()\n\n\t// Check whether this object already exists in k8s\n\tcurConfigMap, err := w.c.getConfigMap(&configMap.ObjectMeta, false)\n\n\tif curConfigMap != nil {\n\t\t// We have ConfigMap - try to update it\n\t\tif !update {\n\t\t\treturn nil\n\t\t}\n\t\terr = w.updateConfigMap(chi, configMap)\n\t}\n\n\tif apierrors.IsNotFound(err) {\n\t\t// ConfigMap not found - even during Update process - try to create it\n\t\terr = w.createConfigMap(chi, configMap)\n\t}\n\n\tif err != nil {\n\t\tw.a.WithEvent(chi, eventActionReconcile, eventReasonReconcileFailed).\n\t\t\tWithStatusAction(chi).\n\t\t\tWithStatusError(chi).\n\t\t\tM(chi).A().\n\t\t\tError(\"FAILED to reconcile ConfigMap: %s CHI: %s \", configMap.Name, chi.Name)\n\t}\n\n\treturn err\n}", "func (r *InstanceReconciler) configmapForInstance(m *terraformv1alpha1.Instance, input util.TerraVars) *corev1.ConfigMap {\n\tconfigMapData := make(map[string]string, 0)\n\n\te := reflect.ValueOf(&input).Elem()\n\n\tfor i := 0; i < e.NumField(); i++ {\n\t\tvarName := e.Type().Field(i).Name\n\t\t//varType := e.Type().Field(i).Type\n\t\tvarValue := fmt.Sprintf(\"%v\", e.Field(i).Interface())\n\n\t\tconfigMapData[varName] = varValue\n\t}\n\n\tcm := &corev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: m.Name,\n\t\t\tNamespace: m.Namespace,\n\t\t},\n\t\tData: configMapData,\n\t}\n\treturn cm\n}", "func newStorageConfigFromConfigMap(ctx context.Context, configMap *corev1.ConfigMap, c client.Reader, ns string) (*StorageConfig, error) {\n\tvar sc StorageConfig\n\thasDefault := false\n\tfor k, v := range configMap.Data {\n\t\tvar bc BucketConfig\n\t\terr := yaml.Unmarshal([]byte(v), &bc)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbc.fixEndpoint()\n\t\tbc.isDefault = k == \"default\"\n\n\t\t// Try loading the secret\n\t\tvar secret corev1.Secret\n\t\tkey := client.ObjectKey{\n\t\t\tName: bc.SecretName,\n\t\t\tNamespace: configMap.GetNamespace(),\n\t\t}\n\t\tif err := c.Get(ctx, key, &secret); err != nil {\n\t\t\treturn nil, maskAny(err)\n\t\t}\n\t\tif raw, found := secret.Data[constants.SecretKeyS3AccessKey]; found {\n\t\t\tbc.accessKey = string(raw)\n\t\t} else {\n\t\t\treturn nil, maskAny(fmt.Errorf(\"Config %#v refers to Secret '%s' that has no '%s' field\", configMap.Data, bc.SecretName, constants.SecretKeyS3AccessKey))\n\t\t}\n\t\tif raw, found := secret.Data[constants.SecretKeyS3SecretKey]; found {\n\t\t\tbc.secretKey = string(raw)\n\t\t} else {\n\t\t\treturn nil, maskAny(fmt.Errorf(\"Config %#v refers to Secret '%s' that has no '%s' field\", configMap.Data, bc.SecretName, constants.SecretKeyS3SecretKey))\n\t\t}\n\n\t\t// Add to config\n\t\thasDefault = hasDefault || bc.isDefault\n\t\tsc.Buckets = append(sc.Buckets, bc)\n\t}\n\tif !hasDefault {\n\t\treturn nil, maskAny(fmt.Errorf(\"Config %#v must have a default bucket\", configMap.Data))\n\t}\n\tsort.Slice(sc.Buckets, func(i, j int) bool {\n\t\ta, b := sc.Buckets[i], sc.Buckets[j]\n\t\tif a.isDefault && !b.isDefault {\n\t\t\treturn true\n\t\t}\n\t\tif !a.isDefault && b.isDefault {\n\t\t\treturn false\n\t\t}\n\t\treturn strings.Compare(a.Name, b.Name) < 0\n\t})\n\treturn &sc, nil\n}", "func (c *Controller) createOrUpdateConfigMapResource(chi *chop.ClickHouseInstallation, configMap *core.ConfigMap) error {\n\t// Check whether object with such name already exists in k8s\n\tres, err := c.configMapLister.ConfigMaps(chi.Namespace).Get(configMap.Name)\n\tif res != nil {\n\t\t// Object with such name already exists, this is not an error\n\t\tglog.V(1).Infof(\"Update ConfigMap %s/%s\\n\", configMap.Namespace, configMap.Name)\n\t\t_, err := c.kubeClient.CoreV1().ConfigMaps(chi.Namespace).Update(configMap)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\t// Object with such name does not exist or error happened\n\n\tif apierrors.IsNotFound(err) {\n\t\t// Object with such name not found - create it\n\t\t_, err = c.kubeClient.CoreV1().ConfigMaps(chi.Namespace).Create(configMap)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Object created\n\treturn nil\n}", "func newConfig() Config {\n\treturn Config{\n\t\tDefaultContainerConfig: newDefaultContainerConfig(),\n\t\tContainersConfig: map[string]ContainerConfig{},\n\t\tExclude: []string{},\n\t}\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"configmap-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource ConfigMap\n\terr = c.Watch(&source.Kind{Type: &corev1.ConfigMap{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// TODO(user): Modify this to be the types you create that are owned by the primary resource\n\t// Watch for changes to secondary resource Pods and requeue the owner ConfigMap\n\terr = c.Watch(&source.Kind{Type: &corev1.Pod{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &corev1.ConfigMap{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func NewController(\n\topt reconciler.Options,\n\tboosclientset clientset.Interface,\n\timmutableMapInformer informers.ImmutableMapInformer,\n\tconfigMapInformer corev1informers.ConfigMapInformer,\n) *controller.Impl {\n\tr := &Reconciler{\n\t\tBase: reconciler.NewBase(opt, controllerAgentName),\n\t\tboosclientset: boosclientset,\n\t\timmutableMapLister: immutableMapInformer.Lister(),\n\t\tconfigMapLister: configMapInformer.Lister(),\n\t}\n\timpl := controller.NewImpl(r, r.Logger, \"ImmutableMaps\",\n\t\treconciler.MustNewStatsReporter(\"ImmutableMaps\", r.Logger))\n\n\tr.Logger.Info(\"Setting up event handlers\")\n\n\t// Set up an event handler for when ImmutableMap resources change.\n\timmutableMapInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: impl.Enqueue,\n\t\tUpdateFunc: controller.PassNew(impl.Enqueue),\n\t\tDeleteFunc: impl.Enqueue,\n\t})\n\n\t// Set up an event handler for when Knative Service resources that we own change.\n\tconfigMapInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{\n\t\tFilterFunc: controller.Filter(v1alpha1.SchemeGroupVersion.WithKind(\"ImmutableMap\")),\n\t\tHandler: cache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: impl.EnqueueControllerOf,\n\t\t\tUpdateFunc: controller.PassNew(impl.EnqueueControllerOf),\n\t\t\tDeleteFunc: impl.EnqueueControllerOf,\n\t\t},\n\t})\n\n\treturn impl\n}", "func configMapOperations(t *testing.T, kubeclient clientset.Interface, namespace string) {\n\t// create, get, watch, update, patch, list and delete configmap.\n\tconfigMap := &apiv1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"audit-configmap\",\n\t\t\tNamespace: namespace,\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"map-key\": \"map-value\",\n\t\t},\n\t}\n\t// add admission label to config maps that are to be sent to webhook\n\tif namespace != nonAdmissionWebhookNamespace {\n\t\tconfigMap.Labels = map[string]string{\n\t\t\t\"admission\": \"true\",\n\t\t}\n\t}\n\n\t_, err := kubeclient.CoreV1().ConfigMaps(namespace).Create(context.TODO(), configMap, metav1.CreateOptions{})\n\texpectNoError(t, err, \"failed to create audit-configmap\")\n\n\t_, err = kubeclient.CoreV1().ConfigMaps(namespace).Get(context.TODO(), configMap.Name, metav1.GetOptions{})\n\texpectNoError(t, err, \"failed to get audit-configmap\")\n\n\tconfigMapChan, err := kubeclient.CoreV1().ConfigMaps(namespace).Watch(context.TODO(), watchOptions)\n\texpectNoError(t, err, \"failed to create watch for config maps\")\n\tfor range configMapChan.ResultChan() {\n\t\t// Block until watchOptions.TimeoutSeconds expires.\n\t\t// If the test finishes before watchOptions.TimeoutSeconds expires, the watch audit\n\t\t// event at stage ResponseComplete will not be generated.\n\t}\n\n\t_, err = kubeclient.CoreV1().ConfigMaps(namespace).Update(context.TODO(), configMap, metav1.UpdateOptions{})\n\texpectNoError(t, err, \"failed to update audit-configmap\")\n\n\t_, err = kubeclient.CoreV1().ConfigMaps(namespace).Patch(context.TODO(), configMap.Name, types.JSONPatchType, patch, metav1.PatchOptions{})\n\texpectNoError(t, err, \"failed to patch configmap\")\n\n\t_, err = kubeclient.CoreV1().ConfigMaps(namespace).List(context.TODO(), metav1.ListOptions{})\n\texpectNoError(t, err, \"failed to list config maps\")\n\n\terr = kubeclient.CoreV1().ConfigMaps(namespace).Delete(context.TODO(), configMap.Name, metav1.DeleteOptions{})\n\texpectNoError(t, err, \"failed to delete audit-configmap\")\n}", "func (r *ReconcileComplianceScan) reconcileReplicatedTailoringConfigMap(scan *compv1alpha1.ComplianceScan, origName, origNs, privName, privNs, scanName string, logger logr.Logger) error {\n\tlogger.Info(\"Reconciling Tailoring ConfigMap\", \"ConfigMap.Name\", origName, \"ConfigMap.Namespace\", origNs)\n\n\torigCM := &corev1.ConfigMap{}\n\torigKey := types.NamespacedName{Name: origName, Namespace: origNs}\n\terr := r.client.Get(context.TODO(), origKey, origCM)\n\t// Tailoring ConfigMap not found\n\tif err != nil && errors.IsNotFound(err) {\n\t\t// We previously had dealt with this issue, just requeue\n\t\tif strings.HasPrefix(scan.Status.ErrorMessage, tailoringNotFoundPrefix) {\n\t\t\treturn common.NewRetriableCtrlErrorWithCustomHandler(func() (reconcile.Result, error) {\n\t\t\t\t// A ConfigMap not being found might be a temporary issue\n\t\t\t\tif r.recorder != nil {\n\t\t\t\t\tr.recorder.Eventf(\n\t\t\t\t\t\tscan, corev1.EventTypeWarning, \"TailoringError\",\n\t\t\t\t\t\t\"Tailoring ConfigMap '%s' not found\", origKey,\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\treturn reconcile.Result{RequeueAfter: requeueAfterDefault, Requeue: true}, nil\n\t\t\t}, \"Tailoring ConfigMap not found\")\n\t\t}\n\t\t// A ConfigMap not being found might be a temporary issue (update and let the reconcile loop requeue)\n\t\treturn common.NewRetriableCtrlErrorWithCustomHandler(func() (reconcile.Result, error) {\n\t\t\tif r.recorder != nil {\n\t\t\t\tr.recorder.Eventf(\n\t\t\t\t\tscan, corev1.EventTypeWarning, \"TailoringError\",\n\t\t\t\t\t\"Tailoring ConfigMap '%s' not found\", origKey,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tlog.Info(\"Updating scan status due to missing Tailoring ConfigMap\")\n\t\t\tscanCopy := scan.DeepCopy()\n\t\t\tscanCopy.Status.ErrorMessage = tailoringNotFoundPrefix + err.Error()\n\t\t\tscanCopy.Status.Result = compv1alpha1.ResultError\n\t\t\tif updateerr := r.client.Status().Update(context.TODO(), scanCopy); updateerr != nil {\n\t\t\t\tlog.Error(updateerr, \"Failed to update a scan\")\n\t\t\t\treturn reconcile.Result{}, updateerr\n\t\t\t}\n\t\t\treturn reconcile.Result{RequeueAfter: requeueAfterDefault, Requeue: true}, nil\n\t\t}, \"Tailoring ConfigMap not found\")\n\t} else if err != nil {\n\t\tlog.Error(err, \"Failed to get spec tailoring ConfigMap\", \"ConfigMap.Name\", origName, \"ConfigMap.Namespace\", origNs)\n\t\treturn err\n\t} else if scan.Status.Result == compv1alpha1.ResultError {\n\t\t// We had an error caused by a previously not found configmap. Let's remove it\n\t\tif strings.HasPrefix(scan.Status.ErrorMessage, tailoringNotFoundPrefix) {\n\t\t\treturn common.NewRetriableCtrlErrorWithCustomHandler(func() (reconcile.Result, error) {\n\t\t\t\tlog.Info(\"Updating scan status since Tailoring ConfigMap was now found\")\n\t\t\t\tscanCopy := scan.DeepCopy()\n\t\t\t\tscanCopy.Status.ErrorMessage = \"\"\n\t\t\t\tscanCopy.Status.Result = compv1alpha1.ResultNotAvailable\n\t\t\t\tif updateerr := r.client.Status().Update(context.TODO(), scanCopy); updateerr != nil {\n\t\t\t\t\tlog.Error(updateerr, \"Failed to update a scan\")\n\t\t\t\t\treturn reconcile.Result{}, updateerr\n\t\t\t\t}\n\t\t\t\treturn reconcile.Result{RequeueAfter: requeueAfterDefault, Requeue: true}, nil\n\t\t\t}, \"Tailoring ConfigMap previously not found, was now found\")\n\t\t}\n\t}\n\n\torigData, ok := origCM.Data[\"tailoring.xml\"]\n\tif !ok {\n\t\treturn common.NewNonRetriableCtrlError(\"Tailoring ConfigMap missing `tailoring.xml` key\")\n\t}\n\tif origData == \"\" {\n\t\treturn common.NewNonRetriableCtrlError(\"Tailoring ConfigMap's key `tailoring.xml` is empty\")\n\t}\n\n\tprivCM := &corev1.ConfigMap{}\n\tprivKey := types.NamespacedName{Name: privName, Namespace: privNs}\n\terr = r.client.Get(context.TODO(), privKey, privCM)\n\tif err != nil && errors.IsNotFound(err) {\n\t\tnewCM := &corev1.ConfigMap{}\n\t\tnewCM.SetName(privName)\n\t\tnewCM.SetNamespace(privNs)\n\t\tif newCM.Labels == nil {\n\t\t\tnewCM.Labels = make(map[string]string)\n\t\t}\n\t\tnewCM.Labels[compv1alpha1.ComplianceScanLabel] = scanName\n\t\tnewCM.Labels[compv1alpha1.ScriptLabel] = \"\"\n\t\tif newCM.Data == nil {\n\t\t\tnewCM.Data = make(map[string]string)\n\t\t}\n\t\tnewCM.Data[\"tailoring.xml\"] = origData\n\t\tlogger.Info(\"Creating private Tailoring ConfigMap\", \"ConfigMap.Name\", privName, \"ConfigMap.Namespace\", privNs)\n\t\terr = r.client.Create(context.TODO(), newCM)\n\t\t// Ignore error if CM already exists\n\t\tif err != nil && !errors.IsAlreadyExists(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t} else if err != nil {\n\t\tlog.Error(err, \"Failed to get private tailoring ConfigMap\", \"ConfigMap.Name\", privName, \"ConfigMap.Namespace\", privNs)\n\t\treturn err\n\t}\n\tprivData, _ := privCM.Data[\"tailoring.xml\"]\n\n\t// privCM needs update\n\tif privData != origData {\n\t\tupdatedCM := privCM.DeepCopy()\n\t\tif updatedCM.Data == nil {\n\t\t\tupdatedCM.Data = make(map[string]string)\n\t\t}\n\t\tif updatedCM.Labels == nil {\n\t\t\tupdatedCM.Labels = make(map[string]string)\n\t\t}\n\t\tupdatedCM.Labels[compv1alpha1.ComplianceScanLabel] = scanName\n\t\tupdatedCM.Labels[compv1alpha1.ScriptLabel] = \"\"\n\t\tupdatedCM.Data[\"tailoring.xml\"] = origData\n\t\tlogger.Info(\"Updating private Tailoring ConfigMap\", \"ConfigMap.Name\", privName, \"ConfigMap.Namespace\", privNs)\n\t\treturn r.client.Update(context.TODO(), updatedCM)\n\t}\n\tlogger.Info(\"Private Tailoring ConfigMap is up-to-date\", \"ConfigMap.Name\", privName, \"ConfigMap.Namespace\", privNs)\n\treturn nil\n}", "func validateNewConfigMap(configMap *corev1.ConfigMap, keyName string) error {\n\tif errs := validation.IsConfigMapKey(keyName); len(errs) > 0 {\n\t\treturn fmt.Errorf(\"%q is not a valid key name for a ConfigMap: %s\", keyName, strings.Join(errs, \",\"))\n\t}\n\tif _, exists := configMap.Data[keyName]; exists {\n\t\treturn fmt.Errorf(\"cannot add key %q, another key by that name already exists in Data for ConfigMap %q\", keyName, configMap.Name)\n\t}\n\tif _, exists := configMap.BinaryData[keyName]; exists {\n\t\treturn fmt.Errorf(\"cannot add key %q, another key by that name already exists in BinaryData for ConfigMap %q\", keyName, configMap.Name)\n\t}\n\n\treturn nil\n}", "func (m *MockConfigMapClient) CreateConfigMap(arg0 *v10.ConfigMap) (*v10.ConfigMap, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateConfigMap\", arg0)\n\tret0, _ := ret[0].(*v10.ConfigMap)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (configMapTemplateFactory) NewExisting(name string, ci client.Interface, gc interfaces.GraphContext) interfaces.Resource {\n\treturn report.SimpleReporter{BaseResource: existingConfigMap{Name: name, Client: ci.ConfigMaps()}}\n}", "func (r *ReconcileConfigMap) Reconcile(request reconcile.Request) (reconcile.Result, error) {\n\t// Fetch the ConfigMap instance\n\tcminstance := &corev1.ConfigMap{}\n\tif err := r.client.Get(context.TODO(), request.NamespacedName, cminstance); err != nil {\n\t\treturn reconcile.Result{}, IgnoreNotFound(err)\n\t}\n\tpolicyName, ok := cminstance.Labels[\"appName\"]\n\tif !ok {\n\t\treturn reconcile.Result{}, nil\n\t}\n\tpolicyNamespace, ok := cminstance.Labels[\"appNamespace\"]\n\tif !ok {\n\t\treturn reconcile.Result{}, nil\n\t}\n\n\treqLogger := log.WithValues(\"SelinuxPolicy.Name\", policyName, \"SelinuxPolicy.Namespace\", policyNamespace)\n\n\tpolicyObjKey := types.NamespacedName{Name: policyName, Namespace: policyNamespace}\n\tpolicy := &spov1alpha1.SelinuxPolicy{}\n\tif err := r.client.Get(context.TODO(), policyObjKey, policy); err != nil {\n\t\treturn reconcile.Result{}, IgnoreNotFound(err)\n\t}\n\n\tif policy.Status.State == \"\" || policy.Status.State == spov1alpha1.PolicyStatePending {\n\t\tpolicyCopy := policy.DeepCopy()\n\t\tpolicyCopy.Status.State = spov1alpha1.PolicyStateInProgress\n\t\tpolicyCopy.Status.SetConditions(rcommonv1.Creating())\n\t\tif err := r.client.Status().Update(context.TODO(), policyCopy); err != nil {\n\t\t\treturn reconcile.Result{}, errors.Wrap(err, \"Updating policy without status\")\n\t\t}\n\t\treturn reconcile.Result{Requeue: true}, nil\n\t}\n\n\t// object is not being deleted\n\tif cminstance.ObjectMeta.DeletionTimestamp.IsZero() {\n\t\treturn r.reconcileInstallerPods(policy, cminstance, reqLogger)\n\t}\n\treturn reconcile.Result{}, nil\n}", "func newConfigHandler() *configHandler {\n return &configHandler {\n database: map[string]Config{},\n }\n}", "func (r *ReconcileMobileSecurityService) buildConfigMap(mss *mobilesecurityservicev1alpha1.MobileSecurityService) *corev1.ConfigMap {\n\tser := &corev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: mss.Spec.ConfigMapName,\n\t\t\tNamespace: mss.Namespace,\n\t\t\tLabels: getAppLabels(mss.Name),\n\t\t},\n\t\tData: getAppEnvVarsMap(mss),\n\t}\n\t// Set MobileSecurityService instance as the owner and controller\n\tcontrollerutil.SetControllerReference(mss, ser, r.scheme)\n\treturn ser\n}", "func ConfigMap(\n\tinCluster *v1beta1.PostgresCluster,\n\toutConfigMap *corev1.ConfigMap,\n) error {\n\tif inCluster.Spec.UserInterface == nil || inCluster.Spec.UserInterface.PGAdmin == nil {\n\t\t// pgAdmin is disabled; there is nothing to do.\n\t\treturn nil\n\t}\n\n\tinitialize.StringMap(&outConfigMap.Data)\n\n\t// To avoid spurious reconciles, the following value must not change when\n\t// the spec does not change. [json.Encoder] and [json.Marshal] do this by\n\t// emitting map keys in sorted order. Indent so the value is not rendered\n\t// as one long line by `kubectl`.\n\tbuffer := new(bytes.Buffer)\n\tencoder := json.NewEncoder(buffer)\n\tencoder.SetEscapeHTML(false)\n\tencoder.SetIndent(\"\", \" \")\n\terr := encoder.Encode(systemSettings(inCluster.Spec.UserInterface.PGAdmin))\n\tif err == nil {\n\t\toutConfigMap.Data[settingsConfigMapKey] = buffer.String()\n\t}\n\treturn err\n}", "func (*deployInsideDeployConfigMapHandler) updateConfigMap(_ context.Context, _ *apiv1.ConfigMap, _ *pipeline.CfgData, err error) error {\n\treturn nil\n}", "func newConfig(old *Config, vars Vars) *Config {\n\tv := mergeVars(old.Vars, vars)\n\n\treturn &Config{\n\t\tAppID: old.AppID,\n\t\tVars: v,\n\t}\n}", "func GetConfigmap(namespace string, configmapName string, testData string) *v1.ConfigMap {\n\treturn &v1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: configmapName,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: map[string]string{\"firstLabel\": \"temp\"},\n\t\t},\n\t\tData: map[string]string{\"test.url\": testData},\n\t}\n}", "func (c *Catalog) InterpolateOpsConfigMap(name string) corev1.ConfigMap {\n\treturn corev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{Name: name},\n\t\tData: map[string]string{\n\t\t\t\"ops\": `- type: replace\n path: /instance_groups/name=nats?/instances\n value: 1\n`,\n\t\t},\n\t}\n}", "func newConfig(opts ...Option) config {\n\tc := config{\n\t\tMeterProvider: otel.GetMeterProvider(),\n\t}\n\tfor _, opt := range opts {\n\t\topt.apply(&c)\n\t}\n\treturn c\n}", "func NewReplicator(operator operator.Operator) *Replicator {\n\treturn &Replicator{operator}\n}" ]
[ "0.71497184", "0.6927563", "0.65653753", "0.6345264", "0.6338276", "0.63350874", "0.6253385", "0.61591893", "0.6085698", "0.60481936", "0.60005623", "0.598205", "0.5976869", "0.5919875", "0.59195656", "0.59191275", "0.59029496", "0.588134", "0.5876783", "0.58281237", "0.5794557", "0.57766765", "0.5711093", "0.5710301", "0.5705318", "0.5702129", "0.56590146", "0.5642787", "0.56110215", "0.55993325", "0.55382264", "0.5523712", "0.55051345", "0.54893816", "0.5485657", "0.5480898", "0.54787374", "0.5478012", "0.547738", "0.547639", "0.5458392", "0.5456156", "0.5448177", "0.5433921", "0.5432024", "0.54253995", "0.54014266", "0.53936404", "0.5390682", "0.5385406", "0.53339076", "0.53335476", "0.52870476", "0.52802205", "0.5277348", "0.5233994", "0.519471", "0.51839393", "0.5180013", "0.5179032", "0.51789993", "0.5178291", "0.51709515", "0.51565236", "0.51491165", "0.5147706", "0.5125368", "0.5116779", "0.51157933", "0.5111629", "0.51093215", "0.5099798", "0.50994486", "0.5092503", "0.50872976", "0.5084951", "0.5081404", "0.5079541", "0.5078", "0.5067871", "0.5065553", "0.5065505", "0.5055454", "0.5046832", "0.50327015", "0.5032588", "0.5030419", "0.50195706", "0.50106114", "0.4992744", "0.4969478", "0.49518982", "0.49484667", "0.49468067", "0.49394995", "0.49336618", "0.4929764", "0.4929406", "0.49176112", "0.4915665" ]
0.8266834
0
RequestIDFromContext is get the request id from context
func RequestIDFromContext(ctx context.Context) string { return ctx.Value(requestIDKey).(string) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func RequestIDFromContext(ctx context.Context) string {\n\tif ctx == nil {\n\t\treturn \"\"\n\t}\n\tif gCtx, ok := ctx.(*gin.Context); ok {\n\t\tctx = gCtx.Request.Context()\n\t}\n\tif requestId, ok := ctx.Value(requestIdKey).(string); ok {\n\t\treturn requestId\n\t}\n\treturn \"\"\n}", "func ContextRequestId(ctx context.Context) (requestId string) {\n\tif d, ok := ctx.Value(contextHandlerDetailsKey).(*handlerDetails); ok {\n\t\trequestId = d.requestId\n\t}\n\treturn\n}", "func RequestID(ctx context.Context) string {\n\tif ctx == nil {\n\t\treturn \"\"\n\t}\n\n\tval, _ := ctx.Value(reqidKey).(string)\n\treturn val\n}", "func requestID(ctx context.Context) uuid.UUID {\n\tval := ctx.Value(requestIDKey)\n\tif val == nil {\n\t\treturn uuid.UUID{}\n\t}\n\treturn val.(uuid.UUID)\n}", "func RequestID(ctx context.Context) string {\n\traw := ctx.Value(requestID)\n\tvalue, ok := raw.(*id)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn value.String()\n}", "func RequestID(c context.Context) string {\n\tRequestID := c.Value(contextKeyRequestID)\n\tif RequestID == nil {\n\t\treturn \"\"\n\t}\n\treturn RequestID.(string)\n}", "func RequestID(req *http.Request) string {\n\tif req == nil {\n\t\treturn \"\"\n\t}\n\treqIDContextValue := req.Context().Value(log.ContextreqIDKey)\n\tif reqIDContextValue == nil {\n\t\treturn \"\"\n\t}\n\treturn reqIDContextValue.(string)\n}", "func getRequestID(c *gin.Context) string {\n\tif id := c.Request.Header.Get(\"x-request-id\"); len(id) > 0 {\n\t\treturn id\n\t}\n\treturn uuid.New().String()\n}", "func CtxRequestID(c *gin.Context) string {\n\t// first get from context\n\trequestidItf, _ := c.Get(RequestIDKey)\n\tif requestidItf != nil {\n\t\trequestid := requestidItf.(string)\n\t\tif requestid != \"\" {\n\t\t\treturn requestid\n\t\t}\n\t}\n\t// if not then get request id from header\n\trequestid := c.Request.Header.Get(RequestIDKey)\n\tif requestid != \"\" {\n\t\treturn requestid\n\t}\n\t// else gen a request id\n\treturn uuid.NewV4().String()\n}", "func GCtxRequestID(c *gin.Context) string {\n\tif v, isExist := c.Get(ContextRequestIDKey); isExist {\n\t\tif requestID, ok := v.(string); ok {\n\t\t\treturn requestID\n\t\t}\n\t}\n\treturn \"\"\n}", "func GetRequestID(ctx context.Context) string {\n\tid, ok := ctx.Value(contextKey(\"requestID\")).(string)\n\tif !ok {\n\t\tlogrus.Warn(\"requestID not found in context\")\n\t\treturn \"\"\n\t}\n\treturn id\n}", "func GetReqIDFromContext(ctx context.Context) string {\n\treqID, ok := ctx.Value(constant.ReqID).(string)\n\tif !ok {\n\t\treqID = constant.EmptyReq\n\t}\n\treturn reqID\n}", "func requestIDFromGRPCContext(ctx context.Context) string {\n\tmd, ok := metadata.FromIncomingContext(ctx)\n\tif ok {\n\t\tif v, ok := md[\"request-id\"]; ok {\n\t\t\treturn v[0]\n\t\t}\n\t}\n\treturn uuid.New().String()\n}", "func RequestID(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\trequestID := uuid.New().String()\n\t\tnctx := context.WithValue(r.Context(), contextKey(\"requestID\"), requestID)\n\t\tnext.ServeHTTP(w, r.WithContext(nctx))\n\t})\n}", "func GetRequestID(c echo.Context) string {\n\treturn c.Response().Header().Get(echo.HeaderXRequestID)\n}", "func GetRequestID(ctx context.Context) string {\n\tID := ctx.Value(RequestIDContextKey)\n\tif s, ok := ID.(string); ok {\n\t\treturn s\n\t}\n\treturn \"\"\n}", "func GetRequestID(ctx context.Context) int {\n\tif rv := ctx.Value(requestIDKey); rv != nil {\n\t\tif id, ok := rv.(int); ok {\n\t\t\treturn id\n\t\t}\n\t}\n\n\treturn -1\n}", "func GetRequestID(ctx context.Context) string {\n\n\treqID := ctx.Value(ContextKeyRequestID)\n\n\tif ret, ok := reqID.(string); ok {\n\t\treturn ret\n\t}\n\n\treturn \"\"\n}", "func (rs *requestContext) RequestID() string {\n\treturn rs.requestID\n}", "func GetReqID(ctx context.Context) string {\n\tif ctx == nil {\n\t\treturn \"\"\n\t}\n\tif reqID, ok := ctx.Value(RequestIDKey).(string); ok {\n\t\treturn reqID\n\t}\n\treturn \"\"\n}", "func GetReqID(ctx context.Context) string {\n\tif ctx == nil {\n\t\treturn \"\"\n\t}\n\tif reqID, ok := ctx.Value(RequestIDKey).(string); ok {\n\t\treturn reqID\n\t}\n\treturn \"\"\n}", "func RequestID(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tctx := newContextWithRequestID(r.Context(), r)\n\t\tw.Header().Set(requestIDHeaderKey, requestIDFromContext(ctx))\n\t\th.ServeHTTP(w, r.WithContext(ctx))\n\t})\n}", "func GetRequestID(r *http.Request) string {\n\treturn r.Header.Get(\"X-Request-Id\")\n}", "func withRequestID(next http.HandlerFunc) http.HandlerFunc {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\trequestID := r.Header.Get(\"x-request-id\")\n\t\tif requestID == \"\" {\n\t\t\trequestID = uuid.Must(uuid.NewV4()).String()\n\t\t}\n\n\t\tctx := log.With(r.Context(), zap.String(\"request_id\", requestID))\n\t\tr = r.WithContext(ctx)\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func RequestID() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\t// Check for incoming header, use it if exists\n\t\trequestID := c.Request.Header.Get(HeaderXRequestIDKey)\n\n\t\t// Create request id\n\t\tif requestID == \"\" {\n\t\t\trequestID = krand.String(krand.R_All, 12) // 生成长度为12的随机字符串\n\t\t\tc.Request.Header.Set(HeaderXRequestIDKey, requestID)\n\t\t\t// Expose it for use in the application\n\t\t\tc.Set(ContextRequestIDKey, requestID)\n\t\t}\n\n\t\t// Set X-Request-ID header\n\t\tc.Writer.Header().Set(HeaderXRequestIDKey, requestID)\n\n\t\tc.Next()\n\t}\n}", "func CtxRequestID(ctx context.Context) string {\n\tv := ctx.Value(ContextRequestIDKey)\n\tif str, ok := v.(string); ok {\n\t\treturn str\n\t}\n\treturn \"\"\n}", "func HeaderRequestID(c *gin.Context) string {\n\treturn c.Request.Header.Get(HeaderXRequestIDKey)\n}", "func ProcessRequestById(c *gin.Context) {}", "func AddRequestIDToContext() echo.MiddlewareFunc {\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) error {\n\t\t\trequestID := c.Response().Header().Get(echo.HeaderXRequestID)\n\t\t\tc.Set(\"request_id\", requestID)\n\t\t\treturn next(c)\n\t\t}\n\t}\n}", "func GetRequestID(requestIDParams *string) string {\n\tlog.Debug(\"entering func getRequestID\")\n\t//generate UUID as request ID if it doesn't exist in request header\n\tif requestIDParams == nil || *requestIDParams == \"\" {\n\t\ttheUUID, err := uuid.NewUUID()\n\t\tnewUUID := \"\"\n\t\tif err == nil {\n\t\t\tnewUUID = theUUID.String()\n\t\t} else {\n\t\t\tnewUUID = GenerateUUID()\n\t\t}\n\t\trequestIDParams = &newUUID\n\t}\n\treturn *requestIDParams\n}", "func RequestID() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tc.Header(\"X-Request-Id\", uuid.New().String())\n\t\tc.Next()\n\t}\n}", "func APIRequestID(ctx context.Context) string {\n\tval := ctx.Value(APIRequestIDKey)\n\tif val == nil {\n\t\treturn \"\"\n\t}\n\trequestID, ok := val.(string)\n\tif !ok {\n\t\tglog.Warning(\"Could not convert APIRequestID val to string\")\n\t\treturn \"\"\n\t}\n\treturn requestID\n}", "func RequestID(req *http.Request) string {\n\tid := req.Header.Get(\"X-Request-ID\")\n\tif id == \"\" {\n\t\tn := Sequence(req)\n\t\tid = fmt.Sprintf(\"%d\", n)\n\t}\n\treturn id\n}", "func (self *ProxyRequest) requestId() string {\n\n\tt := time.Now().Local()\n\n\t// This should provide an extremely low chance to create race conditions.\n\tname := fmt.Sprintf(\n\t\t\"%s-%04d%02d%02d-%02d%02d%02d-%09d\",\n\t\tself.Request.Method,\n\t\tt.Year(),\n\t\tt.Month(),\n\t\tt.Day(),\n\t\tt.Hour(),\n\t\tt.Minute(),\n\t\tt.Second(),\n\t\tt.Nanosecond(),\n\t)\n\n\treturn name\n}", "func RequestID(nextRequestID IdGenerator) mux.MiddlewareFunc {\n\treturn TraceRequest(\"X-Request-Id\", nextRequestID)\n}", "func GetCtxRequestID(ctx context.Context) string {\n\tid, ok := ctx.Value(contextKeyRequestID).(string)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn id\n}", "func GenerateRequestID(ctx context.Context, o *RequestIDOptions) context.Context {\n\tvar id string\n\t{\n\t\tif o.useRequestID {\n\t\t\tif i := ctx.Value(RequestIDKey); i != nil {\n\t\t\t\tid = i.(string)\n\t\t\t\tif o.requestIDLimit > 0 && len(id) > o.requestIDLimit {\n\t\t\t\t\tid = id[:o.requestIDLimit]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif id == \"\" {\n\t\t\tid = shortID()\n\t\t}\n\t}\n\treturn context.WithValue(ctx, RequestIDKey, id)\n}", "func GetRequestID() int {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\trequestID = requestID + 1\n\treturn requestID\n}", "func WithRequestIDFromContext(name ...string) Option {\n\tvar requestIDName string\n\tif len(name) > 0 && name[0] != \"\" {\n\t\trequestIDName = name[0]\n\t} else {\n\t\trequestIDName = ContextRequestIDKey\n\t}\n\treturn func(o *options) {\n\t\to.requestIDFrom = 2\n\t\to.requestIDName = requestIDName\n\t}\n}", "func RequestID(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Header.Get(RequestIDHeader) == \"\" {\n\t\t\tr.Header.Set(RequestIDHeader, uuid.Must(uuid.NewV4()).String())\n\t\t}\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func RequestIDHandler(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {\n\t\tctx := newContextWithRequestID(req.Context(), req)\n\t\tif next != nil {\n\t\t\tnext.ServeHTTP(rw, req.WithContext(ctx))\n\t\t}\n\t})\n}", "func RequestID(headerName string) func(next http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\tfn := func(w http.ResponseWriter, req *http.Request) {\n\t\t\trequestID := req.Header.Get(headerName)\n\t\t\tif requestID == \"\" {\n\t\t\t\trequestID = NewRequestID()\n\t\t\t\treq.Header.Set(headerName, requestID)\n\t\t\t}\n\n\t\t\tctx := WithRequestID(req.Context(), requestID)\n\t\t\tnext.ServeHTTP(w, req.WithContext(ctx))\n\t\t}\n\t\treturn http.HandlerFunc(fn)\n\t}\n}", "func GetRequestID(ctx context.Context) (string, bool) {\n\tv, ok := ctx.Value(RequestIDKey).(string)\n\treturn v, ok\n}", "func RequestID() echo.MiddlewareFunc {\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) error {\n\t\t\tif DefaultSkipper(c) {\n\t\t\t\treturn next(c)\n\t\t\t}\n\n\t\t\treq := c.Request()\n\t\t\tres := c.Response()\n\t\t\trid := req.Header.Get(echo.HeaderXRequestID)\n\t\t\tif rid == \"\" {\n\t\t\t\trid = uuid.New().String()\n\t\t\t}\n\t\t\tres.Header().Set(echo.HeaderXRequestID, rid)\n\n\t\t\tctx := contextx.SetID(req.Context(), rid)\n\t\t\tc.SetRequest(req.WithContext(ctx))\n\n\t\t\treturn next(c)\n\t\t}\n\t}\n}", "func (s *SecurityGroupLimitExceeded) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func GetID(ctx context.Context) string {\n\tif ctx == nil {\n\t\tpanic(\"Can not get request ID from empty context\")\n\t}\n\n\tif requestID, ok := ctx.Value(requestIDKey).(string); ok {\n\t\treturn requestID\n\t}\n\n\treturn \"\"\n}", "func RequestID() echo.MiddlewareFunc {\n\treturn middleware.RequestID()\n}", "func (s *InternalServiceException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *InternalServiceException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *InternalServiceException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *TooManyTagsException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *TooManyTagsException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *TooManyTagsException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *TooManyTagsException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (c *CustomContext) injectRequestID(prev zerolog.Logger) zerolog.Logger {\n\tid := c.Response().Header().Get(echo.HeaderXRequestID)\n\treturn prev.With().Str(\"requestId\", id).Logger()\n}", "func (s *ServiceException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *AccessPointLimitExceeded) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func FromContext(ctx context.Context) string {\n\tv := ctx.Value(reqIDKey)\n\ts, _ := v.(string)\n\treturn s\n}", "func (si SignedIdentifiers) RequestID() string {\n\treturn si.rawResponse.Header.Get(\"x-ms-request-id\")\n}", "func FnIDFromContext(ctx context.Context) string {\n\tr, _ := ctx.Value(ctxFnIDKey(api.FnID)).(string)\n\treturn r\n}", "func WithRequestID(ctx context.Context, reqid string) context.Context {\n\treturn context.WithValue(ctx, reqidKey, reqid)\n}", "func (e *engine) setRequestID(ctx *Context) {\n\tif ess.IsStrEmpty(ctx.Req.Header.Get(e.requestIDHeader)) {\n\t\tctx.Req.Header.Set(e.requestIDHeader, ess.NewGUID())\n\t} else {\n\t\tlog.Debugf(\"Request already has ID: %v\", ctx.Req.Header.Get(e.requestIDHeader))\n\t}\n\tctx.Reply().Header(e.requestIDHeader, ctx.Req.Header.Get(e.requestIDHeader))\n}", "func RequestIDFilter(request *restful.Request, response *restful.Response, chain *restful.FilterChain) {\n\trequestID := request.Request.Header.Get(string(utils.ContextValueKeyRequestID))\n\tif len(requestID) == 0 {\n\t\trequestID = uuid.New().String()\n\t}\n\tctx := context.WithValue(request.Request.Context(), utils.ContextValueKeyRequestID, requestID)\n\trequest.Request = request.Request.WithContext(ctx)\n\tchain.ProcessFilter(request, response)\n}", "func addRequestID() Wrapper {\n\treturn func(fn http.HandlerFunc) http.HandlerFunc {\n\t\treturn func(w http.ResponseWriter, req *http.Request) {\n\t\t\tvar rid string = req.Header.Get(\"Request-ID\")\n\t\t\tif rid == \"\" || len(rid) > 8 {\n\t\t\t\trid = randStringBytesMaskSrc(8)\n\t\t\t}\n\n\t\t\treq = req.WithContext(context.WithValue(req.Context(), \"rid\", rid))\n\t\t\treq.Header.Add(\"Request-ID\", rid)\n\n\t\t\tfn(w, req)\n\t\t}\n\t}\n}", "func (s *TagLimitExceededException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func RequestIDMiddleware(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tctx := r.Context()\n\t\trequestID := r.Header.Get(xRequestID)\n\t\tif requestID == \"\" {\n\t\t\trequestID = uuid.New().String()\n\t\t}\n\t\tctx = context.WithValue(ctx, RequestIDKey, requestID)\n\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t}\n\treturn http.HandlerFunc(fn)\n}", "func (s *InvalidRequestException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *InvalidRequestException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *InvalidRequestException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *InvalidRequestException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *RequestTimeoutException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *TooManyRequests) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *NetworkInterfaceLimitExceeded) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func UseRequestID(headerName string) func(http.Handler) http.Handler {\n\tf := func(h http.Handler) http.Handler {\n\t\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\t\tvar reqID string\n\t\t\tif reqID = r.Header.Get(headerName); reqID == \"\" {\n\t\t\t\t// first occurrence\n\t\t\t\treqID = pkg.GenerateNewStringUUID()\n\t\t\t}\n\t\t\tctx := r.Context()\n\t\t\tctx = context.WithValue(ctx, pkg.RequestID, reqID)\n\n\t\t\t// setup logger\n\t\t\trequestLogger := log.WithField(pkg.RequestID, reqID)\n\t\t\tctx = context.WithValue(ctx, pkg.RequestID, requestLogger)\n\n\t\t\th.ServeHTTP(w, r.WithContext(ctx))\n\t\t}\n\t\treturn http.HandlerFunc(fn)\n\t}\n\treturn f\n}", "func AddRequestID(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tmyid := atomic.AddUint64(&reqID, 1)\n\t\tctx := r.Context()\n\t\tctx = context.WithValue(ctx, RequestIDKey, fmt.Sprintf(\"%s-%06d\", prefix, myid))\n\t\th.ServeHTTP(w, r.WithContext(ctx))\n\t})\n}", "func (s *ResourceLimitExceeded) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (alog *AppLogger) RequestID() string {\n\treturn alog.requestID\n}", "func CurrentRequestID() int32 { return atomic.LoadInt32(&globalRequestID) }", "func (t requestIDTracker) requestID(identifier ...string) string {\n\tkey := strings.Join(identifier, \"/\")\n\tid, exists := t.requestIDs[key]\n\tif !exists {\n\t\tid = uuid.New()\n\t\tt.requestIDs[key] = id\n\t}\n\treturn id\n}", "func Test_RequestID_Locals(t *testing.T) {\n\treqId := \"ThisIsARequestId\"\n\tctxKey := \"ThisIsAContextKey\"\n\n\tapp := fiber.New()\n\tapp.Use(New(Config{\n\t\tGenerator: func() string {\n\t\t\treturn reqId\n\t\t},\n\t\tContextKey: ctxKey,\n\t}))\n\n\tvar ctxVal string\n\n\tapp.Use(func(c *fiber.Ctx) error {\n\t\tctxVal = c.Locals(ctxKey).(string)\n\t\treturn c.Next()\n\t})\n\n\t_, err := app.Test(httptest.NewRequest(\"GET\", \"/\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, reqId, ctxVal)\n}", "func (s *ThrottlingException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *ThrottlingException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *ThrottlingException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *ThrottlingException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *ThrottlingException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *ThrottlingException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *ThrottlingException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *ThrottlingException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *ThrottlingException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *ThrottlingException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *ThrottlingException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *ThrottlingException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *ThrottlingException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *ThrottlingException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *ThrottlingException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *ThrottlingException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *ThrottlingException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *ThrottlingException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *ThrottlingException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *ThrottlingException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}" ]
[ "0.8282987", "0.77042204", "0.769616", "0.76211", "0.76147074", "0.7583506", "0.75634944", "0.7542204", "0.75279135", "0.7511003", "0.749952", "0.7479339", "0.7449342", "0.7335127", "0.7257361", "0.7229935", "0.7225493", "0.7152414", "0.71456414", "0.7142945", "0.7142945", "0.7120981", "0.70865977", "0.7083603", "0.7024363", "0.6963017", "0.69547653", "0.6927971", "0.6925776", "0.6899323", "0.68859863", "0.6884445", "0.68785197", "0.6859526", "0.6857969", "0.68511856", "0.68258494", "0.67957765", "0.679188", "0.6791539", "0.6790805", "0.6778449", "0.67764574", "0.67486554", "0.67471117", "0.6722534", "0.6715591", "0.67076325", "0.67069685", "0.67069685", "0.66869766", "0.66869766", "0.66869766", "0.66869766", "0.6683212", "0.6670962", "0.6660729", "0.6655794", "0.6650471", "0.6644135", "0.6626478", "0.66207325", "0.6612207", "0.66105723", "0.6604943", "0.65976113", "0.6591938", "0.6591938", "0.6591938", "0.6591632", "0.65902305", "0.6588377", "0.65797836", "0.65780383", "0.65460175", "0.6544158", "0.6536248", "0.65359384", "0.65337366", "0.653103", "0.6530813", "0.6530813", "0.6530813", "0.6530813", "0.6530813", "0.6530813", "0.6530813", "0.6530813", "0.6530813", "0.6530813", "0.6530813", "0.6530813", "0.6530813", "0.6530813", "0.6530813", "0.6530813", "0.6530813", "0.6530813", "0.6530813", "0.6530813" ]
0.79195726
1